Пример #1
0
func (c *Client) write(payload GameWriter) {
	id := packetIds[reflect.TypeOf(payload)]
	packet := append([]byte{id}, payload.MarshalGame()...)
	applog.Debugf("Id: %d", id)
	applog.Debugf("Writing packet to client: %s", packet)
	c.outgoing <- packet
}
Пример #2
0
func (fs *FileSystem) Load(path string, obj GameReader) error {
	fullPath := filepath.Join(fs.rootPath, path)
	file, err := os.Open(fullPath)
	applog.Debugf("Loading from path: %s", fullPath)
	if err != nil {
		return err
	}
	defer file.Close()
	objSize, err := file.Stat()
	if err != nil {
		return err
	}
	bytes := make([]byte, objSize.Size())
	read, err := file.Read(bytes)
	if read != len(bytes) {
		return errors.New("Read incorrect number of bytes")
	}
	if err != nil && err != io.EOF {
		return err
	}
	err = obj.UnmarshalGame(bytes)
	if err != nil {
		return err
	}
	return nil
}
Пример #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
func MakeFileSystem(path string) *FileSystem {
	cwd, err := os.Getwd()
	if err != nil {
		panic(err)
	}
	fs := &FileSystem{
		rootPath: filepath.Join(cwd, path),
	}
	if res, _ := fs.FileExists("players"); !res {
		err := fs.Mkdir("players")
		// Panic on these errors since there's not much point in recoving
		// from an improperly setup filesystem
		if err != nil {
			panic(err)
		}
	}
	if res, _ := fs.FileExists("world"); !res {
		err := fs.Mkdir("world")
		// Panic on these errors since there's not much point in recoving
		// from an improperly setup filesystem
		if err != nil {
			panic(err)
		}
	}
	applog.Debugf("Finished setting up directories")
	return fs
}
Пример #5
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.")
}
Пример #6
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.")
}
Пример #7
0
func (w *World) HandleConnections() {
	for conn := range w.register {
		applog.Debugf("Received request to register new player")
		client := MakeClient()
		go conn.writePump(client)
		go conn.readPump(client)
		go client.read()
	}
}
Пример #8
0
func (th *TestHandler) Get(ctx *Context) bool {
	data := map[string]string{
		"domain":     ctx.Domain,
		"resource":   ctx.Resource,
		"resourceId": ctx.ResourceId,
	}
	switch {
	case ctx.AcceptsXML():
		applog.Debugf("get XML")
		ctx.RenderTemplate("test:context:xml", data)
	case ctx.AcceptsJSON():
		applog.Debugf("get JSON")
		ctx.MarshalJSON(data, true)
	default:
		applog.Debugf("get HTML")
		ctx.RenderTemplate("test:context:html", data)
	}
	return true
}
Пример #9
0
func (c *Client) read() {
	for packet := range c.incoming {
		applog.Debugf("Received packet from client: %s", packet)
		packetStruct, err := parsePacket(packet)
		if err != nil {
			applog.Criticalf("Error Unmarshalling message. %s", err)
			continue
		}
		(*packetStruct).Handle(world, c.player, c)
	}
}
Пример #10
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.")
}
Пример #11
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)
		}
	}
}
Пример #12
0
func (fs *FileSystem) Save(path string, obj GameWriter) error {
	fullPath := filepath.Join(fs.rootPath, path)
	file, err := os.Create(fullPath)
	applog.Debugf("Saving to path: %s", fullPath)
	if err != nil {
		return err
	}
	defer file.Close()
	bytes := obj.MarshalGame()
	_, err = file.Write(bytes)
	if err != nil {
		return err
	}
	return nil
}
Пример #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
// readPump pumps messages from the websocket connection to the hub.
func (c *connection) readPump(client *Client) {
	applog.Debugf("Started readPump")
	defer func() {
		world.unregister <- client
		c.ws.Close()
	}()
	c.ws.SetReadLimit(maxMessageSize)
	c.ws.SetReadDeadline(time.Now().Add(readWait))
	c.readTemplate(func(r io.Reader) (bool, error) {
		message, err := ioutil.ReadAll(r)
		if err == nil {
			client.incoming <- message
		}
		return false, err
	})
}
Пример #15
0
func (c *connection) readTemplate(handler func(io.Reader) (bool, error)) {
	for {
		op, r, err := c.ws.NextReader()
		if err != nil {
			break
		}
		switch op {
		case websocket.OpPong:
			c.ws.SetReadDeadline(time.Now().Add(readWait))
		case websocket.OpText:
			quit, err := handler(r)
			applog.Debugf("Leaving read loop?: %s || %s", quit, err)
			if quit || err != nil {
				return
			}
		}
	}
}
Пример #16
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
}
Пример #17
0
// writePump pumps messages from the hub to the websocket connection.
func (c *connection) writePump(client *Client) {
	applog.Debugf("Started writePump")
	ticker := time.NewTicker(pingPeriod)
	defer func() {
		ticker.Stop()
		c.ws.Close()
	}()
	for {
		select {
		case message, ok := <-client.outgoing:
			if !ok {
				c.write(websocket.OpClose, []byte{})
				return
			}
			if err := c.write(websocket.OpText, message); err != nil {
				return
			}
		case <-ticker.C:
			if err := c.write(websocket.OpPing, []byte{}); err != nil {
				return
			}
		}
	}
}
Пример #18
0
// Test debugging.
func TestDebug(t *testing.T) {
	applog.Debugf("Hello, I'm debugging %v!", "here")
	applog.SetLevel(applog.LevelError)
	applog.Debugf("Should not be shown!")
}
Пример #19
0
// TestNodeRouter tests the event router for one node.
func TestNodeRouter(t *testing.T) {
	assert := asserts.NewTestingAsserts(t, true)

	assert.Nil(InitSingle(), "init the single backend")
	defer Stop()

	agent1 := NewTestAgent(1)
	agent2 := NewTestAgent(2)
	agent3 := NewTestAgent(3)
	agent4 := NewTestAgent(4)
	router := newNodeRouter()
	defer router.stop()

	applog.Debugf("registering agents")
	assert.Nil(router.register(agent1), "registered agent 1")
	assert.Nil(router.register(agent2), "registered agent 2")
	assert.Nil(router.register(agent3), "registered agent 3")
	assert.Nil(router.register(agent4), "registered agent 4")

	applog.Debugf("lookup agents")
	la1, err := router.lookup(agent1.Id())
	assert.Nil(err, "lookup for agent 1")
	assert.Equal(la1, agent1, "lookup for agent 1")

	applog.Debugf("subscribing agents to topics")
	assert.Nil(router.subscribe(agent1, "foo"), "subscribing agent 1")
	assert.Nil(router.subscribe(agent1, "bar"), "subscribing agent 1")
	assert.Nil(router.subscribe(agent2, "foo"), "subscribing agent 2")
	assert.Nil(router.subscribe(agent2, "baz"), "subscribing agent 2")
	assert.Nil(router.subscribe(agent3, "baz"), "subscribing agent 3")
	assert.Nil(router.subscribe(agent3, "yadda"), "subscribing agent 3")
	assert.Nil(router.subscribe(agent3, "zong"), "subscribing agent 3")
	assert.Nil(router.subscribe(agent4, "foo"), "subscribing agent 4")
	assert.Nil(router.subscribe(agent4, "bar"), "subscribing agent 4")

	applog.Debugf("unsubscribing agents from topics")
	assert.Nil(router.unsubscribe(agent3, "zong"), "usubscribing agent 3")

	applog.Debugf("unsubscribing agents from not subscribed topics")
	assert.Nil(router.unsubscribe(agent3, "argle"), "usubscribing agent 3 from not subscribed topic")

	applog.Debugf("deregistering agents")
	assert.Nil(router.deregister(agent4), "deregistered agent 4")
	time.Sleep(100 * time.Millisecond)
	assert.True(agent4.Stopped, "agent 4 is stopped")

	applog.Debugf("pushing events with subscribers")
	routerPush(assert, router, EmptyPayload, "one")
	time.Sleep(100 * time.Millisecond)
	assert.Equal(agent1.Counters["foo"], 1, "counter foo for agent 1")
	assert.Equal(agent2.Counters["foo"], 1, "counter foo for agent 2")
	assert.Equal(agent3.Counters["foo"], 0, "counter foo for agent 3")
	assert.Equal(agent4.Counters["foo"], 0, "counter foo for agent 4")

	applog.Debugf("pushing events without subscribers")
	routerPush(assert, router, EmptyPayload, "iirks")
	time.Sleep(100 * time.Millisecond)
	assert.Equal(agent1.Counters["iirks"], 0, "counter iirks for agent 1")
	assert.Equal(agent2.Counters["iirks"], 0, "counter iirks for agent 2")
	assert.Equal(agent3.Counters["iirks"], 0, "counter iirks for agent 3")
	assert.Equal(agent4.Counters["iirks"], 0, "counter iirks for agent 4")

	applog.Debugf("pushing events to many subscribers")
	agents := []*TestAgent{}
	for i := 5; i < 10000; i++ {
		agent := NewTestAgent(i)
		agents = append(agents, agent)
		router.register(agent)
		router.subscribe(agent, "flirp")
	}
	time.Sleep(100 * time.Millisecond)
	routerPush(assert, router, EmptyPayload, "flirp")
	routerPush(assert, router, EmptyPayload, "flirp")
	routerPush(assert, router, EmptyPayload, "flirp")
	time.Sleep(100 * time.Millisecond)
	for i := 5; i < 10000; i++ {
		agent := agents[i-5]
		assert.Equal(agent.Counters["flirp"], 3, "counter flirp for agent")
	}
}
Пример #20
0
// TestSimpleSingle the single node backend.
func TestSimpleSingle(t *testing.T) {
	assert := asserts.NewTestingAsserts(t, true)
	provider := config.NewMapConfigurationProvider()
	config := config.New(provider)

	config.Set("backend", "single")

	err := ebus.Init(config)
	assert.Nil(err, "single node backend started")
	defer ebus.Stop()

	applog.Debugf("registering agents")
	agent1 := ebus.NewTestAgent(1)
	_, err = ebus.Register(agent1)
	assert.Nil(err, "registered agent 1")
	agent2 := ebus.NewTestAgent(2)
	_, err = ebus.Register(agent2)
	assert.Nil(err, "registered agent 2")
	agent3 := ebus.NewTestAgent(3)
	_, err = ebus.Register(agent3)
	assert.Nil(err, "registered agent 3")
	agent4 := ebus.NewTestAgent(4)
	_, err = ebus.Register(agent4)
	assert.Nil(err, "registered agent 4")

	applog.Debugf("subscribing agents to topics")
	assert.Nil(ebus.Subscribe(agent1, "foo", "bar"), "subscribing agent 1")
	assert.Nil(ebus.Subscribe(agent2, "foo", "baz"), "subscribing agent 2")
	assert.Nil(ebus.Subscribe(agent3, "baz", "yadda", "zong"), "subscribing agent 3")
	assert.Nil(ebus.Subscribe(agent4, "foo", "bar"), "subscribing agent 4")

	applog.Debugf("unsubscribing agents from topics")
	assert.Nil(ebus.Unsubscribe(agent3, "zong"), "usubscribing agent 3")

	applog.Debugf("unsubscribing agents from not subscribed topics")
	assert.Nil(ebus.Unsubscribe(agent3, "argle"), "usubscribing agent 3 from not subscribed topic")

	applog.Debugf("deregistering agents")
	assert.Nil(ebus.Deregister(agent4), "deregistered agent 4")
	time.Sleep(100 * time.Millisecond)
	assert.True(agent4.Stopped, "agent 4 is stopped")

	applog.Debugf("emitting events with subscribers")
	ebus.Emit(ebus.EmptyPayload, "foo")
	time.Sleep(100 * time.Millisecond)
	assert.Equal(agent1.Counters["foo"], 1, "counter foo for agent 1")
	assert.Equal(agent2.Counters["foo"], 1, "counter foo for agent 2")
	assert.Equal(agent3.Counters["foo"], 0, "counter foo for agent 3")
	assert.Equal(agent4.Counters["foo"], 0, "counter foo for agent 4")

	applog.Debugf("emitting events without subscribers")
	ebus.Emit(ebus.EmptyPayload, "iirks")
	time.Sleep(100 * time.Millisecond)
	assert.Equal(agent1.Counters["iirks"], 0, "counter iirks for agent 1")
	assert.Equal(agent2.Counters["iirks"], 0, "counter iirks for agent 2")
	assert.Equal(agent3.Counters["iirks"], 0, "counter iirks for agent 3")
	assert.Equal(agent4.Counters["iirks"], 0, "counter iirks for agent 4")

	applog.Debugf("pushing events to many subscribers")
	agents := []*ebus.TestAgent{}
	for i := 5; i < 10000; i++ {
		agent := ebus.NewTestAgent(i)
		agents = append(agents, agent)
		ebus.Register(agent)
		ebus.Subscribe(agent, "flirp")
	}
	time.Sleep(100 * time.Millisecond)
	ebus.Emit(ebus.EmptyPayload, "flirp")
	ebus.Emit(ebus.EmptyPayload, "flirp")
	ebus.Emit(ebus.EmptyPayload, "flirp")
	time.Sleep(100 * time.Millisecond)
	for i := 5; i < 10000; i++ {
		agent := agents[i-5]
		assert.Equal(agent.Counters["flirp"], 3, "counter flirp for agent")
	}
}