This repository has been archived by the owner on Jan 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 327
/
nomad.go
249 lines (223 loc) · 7.01 KB
/
nomad.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package nomad
import (
"context"
"fmt"
"github.com/hashicorp/nomad/api"
"github.com/hashicorp/waypoint-plugin-sdk/terminal"
"time"
)
const (
// bytes
DefaultCSIVolumeCapacityMin = int64(1073741824)
DefaultCSIVolumeCapacityMax = int64(2147483648)
DefaultCSIVolumeMountFS = "xfs"
DefaultResourcesCPU = 200
DefaultResourcesMemory = 600
)
type NomadConfig struct {
authSoftFail bool `hcl:"auth_soft_fail,optional"`
image string `hcl:"server_image,optional"`
namespace string `hcl:"namespace,optional"`
serviceAnnotations map[string]string `hcl:"service_annotations,optional"`
consulService bool `hcl:"consul_service,optional"`
consulServiceUITags []string `hcl:"consul_service_ui_tags:optional"`
consulServiceBackendTags []string `hcl:"consul_service_backend_tags:optional"`
consulDatacenter string `hcl:"consul_datacenter,optional"`
consulDomain string `hcl:"consul_datacenter,optional"`
// If set along with consul, will use this hostname instead of
// making a consul DNS hostname for the server address in its context
consulServiceHostname string `hcl:"consul_service_hostname,optional"`
odrImage string `hcl:"odr_image,optional"`
region string `hcl:"namespace,optional"`
datacenters []string `hcl:"datacenters,optional"`
policyOverride bool `hcl:"policy_override,optional"`
serverResourcesCPU string `hcl:"server_resources_cpu,optional"`
serverResourcesMemory string `hcl:"server_resources_memory,optional"`
runnerResourcesCPU string `hcl:"runner_resources_cpu,optional"`
runnerResourcesMemory string `hcl:"runner_resources_memory,optional"`
hostVolume string `hcl:"host_volume,optional"`
csiVolumeProvider string `hcl:"csi_volume_provider,optional"`
csiVolumeCapacityMin int64 `hcl:"csi_volume_capacity_min,optional"`
csiVolumeCapacityMax int64 `hcl:"csi_volume_capacity_max,optional"`
csiFS string `hcl:"csi_fs,optional"`
nomadHost string `hcl:"nomad_host,optional"`
csiTopologies map[string]string `hcl:"nomad_csi_topologies,optional"`
csiExternalId string `hcl:"nomad_csi_external_id,optional"`
csiPluginId string `hcl:"nomad_csi_plugin_id,optional"`
csiSecrets map[string]string `hcl:"nomad_csi_secrets,optional"`
}
func RunJob(
ctx context.Context,
s terminal.Step,
client *api.Client,
job *api.Job,
policyOverride bool,
) (string, error) {
jobOpts := &api.RegisterOptions{
PolicyOverride: policyOverride,
}
resp, _, err := client.Jobs().RegisterOpts(job, jobOpts, nil)
if err != nil {
return "", err
}
s.Update("Waiting for allocation to be scheduled")
qopts := &api.QueryOptions{
WaitIndex: resp.EvalCreateIndex,
WaitTime: time.Duration(500 * time.Millisecond),
}
eval, meta, err := waitForEvaluation(ctx, s, client, resp, qopts)
if err != nil {
return "", err
}
if eval == nil {
return "", fmt.Errorf("evaluation status could not be determined")
}
qopts.WaitIndex = meta.LastIndex
var allocID string
retries := 0
maxRetries := 3
for {
allocs, qmeta, err := client.Evaluations().Allocations(eval.ID, qopts)
if err != nil {
return "", err
}
qopts.WaitIndex = qmeta.LastIndex
if len(allocs) == 0 {
return "", fmt.Errorf("no allocations found after evaluation completed")
}
switch allocs[0].ClientStatus {
case "running":
allocID = allocs[0].ID
s.Update("Nomad allocation running")
retries++
case "pending":
s.Update(fmt.Sprintf("Waiting for allocation %q to start", allocs[0].ID))
// retry
default:
return "", fmt.Errorf("allocation failed")
}
if allocID != "" {
if retries == maxRetries {
return allocID, nil
} else {
s.Update("Ensuring allocation %q has properly started up...", allocs[0].ID)
time.Sleep(1 * time.Second)
}
}
select {
case <-time.After(500 * time.Millisecond):
case <-ctx.Done():
return "", ctx.Err()
}
}
}
func waitForEvaluation(
ctx context.Context,
s terminal.Step,
client *api.Client,
resp *api.JobRegisterResponse,
qopts *api.QueryOptions,
) (*api.Evaluation, *api.QueryMeta, error) {
for {
eval, meta, err := client.Evaluations().Info(resp.EvalID, qopts)
if err != nil {
return nil, nil, err
}
qopts.WaitIndex = meta.LastIndex
switch eval.Status {
case "pending":
s.Update("Nomad allocation pending...")
case "complete":
s.Update("Nomad allocation created")
return eval, meta, nil
case "failed", "canceled", "blocked":
s.Update("Nomad failed to schedule the job")
s.Status(terminal.StatusError)
return nil, nil, fmt.Errorf("Nomad evaluation did not transition to 'complete'")
default:
return nil, nil, fmt.Errorf("receieved unknown eval status from Nomad: %q", eval.Status)
}
}
}
func CreatePersistentVolume(
ctx context.Context,
client *api.Client,
id, name, csiPluginId, csiVolumeProvider, csiFS, csiExternalId string,
csiVolumeCapacityMin, csiVolumeCapacityMax int64,
csiTopologies, csiSecrets, csiParams map[string]string,
csiMountFlags []string,
) error {
vol := api.CSIVolume{
ID: id,
Name: name,
ExternalID: csiExternalId,
RequestedCapabilities: []*api.CSIVolumeCapability{
{
AccessMode: "single-node-writer",
AttachmentMode: "file-system",
},
},
MountOptions: &api.CSIMountOptions{
FSType: DefaultCSIVolumeMountFS,
MountFlags: csiMountFlags,
},
RequestedCapacityMin: DefaultCSIVolumeCapacityMin,
RequestedCapacityMax: DefaultCSIVolumeCapacityMax,
PluginID: csiPluginId,
Parameters: csiParams,
Provider: csiVolumeProvider,
RequestedTopologies: &api.CSITopologyRequest{
Required: nil,
Preferred: nil,
},
Secrets: nil,
}
if csiVolumeCapacityMin != 0 {
vol.RequestedCapacityMin = csiVolumeCapacityMin
}
if csiVolumeCapacityMax != 0 {
vol.RequestedCapacityMax = csiVolumeCapacityMax
}
if csiFS != "" {
vol.MountOptions.FSType = csiFS
}
if len(csiTopologies) != 0 {
vol.RequestedTopologies.Required = []*api.CSITopology{
{
Segments: csiTopologies,
},
}
}
if len(csiSecrets) != 0 {
vol.Secrets = csiSecrets
}
_, _, err := client.CSIVolumes().Create(&vol, &api.WriteOptions{})
if err != nil {
return err
}
return nil
}
func SetupPretask(volumeMounts []*api.VolumeMount) *api.Task {
preTask := api.NewTask("pre_task", "docker")
// Observed WP user and group IDs in the published container, update if those ever change
waypointUserID := 100
waypointGroupID := 1000
cpu := DefaultResourcesCPU
mem := DefaultResourcesMemory
preTask.Config = map[string]interface{}{
// Doing this because this is the only way https://github.com/hashicorp/nomad/issues/8892
"image": "busybox:latest",
"command": "sh",
"args": []string{"-c", fmt.Sprintf("chown -R %d:%d /data/", waypointUserID, waypointGroupID)},
}
preTask.VolumeMounts = volumeMounts
preTask.Resources = &api.Resources{
CPU: &cpu,
MemoryMB: &mem,
}
preTask.Lifecycle = &api.TaskLifecycle{
Hook: "prestart",
Sidecar: false,
}
return preTask
}