-
Notifications
You must be signed in to change notification settings - Fork 23
/
executor.go
420 lines (380 loc) · 14.1 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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
// 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 hostspool
import (
"context"
"encoding/json"
"strings"
"github.com/ystia/yorc/helper/labelsutil"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/consul/api"
"github.com/pkg/errors"
"strconv"
"github.com/dustin/go-humanize"
"github.com/ystia/yorc/config"
"github.com/ystia/yorc/deployments"
"github.com/ystia/yorc/events"
"github.com/ystia/yorc/tasks"
"github.com/ystia/yorc/tosca"
)
type defaultExecutor struct {
}
func (e *defaultExecutor) ExecDelegate(ctx context.Context, cfg config.Configuration, taskID, deploymentID, nodeName, delegateOperation string) error {
cc, err := cfg.GetConsulClient()
if err != nil {
return err
}
// Fill log optional fields for log registration
logOptFields, ok := events.FromContext(ctx)
if !ok {
return errors.New("Missing contextual log optional fields")
}
logOptFields[events.NodeID] = nodeName
logOptFields[events.ExecutionID] = taskID
logOptFields[events.OperationName] = delegateOperation
logOptFields[events.InterfaceName] = "delegate"
ctx = events.NewContext(ctx, logOptFields)
instances, err := tasks.GetInstances(cc.KV(), taskID, deploymentID, nodeName)
if err != nil {
return err
}
allocatedResources, err := e.getAllocatedResourcesFromHostCapabilities(cc.KV(), deploymentID, nodeName)
if err != nil {
return errors.Wrapf(err, "failed to retrieve allocated resources from host capabilities for node %q and deploymentID %q", nodeName, deploymentID)
}
switch strings.ToLower(delegateOperation) {
case "install":
for _, instance := range instances {
deployments.SetInstanceStateWithContextualLogs(events.AddLogOptionalFields(ctx, events.LogOptionalFields{events.InstanceID: instance}), cc.KV(), deploymentID, nodeName, instance, tosca.NodeStateCreating)
}
err = e.hostsPoolCreate(ctx, cc, cfg, taskID, deploymentID, nodeName, allocatedResources)
if err != nil {
return err
}
for _, instance := range instances {
deployments.SetInstanceStateWithContextualLogs(events.AddLogOptionalFields(ctx, events.LogOptionalFields{events.InstanceID: instance}), cc.KV(), deploymentID, nodeName, instance, tosca.NodeStateStarted)
}
return nil
case "uninstall":
for _, instance := range instances {
deployments.SetInstanceStateWithContextualLogs(events.AddLogOptionalFields(ctx, events.LogOptionalFields{events.InstanceID: instance}), cc.KV(), deploymentID, nodeName, instance, tosca.NodeStateDeleting)
}
err = e.hostsPoolDelete(ctx, cc, cfg, taskID, deploymentID, nodeName, allocatedResources)
if err != nil {
return err
}
for _, instance := range instances {
deployments.SetInstanceStateWithContextualLogs(events.AddLogOptionalFields(ctx, events.LogOptionalFields{events.InstanceID: instance}), cc.KV(), deploymentID, nodeName, instance, tosca.NodeStateDeleted)
}
return nil
}
return errors.Errorf("operation %q not supported", delegateOperation)
}
func (e *defaultExecutor) hostsPoolCreate(originalCtx context.Context, cc *api.Client, cfg config.Configuration, taskID, deploymentID, nodeName string, allocatedResources map[string]string) error {
hpManager := NewManager(cc)
_, jsonProp, err := deployments.GetNodeProperty(cc.KV(), deploymentID, nodeName, "filters")
if err != nil {
return err
}
var filtersString []string
if jsonProp != "" {
err = json.Unmarshal([]byte(jsonProp), &filtersString)
if err != nil {
return errors.Wrapf(err, `failed to parse property "filter" for node %q as json %q`, nodeName, jsonProp)
}
}
filters, err := createFiltersFromComputeCapabilities(cc.KV(), deploymentID, nodeName)
if err != nil {
return err
}
for i := range filtersString {
f, err := labelsutil.CreateFilter(filtersString[i])
if err != nil {
return err
}
filters = append(filters, f)
}
shareable := false
if _, s, err := deployments.GetNodeProperty(cc.KV(), deploymentID, nodeName, "shareable"); err != nil {
return err
} else if s != "" {
shareable, err = strconv.ParseBool(s)
if err != nil {
return err
}
}
instances, err := tasks.GetInstances(cc.KV(), taskID, deploymentID, nodeName)
if err != nil {
return err
}
for _, instance := range instances {
logOptFields, _ := events.FromContext(originalCtx)
logOptFields[events.InstanceID] = instance
ctx := events.NewContext(originalCtx, logOptFields)
allocation := &Allocation{NodeName: nodeName, Instance: instance, DeploymentID: deploymentID, Shareable: shareable, Resources: allocatedResources}
hostname, warnings, err := hpManager.Allocate(allocation, filters...)
for _, warn := range warnings {
events.WithContextOptionalFields(ctx).
NewLogEntry(events.LogLevelWARN, deploymentID).Registerf(`%v`, warn)
}
if err != nil {
return err
}
err = deployments.SetInstanceAttribute(deploymentID, nodeName, instance, "hostname", hostname)
if err != nil {
return err
}
host, err := hpManager.GetHost(hostname)
if err != nil {
return err
}
err = deployments.SetInstanceCapabilityAttribute(deploymentID, nodeName, instance, "endpoint", "ip_address", host.Connection.Host)
if err != nil {
return err
}
credentials := map[string]interface{}{"user": host.Connection.User}
if host.Connection.Password != "" {
credentials["token"] = host.Connection.Password
}
if host.Connection.PrivateKey != "" {
credentials["keys"] = []string{host.Connection.PrivateKey}
}
err = deployments.SetInstanceCapabilityAttributeComplex(deploymentID, nodeName, instance, "endpoint", "credentials", credentials)
if err != nil {
return err
}
privateAddress, ok := host.Labels["private_address"]
if !ok {
privateAddress = host.Connection.Host
events.WithContextOptionalFields(ctx).
NewLogEntry(events.LogLevelWARN, deploymentID).Registerf(`no "private_address" label for host %q, we will use the address from the connection section`, hostname)
}
err = deployments.SetInstanceAttribute(deploymentID, nodeName, instance, "ip_address", privateAddress)
if err != nil {
return err
}
err = deployments.SetInstanceAttribute(deploymentID, nodeName, instance, "private_address", privateAddress)
if err != nil {
return err
}
if publicAddress, ok := host.Labels["public_address"]; ok {
err = deployments.SetInstanceAttribute(deploymentID, nodeName, instance, "public_address", publicAddress)
if err != nil {
return err
}
}
if host.Connection.Port != 0 {
err = deployments.SetInstanceCapabilityAttribute(deploymentID, nodeName, instance, "endpoint", "port", strconv.FormatUint(host.Connection.Port, 10))
if err != nil {
return err
}
}
for label, value := range host.Labels {
err = setAttributeFromLabel(deploymentID, nodeName, instance, label, value, "networks", "network_name")
if err != nil {
return err
}
err = setAttributeFromLabel(deploymentID, nodeName, instance, label, value, "networks", "network_id")
if err != nil {
return err
}
// This is bad as we split value even if we are not sure that it matches
err = setAttributeFromLabel(deploymentID, nodeName, instance, label, strings.Split(value, ","), "networks", "addresses")
if err != nil {
return err
}
}
return hpManager.UpdateResourcesLabels(hostname, allocatedResources, subtract, updateResourcesLabels)
}
return nil
}
func (e *defaultExecutor) getAllocatedResourcesFromHostCapabilities(kv *api.KV, deploymentID, nodeName string) (map[string]string, error) {
res := make(map[string]string, 0)
found, p, err := deployments.GetCapabilityProperty(kv, deploymentID, nodeName, "host", "num_cpus")
if err != nil {
return nil, err
}
if found && p != "" {
res["host.num_cpus"] = p
}
found, p, err = deployments.GetCapabilityProperty(kv, deploymentID, nodeName, "host", "mem_size")
if err != nil {
return nil, err
}
if found && p != "" {
res["host.mem_size"] = p
}
found, p, err = deployments.GetCapabilityProperty(kv, deploymentID, nodeName, "host", "disk_size")
if err != nil {
return nil, err
}
if found && p != "" {
res["host.disk_size"] = p
}
return res, nil
}
func appendCapabilityFilter(kv *api.KV, deploymentID, nodeName, capName, propName, op string, filters []labelsutil.Filter) ([]labelsutil.Filter, error) {
found, p, err := deployments.GetCapabilityProperty(kv, deploymentID, nodeName, capName, propName)
if err != nil {
return filters, err
}
if found && p != "" {
f, err := labelsutil.CreateFilter(capName + "." + propName + " " + op + " " + p)
if err != nil {
return filters, err
}
return append(filters, f), nil
}
return filters, nil
}
func createFiltersFromComputeCapabilities(kv *api.KV, deploymentID, nodeName string) ([]labelsutil.Filter, error) {
var err error
filters := make([]labelsutil.Filter, 0)
filters, err = appendCapabilityFilter(kv, deploymentID, nodeName, "host", "num_cpus", ">=", filters)
if err != nil {
return nil, err
}
filters, err = appendCapabilityFilter(kv, deploymentID, nodeName, "host", "cpu_frequency", ">=", filters)
if err != nil {
return nil, err
}
filters, err = appendCapabilityFilter(kv, deploymentID, nodeName, "host", "disk_size", ">=", filters)
if err != nil {
return nil, err
}
filters, err = appendCapabilityFilter(kv, deploymentID, nodeName, "host", "mem_size", ">=", filters)
if err != nil {
return nil, err
}
filters, err = appendCapabilityFilter(kv, deploymentID, nodeName, "os", "architecture", "=", filters)
if err != nil {
return nil, err
}
filters, err = appendCapabilityFilter(kv, deploymentID, nodeName, "os", "type", "=", filters)
if err != nil {
return nil, err
}
filters, err = appendCapabilityFilter(kv, deploymentID, nodeName, "os", "distribution", "=", filters)
if err != nil {
return nil, err
}
filters, err = appendCapabilityFilter(kv, deploymentID, nodeName, "os", "version", "=", filters)
if err != nil {
return nil, err
}
return filters, nil
}
func (e *defaultExecutor) hostsPoolDelete(originalCtx context.Context, cc *api.Client, cfg config.Configuration, taskID, deploymentID, nodeName string, allocatedResources map[string]string) error {
hpManager := NewManager(cc)
instances, err := tasks.GetInstances(cc.KV(), taskID, deploymentID, nodeName)
if err != nil {
return err
}
var errs error
for _, instance := range instances {
logOptFields, _ := events.FromContext(originalCtx)
logOptFields[events.InstanceID] = instance
ctx := events.NewContext(originalCtx, logOptFields)
found, hostname, err := deployments.GetInstanceAttribute(cc.KV(), deploymentID, nodeName, instance, "hostname")
if err != nil {
errs = multierror.Append(errs, err)
}
if !found {
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelWARN, deploymentID).Registerf("instance %q of node %q does not have a registered hostname. This may be due to an error at creation time. Should be checked.", instance, nodeName)
continue
}
allocation := &Allocation{NodeName: nodeName, Instance: instance, DeploymentID: deploymentID}
err = hpManager.Release(hostname, allocation)
if err != nil {
errs = multierror.Append(errs, err)
}
return hpManager.UpdateResourcesLabels(hostname, allocatedResources, add, updateResourcesLabels)
}
return errors.Wrap(errs, "errors encountered during hosts pool node release. Some hosts maybe not properly released.")
}
func setAttributeFromLabel(deploymentID, nodeName, instance, label string, value interface{}, prefix, suffix string) error {
if strings.HasPrefix(label, prefix+".") && strings.HasSuffix(label, "."+suffix) {
attrName := strings.Replace(strings.Replace(label, prefix+".", prefix+"/", -1), "."+suffix, "/"+suffix, -1)
err := deployments.SetInstanceAttributeComplex(deploymentID, nodeName, instance, attrName, value)
if err != nil {
return err
}
}
return nil
}
func updateResourcesLabels(origin map[string]string, diff map[string]string, operation func(a int64, b int64) int64) (map[string]string, error) {
labels := make(map[string]string)
// Host Resources Labels can only be updated when deployment resources requirement is described
if cpusDiffStr, ok := diff["host.num_cpus"]; ok {
if cpusOriginStr, ok := origin["host.num_cpus"]; ok {
cpusOrigin, err := strconv.Atoi(cpusOriginStr)
if err != nil {
return nil, err
}
cpusDiff, err := strconv.Atoi(cpusDiffStr)
if err != nil {
return nil, err
}
res := operation(int64(cpusOrigin), int64(cpusDiff))
labels["host.num_cpus"] = strconv.Itoa(int(res))
}
}
if memDiffStr, ok := diff["host.mem_size"]; ok {
if memOriginStr, ok := origin["host.mem_size"]; ok {
memOrigin, err := humanize.ParseBytes(memOriginStr)
if err != nil {
return nil, err
}
memDiff, err := humanize.ParseBytes(memDiffStr)
if err != nil {
return nil, err
}
res := operation(int64(memOrigin), int64(memDiff))
labels["host.mem_size"] = formatBytes(res, isIECformat(memOriginStr))
}
}
if diskDiffStr, ok := diff["host.disk_size"]; ok {
if diskOriginStr, ok := origin["host.disk_size"]; ok {
diskOrigin, err := humanize.ParseBytes(diskOriginStr)
if err != nil {
return nil, err
}
diskDiff, err := humanize.ParseBytes(diskDiffStr)
if err != nil {
return nil, err
}
res := operation(int64(diskOrigin), int64(diskDiff))
labels["host.disk_size"] = formatBytes(res, isIECformat(diskOriginStr))
}
}
return labels, nil
}
func add(valA int64, valB int64) int64 {
return valA + valB
}
func subtract(valA int64, valB int64) int64 {
return valA - valB
}
func formatBytes(value int64, isIEC bool) string {
if isIEC {
return humanize.IBytes(uint64(value))
}
return humanize.Bytes(uint64(value))
}
func isIECformat(value string) bool {
if value != "" && strings.HasSuffix(value, "iB") {
return true
}
return false
}