func readAndPushDataToStackdriver()

in prometheus-to-sd/main.go [217:274]


func readAndPushDataToStackdriver(ctx context.Context, client *monitoring.MetricClient, gceConf *config.GceConfig, sourceConfig *config.SourceConfig, monitoredResourceLabels map[string]string, prefix string) {
	glog.Infof("Running prometheus-to-sd, monitored target is %s %s://%v:%v", sourceConfig.Component, sourceConfig.Protocol, sourceConfig.Host, sourceConfig.Port)
	commonConfig := &config.CommonConfig{
		GceConfig:                   gceConf,
		SourceConfig:                sourceConfig,
		OmitComponentName:           *omitComponentName,
		DowncaseMetricNames:         *downcaseMetricNames,
		MonitoredResourceLabels:     monitoredResourceLabels,
		MonitoredResourceTypePrefix: prefix,
	}
	metricDescriptorCache := translator.NewMetricDescriptorCache(client, commonConfig)
	signal := time.After(0)
	useWhitelistedMetricsAutodiscovery := *autoWhitelistMetrics && len(sourceConfig.Whitelisted) == 0
	timeSeriesBuilder := translator.NewTimeSeriesBuilder(commonConfig, metricDescriptorCache)
	exportTicker := time.Tick(*exportInterval)

	for range time.Tick(*scrapeInterval) {
		// Possibly exporting as a first thing, since errors down the
		// road will jump to next iteration of the loop.
		select {
		case <-exportTicker:
			ts, scrapeTimestamp, err := timeSeriesBuilder.Build(ctx)
			// Mark cache as stale at the first export attempt after each refresh. Cache is considered refreshed only if after
			// previous export there was successful call to Refresh function.
			metricDescriptorCache.MarkStale()
			if err != nil {
				glog.Errorf("Could not build time series for component %v: %v", sourceConfig.Component, err)
			} else {
				translator.SendToStackdriver(ctx, client, commonConfig, ts, scrapeTimestamp)
			}
		default:
		}

		glog.V(4).Infof("Scraping metrics of component %v", sourceConfig.Component)
		select {
		case <-signal:
			glog.V(4).Infof("Updating metrics cache for component %v", sourceConfig.Component)
			metricDescriptorCache.Refresh(ctx)
			if useWhitelistedMetricsAutodiscovery {
				sourceConfig.UpdateWhitelistedMetrics(metricDescriptorCache.GetMetricNames())
				glog.V(2).Infof("Autodiscovered whitelisted metrics for component %v: %v", sourceConfig.Component, sourceConfig.Whitelisted)
			}
			signal = time.After(*metricDescriptorsResolution)
		default:
		}
		if useWhitelistedMetricsAutodiscovery && len(sourceConfig.Whitelisted) == 0 {
			glog.V(4).Infof("Skipping %v component as there are no metric to expose.", sourceConfig.Component)
			continue
		}
		scrapeTimestamp := time.Now()
		metrics, err := translator.GetPrometheusMetrics(sourceConfig)
		if err != nil {
			glog.V(2).Infof("Error while getting Prometheus metrics %v for component %v", err, sourceConfig.Component)
			continue
		}
		timeSeriesBuilder.Update(metrics, scrapeTimestamp)
	}
}