func()

in pkg/monitoring/monitoring.go [168:229]


func (c *Client) reportCumulativeCount(ctx context.Context, metricType, imageName string, success bool) error {
	reset := &timestamp.Timestamp{
		Seconds: c.resetTs.Unix(),
	}
	// For cumulative metrics, end time should be > than reset time. Thus, sleep for 2 seconds if
	// we find less than 1s has passed since resetTs. Sleep 2s instead of 1s to avoid flakes
	// from floating point addition errors.
	// This logic doesn't handle when time jumps back during daylight savings but we don't care
	// because:
	// 1. May cause a spurious but self recovering alert once a year which is too infrequent to
	//    bother handling.
	// 2. We expect to run this tool during business hours and daylight savings usually doesn't
	//    happen during then.
	if time.Now().Sub(c.resetTs).Seconds() < 1 {
		time.Sleep(time.Second * 2)
	}
	now := &timestamp.Timestamp{
		Seconds: time.Now().Unix(),
	}
	req := &monitoringpb.CreateTimeSeriesRequest{
		Name: "projects/" + c.projectID,
		TimeSeries: []*monitoringpb.TimeSeries{{
			Metric: &metric.Metric{
				Type: metricType,
				Labels: map[string]string{
					"docker_image": imageName,
					"success":      fmt.Sprintf("%v", success),
				},
			},
			// Cloud Monitoring insists a "Resource" be defined if we want to create alerts based
			// on the metric. The values here are mostly placeholders to satisfy Cloud Monitoring.
			// See https://cloud.google.com/monitoring/api/resources#tag_generic_task
			Resource: &monitoredres.MonitoredResource{
				Type: "generic_task",
				Labels: map[string]string{
					"project_id": c.projectID,
					"job":        "monitoring",
					// Cloud monitoring errors out unless we provide a location recognized by GCP or
					// AWS.
					"location":  "us-central1",
					"namespace": "monitoring",
					"task_id":   "monitoring",
				},
			},
			Points: []*monitoringpb.Point{{
				Interval: &monitoringpb.TimeInterval{
					StartTime: reset,
					EndTime:   now,
				},
				Value: &monitoringpb.TypedValue{
					Value: &monitoringpb.TypedValue_Int64Value{
						Int64Value: int64(1),
					},
				},
			}},
		}},
	}
	if err := c.mc.CreateTimeSeries(ctx, req); err != nil {
		return fmt.Errorf("unable to report time series to Google Cloud Monitoring: %w", err)
	}
	return nil
}