func init() { chanmap = make(map[string]*hbot.IrcChannel) config, err := globalconf.NewWithOptions(&globalconf.Options{ Filename: configFile, }) if err != nil { log.Fatalf("Cannot parse configuration file: %s", err) } globalconf.Register("tumblr", tumblrConf) globalconf.Register("twitter", twitterConf) globalconf.Register("logger", loggerConf) globalconf.Register("commands", commandsConf) config.ParseAll() }
func ReadDaqConfig(fileLocation string) *DaqConfig { f := flag.NewFlagSet("daq", flag.ContinueOnError) flagDaqInterval := f.Uint("daq_interval", 5, "Daq interval in minutes") flagMockerOn := f.Bool("daq_mocker_on", false, "Mocker state") globalconf.Register("daq", f) g, err := globalconf.NewWithOptions(&globalconf.Options{ Filename: fileLocation, }) if err != nil { log.Printf("[config][warning] Could not parse config file %s"+ " Error: %s, Falling back to default settings", fileLocation, err.Error()) } else { g.ParseAll() } return &DaqConfig{ Interval: *flagDaqInterval, MockerOn: *flagMockerOn, } }
func ReadDbConfig(fileLocation string) *DatabaseConfig { f := flag.NewFlagSet("database", flag.ContinueOnError) flagDBHostname := f.String("db_host", "127.0.0.1", "Database hostname") flagDBPort := f.Uint("db_port", 5432, "Database port") flagDBUsername := f.String("db_username", "ubi", "Database username") flagDBPassword := f.String("db_password", "password", "Database password") flagDBName := f.String("db_name", "ubi_course", "Database name") flagDBSSLMode := f.String("db_sslmode", "disable", "Database SSL mode") globalconf.Register("database", f) g, err := globalconf.NewWithOptions(&globalconf.Options{ Filename: fileLocation, }) if err != nil { log.Printf("[config][warning] Could not parse config file '%s': %s. "+ "Falling back to default settings", fileLocation, err.Error()) } else { g.ParseAll() } return &DatabaseConfig{ Hostname: *flagDBHostname, Port: uint16(*flagDBPort), Username: *flagDBUsername, Password: *flagDBPassword, Name: *flagDBName, SSLMode: *flagDBSSLMode, } }
func ReadApiConfig(fileLocation string) (a *ApiConfig) { f := flag.NewFlagSet("api", flag.ContinueOnError) flagApiHostname := f.String("api_host", "127.0.0.1", "Api hostname") flagApiPort := f.Uint("api_port", 8844, "Api port") globalconf.Register("api", f) g, err := globalconf.NewWithOptions(&globalconf.Options{ Filename: fileLocation, }) if err != nil { log.Printf("[config][warning] Could not parse config file %s"+ " Error: %s, Falling back to default settings", fileLocation, err.Error()) } else { g.ParseAll() } return &ApiConfig{ Host: *flagApiHostname, Port: uint16(*flagApiPort), } }
func ReadConfig(filename string) Config { dbFlagSet := flag.NewFlagSet("mysql", flag.ExitOnError) flagUser := dbFlagSet.String("username", "", "Database username") flagPass := dbFlagSet.String("password", "", "Database password") flagHost := dbFlagSet.String("host", "localhost", "Database host") flagDbName := dbFlagSet.String("database", "", "Database name") globalconf.Register("mysql", dbFlagSet) conf, err := globalconf.NewWithOptions(&globalconf.Options{ Filename: filename, }) if err != nil { log.Fatalf(err.Error()) } conf.ParseAll() return Config{ Username: *flagUser, Host: *flagHost, Password: *flagPass, Database: *flagDbName, } }
// Register attaches services, to be initialized in a future date. func Register(name string, rcvr Service, fs *flag.FlagSet) error { if _, exists := services[name]; exists { return fmt.Errorf("Service '%s' already exists, refusing to overwrite", name) } if fs != nil { globalconf.Register(name, fs) } services[name] = rcvr return nil }
func ReadMockerConfig(fileLocation string) *MockerConfig { f := flag.NewFlagSet("mocker", flag.ContinueOnError) flagMockerAmount := f.Uint("mocker_place_amount", 5, "Amount of mocked places") flagMockerRecordsMin := f.Uint("mocker_records_min", 0, "Minimum amount of queuers") flagMockerRecordsMax := f.Uint("mocker_records_max", 5, "Maximum amount of queuers") flagMockerTimeMin := f.Uint("mocker_time_min", 1, "Minimum time in queue") flagMockerTimeMax := f.Uint("mocker_time_max", 50, "Maximum time in queue") flagMockerHistoric := f.Bool("mocker_historic", false, "Enable historic data generation") flagMockerHistoricWeeks := f.Uint("mocker_historic_weeks", 0, "Number of weeks to generate historic data") flagMockerHistoricInterval := f.Uint("mocker_historic_interval", 15, "Interval for gistoric records") globalconf.Register("mocker", f) g, err := globalconf.NewWithOptions(&globalconf.Options{ Filename: fileLocation, }) if err != nil { log.Printf("[config][warning] Could not parse config file %s"+ " Error: %s, Falling back to default settings", fileLocation, err.Error()) } else { g.ParseAll() } return &MockerConfig{ PlaceAmount: *flagMockerAmount, RecordsMin: *flagMockerRecordsMin, RecordsMax: *flagMockerRecordsMax, TimeMin: *flagMockerTimeMin, TimeMax: *flagMockerTimeMax, Historic: *flagMockerHistoric, HistoricWeek: *flagMockerHistoricWeeks, HistoricInterval: *flagMockerHistoricInterval, } }
func Main() { userset := flag.NewFlagSet("fleet", flag.ExitOnError) printVersion := userset.Bool("version", false, "Print the version and exit") cfgPath := userset.String("config", "", fmt.Sprintf("Path to config file. Fleet will look for a config at %s by default.", DefaultConfigFile)) userset.Usage = func() { fmt.Fprintf(os.Stderr, "%s\nUsage of %s:\n", FleetdDescription, os.Args[0]) userset.PrintDefaults() } err := userset.Parse(os.Args[1:]) if err != nil { userset.Usage() os.Exit(1) } args := userset.Args() if len(args) > 0 { // support `fleetd version` the same as `fleetd --version` if args[0] == "version" { *printVersion = true } else { fmt.Fprintf(os.Stderr, "%s takes no arguments. Did you mean to invoke fleetctl instead?\n", os.Args[0]) userset.Usage() os.Exit(1) } } if *printVersion { fmt.Println("fleetd version", version.Version) os.Exit(0) } log.Infof("Starting fleetd version %v", version.Version) cfgset := flag.NewFlagSet("fleet", flag.ExitOnError) cfgset.Int("verbosity", 0, "Logging level") cfgset.Var(&pkg.StringSlice{"http://127.0.0.1:2379", "http://127.0.0.1:4001"}, "etcd_servers", "List of etcd endpoints") cfgset.String("etcd_username", "", "username for secure etcd communication") cfgset.String("etcd_password", "", "password for secure etcd communication") cfgset.String("etcd_keyfile", "", "SSL key file used to secure etcd communication") cfgset.String("etcd_certfile", "", "SSL certification file used to secure etcd communication") cfgset.String("etcd_cafile", "", "SSL Certificate Authority file used to secure etcd communication") cfgset.String("etcd_key_prefix", registry.DefaultKeyPrefix, "Keyspace for fleet data in etcd") cfgset.Float64("etcd_request_timeout", 1.0, "Amount of time in seconds to allow a single etcd request before considering it failed.") cfgset.Float64("engine_reconcile_interval", 2.0, "Interval at which the engine should reconcile the cluster schedule in etcd.") cfgset.String("public_ip", "", "IP address that fleet machine should publish") cfgset.String("metadata", "", "List of key-value metadata to assign to the fleet machine") cfgset.String("agent_ttl", agent.DefaultTTL, "TTL in seconds of fleet machine state in etcd") cfgset.String("units_directory", "/run/fleet/units/", "Path to the fleet units directory") cfgset.Bool("systemd_user", false, "When true use systemd --user)") cfgset.Int("token_limit", 100, "Maximum number of entries per page returned from API requests") cfgset.Bool("enable_grpc", false, "When possible, uses grpc to communicate between engine and agent") cfgset.Bool("disable_engine", false, "Disable the engine entirely, use with care") cfgset.Bool("disable_watches", false, "Disable the use of etcd watches. Increases scheduling latency") cfgset.Bool("verify_units", false, "DEPRECATED - This option is ignored") cfgset.String("authorized_keys_file", "", "DEPRECATED - This option is ignored") globalconf.Register("", cfgset) cfg, err := getConfig(cfgset, *cfgPath) if err != nil { log.Fatal(err) } log.Debugf("Creating Server") srv, err := server.New(*cfg, nil) if err != nil { log.Fatalf("Failed creating Server: %v", err) } srv.Run() srvMutex := sync.Mutex{} reconfigure := func() { log.Infof("Reloading configuration from %s", *cfgPath) srvMutex.Lock() defer srvMutex.Unlock() cfg, err := getConfig(cfgset, *cfgPath) if err != nil { log.Fatal(err) } log.Infof("Restarting server components") srv.SetReconfigServer(true) // Get Server.listeners[] to keep it for a new server, // before killing the old server. oldListeners := srv.GetApiServerListeners() srv.Kill() // The new server takes the original listeners. srv, err = server.New(*cfg, oldListeners) if err != nil { log.Fatal(err) } srv.Run() srv.SetReconfigServer(false) } shutdown := func() { log.Infof("Gracefully shutting down") srvMutex.Lock() defer srvMutex.Unlock() srv.Kill() srv.Purge() os.Exit(0) } writeState := func() { log.Infof("Dumping server state") srvMutex.Lock() defer srvMutex.Unlock() encoded, err := json.Marshal(srv) if err != nil { log.Errorf("Failed to dump server state: %v", err) return } if _, err := os.Stdout.Write(encoded); err != nil { log.Errorf("Failed to dump server state: %v", err) return } os.Stdout.Write([]byte("\n")) log.Debugf("Finished dumping server state") } signals := map[os.Signal]func(){ syscall.SIGHUP: reconfigure, syscall.SIGTERM: shutdown, syscall.SIGINT: shutdown, syscall.SIGUSR1: writeState, } listenForSignals(signals) }
func main() { ctxLog = log.WithField("version", version.Version).WithField("git-hash", version.GitHash).WithField("build-time", version.BuiltTimestamp) userset := flag.NewFlagSet("apihostd", flag.ExitOnError) printVersion := userset.Bool("version", false, "Print the version and exit") cfgPath := userset.String("config", DefaultConfigFile, fmt.Sprintf("Path to config file. apihostd will look for a config at %s by default.", DefaultConfigFile)) err := userset.Parse(os.Args[1:]) if err == flag.ErrHelp { userset.Usage() os.Exit(1) } args := userset.Args() if len(args) == 1 && args[0] == "version" { *printVersion = true } else if len(args) != 0 { userset.Usage() os.Exit(1) } if *printVersion { fmt.Printf("Version: %s \n", version.Version) fmt.Printf("Git hash: %s \n", version.GitHash) fmt.Printf("Build timestamp: %s \n", version.BuiltTimestamp) os.Exit(0) } cfgset := flag.NewFlagSet("apihostd", flag.ExitOnError) // Generic cfgset.Int("verbosity", 0, "Logging level") cfgset.String("ip", "", "Server IP to bind") cfgset.String("port", "", "Port to listen on") // CORS cfgset.String("cors_allowed_origins", "*", "A list of origins a cross-domain request can be executed from") cfgset.String("cors_allowed_methods", "GET,POST,DELETE", "A list of methods the client is allowed to use with cross-domain requests") cfgset.String("cors_allowed_headers", "origin, content-type, accept, authorization", "A list of non simple headers the client is allowed to use with cross-domain requests.") cfgset.String("cors_exposed_headers", "", "Indicates which headers are safe to expose to the API of a CORS API specification") cfgset.Bool("cors_allow_credentials", false, "Indicates whether the request can include user credentials like cookies, HTTP authentication or client side SSL certificates.") cfgset.Int("cors_max_age", 0, "Indicates how long (in seconds) the results of a preflight request can be cached.") cfgset.Bool("cors_options_pass_through", false, "Instructs preflight to let other potential next handlers to process the OPTIONS method.") cfgset.Bool("cors_debug", false, "Debugging flag adds additional output to debug server side CORS issues.") // JWT cfgset.String("jwt_sign_key", "", "JWT signing key") globalconf.Register("", cfgset) cfg, err := getConfig(cfgset, *cfgPath) if err != nil { ctxLog.Fatalf(err.Error()) } srv, err := server.New(*cfg) if err != nil { ctxLog.Fatalf("Failed creating Server: %v", err.Error()) } srv.Run() reconfigure := func() { ctxLog.Infof("Reloading configuration from %s", *cfgPath) cfg, err := getConfig(cfgset, *cfgPath) if err != nil { ctxLog.Fatalf(err.Error()) } ctxLog.Infof("Restarting server components") srv.Stop() srv, err = server.New(*cfg) if err != nil { ctxLog.Fatalf(err.Error()) } srv.Run() } shutdown := func() { ctxLog.Infof("Gracefully shutting down") srv.Stop() srv.Purge() os.Exit(0) } writeState := func() { ctxLog.Infof("Dumping server state") encoded, err := json.Marshal(srv) if err != nil { ctxLog.Errorf("Failed to dump server state: %v", err) return } if _, err := os.Stdout.Write(encoded); err != nil { ctxLog.Errorf("Failed to dump server state: %v", err) return } os.Stdout.Write([]byte("\n")) } signals := map[os.Signal]func(){ syscall.SIGHUP: reconfigure, syscall.SIGTERM: shutdown, syscall.SIGINT: shutdown, syscall.SIGUSR1: writeState, syscall.SIGABRT: shutdown, } listenForSignals(signals) }