Пример #1
0
func TestLogger(t *testing.T) {
	Convey("logger", t, func() {
		c := Use(logging.SetLevel(context.Background(), logging.Debug))
		l := logging.Get(c)
		So(l, ShouldNotBeNil)
		l.Debugf("test %s", logging.Debug)
		l.Infof("test %s", logging.Info)
		l.Warningf("test %s", logging.Warning)
		l.Errorf("test %s", logging.Error)
		l.Errorf("test WAT: %s", logging.Level(9001))
		ml := l.(*MemLogger)
		mld := ml.data

		So(len(*mld), ShouldEqual, 5)
		So((*mld)[0], ShouldResemble, LogEntry{logging.Debug, "test debug", nil})
		So((*mld)[1], ShouldResemble, LogEntry{logging.Info, "test info", nil})
		So((*mld)[2], ShouldResemble, LogEntry{logging.Warning, "test warning", nil})
		So((*mld)[3], ShouldResemble, LogEntry{logging.Error, "test error", nil})
		So((*mld)[4], ShouldResemble, LogEntry{logging.Error, "test WAT: unknown", nil})
	})

	Convey("logger context", t, func() {
		c := Use(context.Background())
		l := logging.Get(c)
		So(l, ShouldNotBeNil)
		ml := l.(*MemLogger)

		l.Infof("totally works: %s", "yes")

		So(len(*ml.data), ShouldEqual, 1)
		So((*ml.data)[0], ShouldResemble, LogEntry{logging.Info, "totally works: yes", nil})
	})

	Convey("field data", t, func() {
		c := Use(context.Background())
		data := map[string]interface{}{
			"trombone": 50,
			"cat":      "amazing",
		}
		c = logging.SetFields(c, logging.NewFields(data))
		l := logging.Get(c)
		ml := l.(*MemLogger)

		l.Infof("Some unsuspecting log")
		So((*ml.data)[0].Data["trombone"], ShouldEqual, 50)
		So((*ml.data)[0].Data["cat"], ShouldEqual, "amazing")
	})
}
Пример #2
0
// Run will run f every cyle (at least once), and fail if maxErrs are returned by
// f in a row. It returns Results indiciating success, number of overruns and
// errors. Use context.WithCancel/Timeout/Deadline to limit the overall run time.
func Run(ctx context.Context, f Runner, cycle time.Duration, maxErrs int, c clock.Clock) (ret *Results) {
	// TODO: ts_mon stuff.
	ret = &Results{Success: true}

	tmr := c.NewTimer()
	defer tmr.Stop()

	nextCycle := cycle
	consecErrs := 0
	log := logging.Get(ctx)

	run := func() {
		t0 := c.Now()
		// TODO(seanmccullough) Optionally cancel overruns via context.WithTimeout.
		err := f(ctx)
		dur := c.Now().Sub(t0)
		if dur > cycle {
			log.Errorf("Task overran by %v (%v - %v)", (dur - cycle), dur, cycle)
			ret.Overruns++
		}

		if err != nil {
			log.Errorf("Got an error: %v", err)
			ret.Errs++
			if consecErrs++; consecErrs >= maxErrs {
				ret.Success = false
				return
			}
		} else {
			consecErrs = 0
		}

		nextCycle = cycle - dur
		if tmr.Reset(nextCycle) {
			log.Errorf("Timer was still active")
		}
	}

	// Run f at least once.
	run()

	// Keep running f until ctx is done.
	for {
		select {
		case <-ctx.Done():
			tmr.Stop()
			return ret
		case <-tmr.GetC():
			run()
		}
	}
}
Пример #3
0
func (c *config) createAuthenticatedClient(ctx context.Context) (*http.Client, error) {
	scopes := []string{}
	scopes = append(scopes, cloudLoggingScopes...)
	scopes = append(scopes, pubsubScopes...)

	// Get our authenticated client.
	options := auth.Options{
		Scopes:                 scopes,
		ServiceAccountJSONPath: c.serviceAccountJSONPath,
		Logger:                 log.Get(ctx),
	}
	authenticator := auth.NewAuthenticator(options)

	mode := auth.SilentLogin
	if c.authInteractive {
		mode = auth.InteractiveLogin
	}

	return auth.AuthenticatedClient(mode, authenticator)
}
Пример #4
0
func TestAuthenticator(t *testing.T) {
	Convey("Given mocked secrets dir", t, func() {
		tempDir := mockSecretsDir()

		Convey("Check NewAuthenticator defaults", func() {
			clientID, clientSecret := DefaultClient()
			ctx := context.Background()
			a := NewAuthenticator(Options{Context: ctx}).(*authenticatorImpl)
			So(a.opts, ShouldResemble, &Options{
				Method:                 AutoSelectMethod,
				Scopes:                 []string{OAuthScopeEmail},
				ClientID:               clientID,
				ClientSecret:           clientSecret,
				ServiceAccountJSONPath: filepath.Join(tempDir, "service_account.json"),
				GCEAccountName:         "default",
				Context:                ctx,
				Logger:                 logging.Get(ctx),
			})
		})
	})
}
Пример #5
0
func TestCloudLoggingConfig(t *testing.T) {
	Convey(`A test logging config, using a test HTTP client/server`, t, func() {
		ctx := context.Background()

		config := &loggerConfig{
			projectName:  "test-project",
			resourceType: "test-resource",
			logsID:       "test-logs-id",
		}

		client := &http.Client{}

		Convey(`Requires a project name.`, func() {
			config.projectName = ""
			_, _, err := config.use(ctx, client)
			So(err, ShouldNotBeNil)
		})

		Convey(`Requires a resource type.`, func() {
			config.resourceType = ""
			_, _, err := config.use(ctx, client)
			So(err, ShouldNotBeNil)
		})

		Convey(`Requires a logs ID.`, func() {
			config.logsID = ""
			_, _, err := config.use(ctx, client)
			So(err, ShouldNotBeNil)
		})

		Convey(`Installs a bound cloud logger into a context.`, func() {
			ctx, closeFunc, err := config.use(ctx, client)
			So(err, ShouldBeNil)
			defer closeFunc()

			So(log.Get(ctx), ShouldHaveSameTypeAs, &boundCloudLogger{})
		})
	})
}
Пример #6
0
func (c *endpointConfig) createService(ctx context.Context) (endpointService, error) {
	if c.url == "" {
		return nil, errors.New("endpoint: you must supply a monitoring endpoint")
	}

	authenticator := auth.NewAuthenticator(
		auth.Options{
			Method:                 auth.ServiceAccountMethod,
			Scopes:                 endpointScopes,
			ServiceAccountJSONPath: c.serviceAccountJSONPath,
			Logger:                 log.Get(ctx),
		})
	client, err := auth.AuthenticatedClient(auth.SilentLogin, authenticator)
	if err != nil {
		log.Errorf(log.SetError(ctx, err), "Failed to configure endpoint client.")
		return nil, errors.New("endpoint: failed to configure endpoint client")
	}

	return &endpointServiceImpl{
		endpointConfig: *c,
		client:         client,
	}, nil
}
Пример #7
0
// NewAuthenticator returns a new instance of Authenticator given its options.
func NewAuthenticator(opts Options) Authenticator {
	// Add default scope, sort scopes.
	if len(opts.Scopes) == 0 {
		opts.Scopes = []string{OAuthScopeEmail}
	}
	tmp := make([]string, len(opts.Scopes))
	copy(tmp, opts.Scopes)
	sort.Strings(tmp)
	opts.Scopes = tmp

	// Fill in blanks with default values.
	if opts.ClientID == "" || opts.ClientSecret == "" {
		opts.ClientID, opts.ClientSecret = DefaultClient()
	}
	if opts.ServiceAccountJSONPath == "" {
		opts.ServiceAccountJSONPath = filepath.Join(SecretsDir(), "service_account.json")
	}
	if opts.GCEAccountName == "" {
		opts.GCEAccountName = "default"
	}
	if opts.Context == nil {
		opts.Context = context.Background()
	}
	if opts.Logger == nil {
		opts.Logger = logging.Get(opts.Context)
	}

	// See ensureInitialized for the rest of the initialization.
	auth := &authenticatorImpl{opts: &opts, log: opts.Logger}
	auth.transport = &authTransport{
		parent: auth,
		base:   internal.TransportFromContext(opts.Context),
		log:    opts.Logger,
	}
	return auth
}