/
prepare.go
79 lines (67 loc) · 2.63 KB
/
prepare.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package command
import (
"context"
"encoding/base64"
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/veertuinc/anka-cloud-gitlab-executor/internal/ankacloud"
"github.com/veertuinc/anka-cloud-gitlab-executor/internal/gitlab"
"github.com/veertuinc/anka-cloud-gitlab-executor/internal/log"
)
var prepareCommand = &cobra.Command{
Use: "prepare",
RunE: func(cmd *cobra.Command, args []string) error {
env, ok := cmd.Context().Value(contextKey("env")).(gitlab.Environment)
if !ok {
return fmt.Errorf("failed to get environment from context")
}
return executePrepare(cmd.Context(), env)
},
}
func executePrepare(ctx context.Context, env gitlab.Environment) error {
log.SetOutput(os.Stderr)
log.Println("running prepare stage")
apiClientConfig := getAPIClientConfig(env)
apiClient, err := ankacloud.NewAPIClient(apiClientConfig)
if err != nil {
return fmt.Errorf("failed to initialize API client with config +%v: %w", apiClientConfig, err)
}
controller := ankacloud.NewController(apiClient)
templateId := env.TemplateId
if templateId == "" {
if env.TemplateName == "" {
return fmt.Errorf("%w: either template id or temaplte name must be specified", gitlab.ErrMissingVar)
}
log.Println("please consider using template id instead of template name, since template names are not guaranteed to be unique")
templateId, err = controller.GetTemplateIdByName(ctx, env.TemplateName)
if err != nil {
return fmt.Errorf("failed to get template id of template named %q: %w", env.TemplateName, err)
}
log.Printf("template with id %q and name %q will be used\n", templateId, env.TemplateName)
}
req := ankacloud.CreateInstanceRequest{
TemplateId: templateId,
ExternalId: env.GitlabJobId,
Tag: env.TemplateTag,
NodeId: env.NodeId,
Priority: env.Priority,
NodeGroupId: env.NodeGroupId,
StartupScriptCondition: ankacloud.WaitForNetwork,
StartupScriptMonitoring: true,
StartupScriptTimeout: 5 * 60,
StartupScript: base64.StdEncoding.EncodeToString([]byte("sleep 5")), // even though we wait for network, it is recommended to wait a bit more
Vcpu: env.VmVcpu,
VramMb: env.VmVramMb,
}
log.Printf("creating instance with config: %+v\n", req)
instanceId, err := controller.CreateInstance(ctx, req)
if err != nil {
return fmt.Errorf("failed to create instance: %w", err)
}
if err := controller.WaitForInstanceToBeScheduled(ctx, instanceId); err != nil {
return fmt.Errorf("failed to wait for instance %q to be scheduled: %w", instanceId, err)
}
log.Printf("created instance id: %s\n", instanceId)
return nil
}