|
| 1 | +package cloudrun |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "time" |
| 8 | + |
| 9 | + "cloud.google.com/go/run/apiv2/runpb" |
| 10 | + "github.com/nullstone-io/deployment-sdk/app" |
| 11 | + "github.com/nullstone-io/deployment-sdk/gcp" |
| 12 | + "github.com/nullstone-io/deployment-sdk/gcp/cloudrun" |
| 13 | + "golang.org/x/sync/errgroup" |
| 14 | + "gopkg.in/nullstone-io/nullstone.v0/admin" |
| 15 | +) |
| 16 | + |
| 17 | +type JobRunner struct { |
| 18 | + JobName string |
| 19 | + MainContainerName string |
| 20 | + Adminer gcp.ServiceAccount |
| 21 | +} |
| 22 | + |
| 23 | +const ( |
| 24 | + // Polling interval for checking job status |
| 25 | + defaultPollInterval = 2 * time.Second |
| 26 | +) |
| 27 | + |
| 28 | +func (r JobRunner) Run(ctx context.Context, options admin.RunOptions, cmd []string) error { |
| 29 | + // Start the job execution |
| 30 | + exec, err := r.startJob(ctx, cmd) |
| 31 | + if err != nil { |
| 32 | + return fmt.Errorf("error running job: %w", err) |
| 33 | + } |
| 34 | + |
| 35 | + eg, ctx := errgroup.WithContext(ctx) |
| 36 | + eg.Go(func() error { |
| 37 | + absoluteTime := time.Now() |
| 38 | + executionFilter := fmt.Sprintf("resource.labels.execution_id=%q", exec.Uid) |
| 39 | + logStreamOptions := app.LogStreamOptions{ |
| 40 | + StartTime: &absoluteTime, |
| 41 | + WatchInterval: time.Duration(0), // this makes sure the log stream doesn't exist until the context is canceled |
| 42 | + Emitter: options.LogEmitter, |
| 43 | + Selector: &executionFilter, |
| 44 | + } |
| 45 | + if err := options.LogStreamer.Stream(ctx, logStreamOptions); err != nil { |
| 46 | + if errors.Is(err, context.Canceled) { |
| 47 | + return nil |
| 48 | + } |
| 49 | + return err |
| 50 | + } |
| 51 | + return nil |
| 52 | + }) |
| 53 | + |
| 54 | + // TODO: How do we report start failures that aren't reported to logs? (e.g. container pull error) |
| 55 | + |
| 56 | + // Monitor the job execution |
| 57 | + eg.Go(func() error { |
| 58 | + return r.monitorExecution(ctx, exec) |
| 59 | + }) |
| 60 | + |
| 61 | + // Wait for all goroutines to complete |
| 62 | + return eg.Wait() |
| 63 | +} |
| 64 | + |
| 65 | +func (r JobRunner) startJob(ctx context.Context, cmd []string) (*runpb.Execution, error) { |
| 66 | + // Create a client for Cloud Run Jobs |
| 67 | + client, err := cloudrun.NewJobsClient(ctx, r.Adminer) |
| 68 | + if err != nil { |
| 69 | + return nil, fmt.Errorf("error creating Cloud Run Jobs client: %w", err) |
| 70 | + } |
| 71 | + |
| 72 | + // If a command is provided, use it as "args" in main container overrides |
| 73 | + req := &runpb.RunJobRequest{ |
| 74 | + Name: r.JobName, |
| 75 | + Overrides: &runpb.RunJobRequest_Overrides{ContainerOverrides: make([]*runpb.RunJobRequest_Overrides_ContainerOverride, 0)}, |
| 76 | + } |
| 77 | + if len(cmd) > 0 { |
| 78 | + req.Overrides = &runpb.RunJobRequest_Overrides{ |
| 79 | + ContainerOverrides: []*runpb.RunJobRequest_Overrides_ContainerOverride{ |
| 80 | + { |
| 81 | + Name: r.MainContainerName, |
| 82 | + Args: cmd, |
| 83 | + }, |
| 84 | + }, |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + op, err := client.RunJob(ctx, req) |
| 89 | + if err != nil { |
| 90 | + return nil, fmt.Errorf("error running job: %w", err) |
| 91 | + } |
| 92 | + if _, err := op.Wait(ctx); err != nil { |
| 93 | + return nil, fmt.Errorf("an error occurred waiting for job to start: %w", err) |
| 94 | + } |
| 95 | + return op.Metadata() |
| 96 | +} |
| 97 | + |
| 98 | +// monitorExecution monitors the job execution until it completes |
| 99 | +func (r JobRunner) monitorExecution(ctx context.Context, exec *runpb.Execution) error { |
| 100 | + client, err := cloudrun.NewExecutionsClient(ctx, r.Adminer) |
| 101 | + if err != nil { |
| 102 | + return fmt.Errorf("error creating Cloud Run Executions client: %w", err) |
| 103 | + } |
| 104 | + |
| 105 | + ticker := time.NewTicker(defaultPollInterval) |
| 106 | + defer ticker.Stop() |
| 107 | + |
| 108 | + for { |
| 109 | + select { |
| 110 | + case <-ctx.Done(): |
| 111 | + return ctx.Err() |
| 112 | + case <-ticker.C: |
| 113 | + updated, err := client.GetExecution(ctx, &runpb.GetExecutionRequest{Name: exec.Name}) |
| 114 | + if err != nil { |
| 115 | + return fmt.Errorf("error getting job execution status: %w", err) |
| 116 | + } |
| 117 | + |
| 118 | + if (updated.FailedCount + updated.SucceededCount) >= updated.TaskCount { |
| 119 | + // Job execution completed |
| 120 | + if updated.FailedCount == 1 && updated.TaskCount == 1 { |
| 121 | + return fmt.Errorf("job execution failed") |
| 122 | + } |
| 123 | + if updated.FailedCount > 1 { |
| 124 | + return fmt.Errorf("%d of %d job executions failed", updated.FailedCount, updated.TaskCount) |
| 125 | + } |
| 126 | + return nil |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | +} |
0 commit comments