예제 #1
0
func (s *server) createMux(ctx types.Context) *mux.Router {
	m := mux.NewRouter()
	for _, apiRouter := range s.routers {
		for _, r := range apiRouter.Routes() {

			ctx := ctx.WithValue(context.RouteKey, r)

			f := s.makeHTTPHandler(ctx, r)
			mr := m.Path(r.GetPath())
			mr = mr.Name(r.GetName())
			mr = mr.Methods(r.GetMethod())
			mr = mr.Queries(r.GetQueries()...)
			mr.Handler(f)

			if l, ok := context.GetLogLevel(ctx); ok && l >= log.DebugLevel {
				ctx.WithFields(log.Fields{
					"path":         r.GetPath(),
					"method":       r.GetMethod(),
					"queries":      r.GetQueries(),
					"len(queries)": len(r.GetQueries()),
				}).Debug("registered route")
			} else {
				ctx.Info("registered route")
			}
		}
	}
	return m
}
예제 #2
0
func (d *driver) Login(ctx types.Context) (interface{}, error) {
	sessionsL.Lock()
	defer sessionsL.Unlock()

	var (
		endpoint *string
		ckey     string
		hkey     = md5.New()
		akey     = d.accessKey
		region   = d.mustRegion(ctx)
	)

	if region != nil && d.endpointFormat != "" {
		szEndpoint := fmt.Sprintf(d.endpointFormat, *region)
		endpoint = &szEndpoint
	} else {
		endpoint = d.endpoint
	}

	if !d.disableSessionCache {
		writeHkey(hkey, region)
		writeHkey(hkey, endpoint)
		writeHkey(hkey, &akey)
		ckey = fmt.Sprintf("%x", hkey.Sum(nil))

		// if the session is cached then return it
		if svc, ok := sessions[ckey]; ok {
			ctx.WithField(cacheKeyC, ckey).Debug("using cached efs service")
			return svc, nil
		}
	}

	var (
		skey   = d.getSecretKey()
		fields = map[string]interface{}{
			efs.AccessKey: akey,
			efs.Tag:       d.tag,
			cacheKeyC:     ckey,
		}
	)

	if skey == "" {
		fields[efs.SecretKey] = ""
	} else {
		fields[efs.SecretKey] = "******"
	}
	if region != nil {
		fields[efs.Region] = *region
	}
	if endpoint != nil {
		fields[efs.Endpoint] = *endpoint
	}

	ctx.WithFields(fields).Debug("efs service connetion attempt")
	sess := session.New()

	var (
		awsLogger   = &awsLogger{ctx: ctx}
		awsLogLevel = aws.LogOff
	)
	if ll, ok := context.GetLogLevel(ctx); ok {
		switch ll {
		case log.DebugLevel:
			awsLogger.lvl = log.DebugLevel
			awsLogLevel = aws.LogDebugWithHTTPBody
		case log.InfoLevel:
			awsLogger.lvl = log.InfoLevel
			awsLogLevel = aws.LogDebug
		}
	}

	svc := awsefs.New(sess, &aws.Config{
		Region:     region,
		Endpoint:   endpoint,
		MaxRetries: d.maxRetries,
		Credentials: credentials.NewChainCredentials(
			[]credentials.Provider{
				&credentials.StaticProvider{
					Value: credentials.Value{
						AccessKeyID:     akey,
						SecretAccessKey: skey,
					},
				},
				&credentials.EnvProvider{},
				&credentials.SharedCredentialsProvider{},
				&ec2rolecreds.EC2RoleProvider{
					Client: ec2metadata.New(sess),
				},
			},
		),
		Logger:   awsLogger,
		LogLevel: aws.LogLevel(awsLogLevel),
	})

	ctx.WithFields(fields).Info("efs service connection created")

	if !d.disableSessionCache {
		sessions[ckey] = svc
		ctx.WithFields(fields).Info("efs service connection cached")
	}

	return svc, nil
}
예제 #3
0
func newServer(goCtx gocontext.Context, config gofig.Config) (*server, error) {

	adminTokenUUID, err := types.NewUUID()
	if err != nil {
		return nil, err
	}
	adminToken := adminTokenUUID.String()
	serverName := randomServerName()

	ctx := context.New(goCtx)
	ctx = ctx.WithValue(context.ServerKey, serverName)
	ctx = ctx.WithValue(context.AdminTokenKey, adminToken)

	if lvl, ok := context.GetLogLevel(ctx); ok {
		switch lvl {
		case log.DebugLevel:
			ctx = context.WithValue(
				ctx, gournal.LevelKey(),
				gournal.DebugLevel)
		case log.InfoLevel:
			ctx = context.WithValue(
				ctx, gournal.LevelKey(),
				gournal.InfoLevel)
		case log.WarnLevel:
			ctx = context.WithValue(
				ctx, gournal.LevelKey(),
				gournal.WarnLevel)
		case log.ErrorLevel:
			ctx = context.WithValue(
				ctx, gournal.LevelKey(),
				gournal.ErrorLevel)
		case log.FatalLevel:
			ctx = context.WithValue(
				ctx, gournal.LevelKey(),
				gournal.FatalLevel)
		case log.PanicLevel:
			ctx = context.WithValue(
				ctx, gournal.LevelKey(),
				gournal.PanicLevel)
		}
	}

	if logger, ok := ctx.Value(context.LoggerKey).(*log.Logger); ok {
		ctx = context.WithValue(
			ctx, gournal.AppenderKey(),
			glogrus.NewWithOptions(
				logger.Out, logger.Level, logger.Formatter))
	}

	if config == nil {
		var err error
		if config, err = apicnfg.NewConfig(); err != nil {
			return nil, err
		}
	}
	config = config.Scope(types.ConfigServer)

	s := &server{
		ctx:          ctx,
		name:         serverName,
		adminToken:   adminToken,
		config:       config,
		closeSignal:  make(chan int),
		closedSignal: make(chan int),
		closeOnce:    &sync.Once{},
	}

	if logger, ok := s.ctx.Value(context.LoggerKey).(*log.Logger); ok {
		s.PrintServerStartupHeader(logger.Out)
	} else {
		s.PrintServerStartupHeader(os.Stdout)
	}

	if lvl, err := log.ParseLevel(
		config.GetString(types.ConfigLogLevel)); err == nil {
		context.SetLogLevel(s.ctx, lvl)
	}

	logFields := log.Fields{}
	logConfig, err := utils.ParseLoggingConfig(
		config, logFields, "libstorage.server")
	if err != nil {
		return nil, err
	}

	// always update the server context's log level
	context.SetLogLevel(s.ctx, logConfig.Level)
	s.ctx.WithFields(logFields).Info("configured logging")

	s.ctx.Info("initializing server")

	if err := s.initEndpoints(s.ctx); err != nil {
		return nil, err
	}
	s.ctx.Info("initialized endpoints")

	if err := services.Init(s.ctx, s.config); err != nil {
		return nil, err
	}
	s.ctx.Info("initialized services")

	if logConfig.HTTPRequests || logConfig.HTTPResponses {
		s.logHTTPEnabled = true
		s.logHTTPRequests = logConfig.HTTPRequests
		s.logHTTPResponses = logConfig.HTTPResponses
		s.stdOut = getLogIO(logConfig.Stdout, types.ConfigLogStdout)
		s.stdErr = getLogIO(logConfig.Stderr, types.ConfigLogStderr)
	}

	s.initGlobalMiddleware()

	if err := s.initRouters(); err != nil {
		return nil, err
	}

	servers = append(servers, s)

	return s, nil
}