Exemple #1
0
func (hook *SourceFileHook) Levels() []log.Level {
	levels := make([]log.Level, hook.LogLevel+1)
	for i, _ := range levels {
		levels[i] = log.Level(i)
	}
	return levels
}
Exemple #2
0
func init() {
	var cfgFile string
	flag.StringVar(&cfgFile, "c", "myMon.cfg", "myMon configure file")
	flag.Parse()

	if _, err := os.Stat(cfgFile); err != nil {
		if os.IsNotExist(err) {
			log.WithField("cfg", cfgFile).Fatalf("myMon config file does not exists: %v", err)
		}
	}

	if err := cfg.readConf(cfgFile); err != nil {
		log.Fatalf("Read configure file failed: %v", err)
	}

	// Init log file
	log.SetFormatter(&log.JSONFormatter{})
	log.SetLevel(log.Level(cfg.LogLevel))

	if cfg.LogFile != "" {
		f, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
		if err == nil {
			log.SetOutput(f)
			return
		}
	}
	log.SetOutput(os.Stderr)
}
Exemple #3
0
// Setup should be called once at the beginning of the application to
// initialize the package level logger.
func Setup(useSyslog bool, level Level) error {
	if Configured {
		return fmt.Errorf("Application logger has already been configured.")
	}

	if useSyslog {
		// Route normal log output to /dev/null
		log.Out = ioutil.Discard

		// Add syslog hook
		sysLvl, err := syslogLevel(level)
		if err != nil {
			return err
		}
		hook, err := logrus_syslog.NewSyslogHook("", "", sysLvl, "")
		if err != nil {
			return err
		}
		log.Hooks.Add(hook)
	} else {
		log.Out = os.Stdout
		log.Level = logrus.Level(level)
	}

	Configured = true
	return nil
}
Exemple #4
0
func init() {
	c := config.Get()
	l := c.GetInt("log.level")

	Log = log.New()
	Log.Out = os.Stderr
	Log.Level = log.Level(l)
}
Exemple #5
0
// InitLogger ...
func InitLogger(config LoggerConfig) {
	Logger = logrus.New()
	Logger.Level = logrus.Level(config.Level)

	switch config.Adapter {
	case LoggerAdapterConsole:
		Logger.Formatter = &lib.ConsoleFormatter{}
	default:
		Logger.Fatal(ErrLoggerAdapterNotSupported)
	}
}
func run(c *cli.Context) error {
	log.SetLevel(log.Level(uint8(c.Int("log-level"))))

	pubsub, err := mqttpubsub.NewBackend(c.String("mqtt-server"), c.String("mqtt-username"), c.String("mqtt-password"))
	if err != nil {
		log.Fatalf("could not setup mqtt backend: %s", err)
	}
	defer pubsub.Close()

	onNew := func(mac lorawan.EUI64) error {
		return pubsub.SubscribeGatewayTX(mac)
	}

	onDelete := func(mac lorawan.EUI64) error {
		return pubsub.UnSubscribeGatewayTX(mac)
	}

	gw, err := gateway.NewBackend(c.String("udp-bind"), onNew, onDelete)
	if err != nil {
		log.Fatalf("could not setup gateway backend: %s", err)
	}
	defer gw.Close()

	go func() {
		for rxPacket := range gw.RXPacketChan() {
			if err := pubsub.PublishGatewayRX(rxPacket.RXInfo.MAC, rxPacket); err != nil {
				log.Errorf("could not publish RXPacket: %s", err)
			}
		}
	}()

	go func() {
		for stats := range gw.StatsChan() {
			if err := pubsub.PublishGatewayStats(stats.MAC, stats); err != nil {
				log.Errorf("could not publish GatewayStatsPacket: %s", err)
			}
		}
	}()

	go func() {
		for txPacket := range pubsub.TXPacketChan() {
			if err := gw.Send(txPacket); err != nil {
				log.Errorf("could not send TXPacket: %s", err)
			}
		}
	}()

	sigChan := make(chan os.Signal)
	signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
	log.WithField("signal", <-sigChan).Info("signal received")
	log.Warning("shutting down server")
	return nil
}
Exemple #7
0
func InitLog(cfg *Cfg) {
	// Init log file
	log.SetFormatter(&log.JSONFormatter{})
	log.SetLevel(log.Level(cfg.LogLevel))

	if cfg.LogFile != "" {
		f, err := os.OpenFile(cfg.LogFile, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
		if err == nil {
			log.SetOutput(f)
			return
		}
	}
	log.SetOutput(os.Stderr)
}
Exemple #8
0
func getConfig(flagset *flag.FlagSet, userCfgFile string) (*config.Config, error) {
	opts := globalconf.Options{EnvPrefix: "API_HOSTD_"}

	if userCfgFile != "" {
		// Fail hard if a user-provided config is not usable
		fi, err := os.Stat(userCfgFile)
		if err != nil {
			ctxLog.Fatalf("Unable to use config file %s: %v", userCfgFile, err)
		}
		if fi.IsDir() {
			ctxLog.Fatalf("Provided config %s is a directory, not a file", userCfgFile)
		}
		opts.Filename = userCfgFile
	} else if _, err := os.Stat(DefaultConfigFile); err == nil {
		opts.Filename = DefaultConfigFile
	}

	gconf, err := globalconf.NewWithOptions(&opts)
	if err != nil {
		return nil, err
	}

	gconf.ParseSet("", flagset)

	cfg := config.Config{
		Verbosity: (*flagset.Lookup("verbosity")).Value.(flag.Getter).Get().(int),
		IP:        (*flagset.Lookup("ip")).Value.(flag.Getter).Get().(string),
		Port:      (*flagset.Lookup("port")).Value.(flag.Getter).Get().(string),
		Secret:    (*flagset.Lookup("jwt_sign_key")).Value.(flag.Getter).Get().(string),

		CORSAllowedOrigins:     config.StringToSlice((*flagset.Lookup("cors_allowed_origins")).Value.(flag.Getter).Get().(string)),
		CORSAllowedMethods:     config.StringToSlice((*flagset.Lookup("cors_allowed_methods")).Value.(flag.Getter).Get().(string)),
		CORSAllowedHeaders:     config.StringToSlice((*flagset.Lookup("cors_allowed_headers")).Value.(flag.Getter).Get().(string)),
		CORSExposedHeaders:     config.StringToSlice((*flagset.Lookup("cors_exposed_headers")).Value.(flag.Getter).Get().(string)),
		CORSAllowCredentials:   (*flagset.Lookup("cors_allow_credentials")).Value.(flag.Getter).Get().(bool),
		CORSMaxAge:             (*flagset.Lookup("cors_max_age")).Value.(flag.Getter).Get().(int),
		CORSOptionsPassThrough: (*flagset.Lookup("cors_options_pass_through")).Value.(flag.Getter).Get().(bool),
		CORSDebug:              (*flagset.Lookup("cors_debug")).Value.(flag.Getter).Get().(bool),
	}

	log.SetLevel(log.Level(cfg.Verbosity))

	ctxLog.Infof("Loaded config: [%+v]", cfg)

	return &cfg, nil
}
Exemple #9
0
func setConfig(config *HiveConfig) (*schedule.GlobalConfigStruct, string, string) {
	maxprocs := config.Maxprocs
	port := config.Port
	managerport := config.ManagerPort
	loglevel := config.Loglevel
	cpuProfName := config.CpuProfName
	memProfName := config.MemProfName

	runtime.GOMAXPROCS(maxprocs)

	dg := schedule.DefaultGlobal()
	dg.L.Level = logrus.Level(loglevel)
	dg.Port = ":" + port
	dg.ManagerPort = ":" + managerport

	return dg, cpuProfName, memProfName
}
Exemple #10
0
func run(c *cli.Context) {
	var (
		flag uint32
		tpl  *template.Template
		ctx  = context.Background()
	)
	if !c.Args().Present() {
		cli.ShowAppHelp(c)
		return
	}

	log.SetLevel(log.Level(c.Int("verbose")))

	watcher, err := inotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	// Format.
	if fmtString := c.String("format"); fmtString != "" {
		tpl = template.Must(template.New("event-format").Parse(fmtString))
	}

	// Event flags.
	for _, event := range c.StringSlice("event") {
		flag |= parseEvent(event)
	}
	if flag == 0 {
		flag = inotify.IN_ALL_EVENTS
	}

	watch(watcher, c.Args(), flag, c.Bool("recursive"), true)

	// Configure timeout.
	if timeout := time.Duration(c.Int("timeout")) * time.Second; timeout > 0 {
		ctx, _ = context.WithTimeout(ctx, timeout)
	}

	match := buildMatcherFunc(c.StringSlice("exclude"), c.StringSlice("include"))
	waitForWatcher(ctx, watcher, match, tpl, c.Bool("monitor"))
}
Exemple #11
0
func upgrade(context *cli.Context) {
	verbosity = context.Int("verbosity")
	if !context.IsSet("verbosity") {
		if verbosity < 2 {
			verbosity = 2
		}
	}
	spirit.Logger().Level = logrus.Level(verbosity)

	var err error

	defer func() {
		if err != nil {
			spirit.Logger().Error(err)
			os.Exit(128)
		}
	}()

	var out []byte
	cmd := "go get -u github.com/gogap/spirit-tool"
	if verbosity > 0 {
		cmd = "go get -v -u github.com/gogap/spirit-tool"
	}
	if out, err = execCommand(cmd); err != nil {
		spirit.Logger().Errorln(err)
		return
	}
	spirit.Logger().Infoln(out)

	cmd = "go install github.com/gogap/spirit-tool"
	if verbosity > 0 {
		cmd = "go install -v github.com/gogap/spirit-tool"
	}
	if out, err = execCommand(cmd); err != nil {
		spirit.Logger().Errorln(err)
		return
	}
	spirit.Logger().Infoln(out)

	return
}
Exemple #12
0
// NewCluster returns a new cluster with the given config
func NewCluster(config Config) (*Cluster, error) {
	logger := logrus.New()
	logger.Out = config.LogOutput
	logger.Level = logrus.Level(config.LogLevel)

	if config.SerfConfig == nil {
		return nil, fmt.Errorf("Config.SerfConfig cannot be nil")
	}
	if config.SerfConfig.EventCh != nil {
		return nil, fmt.Errorf("SerfConfig.EventCh must be nil (try using Config.SerfEvents instead)")
	}

	memberMap := make(map[string]*serf.Member)
	memberMutex := sync.Mutex{}

	ring := &ring{members: make([]*serf.Member, 0, 0)}

	serfEvents := make(chan serf.Event, 256)
	config.SerfConfig.EventCh = serfEvents
	nodeSerf, err := serf.Create(config.SerfConfig)
	if err != nil {
		return nil, fmt.Errorf("Unable to create serf: %v", err)
	}

	exit := make(chan bool)

	cluster := &Cluster{
		exit:        exit,
		config:      config,
		memberMap:   memberMap,
		ring:        ring,
		memberMutex: memberMutex,
		serfEvents:  serfEvents,
		Serf:        nodeSerf,
		logger:      logger,
	}

	return cluster, nil
}
Exemple #13
0
func main() {
	flag.Usage = usage
	flag.Parse()

	if debug {
		go debugServer(DebugAddress)
	}

	ctx := context.Background()

	filename := filepath.Base(configFile)
	ext := filepath.Ext(configFile)
	configPath := filepath.Dir(configFile)

	viper.SetConfigType(strings.TrimPrefix(ext, "."))
	viper.SetConfigName(strings.TrimSuffix(filename, ext))
	viper.AddConfigPath(configPath)
	err := viper.ReadInConfig()
	if err != nil {
		logrus.Error("Viper Error: ", err.Error())
		logrus.Error("Could not read config at ", configFile)
		os.Exit(1)
	}
	logrus.SetLevel(logrus.Level(viper.GetInt("logging.level")))

	sigHup := make(chan os.Signal)
	sigTerm := make(chan os.Signal)

	signal.Notify(sigHup, syscall.SIGHUP)
	signal.Notify(sigTerm, syscall.SIGTERM)

	var trust signed.CryptoService
	if viper.GetString("trust_service.type") == "remote" {
		logrus.Info("[Notary Server] : Using remote signing service")
		trust = signer.NewRufusSigner(
			viper.GetString("trust_service.hostname"),
			viper.GetString("trust_service.port"),
			viper.GetString("trust_service.tls_ca_file"),
		)
	} else {
		logrus.Info("[Notary Server] : Using local signing service")
		trust = signed.NewEd25519()
	}

	if viper.GetString("store.backend") == "mysql" {
		dbURL := viper.GetString("storage.db_url")
		db, err := sql.Open("mysql", dbURL)
		if err != nil {
			logrus.Fatal("[Notary Server] Error starting DB driver: ", err.Error())
			return // not strictly needed but let's be explicit
		}
		ctx = context.WithValue(ctx, "metaStore", storage.NewMySQLStorage(db))
	} else {
		ctx = context.WithValue(ctx, "metaStore", storage.NewMemStorage())
	}
	logrus.Info("[Notary Server] Starting Server")
	err = server.Run(
		ctx,
		viper.GetString("server.addr"),
		viper.GetString("server.tls_cert_file"),
		viper.GetString("server.tls_key_file"),
		trust,
	)

	logrus.Error("[Notary Server]", err.Error())
	return
}
Exemple #14
0
func main() {
	flag.Usage = usage
	flag.Parse()

	if debug {
		go debugServer(debugAddr)
	}

	// when the signer starts print the version for debugging and issue logs later
	logrus.Infof("Version: %s, Git commit: %s", version.NotaryVersion, version.GitCommit)

	filename := filepath.Base(configFile)
	ext := filepath.Ext(configFile)
	configPath := filepath.Dir(configFile)

	viper.SetConfigType(strings.TrimPrefix(ext, "."))
	viper.SetConfigName(strings.TrimSuffix(filename, ext))
	viper.AddConfigPath(configPath)
	err := viper.ReadInConfig()
	if err != nil {
		logrus.Error("Viper Error: ", err.Error())
		logrus.Error("Could not read config at ", configFile)
		os.Exit(1)
	}

	logrus.SetLevel(logrus.Level(viper.GetInt("logging.level")))

	certFile := viper.GetString("server.cert_file")
	keyFile := viper.GetString("server.key_file")
	if certFile == "" || keyFile == "" {
		usage()
		log.Fatalf("Certificate and key are mandatory")
	}

	tlsConfig := &tls.Config{
		MinVersion:               tls.VersionTLS12,
		PreferServerCipherSuites: true,
		CipherSuites: []uint16{
			tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
			tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
			tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
			tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
			tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
			tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
			tls.TLS_RSA_WITH_AES_128_CBC_SHA,
			tls.TLS_RSA_WITH_AES_256_CBC_SHA},
	}
	tlsConfig.Rand = rand.Reader

	cryptoServices := make(signer.CryptoServiceIndex)

	pin := viper.GetString(pinCode)
	pkcs11Lib := viper.GetString("crypto.pkcs11lib")
	if pkcs11Lib != "" {
		if pin == "" {
			log.Fatalf("Using PIN is mandatory with pkcs11")
		}

		ctx, session := SetupHSMEnv(pkcs11Lib, pin)

		defer cleanup(ctx, session)

		cryptoServices[data.RSAKey] = api.NewRSAHardwareCryptoService(ctx, session)
	}

	configDBType := strings.ToLower(viper.GetString("storage.backend"))
	dbURL := viper.GetString("storage.db_url")
	if configDBType != dbType || dbURL == "" {
		usage()
		log.Fatalf("Currently only a MySQL database backend is supported.")
	}
	dbSQL, err := sql.Open(configDBType, dbURL)
	if err != nil {
		log.Fatalf("failed to open the database: %s, %v", dbURL, err)
	}

	defaultAlias := viper.GetString(defaultAliasEnv)
	logrus.Debug("Default Alias: ", defaultAlias)
	keyStore, err := signer.NewKeyDBStore(passphraseRetriever, defaultAlias, configDBType, dbSQL)
	if err != nil {
		log.Fatalf("failed to create a new keydbstore: %v", err)
	}
	cryptoService := cryptoservice.NewCryptoService("", keyStore)

	cryptoServices[data.ED25519Key] = cryptoService
	cryptoServices[data.ECDSAKey] = cryptoService

	//RPC server setup
	kms := &api.KeyManagementServer{CryptoServices: cryptoServices}
	ss := &api.SignerServer{CryptoServices: cryptoServices}

	grpcServer := grpc.NewServer()
	pb.RegisterKeyManagementServer(grpcServer, kms)
	pb.RegisterSignerServer(grpcServer, ss)

	rpcAddr := viper.GetString("server.grpc_addr")
	lis, err := net.Listen("tcp", rpcAddr)
	if err != nil {
		log.Fatalf("failed to listen %v", err)
	}
	creds, err := credentials.NewServerTLSFromFile(certFile, keyFile)
	if err != nil {
		log.Fatalf("failed to generate credentials %v", err)
	}
	go grpcServer.Serve(creds.NewListener(lis))

	httpAddr := viper.GetString("server.http_addr")
	if httpAddr == "" {
		log.Fatalf("Server address is required")
	}
	//HTTP server setup
	server := http.Server{
		Addr:      httpAddr,
		Handler:   api.Handlers(cryptoServices),
		TLSConfig: tlsConfig,
	}

	if debug {
		log.Println("RPC server listening on", rpcAddr)
		log.Println("HTTP server listening on", httpAddr)
	}

	err = server.ListenAndServeTLS(certFile, keyFile)
	if err != nil {
		log.Fatal("HTTP server failed to start:", err)
	}
}
Exemple #15
0
func SetLoggerTo(logLevel int) {
	log.SetLevel(log.Level(logLevel))
}
Exemple #16
0
func NewArg(logLevel int) Arg {
	return Arg{
		LogLevel:            log.Level(logLevel),
		PingTimeoutDuration: PingTimeoutDurationDefault,
	}
}
Exemple #17
0
func main() {
	flag.Usage = usage
	flag.Parse()

	if DebugAddress != "" {
		go debugServer(DebugAddress)
	}

	ctx := context.Background()

	conf, err := parseConfig(configFile)
	if err != nil {
		logrus.Fatal("Error parsing config: ", err.Error())
		return // not strictly needed but let's be explicit
	}
	if conf.Logging.Level > 0 {
		logrus.SetLevel(logrus.Level(conf.Logging.Level))
	}

	sigHup := make(chan os.Signal)
	sigTerm := make(chan os.Signal)

	signal.Notify(sigHup, syscall.SIGHUP)
	signal.Notify(sigTerm, syscall.SIGTERM)

	var trust signed.CryptoService
	if conf.TrustService.Type == "remote" {
		logrus.Info("[Notary Server] : Using remote signing service")
		trust = signer.NewRufusSigner(conf.TrustService.Hostname, conf.TrustService.Port, conf.TrustService.TLSCAFile)
	} else {
		logrus.Info("[Notary Server] : Using local signing service")
		trust = signed.NewEd25519()
	}

	db, err := sql.Open("mysql", "dockercondemo:dockercondemo@tcp(notarymysql:3306)/dockercondemo")
	if err != nil {
		logrus.Fatal("Error starting DB driver: ", err.Error())
		return // not strictly needed but let's be explicit
	}
	ctx = context.WithValue(ctx, "versionStore", storage.NewMySQLStorage(db))
	for {
		logrus.Info("[Notary Server] Starting Server")
		childCtx, cancel := context.WithCancel(ctx)
		go server.Run(childCtx, conf.Server, trust)

		for {
			select {
			// On a sighup we cancel and restart a new server
			// with updated config
			case <-sigHup:
				logrus.Infof("[Notary Server] Server restart requested. Attempting to parse config at %s", configFile)
				conf, err = parseConfig(configFile)
				if err != nil {
					logrus.Infof("[Notary Server] Unable to parse config. Old configuration will keep running. Parse Err: %s", err.Error())
					continue
				} else {
					cancel()
					logrus.Info("[Notary Server] Stopping server for restart")
					break
				}
			// On sigkill we cancel and shutdown
			case <-sigTerm:
				cancel()
				logrus.Info("[Notary Server] Shutting Down Hard")
				os.Exit(0)
			}
		}
	}
}
Exemple #18
0
func main() {
	var debugLevel = uint(logrus.InfoLevel)
	flag.StringVar(&configFileName, "config", configFileName, "configuration `fileName`")
	flag.UintVar(&debugLevel, "level", debugLevel, "log `level` [0-5]")
	flag.Parse() // разбираем параметры запуска приложения

	logrus.SetLevel(logrus.Level(debugLevel)) // уровень отладки
	// logrus.SetFormatter(new(logrus.JSONFormatter))
	logrus.SetFormatter(new(prefixed.TextFormatter))
	// hook, err := logrus_syslog.NewSyslogHook("", "", syslog.LOG_INFO, "")
	// if err == nil {
	// 	logrus.AddHook(hook)
	// }

	// выводим в лог информацию о приложении и версии
	logEntry := llog.WithField("version", version)
	if build != "" { // добавляем билд к номеру версии
		logEntry = logEntry.WithField("build", build)
	}
	if date != "" { // добавляем дату сборки к версии
		logEntry = logEntry.WithField("buildDate", date)
	}
	logEntry.Info(appName)

	// запускаем бесконечный цикл чтения конфигурации и установки соединения
	for {
		// загружаем и разбираем конфигурационный файл
		logEntry := llog.WithField("filename", configFileName)
		var err error
		config, err = LoadConfig(configFileName) // загружаем конфигурационный файл
		if err != nil {
			logEntry.WithError(err).Fatal("Error loading config")
		}
		logEntry.WithField("mx", len(config.MX)).Info("Config loaded")

		sglogDB, err = sqlog.Connect(config.SMSGate.MYSQL)
		if err != nil {
			logEntry.WithError(err).Fatal("Error connecting to MySQL")
		}
		// zabbixLog = zabbix.New(config.SMSGate.ZabbixHost)
		zabbixLog = config.SMSGate.SMPP.Zabbix
		zabEntry := llog.WithField("host", zabbixLog.Host)
		zabEntry.WithField("server", zabbixLog.Server).Info("Zabbix")
		// zabbixLog.Send("gw.sms.unknown.destination", "79670238554")

		config.SMSGate.SMPP.Zabbix = config.SMSGate.Zabbix

		config.MXConnect()       // запускаем асинхронно соединение с MX
		config.SMSGate.Connect() // устанавливаем соединение с SMPP серверами
		// инициализируем поддержку системных сигналов и ждем, когда он случится...
		signal := monitorSignals(os.Interrupt, os.Kill, syscall.SIGUSR1)
		config.SMSGate.Close() // останавливаем соединение с SMPP
		config.MXClose()       // останавливаем соединение с MX серверами
		sglogDB.Close()        // закрываем соединение с логом
		// проверяем, что сигнал не является сигналом перечитать конфиг
		if signal != syscall.SIGUSR1 {
			llog.Info("The end")
			return // заканчиваем нашу работу
		}
		llog.Info("Reload") // перечитываем конфиг и начинаем все с начала
	}
}
Exemple #19
0
func main() {
	flag.Usage = usage
	flag.Parse()

	if debug {
		go debugServer(debugAddr)
	}

	// when the signer starts print the version for debugging and issue logs later
	logrus.Infof("Version: %s, Git commit: %s", version.NotaryVersion, version.GitCommit)

	filename := filepath.Base(configFile)
	ext := filepath.Ext(configFile)
	configPath := filepath.Dir(configFile)

	mainViper.SetConfigType(strings.TrimPrefix(ext, "."))
	mainViper.SetConfigName(strings.TrimSuffix(filename, ext))
	mainViper.AddConfigPath(configPath)
	err := mainViper.ReadInConfig()
	if err != nil {
		logrus.Error("Viper Error: ", err.Error())
		logrus.Error("Could not read config at ", configFile)
		os.Exit(1)
	}

	logrus.SetLevel(logrus.Level(mainViper.GetInt("logging.level")))

	tlsConfig, err := signerTLS(mainViper, true)
	if err != nil {
		logrus.Fatalf(err.Error())
	}

	cryptoServices := make(signer.CryptoServiceIndex)

	configDBType := strings.ToLower(mainViper.GetString("storage.backend"))
	dbURL := mainViper.GetString("storage.db_url")
	if configDBType != dbType || dbURL == "" {
		usage()
		log.Fatalf("Currently only a MySQL database backend is supported.")
	}
	dbSQL, err := sql.Open(configDBType, dbURL)
	if err != nil {
		log.Fatalf("failed to open the database: %s, %v", dbURL, err)
	}

	defaultAlias := mainViper.GetString(defaultAliasEnv)
	logrus.Debug("Default Alias: ", defaultAlias)
	keyStore, err := keydbstore.NewKeyDBStore(passphraseRetriever, defaultAlias, configDBType, dbSQL)
	if err != nil {
		log.Fatalf("failed to create a new keydbstore: %v", err)
	}

	health.RegisterPeriodicFunc(
		"DB operational", keyStore.HealthCheck, time.Second*60)

	cryptoService := cryptoservice.NewCryptoService("", keyStore)

	cryptoServices[data.ED25519Key] = cryptoService
	cryptoServices[data.ECDSAKey] = cryptoService

	//RPC server setup
	kms := &api.KeyManagementServer{CryptoServices: cryptoServices,
		HealthChecker: health.CheckStatus}
	ss := &api.SignerServer{CryptoServices: cryptoServices,
		HealthChecker: health.CheckStatus}

	rpcAddr := mainViper.GetString("server.grpc_addr")
	lis, err := net.Listen("tcp", rpcAddr)
	if err != nil {
		log.Fatalf("failed to listen %v", err)
	}
	creds := credentials.NewTLS(tlsConfig)
	opts := []grpc.ServerOption{grpc.Creds(creds)}
	grpcServer := grpc.NewServer(opts...)

	pb.RegisterKeyManagementServer(grpcServer, kms)
	pb.RegisterSignerServer(grpcServer, ss)

	go grpcServer.Serve(lis)

	httpAddr := mainViper.GetString("server.http_addr")
	if httpAddr == "" {
		log.Fatalf("Server address is required")
	}
	//HTTP server setup
	server := http.Server{
		Addr:      httpAddr,
		Handler:   api.Handlers(cryptoServices),
		TLSConfig: tlsConfig,
	}

	if debug {
		log.Println("RPC server listening on", rpcAddr)
		log.Println("HTTP server listening on", httpAddr)
	}

	err = server.ListenAndServeTLS("", "")
	if err != nil {
		log.Fatal("HTTPS server failed to start:", err)
	}
}
// SetLevel sets the standard logger level.
func SetLogLevel(level Level) {
	log.SetLevel(log.Level(level))
	log.Debugf("SetLogLevel(): %s", log.GetLevel().String())
}
Exemple #21
0
func create(context *cli.Context) {
	verbosity = context.Int("verbosity")
	if !context.IsSet("verbosity") {
		if verbosity < 2 {
			verbosity = 2
		}
	}

	spirit.Logger().Level = logrus.Level(verbosity)

	var err error

	defer func() {
		if err != nil {
			spirit.Logger().Error(err)
			os.Exit(128)
		}
	}()

	goPath := context.String("gopath")
	projectPath := context.String("path")
	configFile := context.String("config")
	extSources := context.StringSlice("source")
	getPkg := context.Bool("get")
	updatePkg := context.Bool("update")
	strArgs := context.StringSlice("args")
	forceWrite := context.Bool("force")
	templateName := context.String("template")
	revConfig := context.String("rev")

	if goPath == "" {
		err = fmt.Errorf("could not get GOPATH")
		return
	}

	spirit.Logger().Infof("GOPATH: %s", goPath)

	if projectPath == "" {
		err = fmt.Errorf("please input your project path, like: github.com/your_orgs/project_name ")
		return
	}

	if configFile == "" {
		err = fmt.Errorf("please input config file")
		return
	}

	sources := []string{
		path.Join(goPath, "src", "github.com/gogap/spirit-tool/source/offical.json"),
		path.Join(goPath, "src", "github.com/gogap/spirit-tool/source/third_party.json"),
	}

	sources = append(sources, extSources...)

	tmplArgs := map[string]interface{}{}

	for _, arg := range strArgs {
		arg = strings.TrimSpace(arg)
		if arg != "" {
			v := strings.Split(arg, "=")
			if len(v) != 2 {
				err = fmt.Errorf("the args to template format error, arg: %s", arg)
				return
			}
			tmplArgs[v[0]] = v[1]
		}
	}

	helper := SpiritHelper{}

	if err = helper.LoadSpiritConfig(configFile); err != nil {
		return
	}

	var rev map[string]string
	if revConfig != "" {
		loadKeyValueJSON(revConfig, &rev)
	}

	createOpts := CreateOptions{
		TemplateName:     templateName,
		GoPath:           goPath,
		ProjectPath:      projectPath,
		GetPackages:      getPkg,
		UpdatePackages:   updatePkg,
		ForceWrite:       forceWrite,
		Sources:          sources,
		PackagesRevision: nil,
	}

	if err = helper.CreateProject(createOpts, tmplArgs); err != nil {
		return
	}

	return
}
Exemple #22
0
func init() {
	// Override logrus.Logger defaults with custom defaults
	log.Formatter = new(logFormatter)
	log.Out = os.Stdout
	log.Level = logrus.Level(logrus.InfoLevel)
}
Exemple #23
0
func (logger *Logger) SetLevel(level Level) {
	logger.Logger.Level = logrus.Level(level)
}
Exemple #24
0
func (l *logrusLevelFlag) ToLogrusLevel() logrus.Level {
	return logrus.Level(*l)
}