|
| 1 | +package cs |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "time" |
| 6 | + |
| 7 | + "github.com/codesphere-cloud/cs-go/api" |
| 8 | +) |
| 9 | + |
| 10 | +type WaitForWorkspaceRunningOptions struct { |
| 11 | + Timeout time.Duration |
| 12 | + Delay time.Duration |
| 13 | +} |
| 14 | + |
| 15 | +// Waits for a given workspace to be running. |
| 16 | +// |
| 17 | +// Returns [TimedOut] error if the workspace does not become running in time. |
| 18 | +func WaitForWorkspaceRunning( |
| 19 | + client *api.Client, |
| 20 | + workspace *api.Workspace, |
| 21 | + opts WaitForWorkspaceRunningOptions, |
| 22 | +) error { |
| 23 | + timeout := opts.Timeout |
| 24 | + if timeout == 0 { |
| 25 | + timeout = 20 * time.Minute |
| 26 | + } |
| 27 | + delay := opts.Delay |
| 28 | + if delay == 0 { |
| 29 | + delay = 5 * time.Second |
| 30 | + } |
| 31 | + |
| 32 | + maxWaitTime := time.Now().Add(timeout) |
| 33 | + for time.Now().Before(maxWaitTime) { |
| 34 | + status, err := client.WorkspaceStatus(workspace.Id) |
| 35 | + |
| 36 | + if err != nil { |
| 37 | + // TODO: log error and retry until timeout is reached. |
| 38 | + return err |
| 39 | + } |
| 40 | + if status.IsRunning { |
| 41 | + return nil |
| 42 | + } |
| 43 | + time.Sleep(delay) |
| 44 | + } |
| 45 | + |
| 46 | + return NewTimedOut( |
| 47 | + fmt.Sprintf("Waiting for workspace %s(%d) to be ready", workspace.Name, workspace.Id), |
| 48 | + timeout) |
| 49 | +} |
| 50 | + |
| 51 | +type DeployWorkspaceArgs struct { |
| 52 | + TeamId int |
| 53 | + PlanId int |
| 54 | + Name string |
| 55 | + EnvVars map[string]string |
| 56 | + VpnConfigName *string |
| 57 | + |
| 58 | + Timeout time.Duration |
| 59 | +} |
| 60 | + |
| 61 | +// Deploys a workspace with the given configuration. |
| 62 | +// |
| 63 | +// Returns [TimedOut] error if the timeout is reached |
| 64 | +func DeployWorkspace( |
| 65 | + client api.Client, |
| 66 | + args DeployWorkspaceArgs, |
| 67 | +) error { |
| 68 | + workspace, err := client.CreateWorkspace(api.CreateWorkspaceArgs{ |
| 69 | + TeamId: args.TeamId, |
| 70 | + Name: args.Name, |
| 71 | + PlanId: args.PlanId, |
| 72 | + IsPrivateRepo: true, |
| 73 | + GitUrl: nil, |
| 74 | + InitialBranch: nil, |
| 75 | + SourceWorkspaceId: nil, |
| 76 | + WelcomeMessage: nil, |
| 77 | + Replicas: 1, |
| 78 | + VpnConfig: args.VpnConfigName, |
| 79 | + }) |
| 80 | + if err != nil { |
| 81 | + return err |
| 82 | + } |
| 83 | + WaitForWorkspaceRunning(&client, workspace, WaitForWorkspaceRunningOptions{Timeout: args.Timeout}) |
| 84 | + |
| 85 | + if len(args.EnvVars) != 0 { |
| 86 | + if err := client.SetEnvVarOnWorkspace(workspace.Id, args.EnvVars); err != nil { |
| 87 | + return err |
| 88 | + } |
| 89 | + } |
| 90 | + return nil |
| 91 | +} |
0 commit comments