Пример #1
0
// Dispatch the encapsulated request to the according handler methods
// depending on the HTTP method.
func dispatch(ctx *Context, h ResourceHandler) bool {
	defer func() {
		if err := recover(); err != nil {
			// Shit happens! TODO: Better error handling.
			msg := fmt.Sprintf("internal server error: '%v' in context: '%v'", err, ctx)
			applog.Criticalf(msg)
			http.Error(ctx.ResponseWriter, msg, http.StatusInternalServerError)
		}
	}()

	applog.Infof("dispatching %s", ctx)
	switch ctx.Request.Method {
	case "GET":
		return h.Get(ctx)
	case "PUT":
		if ph, ok := h.(PutResourceHandler); ok {
			return ph.Put(ctx)
		}
	case "POST":
		if ph, ok := h.(PostResourceHandler); ok {
			return ph.Post(ctx)
		}
	case "DELETE":
		if dh, ok := h.(DeleteResourceHandler); ok {
			return dh.Delete(ctx)
		}
	}
	applog.Errorf("method not allowed: %s", ctx)
	http.Error(ctx.ResponseWriter, "405 method not allowed", http.StatusMethodNotAllowed)
	return false
}
Пример #2
0
// handleFunc is the main function of the web server dispatching the
// requests to registered resource handler.
func handleFunc(rw http.ResponseWriter, r *http.Request) {
	ctx := newContext(rw, r)
	resources := srv.domains[ctx.Domain]
	if resources != nil {
		handlers := resources[ctx.Resource]
		if handlers != nil {
			m := monitoring.BeginMeasuring(identifier.Identifier("web", ctx.Domain, ctx.Resource, ctx.Request.Method))
			for _, h := range handlers {
				if !dispatch(ctx, h) {
					break
				}
			}
			m.EndMeasuring()
			return
		}
	}
	// No valid configuration, redirect to default (if not already).
	if ctx.Domain == srv.defaultDomain && ctx.Resource == srv.defaultResource {
		// No default handler registered.
		msg := fmt.Sprintf("domain '%v' and resource '%v' not found!", ctx.Domain, ctx.Resource)
		applog.Errorf(msg)
		http.Error(ctx.ResponseWriter, msg, http.StatusNotFound)
	} else {
		// Redirect to default handler.
		applog.Warningf("domain '%v' and resource '%v' not found, redirecting to default", ctx.Domain, ctx.Resource)
		ctx.Redirect(srv.defaultDomain, srv.defaultResource, "")
	}
}
Пример #3
0
// Test a long run to check stopping and restarting redis.
func TestLongRun(t *testing.T) {
	if testing.Short() {
		return
	}

	assert := asserts.NewTestingAsserts(t, true)
	db := Connect(Configuration{})
	wait := make(chan bool)

	for i := 0; i < 100; i++ {
		go func(ii int) {
			for j := 0; j < 20; j++ {
				key := fmt.Sprintf("long-run:%d:%d", ii, j)
				applog.Debugf("key: %s", key)
				rs := db.Command("set", key, ii+j)
				if !rs.IsOK() {
					applog.Errorf("%v", rs.Error())
				}
				time.Sleep(time.Second)
				if ii == 99 && j == 19 {
					wait <- true
				}
			}
		}(i)
	}

	<-wait
	rs := db.Command("exists", "long-run:99:19")
	exists, err := rs.ValueAsBool()
	assert.Nil(err, "No error after 'exists'.")
	assert.True(exists, "Wanted key exists.")
}
Пример #4
0
// Emit emits an event to the cell with a given id and returns its
// (possibly new created) context.
func (env *Environment) Emit(id Id, e Event) (ctx *Context, err error) {
	defer func() {
		if err != nil {
			applog.Errorf("can't emit topic %q to %q: %v", e.Topic(), id, err)
		}
	}()
	sleep := 5
	for {
		env.mutex.RLock()
		c, ok := env.cells[id]
		env.mutex.RUnlock()
		if ok {
			if e.Context() == nil {
				e.SetContext(newContext())
			}
			e.Context().incrActivity()
			if err := c.processEvent(e); err != nil {
				return nil, err
			}
			return e.Context(), nil
		}
		// Wait an increasing time befor retry, max 5 seconds.
		if sleep <= 5000 {
			time.Sleep(time.Duration(sleep) * time.Millisecond)
			sleep *= 10
		}
	}
	return nil, CellDoesNotExistError{id}
}
Пример #5
0
// Process processes an event.
func (c *CounterAgent) Process(event Event) error {
	op, ids, err := c.f(event)
	if err != nil {
		c.err = err
		return err
	}
	switch op {
	case CounterOpIncr:
		if ids != nil {
			for _, id := range ids {
				c.counters[id]++
			}
		}
	case CounterOpReset:
		c.counters = make(map[string]int64)
	case CounterOpEmit:
		if ids != nil {
			for _, id := range ids {
				Emit(c.counters, id)
			}
		}
	default:
		applog.Errorf("illegal op code %d of counter agent %q", op, c.id)
	}
	return nil
}
Пример #6
0
// process processes one event.
func (a *agentRunner) process(event Event) (err error) {
	// Error recovering.
	defer func() {
		if r := recover(); r != nil {
			applog.Errorf("agent %q has panicked: %v", a.agent.Id(), r)
			err = a.agent.Recover(r, event)
		}
	}()
	// Handle the event inside a measuring.
	measuring := monitoring.BeginMeasuring(a.measuringId)
	defer measuring.EndMeasuring()
	if err = a.agent.Process(event); err != nil {
		applog.Errorf("agent %q has failed: %v", a.agent.Id(), err)
		return a.agent.Recover(err, event)
	}
	return nil
}
Пример #7
0
// Test logging from level warning and above.
func TestWarningAndAbove(t *testing.T) {
	applog.SetLevel(applog.LevelWarning)

	applog.Debugf("Debug.")
	applog.Infof("Info.")
	applog.Warningf("Warning.")
	applog.Errorf("Error.")
	applog.Criticalf("Critical.")
}
Пример #8
0
// Test log at all levels.
func TestAllLevels(t *testing.T) {
	applog.SetLevel(applog.LevelDebug)

	applog.Debugf("Debug.")
	applog.Infof("Info.")
	applog.Warningf("Warning.")
	applog.Errorf("Error.")
	applog.Criticalf("Critical.")
}
Пример #9
0
// loop is the backend loop of the supervisor.
func (sup *Supervisor) loop() {
	// Finalizing.
	defer sup.finish()
	// Start possible existing children after a restart.
	for _, child := range sup.children {
		child.start()
	}
	// Backend loop.
	for {
		select {
		case msg := <-sup.messages:
			switch msg.code {
			case msgStart:
				if sup.children[msg.id] != nil {
					msg.response <- newErrorMsg(sup.id, &InvalidIdError{true, msg.id})
					continue
				}
				cs := &Handle{
					id:         msg.id,
					supervisor: sup,
					terminate:  make(chan bool),
				}
				msg.sup.setHandle(cs)
				sup.children[msg.id] = msg.sup
				msg.sup.start()
				msg.response <- nil
			case msgChildren:
				children := []string{}
				for id := range sup.children {
					children = append(children, id)
				}
				msg.response <- newChildrenMsg(children)
			case msgTerminate:
				if sup.children[msg.id] == nil {
					msg.response <- newErrorMsg(sup.id, &InvalidIdError{false, msg.id})
					continue
				}
				sup.children[msg.id].stop()
				delete(sup.children, msg.id)
				msg.response <- nil
			case msgError:
				if msg.err() != nil {
					if err := sup.handleChildError(msg.id); err != nil {
						applog.Errorf("supervisor %q cannot handle error of child %q: %v", sup, msg.id, err)
						sup.err = err
						return
					}
				}
			}
		case <-sup.terminate:
			return
		}
	}
}
Пример #10
0
// process encapsulates event processing including error
// recovery and measuring.
func (c *cell) process(e Event) {
	// Error recovering.
	defer func() {
		if r := recover(); r != nil {
			if e != nil {
				applog.Errorf("cell %q has error '%v' with event '%+v'", c.id, r, EventString(e))

			} else {
				applog.Errorf("cell %q has error '%v'", c.id, r)
			}
			c.behavior.Recover(r, e)
		}
	}()
	defer e.Context().decrActivity()
	// Handle the event inside a measuring.
	measuring := monitoring.BeginMeasuring(c.measuringId)
	emitter := &cellEventEmitter{c.subscribers, e.Context()}
	c.behavior.ProcessEvent(e, emitter)
	measuring.EndMeasuring()
}
Пример #11
0
// Test logging with the go logger.
func TestGoLogger(t *testing.T) {
	log.SetOutput(os.Stdout)

	applog.SetLevel(applog.LevelDebug)
	applog.SetLogger(applog.GoLogger{})

	applog.Debugf("Debug.")
	applog.Infof("Info.")
	applog.Warningf("Warning.")
	applog.Errorf("Error.")
	applog.Criticalf("Critical.")
}
Пример #12
0
func (w *World) HandleShutdown() {
	for client := range w.unregister {
		applog.Debugf("Client %s logging out", client)
		if client.player == nil {
			continue
		}
		path := "players/" + client.player.Name
		err := fileSystem.Save(path, client.player)
		if err != nil {
			applog.Errorf("Failed to save player at path: %s. Error: %s",
				path, err)
		}
	}
}
Пример #13
0
// Test logging with an own logger.
func TestOwnLogger(t *testing.T) {
	assert := asserts.NewTestingAsserts(t, true)
	ownLogger := &testLogger{[]string{}}

	applog.SetLevel(applog.LevelDebug)
	applog.SetLogger(ownLogger)

	applog.Debugf("Debug.")
	applog.Infof("Info.")
	applog.Warningf("Warning.")
	applog.Errorf("Error.")
	applog.Criticalf("Critical.")

	assert.Length(ownLogger.logs, 5, "Everything logged.")
}
Пример #14
0
func (w *World) NewPlayer(name string, token string) *Player {
	path := "players/" + name
	if res, _ := fileSystem.FileExists(path); res {
		p, err := fileSystem.LoadPlayer(path)
		if err != nil {
			applog.Errorf("Could not load player at path: %s. Error: %s",
				path, err)
			return nil
		}
		w.players[p.Name] = p
		p.Id = w.getNextId()
		return p
	} else {
		applog.Debugf("Creating a new player")
		p := MakePlayer(w.getNextId(), name, vector.Vector2{0, 0})
		w.players[p.Name] = p
		return p
	}
	return nil
}
Пример #15
0
// backend runs the endless processing loop.
func (a *agentRunner) backend() {
	defer Deregister(a.agent)
	defer a.agent.Stop()
	for {
		message := a.inbox.pop()
		switch message.kind {
		case msgStop:
			return
		case msgSubscribe:
			a.topics[message.topic] = true
		case msgUnsubscribe:
			delete(a.topics, message.topic)
		default:
			if err := a.process(message.event); err != nil {
				applog.Errorf("agent %q is not recoverable after error: %v", a.agent.Id(), err)
				return
			}
		}
	}
}
Пример #16
0
// logCommand logs a command and its execution status.
func (urp *unifiedRequestProtocol) logCommand(ec *envCommand) {
	// Format the command for the log entry.
	formatCommand := func() string {
		var log string
		if ec.multi {
			log = "multi "
		}
		log += "command " + ec.command
		for _, arg := range ec.args {
			log = fmt.Sprintf("%s %v", log, arg)
		}
		return log
	}
	// Positive commands only if wanted, errors always.
	if ec.rs.IsOK() {
		if urp.database.configuration.LogCommands {
			applog.Infof("%s OK", formatCommand())
		}
	} else {
		applog.Errorf("%s ERROR %v", formatCommand(), ec.rs.err)
	}
}
Пример #17
0
// Recover from an error.
func (b *simpeActionBehavior) Recover(err interface{}, e Event) {
	applog.Errorf("cells", "cannot perform simple action func: '%v'", err)
}
Пример #18
0
func (a *WaitAgent) Recover(r interface{}, event ebus.Event) error {
	applog.Errorf("cannot process event %v: %v", event, r)
	return nil
}