Beispiel #1
0
// SubscribeHandler : Subsribes to redis to fetch messages
func SubscribeHandler(subChannel chan string) {
	// create a subscribe connection to RedisDB
	subscribeConn, err := redisurl.ConnectToURL("redis://localhost:6379")
	if err != nil {

		fmt.Println(err)
		os.Exit(1)

	}

	// Before function exits close the connection
	defer subscribeConn.Close()

	pubsubConn := redis.PubSubConn{Conn: subscribeConn}
	pubsubConn.Subscribe("messages") // Subscribed to messages list in redis DB

	for {

		switch val := pubsubConn.Receive().(type) {

		case redis.Message:
			// If the data being received is a text message then push it to the channel
			subChannel <- string(val.Data)

		case redis.Subscription:
			//Handle Subscription here

		case error:
			return
		}
	}

}
Beispiel #2
0
// SubscribeAndServe will subscribe to all provided channels
// on srv.Addr and then calls Serve to handle events on subscribed
// Redis channels. If srv.Addr is blank then "localhost" is used
func (srv *Server) SubscribeAndServe(addr string, subscriptions []string, wr io.Writer) error {
	if addr == "" {
		addr = "redis://localhost:6379"
	}
	srv.Addr = addr

	srv.SubHandler = SubscriptionHandler{
		index: make(map[string]subscription),
		addr:  addr,
	}

	conn, err := redisurl.ConnectToURL(addr)
	if err != nil {
		panic(err)
	}

	// Register subscriptions and start listening
	msgStream := make(chan string)
	srv.SubHandler.CreateSubs(subscriptions, &msgStream)
	srv.SubHandler.Listen()

	// Spin up DBComponent and set to listen on same msgStream
	db := new(RedisComponent)
	db.Register(conn, &msgStream)
	db.Process()

	// Begin serving messages output to dataStream
	return srv.Serve(wr, db.dataStream)
}
Beispiel #3
0
// Slave : Contains go code for master
func Slave(ipAddress string, slaveExit *bool) {

	conn, err := redisurl.ConnectToURL(redisURL)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// Close only when function exits
	defer conn.Close()

	// Add the slave to redis list
	val, err := conn.Do("SADD", "online_slaves", ipAddress)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	if val == nil {
		fmt.Println("Insert error")
		os.Exit(1)
	}

	dirStruct := GetDirStructure()
	masterMsg := MasterMessage{IpAddress: ipAddress, FilePaths: dirStruct}

	jsonObj, err := json.Marshal(masterMsg)
	conn.Do("PUBLISH", masterMessageQueue, jsonObj)

}
Beispiel #4
0
func init() {
	max := maxConnection()
	url := address()
	redisPool = redis.NewPool(func() (redis.Conn, error) {
		return redisurl.ConnectToURL(url)
	}, max)
}
Beispiel #5
0
func newRedisConnection(addr string) redis.Conn {
	conn, err := redisurl.ConnectToURL(addr)
	if err != nil {
		panic(err)
	}
	return conn
}
Beispiel #6
0
//CreateFileMapping : Creates a mapping of file addresses
func CreateFileMapping(masterMsg MasterMessage) {
	conn, err := redisurl.ConnectToURL(redisURL)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	var revIndex util.ReverseIndex

	for _, filepath := range masterMsg.FilePaths {
		index := strings.Index(filepath, "shared")
		filestart := index + 6
		relPath := filepath[filestart:]
		revIndex.AbsolutePath = filepath
		revIndex.Destination = masterMsg.IpAddress

		jsonObj, err := json.Marshal(revIndex)
		if err != nil {
			fmt.Println("Unable to marshal json")
		}

		// Insert the reverse Index in Redis
		conn.Do("SET", relPath, string(jsonObj))
	}

	conn.Close()
}
Beispiel #7
0
// ReceiveMessages : Receive messages fron master_messages redis channel
func ReceiveMessages(newSlaveChannel chan string, ipAddress string) {

	conn, err := redisurl.ConnectToURL(redisURL)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// Close only when function exits
	defer conn.Close()

	// Creating a pubsubConn for master messages
	pubsubConn := redis.PubSubConn{Conn: conn}
	pubsubConn.Subscribe(masterMessageQueue)

	for {
		switch val := pubsubConn.Receive().(type) {

		case redis.Message:
			// If the data being received is a text message then push it to the channel
			newSlaveChannel <- string(val.Data)

		case redis.Subscription:
			//Handle Subscription here

		case error:
			return
		}

	}
}
Beispiel #8
0
func initDb() (c redis.Conn) {
	rp, err := redisurl.ConnectToURL(*redisAddress)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	//defer rp.Close()
	return rp
}
Beispiel #9
0
func newRedisPool(uri string, maxIdle int, maxOpen int, idleTimout time.Duration) *redis.Pool {
	generator := func() (redis.Conn, error) {
		return redisurl.ConnectToURL(uri)
	}

	p := redis.NewPool(generator, maxIdle)
	p.MaxActive = maxOpen
	p.IdleTimeout = idleTimout

	return p
}
Beispiel #10
0
// GetRedisConn : Get redis conn for go-lbapp
func GetRedisConn() (redis.Conn, error) {

	// Connecting to the local redis DB instance
	conn, err := redisurl.ConnectToURL(redisURL)
	if err != nil {
		log.Println("Could not connect to redis DB")
		log.Println(err)

	}

	return conn, err
}
Beispiel #11
0
func getRedisConn() redis.Conn {
	if url := os.Getenv("REDIS_URL"); url != "" {
		conn, err := redisurl.ConnectToURL(url)
		checkErr(err)
		return conn
	}
	hostname, err := os.Hostname()
	checkErr(err)
	conn, err := redis.Dial("tcp", hostname+":6379")
	checkErr(err)
	return conn
}
Beispiel #12
0
func (sh *SubscriptionHandler) CreateSub(eventStream string, msgStream *chan string) {
	conn, err := redisurl.ConnectToURL(sh.addr)
	if err != nil {
		panic(err)
	}

	psc := redis.PubSubConn{Conn: conn}
	err = psc.Subscribe(eventStream)
	if err != nil {
		panic(err)
	}

	sh.index[eventStream] = subscription{&psc, eventStream, msgStream}
}
Beispiel #13
0
// PublishAndCommandHandler : function to publish and handle commands for the code
func PublishAndCommandHandler(username string, chatExit *bool) {

	publishConn, err := redisurl.ConnectToURL("redis://localhost:6379")
	if err != nil {

		fmt.Println(err)
		os.Exit(1)

	}

	// Before function exits close the connection
	defer publishConn.Close()

	// Create a command line reader
	bufferedIO := bufio.NewReader(os.Stdin)
	for {
		line, _, err := bufferedIO.ReadLine()
		if err != nil {
			fmt.Print("error in input function")
		}

		// If user enters an exit request quit it
		if string(line) == "/exit" {

			// If the command is to exit. Quit function by return
			*chatExit = true
			return

		} else if string(line) == "/online" {

			// Get all the names in string format from users
			names, _ := redis.Strings(publishConn.Do("SMEMBERS", "users"))

			// Range first param is index and second is value
			for _, name := range names {

				// Print list of Online users
				fmt.Printf("Online: %s \n", name)
			}

		} else if strings.Index(string(line), "/") == 0 {
			// If the string begins with / and no other command its mostly a typo
			// Ignore this command input
		} else {

			publishConn.Do("PUBLISH", "messages", username+":- \t"+string(line))
		}

	}
}
Beispiel #14
0
func getRedisConn() (redis.Conn, error) {
	connectionString := os.Getenv("REDISTOGO_URL")
	var conn redis.Conn
	var err error
	if connectionString != "" {
		conn, err = redisurl.ConnectToURL(connectionString)
	} else {
		conn, err = redis.Dial("tcp", ":6379")
	}
	if err != nil {
		fmt.Println("Failed to connect to redis")
	}
	fmt.Println("Connected to redis")
	return conn, err
}
Beispiel #15
0
func redisInit() error {
	url := os.Getenv(redisURLEnvVar)
	var err error
	if url != "" {
		Conn, err = redisurl.ConnectToURL(url)
	} else {
		port, err := strconv.Atoi(os.Getenv(redisPortEnvVar))
		if err != nil {
			port = redisDefaultPort
		}

		Conn, err = redis.Dial("tcp", ":"+strconv.Itoa(port))
	}
	return err
}
// GetAll : All file paths printer
func GetAll(w http.ResponseWriter, r *http.Request) {

	currDir := "/"

	var conn, _ = redisurl.ConnectToURL(redisURL)

	files, _ := redis.Strings(conn.Do("KEYS", "*"))
	baseDirEndIndex := len(currDir)
	dirArr := []string{}
	fileArr := []string{}

	for _, file := range files {
		if strings.Index(file, currDir) == 0 {
			relpath := file[baseDirEndIndex:]
			fileordir := strings.Index(relpath, "/")

			if fileordir == -1 {

				fileArr = append(fileArr, relpath)

			} else {

				path := relpath[:fileordir+1]

				if !util.SliceContains(dirArr, path) {
					dirArr = append(dirArr, path)
				}

			}

		}
	}

	// Print the dirs found
	for _, dirname := range dirArr {

		fmt.Fprintf(w, "dir \t--\t %s\n", dirname)
	}

	//Print the files found
	for _, filename := range fileArr {

		fmt.Fprintf(w, "file \t--\t %s\n", filename)
	}

	conn.Close()

}
Beispiel #17
0
func Init() {

	addr := "redis://localhost:6379"

	if os.Getenv("REDISCLOUD_URL") != "" {
		addr = os.Getenv("REDISCLOUD_URL")
	}

	c, err := redisurl.ConnectToURL(addr)

	if err != nil {
		log.Fatal(err)
	}

	instance = c
}
Beispiel #18
0
func handleMasterConnection(conn net.Conn) {

	message, _ := bufio.NewReader(conn).ReadString('\n')

	msg := message[:len(message)-1]
	// output message received
	fmt.Print("Command Received:", string(msg))

	// Extract filename and read its content
	relPath := string(msg)

	redisconn, err := redisurl.ConnectToURL(redisURL)
	if err != nil {

		fmt.Println(err)
	}

	defer redisconn.Close()

	// JSON Obj Values are received as bytes and translated to structs
	val, _ := redis.Bytes(redisconn.Do("GET", relPath))

	var revIndex util.ReverseIndex
	unmarshallErr := json.Unmarshal(val, &revIndex)

	if unmarshallErr != nil {
		fmt.Println(unmarshallErr)
	}

	fmt.Printf("\n %+v \n", revIndex)

	bytesJSON, _ := json.Marshal(revIndex)
	strJSON := string(bytesJSON) + "\n"
	// Send contents to client
	conn.Write([]byte(strJSON))
	conn.Close()

}
func main() {
	redisPool = redis.Pool{
		MaxIdle:   50,
		MaxActive: 500, // max number of connections
		Dial: func() (redis.Conn, error) {
			c, err := redisurl.ConnectToURL(os.Getenv("REDISCLOUD_URL"))
			if err != nil {
				panic(err.Error())
			}
			return c, err
		},
	}

	defer redisPool.Close()

	http.HandleFunc("/log", checkAuth(os.Getenv("AUTH_SECRET"), processLogs))
	http.HandleFunc("/stats/hosts", checkAuth(os.Getenv("AUTH_SECRET"), statsForAllHosts))
	http.HandleFunc("/stats/host/", checkAuth(os.Getenv("AUTH_SECRET"), bucketDataForHost))
	fmt.Println("listening...")
	err := http.ListenAndServe(":"+os.Getenv("PORT"), nil)
	if err != nil {
		panic(err)
	}
}
Beispiel #20
0
func openRedisConn(url string) (redis.Conn, error) {
	if len(url) == 0 {
		return redisurl.Connect()
	}
	return redisurl.ConnectToURL(url)
}
Beispiel #21
0
func main() {
	kingpin.Version(version)
	kingpin.Parse()
	logging.LogStd(fmt.Sprintf("Starting firehose-to-syslog %s ", version), true)

	logging.SetupLogging(*syslogServer, *debug)

	c := cfclient.Config{
		ApiAddress:        *apiEndpoint,
		Username:          *user,
		Password:          *password,
		SkipSslValidation: *skipSSLValidation,
	}
	cfClient := cfclient.NewClient(&c)

	if len(*dopplerEndpoint) > 0 {
		cfClient.Endpoint.DopplerEndpoint = *dopplerEndpoint
	}
	logging.LogStd(fmt.Sprintf("Using %s as doppler endpoint", cfClient.Endpoint.DopplerEndpoint), true)

	logging.LogStd("Setting up event routing!", true)
	err := events.SetupEventRouting(*wantedEvents)
	if err != nil {
		log.Fatal("Error setting up event routing: ", err)
		os.Exit(1)

	}

	//Use bolt for in-memory  - file caching
	db, err := bolt.Open(*boltDatabasePath, 0600, &bolt.Options{Timeout: 1 * time.Second})
	if err != nil {
		log.Fatal("Error opening bolt db: ", err)
		os.Exit(1)

	}
	defer db.Close()

	if *modeProf != "" {
		switch *modeProf {
		case "cpu":
			defer profile.Start(profile.CPUProfile, profile.ProfilePath(*pathProf)).Stop()
		case "mem":
			defer profile.Start(profile.MemProfile, profile.ProfilePath(*pathProf)).Stop()
		case "block":
			defer profile.Start(profile.BlockProfile, profile.ProfilePath(*pathProf)).Stop()
		default:
			// do nothing
		}
	}

	caching.SetCfClient(cfClient)
	caching.SetAppDb(db)
	caching.CreateBucket()

	//Let's Update the database the first time
	logging.LogStd("Start filling app/space/org cache.", true)
	apps := caching.GetAllApp()
	logging.LogStd(fmt.Sprintf("Done filling cache! Found [%d] Apps", len(apps)), true)

	// Ticker Pooling the CC every X sec
	ccPooling := time.NewTicker(*tickerTime)

	go func() {
		for range ccPooling.C {
			apps = caching.GetAllApp()
		}
	}()

	// Parse extra fields from cmd call
	extraFields, err := extrafields.ParseExtraFields(*extraFields)
	if err != nil {
		log.Fatal("Error parsing extra fields: ", err)
		os.Exit(1)
	}

	// Parse filters
	filtersToApply := filters.GetFilters(*filterPath)
	if err != nil {
		log.Fatal("Error parsing filters: ", err)
		os.Exit(1)
	}

	// Ticker Pooling the Filters file every 60 seconds
	filterPolling := time.NewTicker(time.Second * 60)
	go func() {
		for range filterPolling.C {
			filtersToApply = filters.GetFilters(*filterPath)
		}
	}()

	// Connect to redis
	redisConn, err := redisurl.ConnectToURL(*redisUrl)
	if err != nil {
		panic("Can't connect to Redis")
	}
	events.SetupRedisClient(redisConn)

	if logging.Connect() || *debug {

		logging.LogStd("Connected to Syslog Server! Connecting to Firehose...", true)

		firehose := firehose.CreateFirehoseChan(cfClient.Endpoint.DopplerEndpoint, cfClient.GetToken(), *subscriptionId, *skipSSLValidation)
		if firehose != nil {
			logging.LogStd("Firehose Subscription Succesfull! Routing events...", true)
			events.RouteEvents(firehose, extraFields, filtersToApply)
		} else {
			logging.LogError("Failed connecting to Firehose...Please check settings and try again!", "")
		}

	} else {
		logging.LogError("Failed connecting to the Syslog Server...Please check settings and try again!", "")
	}
}
Beispiel #22
0
func main() {

	// Set default value of chat exit to false
	chatExit := false

	args := os.Args
	if len(args) != 2 {

		fmt.Println("Usage: chat_client.go <username>")
		os.Exit(1)
	}

	username := args[1]
	userDBKey := "online-" + username

	// Connecting to the local redis DB instance
	userManageConn, err := redisurl.ConnectToURL(redisURL)
	if err != nil {
		fmt.Println("Could not connect to redis DB")
		fmt.Println(err)
		os.Exit(1)
	}

	// Close the connection when program exits
	defer userManageConn.Close()

	// Insert Data into redis DB, if insert is a success then publish message
	val, err := userManageConn.Do("SET", userDBKey, username, "NX", "EX", "100")

	// If DB throws err on insert
	if err != nil {

		fmt.Println(err)
		os.Exit(1)
	}

	// If the insert is not a success and fails without ok message
	if val == nil {

		fmt.Println("Could not insert, Key exists in DB")
		fmt.Println("User is online on another terminal...")
		os.Exit(1)

	} else {

		// If user key was added , try to insert insert user to set of online users

		setAddVal, err := userManageConn.Do("SADD", "users", username)

		if err != nil {
			fmt.Println(err)
		}
		if setAddVal == nil {
			fmt.Println("User is online on another terminal...")
		}

		// If user was added to the set of online users then publish a new message

		userManageConn.Do("PUBLISH", "messages", "New User Joined: "+username)
		fmt.Println("You joined the application successfully.")
		fmt.Println("Chat Ready. Just Start typing.....")
	}

	// New channel for each user connection to read messages from redisDB
	subscribeToRedisChan := make(chan string)

	// Call to handle Subscribe of redis
	go SubscribeHandler(subscribeToRedisChan)

	// Send hearbeats to keep user alive
	go SendHeartBeat(userManageConn, username, userDBKey, &chatExit)

	// Handle publishing and commands
	go PublishAndCommandHandler(username, &chatExit)

	// While chatExit is not called poll messages from the subscribeChannel
	// This is why we defined the subscribeChannel outside function
	for !chatExit {
		select {
		case line := <-subscribeToRedisChan:

			// Read only messages from others
			if strings.Index(line, username) != 0 {
				fmt.Printf("%s \n", line)
			}

		default:
			// Sleep a second before message arrives again
			time.Sleep(100 * time.Millisecond)

		}
	}

	// Before the function exits remove the user from redis DB
	userManageConn.Do("DEL", userDBKey)
	userManageConn.Do("SREM", "users", username)
	userManageConn.Do("PUBLISH", "messages", "Sad :( User Left :- \t"+username)

}
Beispiel #23
0
func main() {
	oauth2.PathCallback = "/auth/twitch"
	oauth2.PathLogin = "******"
	oauth2.PathLogout = "/logout"

	// Middleware
	m := martini.Classic()
	m.Use(sessions.Sessions("manfred", sessions.NewCookieStore([]byte(SessionSecret))))
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
	}))

	m.Use(TwitchOAuth(&oauth2.Options{
		ClientId:     TwitchClient,
		ClientSecret: TwitchSecret,
		RedirectURL:  TwitchRedirect,
		Scopes:       []string{"user_read", "user_subscriptions"},
	}))

	// Services
	// Redis
	c, err := redisurl.ConnectToURL(RedisURL)
	if err != nil {
		panic(err)
	}
	m.Map(c)

	// Routes
	m.Get("/", oauth2.LoginRequired, func(s sessions.Session, t oauth2.Tokens, r render.Render) {

		EnsureSessionVariables(s, t)

		r.HTML(200, "home", NewTemplateData(s))
	})

	m.Get("/newGame", oauth2.LoginRequired, func(s sessions.Session, r render.Render) {
		r.HTML(200, "newGame", NewTemplateData(s))
	})

	m.Post("/createGame", oauth2.LoginRequired, func(c redis.Conn, t oauth2.Tokens, r render.Render, req *http.Request) {
		u, err := GetTwitchUser(t.Access())
		if err != nil {
			log.Fatal(err)
		}

		uuid := uniuri.NewLen(8)
		mg := ManfredGame{}
		mg.UUID = uuid
		mg.StreamerName = u.DisplayName
		mg.Description = req.PostFormValue("description")
		mg.Game = req.PostFormValue("game")
		mg.PlayerCount = 7 // At some point this could be dynamic based off of the game
		// mg.MustFollow = req.PostFormValue("mustFollow")
		// mg.MustSub = req.PostFormValue("mustSub")

		mg.Save(c)

		r.Redirect("/game/" + uuid)
	})

	m.Post("/game/:gameId", oauth2.LoginRequired, func(s sessions.Session, r render.Render, p martini.Params, req *http.Request) {
		count, err := strconv.ParseInt(req.PostFormValue("inputPlayerCount"), 10, 8)
		if err != nil {
			log.Fatal(err)
			//return 404, "{\"success\": false, \"error\": \"" + err.Error() + "\"}"
		}

		key := GameKey(p["gameId"])
		game := LoadManfredGame(key, c)

		if game == nil {
			log.Fatal(err)
			//return 404, "{\"success\": false, \"error\": \"Unable to find a game with that id\"}"
		}

		// If count has decreased, and players were already selected, we need to remove members
		game.PlayerCount = int(count)
		game.Save(c) // This will extend the expiration time of the game. We might not want that...

		r.Redirect("/game/" + game.UUID)
		// Eventually we should do this via ajax and return: return 200, "{\"success\": true}"
	})

	m.Post("/game/:gameId/players", oauth2.LoginRequired, func(s sessions.Session, r render.Render, p martini.Params, req *http.Request) {
		key := GameKey(p["gameId"])
		game := LoadManfredGame(key, c)

		if game == nil {
			log.Fatal(err)
			//return 404, "{\"success\": false, \"error\": \"Unable to find a game with that id\"}"
		}

		game.ChoosePlayers(c)

		r.Redirect("/game/" + game.UUID)
		// Eventually we should do this via ajax and return: return 200, "{\"success\": true}"
	})

	m.Delete("/game/:gameId/player", oauth2.LoginRequired, func(s sessions.Session, r render.Render, p martini.Params, req *http.Request) (int, string) {
		key := GameKey(p["gameId"])
		game := LoadManfredGame(key, c)

		if game == nil {
			return 404, "{\"success\": false, \"error\": \"Unable to find a game with that id\"}"
		}

		content := make([]byte, req.ContentLength)
		_, err := req.Body.Read(content)
		if err != nil {
			log.Fatal(err)
		}

		type ReplaceRequest struct {
			UserKey TwitchUserKey
		}
		var replace ReplaceRequest
		err = json.Unmarshal(content, &replace)
		if err != nil {
			log.Fatal(err)
		}

		game.ReplacePlayer(replace.UserKey, c)

		return 200, "{\"success\": true}"
	})

	m.Get("/game/:gameId/info", oauth2.LoginRequired, func(s sessions.Session, r render.Render, p martini.Params, req *http.Request) (int, string) {
		key := GameKey(p["gameId"])
		game := LoadManfredGame(key, c)

		if game == nil {
			return 404, "{\"success\": false, \"error\": \"Unable to find a game with that id\"}"
		}

		playerIds := game.GetChosenPlayers(c)

		players := make([]ManfredPlayer, len(playerIds))

		for i, id := range playerIds {
			p := LoadManfredPlayer(id, c)
			if p != nil {
				players[i] = *p
			}
		}

		info := struct {
			PlayerCount int64
			Players     []ManfredPlayer
		}{game.CountPlayersReady(c), players}

		infoString, err := json.Marshal(info)
		if err != nil {
			log.Fatal(err)
		}

		return 200, string(infoString)
	})

	m.Get("/game/:gameId", oauth2.LoginRequired, func(s sessions.Session, r render.Render, p martini.Params, req *http.Request) {
		key := GameKey(p["gameId"])
		game := LoadManfredGame(key, c)

		playerIds := game.GetChosenPlayers(c)

		players := make(map[TwitchUserKey]ManfredPlayer, len(playerIds))

		for _, id := range playerIds {
			p := LoadManfredPlayer(id, c)
			if p != nil {
				players[id] = *p
			}
		}

		templateData := NewTemplateData(s)
		templateData.Data = struct {
			Game        ManfredGame
			GameUrl     string
			PlayerCount int64
			Players     map[TwitchUserKey]ManfredPlayer
		}{*game, fmt.Sprintf("http://%s/play/%s", req.Host, p["gameId"]), game.CountPlayersReady(c), players}

		r.HTML(200, "game", templateData)
	})

	m.Get("/play/:gameId", oauth2.LoginRequired, func(s sessions.Session, t oauth2.Tokens, r render.Render, p martini.Params) {
		EnsureSessionVariables(s, t)
		templateData := NewTemplateData(s)

		gameKey := GameKey(p["gameId"])
		game := LoadManfredGame(gameKey, c)

		playerKey := ConvertToTwitchUserKey(strconv.FormatInt(s.Get("twitchId").(int64), 10)) // There's got to be a better way to do this...
		player := LoadManfredPlayer(playerKey, c)

		setupUrl := "/play/" + p["gameId"] + "/setup"

		if game == nil {
			r.HTML(404, "missing_game", templateData)
			return
		}

		if player == nil {
			r.Redirect(setupUrl)
			return
		}

		handle, ok := player.Handles[game.Game]

		if !ok || handle == "" {
			r.Redirect(setupUrl)
			return
		}

		log.Println("Here be the handle! " + handle)

		playerTwitchId := strconv.FormatInt(s.Get("twitchId").(int64), 10)

		game.AddPlayer(ConvertToTwitchUserKey(playerTwitchId), c)
		game.AddTestPlayer(game.Game, c) // Add this for testing so that the number of players will always increase

		templateData.Data = struct {
			Game     ManfredGame
			Handle   string
			SetupUrl string
		}{*game, handle, setupUrl}
		r.HTML(200, "play", templateData)
	})

	m.Get("/play/:gameId/setup", oauth2.LoginRequired, func(s sessions.Session, t oauth2.Tokens, r render.Render, p martini.Params) {
		EnsureSessionVariables(s, t)

		templateData := NewTemplateData(s)

		gameKey := GameKey(p["gameId"])
		game := LoadManfredGame(gameKey, c)

		playerKey := ConvertToTwitchUserKey(strconv.FormatInt(s.Get("twitchId").(int64), 10)) // There's got to be a better way to do this...
		player := LoadManfredPlayer(playerKey, c)

		currentHandle := ""

		if game == nil {
			r.HTML(404, "missing_game", templateData)
			return
		}

		if player != nil {
			currentHandle = player.Handles[game.Game]
		}

		templateData.Data = struct {
			Game          ManfredGame
			CurrentHandle string
		}{*game, currentHandle}
		r.HTML(200, "setup_player", templateData)
	})

	m.Post("/updateHandle", oauth2.LoginRequired, func(c redis.Conn, t oauth2.Tokens, r render.Render, req *http.Request, s sessions.Session) {

		playerKey := ConvertToTwitchUserKey(strconv.FormatInt(s.Get("twitchId").(int64), 10)) // There's got to be a better way to do this...
		player := LoadManfredPlayer(playerKey, c)

		if player == nil {
			player = new(ManfredPlayer)
			player.Handles = make(map[string]string)
			player.Handles["TWITCH"] = s.Get("userName").(string)
		}

		player.Handles[req.PostFormValue("game")] = req.PostFormValue("handle") // Is there some sort of validation / santization we should be doing here?

		SaveManfredPlayer(*player, playerKey, c)

		gameId := req.PostFormValue("gameId")

		if gameId == "" {
			r.Redirect("/settings")
		} else {
			r.Redirect("/play/" + gameId)
		}
	})

	m.Run()
}
Beispiel #24
0
func main() {

	// Common Variable to manage all processes
	exit := false

	args := os.Args
	if len(args) < 2 {
		fmt.Println("Usage: main.go <master/slave/client/api-server>")
		os.Exit(1)
	}

	// Capturing which mode to launch go server in
	mode := args[1]
	fmt.Printf("Mode Selected %s \n", mode)

	// Manage name of user
	username := "******"
	if len(args) == 3 {
		username = args[2]
	}

	// Use this connection only for setup activities of the node. No more communication should happen through this
	managerConn, err := redisurl.ConnectToURL(redisURL)
	if err != nil {

		fmt.Println(err)
		os.Exit(1)

	}

	// Before function exits close the connection
	defer managerConn.Close()

	// go Channel for commands common for master and slave
	commandChan := make(chan string)

	// Get Ip Address and key / value for this connection
	ipaddr := util.GetIPAddress()
	key := "online." + ipaddr
	val := ipaddr + ":8000"

	switch mode {
	case "slave":

		// Start command line driver
		go components.CommandLineInput(commandChan, &exit)
		go components.CmdHandler(commandChan, &exit)

		fmt.Printf("New Client Started at %s \n", ipaddr)

		// Register Slave to Redis DB
		go components.RegisterSlave(managerConn, key, val)

		// Start File Server
		go components.StartFileServer()

		// Start the main slave process
		components.Slave(ipaddr, &exit)

		// Send Heartbeats
		go util.SendHeartBeat(managerConn, key, val, &exit)

	case "master":

		go components.CommandLineInput(commandChan, &exit)
		go components.CmdHandler(commandChan, &exit)

		newSlaveChan := make(chan string)
		fmt.Printf("Master Started at %s \n", ipaddr)
		go components.ReceiveMessages(newSlaveChan, ipaddr)
		go components.HandleNewSlaves(newSlaveChan)
		go components.GetFileIPServer()

		for !exit {
			time.Sleep(1 * time.Second)
		}

	case "client":

		go components.FileSystemCommandHandler(&exit, username)

	case "api-server":

		go components.CommandLineInput(commandChan, &exit)
		go components.CmdHandler(commandChan, &exit)
		go api.StartServer(&exit)

	default:

		fmt.Println("Incorrect command line argument. Either use master or slave")
		os.Exit(1)

	}

	for !exit {

		time.Sleep(1 * time.Second)
	}

	// Remove the user before slave function exits
	managerConn.Do("SREM", "online_slaves", ipaddr)
	managerConn.Do("DEL", key)

}
Beispiel #25
0
// FileSystemCommandHandler : Manages commands issued by the client
func FileSystemCommandHandler(exit *bool, username string) {

	// Very important var ; used by the commands for reference
	currDir := "/"

	conn, err := redisurl.ConnectToURL(redisURL)
	if err != nil {
		fmt.Println("could not connect to the redis URL")
	}

	for !*exit {
		// Create a command line reader
		fmt.Println("File System commands Available...")

		bufferedIO := bufio.NewReader(os.Stdin)
		for !*exit {

			fmt.Printf("%s-cmd-prompt $:  ", username)
			line, _, err := bufferedIO.ReadLine()
			if err != nil {
				fmt.Print("error in input function")
			}

			// command issued as a string
			cmdLine := string(line)

			// --------------- Pre Hanlder for cat command ----------- //

			cmdFile := ""

			if strings.Index(cmdLine, "cat") == 0 {

				cmdFile = strings.Split(cmdLine, " ")[1]
				cmdLine = "cat"

			}

			//--------------- Pre handlers for cd commands ------------ //
			dir := "" // Needs to be outside loop

			if cmdLine == "cd /" {

				//Pre handler for cd command
				cmdLine = "cd basedir"

			} else if cmdLine == "cd .." {

				// Prehandler for cd .. command
				cmdLine = "cd back"
			} else {

				// Handler for cd <dir> command

				rp := regexp.MustCompile("cd [a-z]+")
				iscdCmd := rp.MatchString(cmdLine)
				if iscdCmd == true {

					dir = strings.Split(cmdLine, " ")[1]
					cmdLine = "cd"
				}

			}

			switch cmdLine {

			case "ls":

				LSHandler(conn, currDir)
				break

			case "cd basedir":

				currDir = CdHandler(conn, "basedir", currDir, "")
				fmt.Printf("Moved to dir: %s \n", currDir)
				break

			case "cd back":

				currDir = CdHandler(conn, "back", currDir, "")

				break

			case "cd":

				currDir = CdHandler(conn, "normal", currDir, dir)
				dir = ""
				break

			case "exit":

				fmt.Println("Program exiting")
				*exit = true

			case "cat":

				data := HandleCat(cmdFile)
				fmt.Println(data)

			default:
				fmt.Println("Unrecognized command")

			}

			fmt.Println()

		}

		return

	}
}