-
Notifications
You must be signed in to change notification settings - Fork 23
/
executor.go
346 lines (309 loc) · 14.7 KB
/
executor.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
// Copyright 2018 Bull S.A.S. Atos Technologies - Bull, Rue Jean Jaures, B.P.68, 78340, Les Clayes-sous-Bois, France.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package slurm
import (
"context"
"fmt"
"strings"
"sync"
"time"
"github.com/hashicorp/consul/api"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
"github.com/ystia/yorc/config"
"github.com/ystia/yorc/deployments"
"github.com/ystia/yorc/events"
"github.com/ystia/yorc/helper/sshutil"
"github.com/ystia/yorc/log"
"github.com/ystia/yorc/prov"
"github.com/ystia/yorc/tasks"
"github.com/ystia/yorc/tosca"
)
type defaultExecutor struct {
client *sshutil.SSHClient
}
type allocationResponse struct {
jobID string
granted bool
}
const reSallocPending = `^salloc: Pending job allocation (\d+)`
const reSallocGranted = `^salloc: Granted job allocation (\d+)`
func getJobExecution(conf config.Configuration, taskID, deploymentID, nodeName string, operation prov.Operation, stepName string) (execution, error) {
consulClient, err := conf.GetConsulClient()
if err != nil {
return nil, err
}
kv := consulClient.KV()
isJob, err := deployments.IsNodeDerivedFrom(kv, deploymentID, nodeName, "yorc.nodes.slurm.Job")
if err != nil {
return nil, err
}
if !isJob {
return nil, errors.Errorf("operation %q supported only for nodes derived from %q", operation.Name, "yorc.nodes.slurm.Job")
}
return newExecution(kv, conf, taskID, deploymentID, nodeName, stepName, operation)
}
func (e *defaultExecutor) ExecAsyncOperation(ctx context.Context, conf config.Configuration, taskID, deploymentID, nodeName string, operation prov.Operation, stepName string) (*prov.Action, time.Duration, error) {
log.Debugf("Slurm defaultExecutor: Execute the operation async: %+v", operation)
exec, err := getJobExecution(conf, taskID, deploymentID, nodeName, operation, stepName)
if err != nil {
return nil, 0, err
}
return exec.executeAsync(ctx)
}
func (e *defaultExecutor) ExecOperation(ctx context.Context, conf config.Configuration, taskID, deploymentID, nodeName string, operation prov.Operation) error {
log.Debugf("Slurm defaultExecutor: Execute the operation: %+v", operation)
exec, err := getJobExecution(conf, taskID, deploymentID, nodeName, operation, "")
if err != nil {
return err
}
return exec.execute(ctx)
}
func (e *defaultExecutor) ExecDelegate(ctx context.Context, cfg config.Configuration, taskID, deploymentID, nodeName, delegateOperation string) error {
consulClient, err := cfg.GetConsulClient()
if err != nil {
return err
}
kv := consulClient.KV()
instances, err := tasks.GetInstances(kv, taskID, deploymentID, nodeName)
if err != nil {
return err
}
e.client, err = GetSSHClient(cfg)
if err != nil {
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelERROR, deploymentID).RegisterAsString(err.Error())
return err
}
operation := strings.ToLower(delegateOperation)
switch {
case operation == "install":
err = e.installNode(ctx, kv, cfg, deploymentID, nodeName, instances, operation)
case operation == "uninstall":
err = e.uninstallNode(ctx, kv, cfg, deploymentID, nodeName, instances, operation)
default:
return errors.Errorf("Unsupported operation %q", delegateOperation)
}
return err
}
func (e *defaultExecutor) installNode(ctx context.Context, kv *api.KV, cfg config.Configuration, deploymentID, nodeName string, instances []string, operation string) error {
for _, instance := range instances {
err := deployments.SetInstanceStateWithContextualLogs(events.AddLogOptionalFields(ctx, events.LogOptionalFields{events.InstanceID: instance}), kv, deploymentID, nodeName, instance, tosca.NodeStateCreating)
if err != nil {
return err
}
}
infra, err := generateInfrastructure(ctx, kv, cfg, deploymentID, nodeName, operation)
if err != nil {
return err
}
return e.createInfrastructure(ctx, kv, cfg, deploymentID, nodeName, infra)
}
func (e *defaultExecutor) uninstallNode(ctx context.Context, kv *api.KV, cfg config.Configuration, deploymentID, nodeName string, instances []string, operation string) error {
for _, instance := range instances {
err := deployments.SetInstanceStateWithContextualLogs(events.AddLogOptionalFields(ctx, events.LogOptionalFields{events.InstanceID: instance}), kv, deploymentID, nodeName, instance, tosca.NodeStateDeleting)
if err != nil {
return err
}
}
infra, err := generateInfrastructure(ctx, kv, cfg, deploymentID, nodeName, operation)
if err != nil {
return err
}
return e.destroyInfrastructure(ctx, kv, cfg, deploymentID, nodeName, infra)
}
func (e *defaultExecutor) createInfrastructure(ctx context.Context, kv *api.KV, cfg config.Configuration, deploymentID, nodeName string, infra *infrastructure) error {
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, deploymentID).RegisterAsString("Creating the slurm infrastructure")
var g errgroup.Group
for _, compute := range infra.nodes {
func(ctx context.Context, comp *nodeAllocation) {
g.Go(func() error {
return e.createNodeAllocation(ctx, kv, comp, deploymentID, nodeName)
})
}(events.AddLogOptionalFields(ctx, events.LogOptionalFields{events.InstanceID: compute.instanceName}), compute)
}
if err := g.Wait(); err != nil {
err = errors.Wrapf(err, "Failed to create slurm infrastructure for deploymentID:%q, node name:%s", deploymentID, nodeName)
log.Debugf("%+v", err)
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelERROR, deploymentID).RegisterAsString(err.Error())
return err
}
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, deploymentID).RegisterAsString("Successfully creating the slurm infrastructure")
return nil
}
func (e *defaultExecutor) destroyInfrastructure(ctx context.Context, kv *api.KV, cfg config.Configuration, deploymentID, nodeName string, infra *infrastructure) error {
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, deploymentID).RegisterAsString("Destroying the slurm infrastructure")
var g errgroup.Group
for _, compute := range infra.nodes {
func(ctx context.Context, comp *nodeAllocation) {
g.Go(func() error {
return e.destroyNodeAllocation(ctx, kv, comp, deploymentID, nodeName)
})
}(events.AddLogOptionalFields(ctx, events.LogOptionalFields{events.InstanceID: compute.instanceName}), compute)
}
if err := g.Wait(); err != nil {
err = errors.Wrapf(err, "Failed to destroy slurm infrastructure for deploymentID:%q, node name:%s", deploymentID, nodeName)
log.Debugf("%+v", err)
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelERROR, deploymentID).RegisterAsString(err.Error())
return err
}
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, deploymentID).RegisterAsString("Successfully destroying the slurm infrastructure")
return nil
}
func (e *defaultExecutor) createNodeAllocation(ctx context.Context, kv *api.KV, nodeAlloc *nodeAllocation, deploymentID, nodeName string) error {
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, deploymentID).RegisterAsString(fmt.Sprintf("Creating node allocation for: deploymentID:%q, node name:%q", deploymentID, nodeName))
// salloc cmd
var sallocCPUFlag, sallocMemFlag, sallocPartitionFlag, sallocGresFlag, sallocConstraintFlag string
if nodeAlloc.cpu != "" {
sallocCPUFlag = fmt.Sprintf(" -c %s", nodeAlloc.cpu)
}
if nodeAlloc.memory != "" {
sallocMemFlag = fmt.Sprintf(" --mem=%s", nodeAlloc.memory)
}
if nodeAlloc.partition != "" {
sallocPartitionFlag = fmt.Sprintf(" -p %s", nodeAlloc.partition)
}
if nodeAlloc.gres != "" {
sallocGresFlag = fmt.Sprintf(" --gres=%s", nodeAlloc.gres)
}
if nodeAlloc.constraint != "" {
sallocConstraintFlag = fmt.Sprintf(" --constraint=%q", nodeAlloc.constraint)
}
// salloc command can potentially be a long synchronous command according to the slurm cluster state
// so we run it with a session wrapper with stderr/stdout in order to allow job cancellation if user decides to give up the deployment
var wg sync.WaitGroup
sessionWrapper, err := e.client.GetSessionWrapper()
if err != nil {
return errors.Wrap(err, "Failed to get an SSH session wrapper")
}
// We keep these both two channels open as 2 routines are concurrently and potentially able to send messages on them and we only get the first sent message. They will be garbage collected.
chErr := make(chan error)
chAllocResp := make(chan allocationResponse)
var allocResponse allocationResponse
go parseSallocResponse(sessionWrapper.Stderr, chAllocResp, chErr)
go parseSallocResponse(sessionWrapper.Stdout, chAllocResp, chErr)
wg.Add(1)
go func() {
defer wg.Done()
select {
case allocResponse = <-chAllocResp:
var mes string
deployments.SetInstanceAttribute(deploymentID, nodeName, nodeAlloc.instanceName, "job_id", allocResponse.jobID)
if allocResponse.granted {
mes = fmt.Sprintf("salloc command returned a GRANTED job allocation notification with job ID:%q", allocResponse.jobID)
} else {
mes = fmt.Sprintf("salloc command returned a PENDING job allocation notification with job ID:%q", allocResponse.jobID)
}
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, deploymentID).RegisterAsString(mes)
return
case err := <-chErr:
log.Debug(err.Error())
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelERROR, deploymentID).RegisterAsString(err.Error())
return
case <-time.After(30 * time.Second):
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelERROR, deploymentID).RegisterAsString("timeout elapsed waiting for jobID parsing after slurm allocation request")
return
}
}()
// Listen to potential cancellation in case of pending allocation
ctxAlloc, cancelAlloc := context.WithCancel(ctx)
chEnd := make(chan struct{})
go func() {
select {
case <-ctx.Done():
if &allocResponse != nil && allocResponse.jobID != "" {
log.Debug("Cancellation message has been sent: the pending job allocation has to be removed")
if err := cancelJobID(allocResponse.jobID, e.client); err != nil {
log.Printf("[Warning] an error occurred during cancelling jobID:%q", allocResponse.jobID)
return
}
// Drain the related jobID compute attribute
deployments.SetInstanceAttribute(deploymentID, nodeName, nodeAlloc.instanceName, "job_id", "")
// Cancel salloc comand
cancelAlloc()
}
return
case <-chEnd:
return
}
}()
// Run the salloc command
sallocCmd := strings.TrimSpace(fmt.Sprintf("salloc --no-shell -J %s%s%s%s%s%s", nodeAlloc.jobName, sallocCPUFlag, sallocMemFlag, sallocPartitionFlag, sallocGresFlag, sallocConstraintFlag))
err = sessionWrapper.RunCommand(ctxAlloc, sallocCmd)
if err != nil {
return errors.Wrap(err, "Failed to allocate Slurm resource")
}
wg.Wait() // we wait until jobID has been set
// retrieve nodename and partition
var nodeAndPartitionAttrs []string
if nodeAndPartitionAttrs, err = getAttributes(e.client, "node_partition", allocResponse.jobID); err != nil {
return err
}
err = deployments.SetInstanceCapabilityAttribute(deploymentID, nodeName, nodeAlloc.instanceName, "endpoint", "ip_address", nodeAndPartitionAttrs[0])
if err != nil {
return errors.Wrapf(err, "Failed to set capability attribute (ip_address) for node name:%s, instance name:%q", nodeName, nodeAlloc.instanceName)
}
err = deployments.SetInstanceAttribute(deploymentID, nodeName, nodeAlloc.instanceName, "ip_address", nodeAndPartitionAttrs[0])
if err != nil {
return errors.Wrapf(err, "Failed to set attribute (ip_address) for node name:%q, instance name:%q", nodeName, nodeAlloc.instanceName)
}
err = deployments.SetInstanceAttribute(deploymentID, nodeName, nodeAlloc.instanceName, "node_name", nodeAndPartitionAttrs[0])
if err != nil {
return errors.Wrapf(err, "Failed to set attribute (node_name) for node name:%q, instance name:%q", nodeName, nodeAlloc.instanceName)
}
err = deployments.SetInstanceAttribute(deploymentID, nodeName, nodeAlloc.instanceName, "partition", nodeAndPartitionAttrs[1])
if err != nil {
return errors.Wrapf(err, "Failed to set attribute (partition) for node name:%q, instance name:%q", nodeName, nodeAlloc.instanceName)
}
// Get cuda_visible_device attribute
var cudaVisibleDevice string
if cudaVisibleDeviceAttrs, err := getAttributes(e.client, "cuda_visible_devices", allocResponse.jobID, nodeName); err != nil {
// cuda_visible_device attribute is not mandatory : just log the error and set the attribute to an empty string
log.Println("[Warning]: " + err.Error())
} else {
cudaVisibleDevice = cudaVisibleDeviceAttrs[0]
}
err = deployments.SetInstanceAttribute(deploymentID, nodeName, nodeAlloc.instanceName, "cuda_visible_devices", cudaVisibleDevice)
if err != nil {
return errors.Wrapf(err, "Failed to set attribute (cuda_visible_devices) for node name:%q, instance name:%q", nodeName, nodeAlloc.instanceName)
}
// Update the instance state
err = deployments.SetInstanceStateWithContextualLogs(ctx, kv, deploymentID, nodeName, nodeAlloc.instanceName, tosca.NodeStateStarted)
if err != nil {
return err
}
close(chEnd)
return nil
}
func (e *defaultExecutor) destroyNodeAllocation(ctx context.Context, kv *api.KV, nodeAlloc *nodeAllocation, deploymentID, nodeName string) error {
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, deploymentID).RegisterAsString(fmt.Sprintf("Destroying node allocation for: deploymentID:%q, node name:%q, instance name:%q", deploymentID, nodeName, nodeAlloc.instanceName))
// scancel cmd
jobID, err := deployments.GetInstanceAttributeValue(kv, deploymentID, nodeName, nodeAlloc.instanceName, "job_id")
if err != nil {
return errors.Wrapf(err, "Failed to retrieve Slurm job ID for node name:%q, instance name:%q", nodeName, nodeAlloc.instanceName)
}
if jobID == nil || jobID.RawString() == "" {
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelWARN, deploymentID).Registerf("No job ID found for node name:%q, instance name:%q. We assume it has already been deleted", nodeName, nodeAlloc.instanceName)
} else {
if err := cancelJobID(jobID.RawString(), e.client); err != nil {
return err
}
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, deploymentID).RegisterAsString(fmt.Sprintf("Cancelling Job ID:%q", jobID.RawString()))
}
// Update the instance state
err = deployments.SetInstanceStateWithContextualLogs(ctx, kv, deploymentID, nodeName, nodeAlloc.instanceName, tosca.NodeStateDeleted)
if err != nil {
return err
}
return nil
}