Example #1
0
//parse args and start as master, scribe, addama proxy or worker
func main() {
	var configurationFile string
	var isMaster bool
	var isScribe bool
	var isAddama bool

	flag.BoolVar(&isMaster, "m", false, "Start as master node.")
	flag.BoolVar(&isScribe, "s", false, "Start as scribe node.")
	flag.BoolVar(&isAddama, "a", false, "Start as addama node.")
	flag.StringVar(&configurationFile, "config", "golem.config", "A configuration file for golem services")
	flag.Parse()

	configFile, err := goconf.ReadConfigFile(configurationFile)
	if err != nil {
		panic(err)
	}

	GlobalLogger(configFile)
	GlobalTls(configFile)
	SubIOBufferSize("default", configFile)
	GoMaxProc("default", configFile)
	ConBufferSize("default", configFile)
	StartHtmlHandler(configFile)

	if isMaster {
		StartMaster(configFile)
	} else if isScribe {
		StartScribe(configFile)
	} else if isAddama {
		StartAddama(configFile)
	} else {
		StartWorker(configFile)
	}
}
Example #2
0
//get redis connection pool
func GetRedisPool() *redis.Pool {
	if pool == nil {
		pool = &redis.Pool{
			MaxIdle:     3,
			IdleTimeout: 240 * time.Second,
			Dial: func() (redis.Conn, error) {
				conf, err := goconf.ReadConfigFile("auth.conf")
				if err != nil {
					fmt.Println(err)
					return nil, err
				}

				host, _ := conf.GetString("redis", "host")
				port, _ := conf.GetInt("redis", "port")
				redis_server := fmt.Sprintf("%s:%d", host, port)

				c, err := redis.Dial("tcp", redis_server)
				if err != nil {
					return nil, err
				}
				return c, err
			},
			TestOnBorrow: func(c redis.Conn, t time.Time) error {
				_, err := c.Do("PING")
				return err
			},
		}
	}
	return pool
}
Example #3
0
// NewConfigFile returns a *ConfigFile object from the `filename`
func NewConfigFile(filename string) (*ConfigFile, error) {
	cfg, err := goconf.ReadConfigFile(filename)
	if err != nil {
		return nil, err
	}
	return &ConfigFile{cfg: cfg}, err
}
Example #4
0
func NewRegistrar(connectionFilePath string) *Registrar {
	connectionFile, _ := goconf.ReadConfigFile(connectionFilePath)
	host, _ := connectionFile.GetString("Connection", "host")
	apikey, _ := connectionFile.GetString("Connection", "apikey")
	logger.Debug("NewRegistrar(%v):%v,%v", connectionFilePath, host, apikey)
	return &Registrar{host: "https://" + host, apikey: apikey}
}
Example #5
0
//Get db connection from mysql
func GetDB() (db *sql.DB) {
	if DBpool == nil {
		conf, err := goconf.ReadConfigFile("auth.conf")
		if err != nil {
			fmt.Println(err)
			return nil
		}

		host, _ := conf.GetString("mysql", "host")
		port, _ := conf.GetInt("mysql", "port")
		user, _ := conf.GetString("mysql", "user")
		password, _ := conf.GetString("mysql", "password")
		db, _ := conf.GetString("mysql", "db")
		db_server := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", user, password, host, port, db)

		DBpool = CreateDbPool(20, "mysql", db_server, true)
	}

	conn, err := DBpool.GetConn()
	if err != nil {
		fmt.Println(err)
		return nil
	}

	return conn
}
Example #6
0
func (config *config) load() (err error) {
	if config.HasPath() {
		config.ConfigFile, err = conf.ReadConfigFile(config.Path())
		if err != nil {
			return
		}
	} else {
		config.ConfigFile = conf.NewConfigFile()
	}
	if config.HasDefaultPath() {
		// Load defaults if a path was given.
		config.Defaults, err = conf.ReadConfigFile(config.DefaultPath())
		if err != nil {
			return
		}
	}
	if config.HasOverridePath() {
		// Load overrides if a path was given.
		config.Overrides, err = conf.ReadConfigFile(config.OverridePath())
		if err != nil {
			return
		}
	}

	for _, section := range config.Defaults.GetSections() {
		options, _ := config.Defaults.GetOptions(section)
		for _, option := range options {
			if !config.ConfigFile.HasOption(section, option) {
				value, _ := config.Defaults.GetRawString(section, option)
				config.ConfigFile.AddOption(section, option, value)
			}
		}
	}

	for _, section := range config.Overrides.GetSections() {
		options, _ := config.Overrides.GetOptions(section)
		for _, option := range options {
			value, _ := config.Overrides.GetRawString(section, option)
			config.ConfigFile.AddOption(section, option, value)
		}
	}

	return
}
Example #7
0
func (c *Config) Read() error {
	readConfigData, err := goconf.ReadConfigFile(*configFile)
	if err != nil {
		return fmt.Errorf("failed to read the config file: %v", err)
	}

	if err := c.readDefaultConfig(readConfigData); err != nil {
		return err
	}

	return nil
}
Example #8
0
func main() {
	flag.Parse()

	cfg, err := conf.ReadConfigFile(*configFile)
	if err != nil {
		log.Fatalf("Failed to read config file %q: %v", *configFile, err)
	}

	fido := watchdog.NewWatchdog()
	server.ShutdownHandler(fido)

	for _, name := range cfg.GetSections() {
		if name == "default" {
			continue
		}

		binary := svcOpt(cfg, name, "binary", true)
		args := svcOpt(cfg, name, "args", false)

		svc, err := fido.AddService(name, binary)
		if err != nil {
			log.Fatalf("Failed to add service %q: %v", name, err)
		}
		svc.AddArgs(args)
		if dep := svcOpt(cfg, name, "dependency", false); dep != "" {
			svc.AddDependency(dep)
		}
		if opt := svcOpt(cfg, name, "priority", false); opt != "" {
			prio, err := strconv.Atoi(opt)
			if err != nil {
				log.Fatalf("Service %s has invalid priority %q: %v", name, opt, err)
			}
			if err := svc.SetPriority(prio); err != nil {
				log.Fatalf("Failed to set priority for service %s: %v", name, err)
			}
		}
		if opt := svcOpt(cfg, name, "term_timeout", false); opt != "" {
			tt, err := time.ParseDuration(opt)
			if err != nil {
				log.Fatalf("Service %s has invalid term_timeout %q: %v", name, opt, err)
			}
			svc.SetTermTimeout(tt)
		}
		// TODO(angusc): Add support for a "group" option.
		if user := svcOpt(cfg, name, "user", false); user != "" {
			if err := svc.SetUser(user); err != nil {
				log.Fatalf("Failed to set user for service %s: %v", name, err)
			}
		}
	}

	fido.Walk()
}
Example #9
0
func (c *Config) Read() error {
	conf, err := goconf.ReadConfigFile(*configFile)
	if err != nil {
		return err
	}
	c.conf = conf

	if err := c.readDefaultConfig(conf); err != nil {
		return err
	}

	return nil
}
Example #10
0
func getdb() *sql.DB {
	var settings, herokupg, localpg string
	herokupg = os.Getenv("DATABASE_URL")
	if herokupg != "" {
		settings, _ = pq.ParseURL(herokupg)
	} else {
		c, _ := goconf.ReadConfigFile("db.config")
		localpg, _ = c.GetString("dev", "postgresurl")
		settings, _ = pq.ParseURL(localpg)
	}
	db, _ := sql.Open("postgres", settings)
	return db
}
Example #11
0
func (c *config) parseConfigFile() (err error) {
	if c.cfg, err = ini.ReadConfigFile(c.file); err != nil {
		return
	}
	if c.dsn, err = c.cfg.GetString("mysql", "dsn"); err != nil {
		return
	}
	if c.extendedInsRows, err = c.cfg.GetInt("mysql", "extended_insert_rows"); err != nil {
		c.extendedInsRows = 100
	}
	if c.useTableLock, err = c.cfg.GetBool("mysql", "use_table_lock"); err != nil {
		c.useTableLock = true
	}
	if c.maxOpenConns, err = c.cfg.GetInt("mysql", "max_open_conns"); err != nil {
		c.maxOpenConns = 50
	}
	var selects []string
	if selects, err = c.cfg.GetOptions("select"); err != nil {
		return
	}
	for _, tableCol := range selects {
		var table, column string
		if table, column, err = c.splitTableColumn(tableCol); err != nil {
			return
		}
		if c.selectMap[table] == nil {
			c.selectMap[table] = make(map[string]string, 0)
		}
		if c.selectMap[table][column], err = c.cfg.GetString("select", tableCol); err != nil {
			return
		}
	}
	if c.loadOptions("where", c.whereMap); err != nil {
		return
	}
	if c.loadOptions("filter", c.filterMap); err != nil {
		return
	}
	return
}
Example #12
0
func initializeBotsFromConfig(configPath string) []*jarvis.Bot {
	bots := []*jarvis.Bot{}
	config, err := goconf.ReadConfigFile(configPath)
	if err != nil {
		fmt.Printf("error reading config: %v\n", err)
		os.Exit(1)
	}

	for _, section := range config.GetSections() {
		tokenRaw, err := config.GetString(section, "SLACK_API_TOKEN")
		if err == nil {
			decryptedToken, err := decryptValue(tokenRaw)
			if err != nil {
				fmt.Printf("error decrypting slack token: %v\n", err)
				os.Exit(1)
			}
			j := jarvis.NewBot(decryptedToken)

			options, _ := config.GetOptions(section)
			for _, option := range options {
				if value, err := config.GetString(section, option); err == nil {
					decryptedValue, err := decryptValue(value)
					if err == nil {
						j.Configuration()[strings.ToUpper(option)] = decryptedValue
					} else {
						j.Configuration()[strings.ToUpper(option)] = value
					}
				}
			}

			j.Init()
			j.Start()
			bots = append(bots, j)
		} else {
			fmt.Printf("Error Reading `SLACK_API_TOKEN`: %v\n", err)
		}
	}
	return bots
}
Example #13
0
func GetSession() (Session *mgo.Session) {
	if MPool == nil {
		conf, err := goconf.ReadConfigFile("auth.conf")
		if err != nil {
			fmt.Println(err)
			return nil
		}

		host, _ := conf.GetString("mongodb", "host")
		port, _ := conf.GetInt("mongodb", "port")
		mongo_server := fmt.Sprintf("%s:%d", host, port)

		MPool = CreateMongoPool(20, mongo_server)
	}

	Session, err := MPool.GetSession()
	if err != nil {
		fmt.Println(err)
		return nil
	}

	return Session
}
Example #14
0
func read_conf() {
	conf, err := goconf.ReadConfigFile("auth.conf")
	if err != nil {
		fmt.Println(err)
	}
	cert, _ = conf.GetString("server", "cert")
	key, _ = conf.GetString("server", "key")
	https_port, _ = conf.GetInt("server", "https_port")
	port, _ = conf.GetInt("server", "port")
	ValidTime, _ := conf.GetInt("sms", "valid_time")
	action.ValidTime = int64(ValidTime)
	RefreshTime, _ := conf.GetInt("sms", "refresh_time")
	action.RefreshTime = int64(RefreshTime)

	sms_host, _ := conf.GetString("sms", "host")
	action.SMSHost = sms_host
	str_key, _ := conf.GetString("sms", "key")
	action.TnterfaceKey = str_key
	str_sign, _ := conf.GetString("sms", "sign")
	action.InterfaceSign = str_sign
	check_text, _ := conf.GetString("sms", "check_text")
	action.CheckText = check_text

}
Example #15
0
File: conf.go Project: deong/GoRL
// parse the configuration file, returning any error encountered
func InitConfig(file string) (err error) {
	rc, err = gc.ReadConfigFile(file)
	return
}
Example #16
0
func main() {
	// Begin here.
	/* -------------------------------------  */
	/* 			Boilerplate					  */
	/* -------------------------------------  */
	/*
		Setting up Logging, this is standard practice for all go programs
	*/
	pwd, err := os.Getwd() // get present working directory
	if err != nil {
		log.Fatal(err)
	}
	fo, err := os.Create(pwd + string(filepath.Separator) + "server.log") // create log file in current dir
	if err != nil {
		log.Fatal(err)
	}
	log.SetOutput(io.Writer(fo))
	// 		Done setting up Logging

	// Initialize the config variables
	// This is triggered only once and loads up the conf file.
	if func() bool {
		_confMap = make(map[string]string)
		pwd, err := os.Getwd() // get present working directory
		if err != nil {
			log.Fatal(err)
		}
		path := pwd + string(filepath.Separator) + "cockpit" + string(filepath.Separator) + "conf"
		_, err = os.Stat(path)
		if err != nil {
			log.Fatal("Config file not found. Config file is located in same directory as executable in a folder .arwen/config")
		}
		_cfile, err = goconf.ReadConfigFile(path)
		if err != nil {
			log.Fatal("Error reading config file." + err.Error())
		}
		return true
	}() {
		log.Print("Loaded Logging, starting up server ...")
	} else {
		log.Fatal("Error loading conf file ...")
	}

	/* -------------------------------------  */
	/*			Coding Begins				  */
	/* -------------------------------------  */
	//Variable stores everything
	_store = make(map[string]interface{})
	_servers = make(map[string]interface{})
	// Channels to manage data
	httpChannel := make(chan map[string]interface{})                       // {action : {object}}
	poller := time.NewTicker(time.Duration(int64(5) * int64(time.Second))) // Actual time variable that is a counter
	alertChannel := make(chan map[string]string)
	pollerChannel := make(chan map[string]interface{})
	//serverChannel := make(chan []Serv)
	HTTPHandler.Init()

	// Load the contents of the servers.json to the _servers
	file, e := ioutil.ReadFile("./cockpit/servers.json")
	if e != nil {
		log.Fatal("File Error")
	}
	log.Print(file)
	if string(file) != "" {
		err = json.Unmarshal(file, &_servers)
		if err != nil {
			log.Fatal("Error reading servers.json")
		}
	}

	// Initiate HTTP Listener
	// Listener for the incoming HTTP request
	go func(store map[string]interface{}, servers map[string]interface{}, ch chan map[string]interface{}) {
		// Define the http listener
		router := mux.NewRouter()
		// ROUTER
		router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("{\"status\":\"alive\"}"))
		})
		router.HandleFunc("/auth", func(w http.ResponseWriter, r *http.Request) {
			HTTPHandler.Auth(w, r)
		})
		router.HandleFunc("/add/{action}", func(w http.ResponseWriter, r *http.Request) {
			HTTPHandler.Add(w, r, ch)
		})
		router.HandleFunc("/server/{action}", func(w http.ResponseWriter, r *http.Request) {
			HTTPHandler.Server(w, r, servers, store)
		})
		router.HandleFunc("/alert", func(w http.ResponseWriter, r *http.Request) {
			// TODO : Put a conditional key here, we need that key to verify that message isn't bogus
			// If a message is recieved on this func, this needs to be sent as an alert ASAP
			log.Print("Message recieved")
			serv := r.FormValue("alert")
			err := r.FormValue("error")
			res := make(map[string]string)
			res["server"] = serv
			res["error"] = err
			alertChannel <- res
			w.Write([]byte("{\"status\":\"posted\"}"))
		})
		http.Handle("/", router)
		http.ListenAndServe(":63000", nil) // TODO add this to conf
	}(_store, _servers, httpChannel)

	for {
		select {
		case item := <-httpChannel:
			// Poll on Request
			for k, _ := range item {
				if k == "server" {
					// Do soemthing
					// Add this info to server map
					ser := make(map[string]interface{})
					ser["name"] = item[k].(map[string]interface{})["name"].(string)
					ser["key"] = item[k].(map[string]interface{})["key"].(string)
					ser["ip"] = item[k].(map[string]interface{})["ip"].(string)
					if _, ok := _servers[item[k].(map[string]interface{})["name"].(string)]; !ok {
						_servers[item[k].(map[string]interface{})["name"].(string)] = ser
					}
					fi, err := os.OpenFile("./cockpit/servers.json", os.O_RDWR, 0660)
					if err != nil {
						panic(err)
					}
					// close fi on exit and check for its returned error
					defer func() {
						if err := fi.Close(); err != nil {
							panic(err)
						}
					}()
					js, err := json.Marshal(_servers)
					if err != nil {
						log.Panic("Error Marshalling json")
					} else {
						_, err := fi.Write(js)
						if err != nil {
							log.Panic("Unable to write to json file")
						}
					}
				}
			}
		case <-poller.C:
			srv := make(map[string]interface{})
			for k, v := range _servers {
				srv[k] = v
			}
			go func(srv map[string]interface{}) {
				r := make(map[string]interface{})
				// Poller
				// Now loop over servers to check the status of the server
				// Dump the contents of _server as json file
				for _, val := range srv {
					ser := val.(map[string]interface{})
					resp, err := http.Get("http://" + ser["ip"].(string) + ":63001" + "/") // TODO: Add it to conf
					if err != nil {
						log.Print("Error in fetching value for the IP " + ser["ip"].(string))
						resp = nil
					}
					//log.Print(resp)
					if resp != nil {
						var f interface{}
						v, er := ioutil.ReadAll(resp.Body)
						if er != nil {
							log.Print("Error reading value from the server")
						} else {
							er := json.Unmarshal([]byte(v), &f)
							if er != nil {
								log.Print("Error in Unmarshaling data")
								var temp interface{}
								r[ser["name"].(string)] = temp
							} else {
								r[ser["name"].(string)] = f
							}
						}
					} else {
						t := make(map[string]interface{})
						t["status"] = "dead"
						r[ser["name"].(string)] = t
					}
					pollerChannel <- r
				}
			}(srv)

		case alert := <-alertChannel:
			// as of now just print this shit
			data := map[string]interface{}{"server": alert["server"],
				"error": alert["error"]}
			regIDs := []string{"APA91bFLfsr-5lsuunNLXs_qRxCjPW6c9spZIUAnuIXUlwQ0pSEi1U9Ln0ctLjSeD4xT5McsIv2MJSBlQE-v3Y8jm6JtNbzKlWXnK90goeEweQ36t-sGkTf_nVZ-jiB-TfxWS3mQHJxkd1M7PXf5-PWLeWfkOpusESD0z_Q0NMIy2tqAp9X_K7s"}
			msg := gcm.NewMessage(data, regIDs...)
			sender := &gcm.Sender{ApiKey: "AIzaSyCNJeYio3_-9tRF8fjuUep7BeV0c0rE8TU"}
			_, err := sender.Send(msg, 2)
			if err != nil {
				log.Print("Failed to send message:", err)
				return
			}
			log.Print(alert)
		case item := <-pollerChannel:
			// Copy to _server
			for k, v := range item {
				_store[k] = v
			}
		}
	}
}
Example #17
0
func NewConfig(filepath string) (*Config, error) {
	config := Config{
		configFilePath: filepath,
	}

	c, err := goconf.ReadConfigFile(filepath)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, errors.New("Could not find config file. Try using the --config=\"<path-to-config-file>\" option to specify a config file.")
		} else {
			return nil, err
		}
	}

	// Change our working directory to that of the config file so that paths referenced in the config file are relative to that location
	err = os.Chdir(path.Dir(filepath))
	if err != nil {
		return nil, err
	}

	// Parse port
	config.port, err = c.GetInt("", "port")
	if err != nil {
		return nil, err
	}

	// Parse database config options
	config.database.host, err = c.GetString("database", "host")
	if err != nil {
		return nil, err
	}
	config.database.port, err = c.GetInt("database", "port")
	if err != nil {
		return nil, err
	}
	config.database.user, err = c.GetString("database", "user")
	if err != nil {
		return nil, err
	}
	config.database.password, err = c.GetString("database", "password")
	if err != nil {
		return nil, err
	}
	config.database.dbname, err = c.GetString("database", "dbname")
	if err != nil {
		return nil, err
	}
	config.database.sslmode, err = c.GetString("database", "sslmode")
	if err != nil {
		return nil, err
	}
	if c.HasOption("database", "max_idle_connections") {
		config.database.maxIdleConnections, err = c.GetInt("database", "max_idle_connections")
		if err != nil {
			return nil, err
		}
	} else {
		config.database.maxIdleConnections = -1
	}

	// Ingest the private key into the global config object
	config.signingKeyPath, err = c.GetString("", "signing-key")
	if err != nil {
		return nil, err
	}
	signingKeyPEM, err := ioutil.ReadFile(config.signingKeyPath)
	if err != nil {
		return nil, err
	}
	config.signingKey, err = NewPrivateKey(signingKeyPEM)
	if err != nil {
		return nil, err
	}

	// Ingest administrators
	config.adminKeysPath, err = c.GetString("", "admins")
	if err != nil {
		return nil, err
	}
	adminPEMBytes, err := ioutil.ReadFile(config.adminKeysPath)
	if err != nil {
		return nil, err
	}
	config.adminUsers, err = NewUserSet(adminPEMBytes)
	if err != nil {
		return nil, err
	}

	// Ingest the readme
	config.readmePath, err = c.GetString("", "readme")
	if err != nil {
		return nil, err
	}
	config.readme, err = ioutil.ReadFile(config.readmePath)
	if err != nil {
		return nil, err
	}

	return &config, nil
}
Example #18
0
//@@TEST: loading known good config from file
func NewConfig(filepath string) (*config, error) {
	conf := config{
		configFilePath: filepath,
	}

	c, err := goconf.ReadConfigFile(filepath)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, errors.New("Could not find config file. Try using the --config=\"<path-to-config-file>\" option to specify a config file.")
		} else {
			return nil, err
		}
	}

	// Change our working directory to that of the config file so that paths referenced in the config file are relative to that location
	err = os.Chdir(path.Dir(filepath))
	if err != nil {
		return nil, err
	}

	// Parse port
	conf.port, err = c.GetInt("", "port")
	if err != nil {
		return nil, err
	}

	// Parse database
	conf.database.host, err = c.GetString("database", "host")
	if err != nil {
		return nil, err
	}
	conf.database.port, err = c.GetInt("database", "port")
	if err != nil {
		return nil, err
	}
	conf.database.user, err = c.GetString("database", "user")
	if err != nil {
		return nil, err
	}
	conf.database.password, err = c.GetString("database", "password")
	if err != nil {
		return nil, err
	}
	conf.database.dbname, err = c.GetString("database", "dbname")
	if err != nil {
		return nil, err
	}
	conf.database.sslmode, err = c.GetString("database", "sslmode")
	if err != nil {
		return nil, err
	}
	// For max_idle_connections missing should translates to -1
	if c.HasOption("database", "max_idle_connections") {
		conf.database.maxIdleConnections, err = c.GetInt("database", "max_idle_connections")
		if err != nil {
			return nil, err
		}
	} else {
		conf.database.maxIdleConnections = -1
	}

	// Parse election-clerk URL
	conf.electionclerkURL, err = c.GetString("", "electionclerk-url")
	if err != nil {
		return nil, err
	}
	_, err = url.Parse(conf.electionclerkURL)
	if err != nil {
		return nil, err
	}

	// Get the ballot-clerk public key
	body, err := httpGetAll(conf.electionclerkURL + "/publickey")
	if err != nil {
		return nil, err
	}
	PEMBlock, _ := pem.Decode(body)
	if PEMBlock.Type != "PUBLIC KEY" {
		return nil, errors.New("Could not parse Election Clerk Public Key")
	}
	cryptoKey, err := x509.ParsePKIXPublicKey(PEMBlock.Bytes)
	if err != nil {
		log.Fatal(err)
	}
	conf.clerkKey, err = NewPublicKeyFromCryptoKey(cryptoKey.(*rsa.PublicKey))
	if err != nil {
		return nil, err
	}

	// Get the admin users
	body, err = httpGetAll(conf.electionclerkURL + "/admins")
	if err != nil {
		return nil, err
	}
	conf.adminUsers, err = NewUserSet(body)
	if err != nil {
		return nil, err
	}

	// Get the list of elections
	body, err = httpGetAll(conf.electionclerkURL + "/election")
	if err != nil {
		return nil, err
	}
	if len(body) != 0 {
		rawElections := bytes.Split(body, []byte("\n\n\n"))
		for _, rawElection := range rawElections {
			election, err := NewElection(rawElection)
			if err != nil {
				return nil, err
			}
			conf.elections[election.ElectionID] = *election
		}
	}

	// Ingest the readme
	conf.readmePath, err = c.GetString("", "readme")
	if err != nil {
		return nil, err
	}
	conf.readme, err = ioutil.ReadFile(conf.readmePath)
	if err != nil {
		return nil, err
	}

	return &conf, nil
}
Example #19
0
func main() {
	cfg, err := goconf.ReadConfigFile("rse.config")
	if err != nil {
		panic(err)
	}

	m := martini.Classic()

	auth_handler := setupAuthHandler(cfg)

	m.Handlers(
		auth_handler,
		martini.Recovery(),
	)

	m.Get("/**", func(request *http.Request, params martini.Params, response http.ResponseWriter) string {
		topic := params["_1"]
		marker, marker_present := request.URL.Query()["marker"]

		// Get message from storage
		// if marker_present {
		//     storage.Get(topic, marker)
		// } else {
		//     storage.Get(topic)
		// }

		// Example return
		events := make([]map[string]string, 0)
		event := make(map[string]string)
		event["property"] = "value"
		events = append(events, event)
		jsonString, _ := json.Marshal(events)
		fmt.Println("Events: " + string(jsonString))

		tempReturn := "Getting messages on " + topic
		if marker_present {
			tempReturn += " with marker of " + marker[0]
		}
		// fmt.Println(tempReturn)
		// return tempReturn + "\r\n"

		response.Header()["Content-Type"] = []string{"application/json"}
		return string(jsonString) + "\r\n"
	})

	m.Post("/**", func(request *http.Request, params martini.Params, response http.ResponseWriter) {
		topic := params["_1"]

		body, err := ioutil.ReadAll(request.Body)
		if err != nil {
			panic("Unable to read body")
		}
		var valid_json interface{}
		err = json.Unmarshal(body, &valid_json)
		if err != nil {
			panic("Invalid JSON")
		}

		fmt.Println("Topic: " + topic)
		fmt.Println("Message: " + string(body))
		// Send message to storage
		// storage.Insert(topic, string(body))

		response.WriteHeader(http.StatusCreated)
	})

	m.Run()
}
Example #20
0
func main() {
	flag.Parse()

	cfg, err := conf.ReadConfigFile(*configFile)
	if err != nil {
		log.Exitf("Failed to read configuration file: %v", err)
	}
	clusterName := cfgOpt(cfg, "cluster", "name")
	if clusterName == "" {
		log.Exit("Unable to get cluster name")
	}

	anycastEnabled := config.DefaultEngineConfig().AnycastEnabled
	if opt := cfgOpt(cfg, "cluster", "anycast_enabled"); opt != "" {
		if anycastEnabled, err = cfg.GetBool("cluster", "anycast_enabled"); err != nil {
			log.Exitf("Unable to parse cluster anycast_enabled: %v", err)
		}
	}
	clusterVIPv4, err := cfgIP(cfg, "cluster", "vip_ipv4")
	if err != nil {
		log.Exitf("Unable to get cluster vip_ipv4: %v", err)
	}
	clusterVIPv6, err := cfgIP(cfg, "cluster", "vip_ipv6")
	if err != nil {
		log.Exitf("Unable to get cluster vip_ipv6: %v", err)
	}
	nodeIPv4, err := cfgIP(cfg, "cluster", "node_ipv4")
	if err != nil {
		log.Exitf("Unable to get cluster node_ipv4: %v", err)
	}
	nodeIPv6, err := cfgIP(cfg, "cluster", "node_ipv6")
	if err != nil {
		log.Exitf("Unable to get cluster node_ipv6: %v", err)
	}
	peerIPv4, err := cfgIP(cfg, "cluster", "peer_ipv4")
	if err != nil {
		log.Exitf("Unable to get cluster peer_ipv4: %v", err)
	}
	peerIPv6, err := cfgIP(cfg, "cluster", "peer_ipv6")
	if err != nil {
		log.Exitf("Unable to get cluster peer_ipv6: %v", err)
	}

	// The default VRID may be overridden via the config file.
	vrid := config.DefaultEngineConfig().VRID
	if cfg.HasOption("cluster", "vrid") {
		id, err := cfg.GetInt("cluster", "vrid")
		if err != nil {
			log.Exitf("Unable to get VRID: %v", err)
		}
		if id < 1 || id > 255 {
			log.Exitf("Invalid VRID %d - must be between 1 and 255 inclusive", id)
		}
		vrid = uint8(id)
	}

	// Optional primary, secondary and tertiary configuration servers.
	configServers := make([]string, 0)
	for _, level := range []string{"primary", "secondary", "tertiary"} {
		if server := cfgOpt(cfg, "config_server", level); server != "" {
			configServers = append(configServers, server)
		}
	}
	if len(configServers) == 0 {
		configServers = config.DefaultEngineConfig().ConfigServers
	}

	nodeInterface := config.DefaultEngineConfig().NodeInterface
	if opt := cfgOpt(cfg, "interface", "node"); opt != "" {
		nodeInterface = opt
	}
	lbInterface := config.DefaultEngineConfig().LBInterface
	if opt := cfgOpt(cfg, "interface", "lb"); opt != "" {
		lbInterface = opt
	}

	// Additional anycast addresses.
	serviceAnycastIPv4 := config.DefaultEngineConfig().ServiceAnycastIPv4
	serviceAnycastIPv6 := config.DefaultEngineConfig().ServiceAnycastIPv6
	if cfg.HasSection("extra_service_anycast") {
		opts, err := cfg.GetOptions("extra_service_anycast")
		if err != nil {
			log.Exitf("Unable to get extra_serivce_anycast options: %v", err)
		}
		for _, opt := range opts {
			ip, err := cfgIP(cfg, "extra_service_anycast", opt)
			if err != nil {
				log.Exitf("Unable to get extra_service_anycast option %q: %v", opt, err)
			}
			if !seesaw.IsAnycast(ip) {
				log.Exitf("%q is not an anycast address", ip)
			}
			if ip.To4() != nil {
				serviceAnycastIPv4 = append(serviceAnycastIPv4, ip)
			} else {
				serviceAnycastIPv6 = append(serviceAnycastIPv6, ip)
			}
		}
	}

	// Override some of the defaults.
	engineCfg := config.DefaultEngineConfig()
	engineCfg.AnycastEnabled = anycastEnabled
	engineCfg.ConfigFile = *configFile
	engineCfg.ConfigServers = configServers
	engineCfg.ClusterFile = *clusterFile
	engineCfg.ClusterName = clusterName
	engineCfg.ClusterVIP.IPv4Addr = clusterVIPv4
	engineCfg.ClusterVIP.IPv6Addr = clusterVIPv6
	engineCfg.LBInterface = lbInterface
	engineCfg.NCCSocket = *nccSocket
	engineCfg.Node.IPv4Addr = nodeIPv4
	engineCfg.Node.IPv6Addr = nodeIPv6
	engineCfg.NodeInterface = nodeInterface
	engineCfg.Peer.IPv4Addr = peerIPv4
	engineCfg.Peer.IPv6Addr = peerIPv6
	engineCfg.ServiceAnycastIPv4 = serviceAnycastIPv4
	engineCfg.ServiceAnycastIPv6 = serviceAnycastIPv6
	engineCfg.SocketPath = *socketPath
	engineCfg.VRID = vrid

	// Gentlemen, start your engines...
	engine := engine.NewEngine(&engineCfg)
	server.ShutdownHandler(engine)
	server.ServerRunDirectory("engine", 0, 0)
	// TODO(jsing): Drop privileges before starting engine.
	engine.Run()
}
Example #21
0
func InitConfig() {
	flag.Parse()

	// Parse data directory
	if Config.DataDir == "" {
		fmt.Println("  --data-dir option not specified. Please create a writable data directory and invoke deadci command with --data-dir=/path/to/data/dir")
		flag.CommandLine.PrintDefaults()
		os.Exit(2)
	}
	Config.DataDir = strings.TrimRight(Config.DataDir, "/ ")

	// Read the config file
	c, err := goconf.ReadConfigFile(Config.DataDir + "/deadci.ini")
	if err != nil {
		log.Fatal(err.Error() + ". Please ensure that your deadci.ini file is readable and in place at " + Config.DataDir + "/deadci.ini")
	}

	// Parse command
	cmd, err := c.GetString("", "command")
	if err != nil {
		log.Fatal(err)
	}
	cmd = strings.Trim(cmd, " ")
	if cmd == "" {
		log.Fatal("Missing command in deadci.ini. Please specify a command to run to build / test your repositories.")
	}
	Config.Command = strings.Split(cmd, " ")
	if len(Config.Command) == 0 {
		log.Fatal("Missing command in deadci.ini. Please specify a command to run to build / test your repositories.")
	}

	// Parse Port
	Config.Port, err = c.GetInt("", "port")
	if err != nil {
		log.Fatal(err)
	}

	// Parse Host
	Config.Host, err = c.GetString("", "host")
	if (err != nil && err.(goconf.GetError).Reason == goconf.OptionNotFound) || Config.Host == "" {
		Config.Host, err = os.Hostname()
		if err != nil {
			log.Fatal("Unable to determine hostname. Please specify a hostname in deadci.ini")
		}
	} else if err != nil {
		log.Fatal(err)
	}

	// Parse Temp Dir
	Config.TempDir, err = c.GetString("", "tempdir")
	if (err != nil && err.(goconf.GetError).Reason == goconf.OptionNotFound) || Config.TempDir == "" {
		Config.TempDir = os.TempDir()
	} else if err != nil {
		log.Fatal(err)
	}
	// Normalize tempdir string
	Config.TempDir = strings.TrimRight(Config.TempDir, "/")

	// Parse Github settings
	if c.HasSection("github") {
		Config.Github.Enabled, err = c.GetBool("github", "enabled")
		if err != nil && err.(goconf.GetError).Reason != goconf.OptionNotFound {
			log.Fatal(err)
		}
		if Config.Github.Enabled {
			Config.Github.Token, err = c.GetString("github", "token")
			if err != nil && err.(goconf.GetError).Reason != goconf.OptionNotFound {
				log.Fatal(err)
			}
			Config.Github.Secret, err = c.GetString("github", "secret")
			if err != nil && err.(goconf.GetError).Reason != goconf.OptionNotFound {
				log.Fatal(err)
			}
		}
	}

	// Parse clone style (git or https)
	Config.HttpsClone, err = c.GetBool("", "httpsclone")
	if err != nil && err.(goconf.GetError).Reason != goconf.OptionNotFound {
		log.Fatal(err)
	}

}
Example #22
0
func init() {
	configFile, _ = goconf.ReadConfigFile(utils.GetRuntimeDir("config.conf"))
}
Example #23
0
func main() {
	homedir := os.ExpandEnv("$HOME")

	// Print usage if there are no arguments
	if len(os.Args) < 2 {
		Usage()
	}

	// Find out a little about myself
	myaddr, err := localAddr()
	if err != nil {
		fmt.Printf("ERROR: %v", err)
	}

	// Pull host/port from config file
	f, err := goconf.ReadConfigFile(homedir + "/.xbmc_config")
	if err != nil {
		fmt.Printf("ERROR:%v\n", err)
		os.Exit(1)
	}
	host, _ := f.GetString("default", "host")
	port, _ := f.GetString("default", "port")

	tv_path, _ := f.GetString("", "tv_path")
	movie_path, _ := f.GetString("", "movie_path")
	music_path, _ := f.GetString("", "music_path")

	mac_addr, _ := f.GetString("", "mac_addr")
	bcast_port, _ := f.GetString("", "bcast_port")

	bcast_addr, err := localBcast(myaddr)
	if err != nil {
		fmt.Printf("ERROR: can't pull the network broadcast address.")
	}

	cmd := os.Args[1]
	args := os.Args[2:]

	req := &clientRequest{}
	req.Version = "2.0"
	req.Params = make(map[string]interface{})

	// Do some stuff
	fmt.Printf("Sending %v... ", cmd)
	switch cmd {
	case "ping":
		c := Connect(host, port)
		defer c.Close()
		req.Method = "JSONRPC.Ping"
		// Returns string
		var res string
		response, _ := Request(c, req, res)
		fmt.Printf("%v\n", response)
	case "reboot":
		c := Connect(host, port)
		defer c.Close()
		req.Method = "System.Reboot"
		var res string
		response, _ := Request(c, req, res)
		fmt.Printf("%v\n", response)
	case "scan":
		c := Connect(host, port)
		defer c.Close()
		req.Method = "VideoLibrary.Scan"
		var res string
		response, _ := Request(c, req, res)
		fmt.Printf("%v\n", response)
	case "scanmusic":
		c := Connect(host, port)
		defer c.Close()
		req.Method = "AudioLibrary.Scan"
		req.Params["directory"] = music_path
		var res string
		response, _ := Request(c, req, res)
		fmt.Printf("%v\n", response)
	case "scantv":
		c := Connect(host, port)
		defer c.Close()
		req.Method = "VideoLibrary.Scan"
		//req.Params["directory"] = string
		req.Params["directory"] = tv_path
		// Returns string
		var res string
		response, _ := Request(c, req, res)
		fmt.Printf("%v\n", response)
	case "scanmovies":
		c := Connect(host, port)
		defer c.Close()
		req.Method = "VideoLibrary.Scan"
		req.Params["directory"] = movie_path
		// Still returns string
		var res string
		response, _ := Request(c, req, res)
		fmt.Printf("%v\n", response)
	case "clean":
		c := Connect(host, port)
		defer c.Close()
		req.Method = "VideoLibrary.Clean"
		// Returns string
		var res string
		response, _ := Request(c, req, res)
		fmt.Printf("%v\n", response)
	case "cleanmusic":
		c := Connect(host, port)
		defer c.Close()
		req.Method = "AudioLibrary.Clean"
		var res string
		response, _ := Request(c, req, res)
		fmt.Printf("%v\n", response)
	case "sendtext":
		c := Connect(host, port)
		defer c.Close()
		// takes next command line argument as input
		// use quotes for strings on the command line
		req.Method = "Input.SendText"
		req.Params["text"] = args[0]
		var res string
		// To be honest, I don't know what this returns
		response, _ := Request(c, req, res)
		fmt.Printf("%v\n", response)
	case "notify":
		c := Connect(host, port)
		defer c.Close()
		// takes next two command line arguments as title
		// and message
		req.Method = "GUI.ShowNotification"
		req.Params["title"] = args[0]
		req.Params["message"] = args[1]
		var res string
		// Returns something other than a string
		response, _ := Request(c, req, res)
		fmt.Printf("%v\n", response)
	case "setvolume":
		c := Connect(host, port)
		defer c.Close()
		req.Method = "Application.SetVolume"
		req.Params["volume"], _ = strconv.Atoi(args[0])
		//res := &clientResponse{}
		var res string
		response, _ := Request(c, req, res)
		fmt.Printf("%v\n", response)
	case "pause":
		c := Connect(host, port)
		defer c.Close()
		req.Method = "Player.PlayPause"
		req.Params[""] = ""
	case "wake":
		err := xbmcwol.SendMagicPacket(mac_addr, bcast_addr.String(), bcast_port)
		if err != nil {
			fmt.Printf("ERROR:%v\n", err)
		}
	case "suspend":
		c := Connect(host, port)
		defer c.Close()
		req.Method = "System.Suspend"
		var res string
		response, _ := Request(c, req, res)
		fmt.Printf("%v\n", response)
	default:
		Usage()
	}
}
Example #24
0
// main reads the config file, connects to each IMAP server in a separate thread
// and watches the notify channel for messages telling it to update the status
// icon.
func main() {
	conf, err := goconf.ReadConfigFile(os.Getenv("HOME") + "/.hasmailrc")
	if err != nil {
		fmt.Println("Failed to load configuration file, exiting...\n", err)
		return
	}

	// This channel will be used to tell us if we should exit the program
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)

	// GTK engage!
	gtk.Init(&os.Args)
	glib.SetApplicationName("hasmail")
	defer gtk.MainQuit()

	// Set up the tray icon
	si := gtk.NewStatusIconFromStock(gtk.STOCK_DISCONNECT)
	si.SetTitle("hasmail")
	si.SetTooltipMarkup("Not connected")

	// Set up the tray icon right click menu
	mi := gtk.NewMenuItemWithLabel("Quit")
	mi.Connect("activate", func() {
		quit <- syscall.SIGINT
	})
	nm := gtk.NewMenu()
	nm.Append(mi)
	nm.ShowAll()
	si.Connect("popup-menu", func(cbx *glib.CallbackContext) {
		nm.Popup(nil, nil, gtk.StatusIconPositionMenu, si, uint(cbx.Args(0)), uint32(cbx.Args(1)))
	})

	/* If the user clicks the tray icon, here's what happens:
	 *   - if only a single account has new emails, and a click command has been
	 *     specified for that account, execute it
	 *   - if the user has specified a default click handler, execute that
	 *   - otherwise, do nothing
	 */
	si.Connect("activate", func(cbx *glib.CallbackContext) {
		command, geterr := conf.GetString("default", "click")
		nonZero := 0
		nonZeroAccount := ""

		for account, unseenList := range parts.Unseen {
			if len(unseenList) > 0 {
				nonZero++
				nonZeroAccount = account
			}
		}

		// Can't just use HasOption here because that also checks "default" section,
		// even though Get* doesn't...
		if nonZero == 1 {
			acommand, ageterr := conf.GetString(nonZeroAccount, "click")
			if ageterr == nil {
				command = acommand
				geterr = ageterr
			}
		}

		if geterr == nil {
			fmt.Printf("Executing user command: %s\n", command)
			shell := os.Getenv("SHELL")
			if shell == "" {
				shell = "/bin/sh"
			}

			sh := exec.Command(shell, "-c", command)
			sh.Env = os.Environ()
			err = sh.Start()
			if err != nil {
				fmt.Printf("Failed to run command '%s' on click\n", command)
				fmt.Println(err)
			}
		} else {
			fmt.Println("No action defined for click\n", geterr)
		}
	})

	go gtk.Main()

	// Connect to all accounts
	sections := conf.GetSections()
	notify := make(chan bool, len(sections))
	for _, account := range sections {
		// default isn't really an account
		if account == "default" {
			continue
		}

		initConnection(notify, conf, account)
	}

	// Let the user know that we've now initiated all the connections
	si.SetFromStock(gtk.STOCK_CONNECT)
	si.SetTooltipText("Connecting")

	// Keep updating the status icon (or quit if the user wants us to)
	for {
		select {
		case <-quit:
			return
		case <-notify:
			totUnseen := 0
			s := ""
			for account, e := range parts.Errs {
				if e == 0 {
					continue
				}

				s += account + ": "

				switch e {
				case 1:
					s += "Connection failed!"
				case 2:
					s += "IDLE not supported!"
				case 3:
					s += "No login credentials given!"
				case 4:
					s += "Login failed!"
				case 5:
					s += "Connection dropped!"
				}

				s += "\n"
			}

			for account, unseenList := range parts.Unseen {
				if parts.Errs[account] != 0 {
					continue
				}

				numUnseen := len(unseenList)

				if numUnseen >= 0 {
					totUnseen += numUnseen
				}
				s += account + ": "

				switch numUnseen {
				case 0:
					s += "No new messages"
				case 1:
					s += "One new message"
				default:
					s += fmt.Sprintf("%d new messages", numUnseen)
				}

				s += "\n"
			}

			// get rid of trailing newline
			s = strings.TrimRight(s, "\n")
			si.SetTooltipText(s)

			// http://developer.gnome.org/gtk3/3.0/gtk3-Stock-Items.html
			switch totUnseen {
			case 0:
				si.SetFromStock(gtk.STOCK_NEW)
			case 1:
				si.SetFromStock(gtk.STOCK_DND)
			default:
				si.SetFromStock(gtk.STOCK_DND_MULTIPLE)
			}
		}
	}
}
Example #25
0
func OpenConfigFile(filename string) (err error) {
	//06.05.2014 naj - first read the config file
	ConfigFile, err = goconf.ReadConfigFile(filename)
	return
}
Example #26
0
func LoadConfig(path *string) bool {
	c, err := goconf.ReadConfigFile(*path)
	if err != nil {
		LogError("Error reading config file: %s: %s", *path, err)
		return false
	}
	Config.Path = *path
	logging, err := c.GetString("system", "logging")
	if err == nil {
		LogReload(logging)
	}
	LogInfo("Load configurations from %s", *path)

	// Scheduler Config
	Config.Scheduler.IntervalSec, err = c.GetInt("scheduler", "interval_sec")
	if err != nil {
		LogWarn("%s", err)
	}
	Config.Scheduler.Site, err = c.GetString("scheduler", "site")
	if err != nil {
		LogWarn("%s", err)
	}

	Config.Scheduler.ApiToken, err = c.GetString("scheduler", "api_token")
	if err != nil {
		LogWarn("%s", err)
	}

	zone, err := c.GetString("recorder", "timezone")
	if err != nil {
		LogWarn("%s", err)
		zone = "Local"
	}
	Config.Recorder.Timezone, err = time.LoadLocation(zone)
	if err != nil {
		LogWarn("%s", err)
	}

	// recorder
	Config.Recorder.BufferSec, err = c.GetInt("recorder", "buffer_sec")
	if err != nil {
		LogWarn("%s", err)
	}
	Config.Recorder.Recpt1, err = c.GetString("recorder", "recpt1")
	if err != nil {
		LogWarn("%s", err)
	}

	Config.Recorder.B25, err = c.GetBool("recorder", "b25")
	if err != nil {
		LogWarn("%s", err)
	}

	Config.Recorder.BaseDir, err = c.GetString("recorder", "basedir")
	if err != nil {
		LogWarn("%s", err)
	}

	Config.Recorder.RetryWait, err = c.GetInt("recorder", "retry_wait")
	if err != nil {
		LogWarn("%s", err)
	}

	return true
}
Example #27
0
func main() {
	// Begin here.
	/* -------------------------------------  */
	/* 			Boilerplate					  */
	/* -------------------------------------  */
	/*
		Setting up Logging, this is standard practice for all go programs
	*/
	pwd, err := os.Getwd() // get present working directory
	if err != nil {
		log.Fatal(err)
	}
	fo, err := os.Create(pwd + string(filepath.Separator) + "worker.log") // create log file in current dir
	if err != nil {
		log.Fatal(err)
	}
	log.SetOutput(io.Writer(fo))
	// 		Done setting up Logging
	if func() bool {
		_confMap = make(map[string]string)
		pwd, err := os.Getwd() // get present working directory
		if err != nil {
			log.Fatal(err)
		}
		path := pwd + string(filepath.Separator) + "cockpit" + string(filepath.Separator) + "workerconf"
		_, err = os.Stat(path)
		if err != nil {
			log.Fatal("Config file not found. Config file is located in same directory as executable in a folder .arwen/config")
		}
		_cfile, err = goconf.ReadConfigFile(path)
		if err != nil {
			log.Fatal("Error reading config file." + err.Error())
		}
		return true
	}() {
		log.Print("Loaded Logging, starting up server ...")
	} else {
		log.Fatal("Error loading conf file ...")
	}

	poller := time.NewTicker(time.Duration(int64(5) * int64(time.Second))) // Actual time variable that is a counter]

	// Make a listener.
	go func() {
		router := mux.NewRouter()
		router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("{\"status\":\"alive\"}"))
		})
		router.HandleFunc("/detail", func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("{\"status\":\"detail\"}"))
		})
		router.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) {
			w.Write([]byte("{\"status\":\"status\"}"))
		})
		http.Handle("/", router)
		http.ListenAndServe(":63001", nil) // TODO add this to conf
	}()
	for {
		select {
		case item := <-alert:
			// This handles alert, and is recieved at push
			// Dial port 6300
			log.Print(item)
		case item := <-data:
			log.Print(item)
		case <-poller.C:
			// Poll for values at certain period of time
			go func() {
				// Checks the commands and raises alerts
				// Read the command.json file
				file, e := ioutil.ReadFile("./cockpit/command.json")
				if e != nil {
					log.Fatal("File Error")
				}
				var cjson interface{}
				err := json.Unmarshal(file, &cjson)
				if err != nil {
					log.Fatal("Error reading command.json")
				}
				for _, val := range cjson.(map[string]interface{})["commands"].(map[string]interface{}) {
					command := val.(map[string]interface{})["command"].(string)
					argument := strings.Fields(val.(map[string]interface{})["argument"].(string))
					_, err := exec.Command(command, argument...).Output()
					if err != nil {
						log.Print("Unable to run program")
						// This means the execution failed.
						//We raise the alert request here.
						_, err := http.PostForm("http://localhost:63000/alert",
							url.Values{"alert": {"TestServer1"}, "error": {"Error Running Program"}})
						if err != nil {
							// og
							log.Print("Error sending data to server")
						}
					}
				}
			}()
		}
	}

}