// flushOAuthTokenGrantsLogCron is handler for /internal/cron/bqlog/oauth-token-grants-flush.
767139
func flushOAuthTokenGrantsLogCron(c *router.Context) {
	// FlushGrantsLog logs errors inside. We also do not retry on errors. It's
	// fine to wait and flush on the next iteration.
	serviceaccounts.FlushGrantsLog(c.Context)
	c.Writer.WriteHeader(http.StatusOK)
}
1372517
func (blog *BLog) flush() {
	blog.lock.Lock()
	defer blog.lock.Unlock()

	if blog.closed {
		return
	}

	blog.writer.Flush()
}
499145
func (s *AccessTokenSession) TokenFunc(retried bool) (string, error) {
	if !s.token.IsValid() || retried {
		refreshToken, refreshable := s.token.(RefreshableAccessToken)
		if !refreshable {
			return "", errors.New("not a refresh token")
		}

		tokenResp, err := s.uaa.RefreshTokenGrant(refreshToken.RefreshValue())
		if err != nil {
			return "", bosherr.WrapError(err, "refreshing token")
		}

		s.token = tokenResp
		if err = s.saveTokenCreds(); err != nil {
			return "", err
		}
	}

	return s.token.Type() + " " + s.token.Value(), nil
}
882255
func (e *endpointDetails) requestToken(w http.ResponseWriter, req *http.Request) {
	authReq := e.osinOAuthClient.NewAuthorizeRequest(osincli.CODE)
	oauthURL := authReq.GetAuthorizeUrl()

	http.Redirect(w, req, oauthURL.String(), http.StatusFound)
}
989061
func (w *Writer) flush(events []*cloudwatchlogs.InputLogEvent) error {
	resp, err := w.client.PutLogEvents(&cloudwatchlogs.PutLogEventsInput{
		LogEvents:     events,
		LogGroupName:  w.group,
		LogStreamName: w.stream,
		SequenceToken: w.sequenceToken,
	})
	if err != nil {
		return err
	}

	if resp.RejectedLogEventsInfo != nil {
		w.err = &RejectedLogEventsInfoError{Info: resp.RejectedLogEventsInfo}
		return w.err
	}

	w.sequenceToken = resp.NextSequenceToken

	return nil
}
826069
func (s *Service) Flush() {
	s.flush(&s.authorizationKV)
	s.flush(&s.organizationKV)
	s.flush(&s.bucketKV)
	s.flush(&s.userKV)
	s.flush(&s.dashboardKV)
	s.flush(&s.viewKV)
	s.flush(&s.variableKV)
	s.flush(&s.dbrpMappingKV)
	s.flush(&s.userResourceMappingKV)
	s.flush(&s.labelKV)
	s.flush(&s.labelMappingKV)
	s.flush(&s.scraperTargetKV)
	s.flush(&s.telegrafConfigKV)
	s.flush(&s.onboardingKV)
	s.flush(&s.basicAuthKV)
	s.flush(&s.sessionKV)
	s.flush(&s.sourceKV)
}
46597
func (l *Log) flushCommitIndex() {
	l.file.Seek(0, os.SEEK_SET)
	fmt.Fprintf(l.file, "%8x\n", l.commitIndex)
	l.file.Seek(0, os.SEEK_END)
}
1211285
func flushMachineTokensLogCron(c *router.Context) {
	// FlushTokenLog logs errors inside. We also do not retry on errors. It's fine
	// to wait and flush on the next iteration.
	machinetoken.FlushTokenLog(c.Context)
	c.Writer.WriteHeader(http.StatusOK)
}
886141
func (mr *MockTokenRevocationStorageMockRecorder) RevokeRefreshToken(arg0, arg1 interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RevokeRefreshToken", reflect.TypeOf((*MockTokenRevocationStorage)(nil).RevokeRefreshToken), arg0, arg1)
}
1192513
func (p *Provider) RefreshToken(refreshToken string) (*oauth2.Token, error) {
	token := &oauth2.Token{RefreshToken: refreshToken}
	ts := p.config.TokenSource(oauth2.NoContext, token)
	newToken, err := ts.Token()
	if err != nil {
		return nil, err
	}
	return newToken, err
}
1226283
func (api *Client) GetAccessLogsContext(ctx context.Context, params AccessLogParameters) ([]Login, *Paging, error) {
	values := url.Values{
		"token": {api.token},
	}
	if params.Count != DEFAULT_LOGINS_COUNT {
		values.Add("count", strconv.Itoa(params.Count))
	}
	if params.Page != DEFAULT_LOGINS_PAGE {
		values.Add("page", strconv.Itoa(params.Page))
	}

	response, err := api.accessLogsRequest(ctx, "team.accessLogs", values)
	if err != nil {
		return nil, nil, err
	}
	return response.Logins, &response.Paging, nil
}
736303
func FlushEventsToBQ(c context.Context) error {
	_, err := eventsLog.Flush(c)
	return err
}
920840
func checkClaimsFromToken(r *http.Request, cred auth.Credentials) (map[string]interface{}, APIErrorCode) {
	token := getSessionToken(r)
	if token != "" && cred.AccessKey == "" {
		return nil, ErrNoAccessKey
	}
	if subtle.ConstantTimeCompare([]byte(token), []byte(cred.SessionToken)) != 1 {
		return nil, ErrInvalidToken
	}
	claims, err := getClaimsFromToken(r)
	if err != nil {
		return nil, toAPIErrorCode(context.Background(), err)
	}
	return claims, ErrNone
}
1151994
func (cl *ChannelLogger) Flush(logger log.Logger) error {
	// Grab the buffer at the here rather than within loop condition so that we
	// do not drain the buffer forever
	cl.Lock()
	defer cl.Unlock()
	bufferLength := cl.BufferLength()
	var errs []error
	for i := 0; i < bufferLength; i++ {
		logLine := cl.WaitReadLogLine()
		if logLine != nil {
			err := logger.Log(logLine...)
			if err != nil {
				errs = append(errs, err)
			}
		}
	}
	return errors.CombineErrors(errs)
}
741340
func (s *Server) Flush(ctx context.Context) {
	span := tracer.StartSpan("flush").(*trace.Span)
	defer span.ClientFinish(s.TraceClient)

	mem := &runtime.MemStats{}
	runtime.ReadMemStats(mem)

	flushTime := time.Now().UnixNano()
	atomic.StoreInt64(&s.lastFlushUnix, flushTime)

	s.Statsd.Gauge("worker.span_chan.total_elements", float64(len(s.SpanChan)), nil, 1.0)
	s.Statsd.Gauge("worker.span_chan.total_capacity", float64(cap(s.SpanChan)), nil, 1.0)
	s.Statsd.Gauge("gc.number", float64(mem.NumGC), nil, 1.0)
	s.Statsd.Gauge("gc.pause_total_ns", float64(mem.PauseTotalNs), nil, 1.0)
	s.Statsd.Gauge("mem.heap_alloc_bytes", float64(mem.HeapAlloc), nil, 1.0)
	s.Statsd.Gauge("flush.flush_timestamp_ns", float64(flushTime), nil, 1.0)

	samples := s.EventWorker.Flush()

	// TODO Concurrency
	for _, sink := range s.metricSinks {
		sink.FlushOtherSamples(span.Attach(ctx), samples)
	}

	go s.flushTraces(span.Attach(ctx))

	var finalMetrics []samplers.InterMetric

	// This ensures that mixedscope histograms and timers behave correctly.
	// That is, they should emit aggregates when forwarding, but no percentiles.
	// Similarly, they should emit percentiles when global, but no aggregates.
	//
	// This serves two purposes:
	//   * Percentiles are only accurate when aggregated globally.
	//   * Avoid double counting and breaking existing queries (if count is also
	//     emitted globally, queries that sum over counts double!)
	var percentiles []float64
	aggregates := s.HistogramAggregates
	if !s.IsLocal() {
		percentiles = s.HistogramPercentiles
		aggregates = samplers.HistogramAggregates{}
	}

	tempMetrics, ms := s.tallyMetrics(percentiles)

	finalMetrics = s.generateInterMetrics(span.Attach(ctx), percentiles, aggregates, tempMetrics, ms)

	s.reportMetricsFlushCounts(ms)

	wg := sync.WaitGroup{}
	if s.IsLocal() {
		wg.Add(1)
		// Forward over gRPC or HTTP depending on the configuration
		if s.forwardUseGRPC {
			go func() {
				s.forwardGRPC(span.Attach(ctx), tempMetrics)
				wg.Done()
			}()
		} else {
			go func() {
				s.flushForward(span.Attach(ctx), tempMetrics)
				wg.Done()
			}()
		}
	} else {
		s.reportGlobalMetricsFlushCounts(ms)
	}

	// If there's nothing to flush, don't bother calling the plugins and stuff.
	if len(finalMetrics) == 0 {
		return
	}

	for _, sink := range s.metricSinks {
		wg.Add(1)
		go func(ms sinks.MetricSink) {
			err := ms.Flush(span.Attach(ctx), finalMetrics)
			if err != nil {
				log.WithError(err).WithField("sink", ms.Name()).Warn("Error flushing sink")
			}
			wg.Done()
		}(sink)
	}
	wg.Wait()

	go func() {
		samples := &ssf.Samples{}
		defer metrics.Report(s.TraceClient, samples)

		tags := map[string]string{"part": "post"}
		for _, p := range s.getPlugins() {
			start := time.Now()
			err := p.Flush(span.Attach(ctx), finalMetrics)
			samples.Add(ssf.Timing(fmt.Sprintf("flush.plugins.%s.total_duration_ns", p.Name()), time.Since(start), time.Nanosecond, tags))
			if err != nil {
				samples.Add(ssf.Count(fmt.Sprintf("flush.plugins.%s.error_total", p.Name()), 1, nil))
			}
			samples.Add(ssf.Gauge(fmt.Sprintf("flush.plugins.%s.post_metrics_total", p.Name()), float32(len(finalMetrics)), nil))
		}
	}()
}
930550
func (i *MintedGrantInfo) toBigQueryMessage() *bqpb.OAuthTokenGrant {
	return &bqpb.OAuthTokenGrant{
		// Information about the produced token.
		Fingerprint:     utils.TokenFingerprint(i.Response.GrantToken),
		TokenId:         fmt.Sprintf("%d", i.GrantBody.TokenId),
		ServiceAccount:  i.GrantBody.ServiceAccount,
		ProxyIdentity:   i.GrantBody.Proxy,
		EndUserIdentity: i.GrantBody.EndUser,
		IssuedAt:        i.GrantBody.IssuedAt,
		Expiration: &timestamp.Timestamp{
			Seconds: i.GrantBody.IssuedAt.Seconds + i.GrantBody.ValidityDuration,
			Nanos:   i.GrantBody.IssuedAt.Nanos,
		},

		// Information supplied by the caller.
		AuditTags: i.Request.AuditTags,

		// Information about the service account rule used.
		ConfigRev:  i.ConfigRev,
		ConfigRule: i.Rule.Name,

		// Information about the request handler environment.
		PeerIp:         i.PeerIP.String(),
		ServiceVersion: i.Response.ServiceVersion,
		GaeRequestId:   i.RequestID,
		AuthDbRev:      i.AuthDBRev,
	}
}
586059
func (b *BufferedLogger) Flush() error {
	b.mu.Lock()
	b.mu.Unlock()
	return b.flush()
}