|
| 1 | +// Package alertwindow provides utility functions for getting the alert time window. |
| 2 | +package alertwindow |
| 3 | + |
| 4 | +import ( |
| 5 | + "context" |
| 6 | + "fmt" |
| 7 | + "os" |
| 8 | + "time" |
| 9 | + |
| 10 | + cdenv "github.com/GoogleCloudPlatform/cloud-deploy-samples/packages/cdenv" |
| 11 | + cdapi "google.golang.org/api/clouddeploy/v1" |
| 12 | +) |
| 13 | + |
| 14 | +// AlertTimeWindow holds the rollout start time and the end time to look for alerts (which is now). |
| 15 | +type AlertTimeWindow struct { |
| 16 | + // StartTime is the start time of the alert window in RFC3339 format. |
| 17 | + StartTime time.Time |
| 18 | + // EndTime is the end time of the alert window in RFC3339 format. |
| 19 | + EndTime time.Time |
| 20 | +} |
| 21 | + |
| 22 | +// TimeWindow returns the start time of the rollout as a string representing the number of |
| 23 | +// milliseconds since the Unix epoch (this is the time format expected by Datadog). |
| 24 | +func TimeWindow(ctx context.Context) (*AlertTimeWindow, error) { |
| 25 | + // Construct the rollout resource name. |
| 26 | + projectID := os.Getenv(cdenv.ProjectIDEnvKey) |
| 27 | + location := os.Getenv(cdenv.LocationEnvKey) |
| 28 | + pipelineID := os.Getenv(cdenv.PipelineEnvKey) |
| 29 | + releaseID := os.Getenv(cdenv.ReleaseEnvKey) |
| 30 | + rolloutID := os.Getenv(cdenv.RolloutEnvKey) |
| 31 | + |
| 32 | + rolloutName := fmt.Sprintf("projects/%s/locations/%s/deliveryPipelines/%s/releases/%s/rollouts/%s", |
| 33 | + projectID, location, pipelineID, releaseID, rolloutID) |
| 34 | + |
| 35 | + cdService, err := cdapi.NewService(ctx) |
| 36 | + if err != nil { |
| 37 | + return nil, fmt.Errorf("unable to create Cloud Deploy API service: %v", err) |
| 38 | + } |
| 39 | + |
| 40 | + rollout, err := cdService.Projects.Locations.DeliveryPipelines.Releases.Rollouts.Get(rolloutName).Do() |
| 41 | + if err != nil { |
| 42 | + return nil, fmt.Errorf("unable to get rollout from Cloud Deploy API: %v", err) |
| 43 | + } |
| 44 | + |
| 45 | + parsedStartTime, err := time.Parse(time.RFC3339, rollout.DeployStartTime) |
| 46 | + if err != nil { |
| 47 | + return nil, fmt.Errorf("unable to convert start time to RFC3339 format in order to validate time") |
| 48 | + } |
| 49 | + |
| 50 | + endTime := time.Now().Format(time.RFC3339) |
| 51 | + parsedEndTime, err := time.Parse(time.RFC3339, endTime) |
| 52 | + if err != nil { |
| 53 | + return nil, fmt.Errorf("unable to convert start time to RFC3339 format in order to validate time") |
| 54 | + } |
| 55 | + if parsedStartTime.After(parsedEndTime) { |
| 56 | + return nil, fmt.Errorf("start time is after end time") |
| 57 | + } |
| 58 | + |
| 59 | + return &AlertTimeWindow{StartTime: parsedStartTime, EndTime: parsedEndTime}, nil |
| 60 | +} |
0 commit comments