func NewStore(stats RuntimeStats) *Storage { storeType := "memory" var redisStore *RedisStore if viper.GetBool("redis_enabled") { redisHost := viper.GetString("redis_port_6379_tcp_addr") redisPort := viper.GetInt("redis_port_6379_tcp_port") connPoolSize := viper.GetInt("redis_connection_pool_size") numConsumers := viper.GetInt("redis_activity_consumers") redisStore = newRedisStore(redisHost, redisPort, numConsumers, connPoolSize, stats) storeType = "redis" } var Store = Storage{ &MemoryStore{make(map[string]map[string]*Socket), make(map[string]map[string]*Socket), 0}, redisStore, storeType, sync.RWMutex{}, sync.RWMutex{}, } return &Store }
func Server() { app, err := NewApplication() if err != nil { logrus.Fatal(err.Error()) } middle, err := app.middlewareStruct() if err != nil { logrus.Fatal(err.Error()) } logrus.Printf("Running on http://%s:%d", viper.GetString("bind"), viper.GetInt("port")) logrus.Printf("IPA server: %s", viper.GetString("ipahost")) http.Handle("/", middle) certFile := viper.GetString("cert") keyFile := viper.GetString("key") if certFile != "" && keyFile != "" { http.ListenAndServeTLS(fmt.Sprintf("%s:%d", viper.GetString("bind"), viper.GetInt("port")), certFile, keyFile, nil) } else { logrus.Warn("**WARNING*** SSL/TLS not enabled. HTTP communication will not be encrypted and vulnerable to snooping.") http.ListenAndServe(fmt.Sprintf("%s:%d", viper.GetString("bind"), viper.GetInt("port")), nil) } }
//Config configure Clair from configFile func Config() { fmtURI(viper.GetString("clair.uri"), viper.GetInt("clair.port")) priority = viper.GetString("clair.priority") healthPort = viper.GetInt("clair.healthPort") Report.Path = viper.GetString("clair.report.path") Report.Format = viper.GetString("clair.report.format") }
func resetPassword(app *Application, answer *model.SecurityAnswer, token *model.Token, r *http.Request) error { ans := r.FormValue("answer") pass := r.FormValue("password") pass2 := r.FormValue("password2") if len(pass) < viper.GetInt("min_passwd_len") || len(pass2) < viper.GetInt("min_passwd_len") { return errors.New(fmt.Sprintf("Please set a password at least %d characters in length.", viper.GetInt("min_passwd_len"))) } if pass != pass2 { return errors.New("Password do not match. Please confirm your password.") } if utf8.RuneCountInString(ans) < 2 || utf8.RuneCountInString(ans) > 100 { return errors.New("Invalid answer. Must be between 2 and 100 characters long.") } err := bcrypt.CompareHashAndPassword([]byte(answer.Answer), []byte(ans)) if err != nil { return errors.New("The security answer you provided does not match. Please check that you are entering the correct answer.") } // Setup password in FreeIPA err = setPassword(token.UserName, "", pass) if err != nil { if ierr, ok := err.(*ipa.ErrPasswordPolicy); ok { logrus.WithFields(logrus.Fields{ "uid": token.UserName, "error": ierr.Error(), }).Error("password does not conform to policy") return errors.New("Your password is too weak. Please ensure your password includes a number and lower/upper case character") } if ierr, ok := err.(*ipa.ErrInvalidPassword); ok { logrus.WithFields(logrus.Fields{ "uid": token.UserName, "error": ierr.Error(), }).Error("invalid password from FreeIPA") return errors.New("Invalid password.") } logrus.WithFields(logrus.Fields{ "uid": token.UserName, "error": err.Error(), }).Error("failed to set user password in FreeIPA") return errors.New("Fatal system error") } // Destroy token err = model.DestroyToken(app.db, token.Token) if err != nil { logrus.WithFields(logrus.Fields{ "uid": token.UserName, "error": err.Error(), }).Error("failed to remove token from database") return errors.New("Fatal system error") } return nil }
//OpenRedis open redis func OpenRedis() *redis.Pool { return &redis.Pool{ MaxIdle: 3, IdleTimeout: 240 * time.Second, Dial: func() (redis.Conn, error) { c, e := redis.Dial( "tcp", fmt.Sprintf( "%s:%d", viper.GetString("redis.host"), viper.GetInt("redis.port"), ), ) if e != nil { return nil, e } if _, e = c.Do("SELECT", viper.GetInt("redis.db")); e != nil { c.Close() return nil, e } return c, nil }, TestOnBorrow: func(c redis.Conn, t time.Time) error { _, err := c.Do("PING") return err }, } }
// OnDisconnect event. Terminates MumbleDJ process or retries connection if // automatic connection retries are enabled. func (dj *MumbleDJ) OnDisconnect(e *gumble.DisconnectEvent) { dj.Queue.Reset() if viper.GetBool("connection.retry_enabled") && (e.Type == gumble.DisconnectError || e.Type == gumble.DisconnectKicked) { logrus.WithFields(logrus.Fields{ "interval_secs": fmt.Sprintf("%d", viper.GetInt("connection.retry_interval")), "attempts": fmt.Sprintf("%d", viper.GetInt("connection.retry_attempts")), }).Warnln("Disconnected from server. Retrying connection...") success := false for retries := 0; retries < viper.GetInt("connection.retry_attempts"); retries++ { logrus.Infoln("Retrying connection...") if client, err := gumble.DialWithDialer(new(net.Dialer), viper.GetString("connection.address")+":"+viper.GetString("connection.port"), dj.GumbleConfig, dj.TLSConfig); err == nil { dj.Client = client logrus.Infoln("Successfully reconnected to the server!") success = true break } time.Sleep(time.Duration(viper.GetInt("connection.retry_interval")) * time.Second) } if !success { dj.KeepAlive <- true logrus.Fatalln("Could not reconnect to server. Exiting...") } } else { dj.KeepAlive <- true logrus.Fatalln("Disconnected from server. No reconnect attempts will be made.") } }
func createEventHubServer() (net.Listener, *grpc.Server, error) { var lis net.Listener var grpcServer *grpc.Server var err error if peer.ValidatorEnabled() { lis, err = net.Listen("tcp", viper.GetString("peer.validator.events.address")) if err != nil { return nil, nil, fmt.Errorf("failed to listen: %v", err) } //TODO - do we need different SSL material for events ? var opts []grpc.ServerOption if comm.TLSEnabled() { creds, err := credentials.NewServerTLSFromFile( viper.GetString("peer.tls.cert.file"), viper.GetString("peer.tls.key.file")) if err != nil { return nil, nil, fmt.Errorf("Failed to generate credentials %v", err) } opts = []grpc.ServerOption{grpc.Creds(creds)} } grpcServer = grpc.NewServer(opts...) ehServer := producer.NewEventsServer( uint(viper.GetInt("peer.validator.events.buffersize")), viper.GetInt("peer.validator.events.timeout")) pb.RegisterEventsServer(grpcServer, ehServer) } return lis, grpcServer, err }
func spikyHorizontalMaze() *Maze { z := fullMaze() ySize := viper.GetInt("height") xSize := viper.GetInt("width") middleX := xSize / 2 middleY := ySize / 2 for x := 0; x < xSize; x++ { for y := 0; y < ySize; y++ { if x > 0 && x != (middleX+1) { z.rooms[y][x].Walls.Left = false } if x < (xSize-1) && x != middleX { z.rooms[y][x].Walls.Right = false } if x == 0 && y > 0 { z.rooms[y][x].Walls.Top = false } if x == 0 && y < (ySize-1) { z.rooms[y][x].Walls.Bottom = false } if x == (xSize-1) && y > 0 { z.rooms[y][x].Walls.Top = false } if x == (xSize-1) && y < (ySize-1) { z.rooms[y][x].Walls.Bottom = false } } } z.rooms[0][middleX].Walls.Right = false z.rooms[ySize-1][middleX].Walls.Right = false z.rooms[0][middleX+1].Walls.Left = false z.rooms[ySize-1][middleX+1].Walls.Left = false z.rooms[middleY][xSize-1].Walls.Bottom = true z.rooms[middleY+1][xSize-1].Walls.Top = true // Random* icarus & treasure icarusX := rand.Intn(xSize) icarusY := rand.Intn(ySize) treasureX := rand.Intn(xSize) treasureY := rand.Intn(ySize) // *Don't let them be in the same cell, no fun then for { if icarusX != treasureX || icarusY != treasureY { break } else { treasureX = rand.Intn(xSize) treasureY = rand.Intn(ySize) } } z.SetStartPoint(icarusX, icarusY) z.SetTreasure(treasureX, treasureY) return z }
func ThreadlessNewStateTransferState(stack PartialStack) *StateTransferState { var err error sts := &StateTransferState{} sts.stateTransferListenersLock = &sync.Mutex{} sts.stack = stack sts.id, _, err = stack.GetNetworkHandles() if nil != err { logger.Debug("Error resolving our own PeerID, this shouldn't happen") sts.id = &protos.PeerID{"ERROR_RESOLVING_ID"} } sts.asynchronousTransferInProgress = false sts.RecoverDamage = viper.GetBool("statetransfer.recoverdamage") sts.stateValid = true // Assume our starting state is correct unless told otherwise sts.validBlockRanges = make([]*blockRange, 0) sts.blockVerifyChunkSize = uint64(viper.GetInt("statetransfer.blocksperrequest")) if sts.blockVerifyChunkSize == 0 { panic(fmt.Errorf("Must set statetransfer.blocksperrequest to be nonzero")) } sts.initiateStateSync = make(chan *syncMark) sts.blockHashReceiver = make(chan *blockHashReply, 1) sts.blockSyncReq = make(chan *blockSyncReq) sts.threadExit = make(chan struct{}) sts.blockThreadIdle = true sts.stateThreadIdle = true sts.blockThreadIdleChan = make(chan struct{}) sts.stateThreadIdleChan = make(chan struct{}) sts.DiscoveryThrottleTime = 1 * time.Second // TODO make this configurable sts.BlockRequestTimeout, err = time.ParseDuration(viper.GetString("statetransfer.timeout.singleblock")) if err != nil { panic(fmt.Errorf("Cannot parse statetransfer.timeout.singleblock timeout: %s", err)) } sts.StateDeltaRequestTimeout, err = time.ParseDuration(viper.GetString("statetransfer.timeout.singlestatedelta")) if err != nil { panic(fmt.Errorf("Cannot parse statetransfer.timeout.singlestatedelta timeout: %s", err)) } sts.StateSnapshotRequestTimeout, err = time.ParseDuration(viper.GetString("statetransfer.timeout.fullstate")) if err != nil { panic(fmt.Errorf("Cannot parse statetransfer.timeout.fullstate timeout: %s", err)) } sts.MaxStateDeltas = viper.GetInt("statetransfer.maxdeltas") if sts.MaxStateDeltas <= 0 { panic(fmt.Errorf("sts.maxdeltas must be greater than 0")) } return sts }
func GetConnection() *sql.DB { if db != nil { return db } else { var err error db, err = sql.Open("mysql", viper.GetString("connections.onepixel.dsl")) if err != nil { log.Fatalf("Error on initializing database connection: %s", err.Error()) } db.SetMaxIdleConns(viper.GetInt("connections.onepixel.maxIdleConnection")) db.SetMaxOpenConns(viper.GetInt("connections.onepixel.maxOpenConnection")) err = db.Ping() if err != nil { log.Fatalf("Error on opening database connection: %s", err.Error()) } return db } }
func startApp(db *gorm.DB) { log := logging.MustGetLogger("log") if viper.GetString("logtype") != "debug" { gin.SetMode(gin.ReleaseMode) } g := gin.Default() //r := NewRessource(db) g.Use(cors.Middleware(cors.Config{ Origins: "*", Methods: "GET, PUT, POST, DELETE", RequestHeaders: "Origin, Authorization, Content-Type", ExposedHeaders: "", MaxAge: 50 * time.Second, Credentials: true, ValidateHeaders: false, })) g.Static("/", "./static") /*v1 := g.Group("api/v1") { v1.GET("/temperatures", r.GetTemperatures) v1.POST("/temperature", r.PostTemperature) }*/ log.Debug("Port: %d", viper.GetInt("server.port")) g.Run(":" + strconv.Itoa(viper.GetInt("server.port"))) }
// InsertTrack inserts track `t` at position `i` in the queue. func (q *Queue) InsertTrack(i int, t interfaces.Track) error { q.mutex.Lock() beforeLen := len(q.Queue) // An error should never occur here since maxTrackDuration is restricted to // ints. Any error in the configuration will be caught during yaml load. maxTrackDuration, _ := time.ParseDuration(fmt.Sprintf("%ds", viper.GetInt("queue.max_track_duration"))) if viper.GetInt("queue.max_track_duration") == 0 || t.GetDuration() <= maxTrackDuration { q.Queue = append(q.Queue, Track{}) copy(q.Queue[i+1:], q.Queue[i:]) q.Queue[i] = t } else { q.mutex.Unlock() return errors.New("The track is too long to add to the queue") } if len(q.Queue) == beforeLen+1 { q.mutex.Unlock() q.playIfNeeded() return nil } q.mutex.Unlock() return errors.New("Could not add track to queue") }
// SinkFactory creates a new object with sinks.Sink interface func SinkFactory() sinks.Sink { sinkType := viper.GetString("sink-type") filename := viper.GetString("filesystem-filename") maxAge := viper.GetInt("filesystem-max-age") maxBackups := viper.GetInt("filesystem-max-backups") maxSize := viper.GetInt("filesystem-max-size") if sinkType == "filesystem" { return sinks.NewFilesystemSink(filename, maxAge, maxBackups, maxSize) } output := viper.GetString("console-output") var stdOutput *os.File if sinkType == "console" { if output == "stdout" { stdOutput = os.Stdout } else if output == "stderr" { stdOutput = os.Stderr } else { log.Warningf("Unknown console output type '%s'. Falling back to 'stdout'", output) } return sinks.NewConsoleSink(stdOutput) } log.Warningf("Unknown sink type '%s'. Falling back to 'filesystem'", sinkType) return sinks.NewFilesystemSink(filename, maxAge, maxBackups, maxSize) }
// launchServer sets up the http fileserver. Exciting! func launchServer() { r := mux.NewRouter(). StrictSlash(true) // Grab all our config junk and prepare to launch ip := viper.GetString("ListenAddr") port := viper.GetInt("ListenPort") fmt.Println(viper.GetInt("ListenPort")) // I... I guess, if you want TLS, you can totally have it cert, key := viper.GetString("CertFile"), viper.GetString("KeyFile") useTLS := len(cert) > 0 && len(key) > 0 scheme := "https" if !useTLS { if port == 0 { port = 80 } scheme = "http" } else if port == 0 { port = 443 } p := fmt.Sprintf("%s:%d", ip, port) root, files := viper.GetString("ServerRoot"), viper.GetString("StaticFiles") reload, err := lr.New(lr.DefaultName, lr.DefaultPort) if err != nil { fmt.Println(err) os.Exit(1) } go reload.ListenAndServe() r.PathPrefix(root). Handler( handlers.CombinedLoggingHandler( os.Stdout, injectReload(root, files, scheme), ), ) go func() { fmt.Printf("Launching ogload on %s\n", p) if !useTLS { if err := http.ListenAndServe(p, r); err != nil { fmt.Printf("Server failed! scheme=%s, addr=%s, err=%v\n", scheme, p, err) os.Exit(1) } return } if err := http.ListenAndServeTLS(p, cert, key, r); err != nil { fmt.Printf("TLS Server failed! scheme=%s, addr=%s, err=%v\n", scheme, p, err) os.Exit(1) } }() wait := watchDir(files, reload) <-wait }
// GetInt returns a config value as an int. func (c *LiveConfig) GetInt(ns, key string) int { if ns == NSRoot { return viper.GetInt(key) } nskey := fmt.Sprintf("%s-%s", ns, key) return viper.GetInt(nskey) }
//Method Creating a short link form a origin url and optionaly a personalized token //Checks that the origin url exists, that the token does not go over a configured size //generates random number if token already exist //generates random string if token is empty //return new shortlink func (bm *BusinessManager) CreateShortLink(inToken string, inOrigin string) (outLink *e.ShortLink, err error) { // function to recover in case of panic while accessing the database defer func() { if r := recover(); r != nil { switch x := r.(type) { case e.DatabaseError: err = x case error: err = x case string: err = errors.New(x) default: err = errors.New("Unknown panic") } outLink = new(e.ShortLink) } }() // check whether url exists if !isExistingUrl(inOrigin) { return outLink, e.InputError{"Bad Request: Specified URL does not exist"} } outOrigin := inOrigin // check personalized token size if len(inToken) > viper.GetInt("NbMaxCharToken") { return new(e.ShortLink), e.InputError{"Bad Request: Token too long"} } // generate a random root token if len(inToken) == 0 { inToken = pickRandomString(viper.GetInt("NbMaxCharToken")) } outToken := inToken // while the token exist for bm.dalManager.ContainsToken(outToken) { outToken = inToken + pickRandomStringNumber(viper.GetInt("MaxRandToken")) } // generate id, timestamp and initialize access count for the new ShortLink outLink = e.NewShortLink(outOrigin, outToken) //store new link in database bm.dalManager.PutLink(outLink) log.WithFields(log.Fields{ "id": outLink.Id, "token": outLink.Token, "origin": outLink.Origin, }).Info("New Short Link Created") return outLink, nil }
/* * Start the process * */ func main() { log.SetOutput(os.Stdout) config_file := flag.String("config", "", "") flag.Parse() default_config_file := "config" default_config_path := "./" if *config_file != "" { default_config_path, default_config_file = GetFileNameAndPath(*config_file) } viper.SetConfigName(default_config_file) viper.AddConfigPath(default_config_path) err := viper.ReadInConfig() if err != nil { log.Println("missing config file") os.Exit(1) } config := Config{} cols := strings.Split(viper.GetString("colums_hash"), ",") config.columns_hash = arrStrToInt(&cols) cols = strings.Split(viper.GetString("columns_content"), ",") config.columns_content = arrStrToInt(&cols) config.output = viper.GetString("outputdir") config.deep_dirs = viper.GetInt("deepdirs") config.delimiter = viper.GetString("delimiter") config.iter = viper.GetInt("pbkdf2_iterations") config.keylength = viper.GetInt("pbkdf2_keylength") config.hash_dir = viper.GetBool("hash_dir") if config.output == "" { config.output = "./output/" } if config.iter == 0 { config.iter = 100 } if config.keylength == 0 { config.keylength = 32 } if config.delimiter == "" { config.delimiter = ";" } log.Println("deleting " + config.output) os.RemoveAll(config.output) statify(viper.GetString("filename"), &config) }
func RunIcarus() { // Run the solver as many times as the user desires. fmt.Println("Solving", viper.GetInt("times"), "times") for x := 0; x < viper.GetInt("times"); x++ { solveMaze() } // Once we have solved the maze the required times, tell daedalus we are done makeRequest("http://127.0.0.1:" + viper.GetString("port") + "/done") }
// CacheConfiguration computes and caches commonly-used constants and // computed constants as package variables. Routines which were previously // global have been embedded here to preserve the original abstraction. func CacheConfiguration() (err error) { // getLocalAddress returns the address:port the local peer is operating on. Affected by env:peer.addressAutoDetect getLocalAddress := func() (peerAddress string, err error) { if viper.GetBool("peer.addressAutoDetect") { // Need to get the port from the peer.address setting, and append to the determined host IP _, port, err := net.SplitHostPort(viper.GetString("peer.address")) if err != nil { err = fmt.Errorf("Error auto detecting Peer's address: %s", err) return "", err } peerAddress = net.JoinHostPort(GetLocalIP(), port) peerLogger.Infof("Auto detected peer address: %s", peerAddress) } else { peerAddress = viper.GetString("peer.address") } return } // getPeerEndpoint returns the PeerEndpoint for this Peer instance. Affected by env:peer.addressAutoDetect getPeerEndpoint := func() (*pb.PeerEndpoint, error) { var peerAddress string var peerType pb.PeerEndpoint_Type peerAddress, err := getLocalAddress() if err != nil { return nil, err } if viper.GetBool("peer.validator.enabled") { peerType = pb.PeerEndpoint_VALIDATOR } else { peerType = pb.PeerEndpoint_NON_VALIDATOR } return &pb.PeerEndpoint{ID: &pb.PeerID{Name: viper.GetString("peer.id")}, Address: peerAddress, Type: peerType}, nil } localAddress, localAddressError = getLocalAddress() peerEndpoint, peerEndpointError = getPeerEndpoint() syncStateSnapshotChannelSize = viper.GetInt("peer.sync.state.snapshot.channelSize") syncStateDeltasChannelSize = viper.GetInt("peer.sync.state.deltas.channelSize") syncBlocksChannelSize = viper.GetInt("peer.sync.blocks.channelSize") validatorEnabled = viper.GetBool("peer.validator.enabled") securityEnabled = viper.GetBool("security.enabled") configurationCached = true if localAddressError != nil { return localAddressError } else if peerEndpointError != nil { return peerEndpointError } return }
// NewCoordinatorImpl constructs a coordinatorImpl func NewCoordinatorImpl(stack PartialStack) Coordinator { var err error sts := &coordinatorImpl{} sts.stack = stack sts.RecoverDamage = viper.GetBool("statetransfer.recoverdamage") sts.stateValid = true // Assume our starting state is correct unless told otherwise sts.validBlockRanges = make([]*blockRange, 0) sts.blockVerifyChunkSize = uint64(viper.GetInt("statetransfer.blocksperrequest")) if sts.blockVerifyChunkSize == 0 { panic(fmt.Errorf("Must set statetransfer.blocksperrequest to be nonzero")) } sts.blockSyncReq = make(chan *blockSyncReq) sts.threadExit = make(chan struct{}) sts.DiscoveryThrottleTime = 1 * time.Second // TODO make this configurable sts.BlockRequestTimeout, err = time.ParseDuration(viper.GetString("statetransfer.timeout.singleblock")) if err != nil { panic(fmt.Errorf("Cannot parse statetransfer.timeout.singleblock timeout: %s", err)) } sts.StateDeltaRequestTimeout, err = time.ParseDuration(viper.GetString("statetransfer.timeout.singlestatedelta")) if err != nil { panic(fmt.Errorf("Cannot parse statetransfer.timeout.singlestatedelta timeout: %s", err)) } sts.StateSnapshotRequestTimeout, err = time.ParseDuration(viper.GetString("statetransfer.timeout.fullstate")) if err != nil { panic(fmt.Errorf("Cannot parse statetransfer.timeout.fullstate timeout: %s", err)) } sts.maxStateDeltas = viper.GetInt("statetransfer.maxdeltas") if sts.maxStateDeltas <= 0 { panic(fmt.Errorf("sts.maxdeltas must be greater than 0")) } tmp := viper.GetInt("peer.sync.blocks.channelSize") if tmp <= 0 { panic(fmt.Errorf("peer.sync.blocks.channelSize must be greater than 0")) } sts.maxBlockRange = uint64(tmp) tmp = viper.GetInt("peer.sync.state.deltas.channelSize") if tmp <= 0 { panic(fmt.Errorf("peer.sync.state.deltas.channelSize must be greater than 0")) } sts.maxStateDeltaRange = uint64(tmp) return sts }
func getHttpConfig(name string, prefix string) httpTestConfig { uri := viper.GetString(prefix + "url") timeout := time.Duration(viper.GetInt(prefix+"timeout")) * time.Millisecond interval := time.Duration(viper.GetInt(prefix+"interval")) * time.Millisecond handler := getResponseHandler(name, prefix) return httpTestConfig{ uri: uri, timeout: timeout, interval: interval, handler: handler, } }
// GetStatus reports the status of the server func (*ServerAdmin) GetStatus(context.Context, *google_protobuf.Empty) (*pb.ServerStatus, error) { status := &pb.ServerStatus{Status: pb.ServerStatus_UNKNOWN} die := make(chan bool) log.Debug("Creating %d workers", viper.GetInt("peer.workers")) for i := 0; i < viper.GetInt("peer.workers"); i++ { go worker(i, die) } runtime.Gosched() <-time.After(1 * time.Millisecond) close(die) log.Debug("returning status: %s", status) return status, nil }
// Creates a maze with all walls // Good starting point for subtractive algorithms func fullMaze() *Maze { z := emptyMaze() ySize := viper.GetInt("height") xSize := viper.GetInt("width") for y := 0; y < ySize; y++ { for x := 0; x < xSize; x++ { z.rooms[y][x].Walls = mazelib.Survey{true, true, true, true} } } return z }
// setConfigDefaults is only necessary because of bugs in viper, noted in main func setConfigDefaults() { if viper.GetString("postgres.sslmode") == "" { viper.Set("postgres.sslmode", "require") } if viper.GetInt("postgres.port") == 0 { viper.Set("postgres.port", 5432) } if viper.GetString("mysql.sslmode") == "" { viper.Set("mysql.sslmode", "true") } if viper.GetInt("mysql.port") == 0 { viper.Set("mysql.port", 3306) } }
// Creates a maze without any walls // Good starting point for additive algorithms func emptyMaze() *Maze { z := Maze{} ySize := viper.GetInt("height") xSize := viper.GetInt("width") z.rooms = make([][]mazelib.Room, ySize) for y := 0; y < ySize; y++ { z.rooms[y] = make([]mazelib.Room, xSize) for x := 0; x < xSize; x++ { z.rooms[y][x] = mazelib.Room{} } } return &z }
func initConfig() { if viper.GetString("db-url") == "" { log.Fatal("Invalid config: db-url is blank. Please specify --db-url on the command line or set the DATABASE_URL environment variable.") } if viper.GetString("stellar-core-db-url") == "" { log.Fatal("Invalid config: stellar-core-db-url is blank. Please specify --stellar-core-db-url on the command line or set the STELLAR_CORE_DATABASE_URL environment variable.") } if viper.GetString("stellar-core-url") == "" { log.Fatal("Invalid config: stellar-core-url is blank. Please specify --stellar-core-url on the command line or set the STELLAR_CORE_URL environment variable.") } ll, err := logrus.ParseLevel(viper.GetString("log-level")) if err != nil { log.Fatalf("Could not parse log-level: %v", viper.GetString("log-level")) } hlog.DefaultLogger.Level = ll cert, key := viper.GetString("tls-cert"), viper.GetString("tls-key") switch { case cert != "" && key == "": log.Fatal("Invalid TLS config: key not configured") case cert == "" && key != "": log.Fatal("Invalid TLS config: cert not configured") } config = horizon.Config{ DatabaseURL: viper.GetString("db-url"), StellarCoreDatabaseURL: viper.GetString("stellar-core-db-url"), StellarCoreURL: viper.GetString("stellar-core-url"), Autopump: viper.GetBool("autopump"), Port: viper.GetInt("port"), RateLimit: throttled.PerHour(viper.GetInt("per-hour-rate-limit")), RedisURL: viper.GetString("redis-url"), LogLevel: ll, SentryDSN: viper.GetString("sentry-dsn"), LogglyToken: viper.GetString("loggly-token"), LogglyHost: viper.GetString("loggly-host"), FriendbotSecret: viper.GetString("friendbot-secret"), TLSCert: cert, TLSKey: key, Ingest: viper.GetBool("ingest"), } }
// NewEngine creates new services for data from config settings func NewEngine() error { gh := strings.TrimSuffix(viper.GetString("gitlab.url"), "/") d := strings.TrimSuffix(viper.GetString("server.hostname"), "/") gitlab.NewEngine(&gitlab.Config{ BasePath: gh + "/api/v3", Domain: d, Oauth2: &oauth2.Config{ ClientID: viper.GetString("gitlab.client"), ClientSecret: viper.GetString("gitlab.secret"), Endpoint: oauth2.Endpoint{ AuthURL: gh + "/oauth/authorize", TokenURL: gh + "/oauth/token", }, RedirectURL: d + "/assets/html/user/views/oauth.html", }, }) c = redis.NewClient(&redis.Options{ Addr: viper.GetString("redis.addr"), Password: viper.GetString("redis.password"), DB: int64(viper.GetInt("redis.db")), }) _, err := c.Ping().Result() if err != nil { log.Fatalf("Error connection to redis %s", err.Error()) } return nil }
func Run() { Gen( viper.GetString("key"), viper.GetInt("len"), ) return }
func signResponse(w http.ResponseWriter, username string) { // @TODO: Store the username in the cookie (in cleartext) so it can be used afterwards cookieMaxAge := time.Duration(viper.GetInt("cookiemaxage")) * time.Hour expiration := fmt.Sprintf("%v", int(time.Now().Unix())+int(cookieMaxAge.Seconds())) mac := hmac.New(sha1.New, []byte(viper.GetString("cookiesecret"))) mac.Write([]byte(expiration)) hash := fmt.Sprintf("%x", mac.Sum(nil)) value := fmt.Sprintf("%v:%v", expiration, hash) cookieContent := fmt.Sprintf("%v=%v", "mycookie", value) expire := time.Now().Add(cookieMaxAge) cookie := http.Cookie{"mycookie", value, "/", viper.GetString("domain"), expire, expire.Format(time.UnixDate), int(cookieMaxAge.Seconds()), secureCookie, true, cookieContent, []string{cookieContent}, } http.SetCookie(w, &cookie) }
// Init initializes the crypto layer. It load from viper the security level // and the logging setting. func Init() (err error) { // Init log log.ExtraCalldepth++ level, err := logging.LogLevel(viper.GetString("logging.crypto")) if err == nil { // No error, use the setting logging.SetLevel(level, "crypto") log.Info("Log level recognized '%s', set to %s", viper.GetString("logging.crypto"), logging.GetLevel("crypto")) } else { log.Warning("Log level not recognized '%s', defaulting to %s: %s", viper.GetString("logging.crypto"), logging.GetLevel("crypto"), err) } // Init security level securityLevel := 256 if viper.IsSet("security.level") { ovveride := viper.GetInt("security.level") if ovveride != 0 { securityLevel = ovveride } } log.Debug("Working at security level [%d]", securityLevel) if err = conf.InitSecurityLevel(securityLevel); err != nil { log.Debug("Failed setting security level: [%s]", err) return } return }