Пример #1
0
func init() {
	/* Initialise configuration instance, w/ GABS. */

	log.Debug("Initialise configuration instance")

	// This has to be a absolute path.
	configurationPath := os.Getenv("RESTAPI_CONFIG")

	// Ascertain if the configuration path is inputted.

	log.Debug("Testing if the configuration path is inputted.")
	if _, err := os.Stat(configurationPath); os.IsNotExist(err) {
		log.Crit("The configuration file does not exist!",
			log.Ctx{"File": configurationPath})
		os.Exit(1)
	}

	log.Debug("Reading configuration file into RAM.")
	configurationFile, err := ioutil.ReadFile(configurationPath)
	if err != nil {
		log.Error("The JSON config could not be loaded..",
			log.Ctx{"Error": err.Error()})
		os.Exit(1)
	}

	log.Debug("Parsing configuration file into a GABS instance.")
	config, err = gabs.ParseJSON(configurationFile)
	if err != nil {
		log.Error("The JSON config could not be parsed.",
			log.Ctx{"Error": err.Error()})
		os.Exit(1)
	}

	/* Finish initializing the configuration instance */
}
Пример #2
0
func StartWebServer() error {
	conf, err := config.GetConfig()
	if err != nil {
		return err
	}

	var hystrixTimeout time.Duration
	conf.Hystrix.Timeout = strings.TrimSpace(conf.Hystrix.Timeout)
	if conf.Hystrix.Timeout != "" {
		hystrixTimeout, err = time.ParseDuration(conf.Hystrix.Timeout)
		if err != nil || hystrixTimeout < time.Millisecond {
			hystrixTimeout = time.Second
			log15.Error("Use default time", "module", "hystrix", "timeout", hystrixTimeout)
		}
	}

	hystrix.ConfigureCommand("waitFor", hystrix.CommandConfig{
		Timeout:                int(int64(hystrixTimeout) / int64(time.Millisecond)), // converted into Millisecond.
		MaxConcurrentRequests:  conf.Hystrix.MaxConcurrentRequests,
		ErrorPercentThreshold:  conf.Hystrix.ErrorPercentThreshold,
		RequestVolumeThreshold: conf.Hystrix.RequestVolumeThreshold,
		SleepWindow:            conf.Hystrix.SleepWindow,
	})

	e := echo.New()
	e.Post("/api/v1/tweet", createTweetV1)
	e.Get("/api/v1/tweets/:id", getAllTweetForV1)
	e.Get("/api/v1/wait/:timeout", waitFor)
	e.Get("/api/v1/wait_protected/:timeout", waitForProtected)
	e.Static("/", "www/static/")
	logsrv := log15.New("pid", os.Getpid(), "addr", conf.Web.Address)
	return listenAndServer(logsrv, conf.Web.Address, handlers.LoggingHandler(os.Stdout, handlers.CompressHandler(e.Router())))
}
Пример #3
0
func (p *Player) neededComponents(components []string, num int) bool {
	for i := range components {
		if i >= num {
			return true
		}
	}
	log15.Error("not enough components given to command", "given", components, "needed", num)
	return false
}
Пример #4
0
//create table example.user(id UUID, login text, passwd text, PRIMARY KEY(id));
//create index on example.user(login);
//insert into example.user(id, login, passwd) values (now(), 'admin', 'f807c2b4caa8ca621298907e5372c975a6e07322');
func main() {
	log15.Root().SetHandler(log15.CallerStackHandler("%+v", log15.StdoutHandler))
	session, err := dao.GetSession()
	if err != nil {
		log15.Error(err.Error())
		os.Exit(1)
	}
	defer session.Close()
	www.StartWebServer()
	os.Exit(0)
}
Пример #5
0
func main() {
	rand.Seed(time.Now().UnixNano())

	h := &Handler{}

	err := bot.Run(func(b *bot.Bot) {
		b.Register(irc.PRIVMSG, h)
	})

	if err != nil {
		log15.Error(err.Error())
	}
}
Пример #6
0
func createTweetV1(c *echo.Context) error {
	tweet := new(dto.Tweet)
	err := c.Bind(tweet)
	if err != nil {
		log15.Error(err.Error())
		return c.JSON(http.StatusBadRequest, nil)
	}
	tweet.GenerateId()
	err = tweet.Insert()
	if err != nil {
		return c.JSON(http.StatusInternalServerError, err)
	}
	return c.JSON(http.StatusOK, tweet)
}
Пример #7
0
func waitForProtected(c *echo.Context) error {
	var response *http.Response
	hystrix.Do("waitFor", func() error {
		var err error
		response, err = http.Get("http://127.0.0.1:8080/api/v1/wait/" + c.Param("timeout"))
		//response, err = http.Get(fmt.Sprintf("%s://%s%s", c.Request().URL.Scheme, c.Request().URL.Host, c.Request().URL.Path))
		if err != nil {
			return err
		}
		r := response.Body
		w := c.Response().Writer()
		io.Copy(w, r)
		return nil
	}, func(err error) error {
		log15.Error(err.Error())
		c.JSON(http.StatusInternalServerError, err.Error())
		return nil
	})

	return nil
}
Пример #8
0
func Server(srv *context.T) {
	log := srv.Log.New("cmp", "dht")
	ch := srv.Router.Sub("/dht/join")
	tch := srv.Router.Sub("/transaction/mem")
	och := srv.Router.Sub("/git/object")

	keyAuth, err := newKeyAuth()
	if err != nil {
		log.Crit("can't generate node key", "err", err)
		os.Exit(1)
	}

	id, err := wendy.NodeIDFromBytes(util.SHA256(keyAuth.Marshal()))
	log = log.New("own_node", id)

	if err != nil {
		log15.Crit("error preparing node id", "err", err)
		os.Exit(0)
	}

	hostname := strings.Split(srv.Config.Network.Hostname, ":")[0]
	node := wendy.NewNode(id, "127.0.0.1", hostname, "localhost", srv.Config.Network.Port)

	cluster := wendy.NewCluster(node, keyAuth)
	cluster.SetLogLevel(wendy.LogLevelError)
	cluster.RegisterCallback(&GitchainApp{cluster: cluster, log: log.New(), srv: srv})
	go cluster.Listen()
	defer cluster.Stop()

	log.Info("node started")

	for i := range srv.Config.Network.Join {
		log.Info("scheduling a connection", "addr", srv.Config.Network.Join[i])
		srv.Router.Pub(srv.Config.Network.Join[i], "/dht/join")
	}

loop:
	select {
	case addri := <-ch:
		if addr, ok := addri.(string); ok {
			log.Debug("received a request to join the cluster", "addr", addr)

			addr := strings.Split(addr, ":")
			port := 31000
			if len(addr) == 2 {
				port, err = strconv.Atoi(addr[1])
				if err != nil {
					log.Error("invalid port number", "addr", addr, "port", addr[1], "err", err)
					goto loop
				}
			}
			err = cluster.Join(addr[0], port)

			if err != nil {
				log.Error("can't join cluster", "addr", addr, "err", err)
				goto loop
			}
		}
	case txei := <-tch:
		if txe, ok := txei.(*transaction.Envelope); ok {
			log.Debug("received transaction", "txn", txe)
			if err = broadcast(cluster, txe, MSG_TRANSACTION); err != nil {
				log.Error("error broadcasting a transaction message", "txn", txe, "err", err)
			} else {
				log.Debug("broadcasted transaction", "txn", txe)
			}
		}
	case obji := <-och:
		if obj, ok := obji.(git.Object); ok {
			id, err := wendy.NodeIDFromBytes(util.SHA256(obj.Hash()))
			if err != nil {
				log15.Error("error preparing msg id for a git object", "obj", obj, "err", err)
			} else {
				msg := cluster.NewMessage(MSG_REGULAR|MSG_OBJECT, id, git.ObjectToBytes(obj))
				if err = cluster.Send(msg); err != nil {
					log.Error("error sending git object", "obj", obj, "err", err)
				}
			}
		}
	}
	goto loop
}
Пример #9
0
// Listen for gameclient/websocket requests on http(s)
func listenAndServe(bindAddress, listenPort string) {
	err := http.ListenAndServe(bindAddress+":"+listenPort, nil)
	if err != nil {
		log15.Error("serving http(s) requests", "error", err)
	}
}
Пример #10
0
func main() {
	// Command line variables
	var debug bool
	var daemon bool
	var bindAddress string
	var listenPort string
	var maxPlayers int

	flag.BoolVar(&debug, "debug", false, "run server in debug mode")
	flag.BoolVar(&daemon, "daemon", false, "run server in daemon mode (no console prompt)")
	flag.StringVar(&bindAddress, "bindAddress", "0.0.0.0", "address to bind to")
	flag.StringVar(&listenPort, "listenPort", "8080", "port to serve client on")
	flag.IntVar(&maxPlayers, "maxPlayers", 4, "max number of players on server simultaneously")
	flag.Parse()

	// Find executable location
	osextDir, err := osext.ExecutableFolder()
	if err != nil {
		log15.Error("Finding executable location", "error", err)
	}

	// Configure GameClient distributor
	http.Handle("/", http.FileServer(http.Dir(osextDir+"/client")))

	// Configure webtron server
	webtronServer := server.New(debug, maxPlayers)
	defer webtronServer.Shutdown()

	// Configure Glue (websocket wrapper) bridge
	glueServer := glue.NewServer(glue.Options{
		HTTPSocketType:    glue.HTTPSocketTypeNone,
		HTTPListenAddress: ":" + listenPort,
		HTTPHandleURL:     "/",
	})
	defer glueServer.Release()
	glueServer.OnNewSocket(webtronServer.ConnectPlayer)
	http.HandleFunc("/ws", glueServer.ServeHTTP)

	if daemon {
		listenAndServe(bindAddress, listenPort)

	} else {
		// Listen for gameclient/websocket requests on http(s)
		go listenAndServe(bindAddress, listenPort)

		// Command line input
		reader := bufio.NewReader(os.Stdin)
	input_loop:
		for {
			fmt.Print("console@webtron:~$ ")
			input, _ := reader.ReadString('\n')
			input = strings.Trim(input, "\n")
			switch input {
			case "":

			case "help":
				fmt.Println(
					"Available commands:\n" +
						"help, exit")

			case "exit", "quit":
				break input_loop

			default:
				fmt.Println("Unknown command: " + input)
			}
		}
	}
}
Пример #11
0
// ReadLoop receives data from the player client
func (p *Player) ReadLoop() {
	for {
		// Wait for available data
		data, err := p.Socket.Read()
		if err != nil {
			// return and release this goroutine if the socket was closed
			if err == glue.ErrSocketClosed {
				return
			}

			log15.Error("read error", "error", err)
			continue
		}

		components := strings.Split(data, ":")
		switch components[0] {
		case msg.CRequestState:
			p.Socket.Write(msg.SNewState + ":" + p.Server.Sim.LatestState)

		case msg.CSpawn:
			if !p.neededComponents(components, 2) {
				break
			}

			if p.Bike != nil && p.Bike.GetState() != "dead" {
				log15.Debug("Player attempted to spawn with existing bike", "bike", p.Bike)
				break
			}

			p.Bike = p.Server.Sim.SpawnGridBike(components[1], components[2])
			p.Socket.Write(msg.SDisplayMessage + ":")

		case msg.CTurn:
			if !p.neededComponents(components, 1) {
				break
			}
			if p.Bike == nil || p.Bike.GetState() != "move" {
				log15.Debug("Player attemped to turn without existing bike", "bike", p.Bike)
				break
			}
			dir := components[1]
			switch dir {
			case "RIGHT":
				p.Bike.SetTurn(0)
			case "DOWN":
				p.Bike.SetTurn(math.Pi / 2)
			case "LEFT":
				p.Bike.SetTurn(math.Pi)
			case "UP":
				p.Bike.SetTurn(3 * math.Pi / 2)
			default:
				log15.Error("invalid TURN argument", "arg", dir)
			}

		// case msg.CBroadcast:
		// 	// Echo the received data to all other clients
		// 	for i := range gs.ConnectedPlayers {
		// 		if gs.ConnectedPlayers[i].Socket.ID() == p.Socket.ID() {
		// 			continue
		// 		}
		// 		gs.ConnectedPlayers[i].Socket.Write(strings.Join(components[1:], ":"))
		// 	}

		default:
			log15.Info("Returning unknown request to the client", "request", data)
			p.Socket.Write(data)
		}
	}
}
Пример #12
0
func (c *client) GetAllInto(destination interface {
	Add(interface{}) error
	Count() int
	MaxCreatedAt() time.Time
	MaxUpdatedAt() time.Time
}) (err error) {

	var response ItembaseResponse
	DocumentsReceived := 0

	err = c.api.Call("GET", c.url, c.auth, nil, c.params, &response)
	if err != nil {
		return
	}

	for _, document := range response.Documents {
		if destination.Add != nil {
			err = destination.Add(document)
			if err != nil {
				log.Info("Error when adding document", "error", err)
			}
		}
	}

	log.Debug("Documents", "found", response.NumDocumentsFound)
	log.Debug("Documents", "returned", response.NumDocumentsReturned)

	if response.NumDocumentsFound == response.NumDocumentsReturned {
		log.Debug("same amount of documents that were found as returned")
		return
	} else {
		DocumentsReceived = response.NumDocumentsReturned
		TotalDocuments := response.NumDocumentsFound
		log.Debug("expecting to receive", "NumDocumentsFound", response.NumDocumentsFound)

		for DocumentsReceived < TotalDocuments {

			log.Debug("expecting", "TotalDocuments", TotalDocuments)

			if c.max > 0 {
				log.Debug("Max", "max", c.max)
				if DocumentsReceived >= c.max {
					log.Debug("Max is reached", "DocumentsReceived", DocumentsReceived)
					return
				}
			}

			if _, ok := c.params["created_at_from"]; ok {
				if c.params["created_at_from"] == destination.MaxCreatedAt().Format(time.RFC3339) {
					log.Error("created_at_from equals to previous created_at_from - We got a loop?", "created_at_from", c.params["created_at_from"])
					return
				}
			}

			c = c.clientWithNewParam("start_at_document", DocumentsReceived)
			err = c.api.Call("GET", c.url, c.auth, nil, c.params, &response)

			if err != nil {
				log.Error("Error when retrieving paginated results", "error", err)
			}

			log.Debug("Documents", "found", response.NumDocumentsFound)
			log.Debug("Documents", "returned", response.NumDocumentsReturned)

			if len(response.Documents) == 0 {
				log.Debug("no documents in response", "response.Documents", len(response.Documents))
				return
			}

			for _, document := range response.Documents {
				if destination.Add != nil {
					destination.Add(document)
					if err != nil {
						log.Info("Error when adding document", "error", err)
					}
				}
			}

			if DocumentsReceived == destination.Count() {
				log.Error("Same amount of documents in destination interface as before. Can happen due to created_at collission during pagination.")
				return
			}

			log.Debug("Documents", "saved", destination.Count())
			DocumentsReceived = destination.Count()

			if len(response.Documents) == 1 {
				log.Debug("only 1 document in response", "response.Documents", len(response.Documents))
				return
			}

		}
	}

	return
}