/
dataset_transfer_execution.go
407 lines (345 loc) · 12.1 KB
/
dataset_transfer_execution.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
// Copyright 2020 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 job
import (
"context"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
scp "github.com/bramvdbogaerde/go-scp"
"github.com/hashicorp/consul/api"
"github.com/pkg/errors"
"github.com/ystia/yorc/v4/config"
"github.com/ystia/yorc/v4/deployments"
"github.com/ystia/yorc/v4/events"
"github.com/ystia/yorc/v4/helper/ziputil"
"github.com/ystia/yorc/v4/log"
"github.com/ystia/yorc/v4/prov"
"github.com/ystia/yorc/v4/prov/operations"
"github.com/ystia/yorc/v4/tosca"
"golang.org/x/crypto/ssh"
)
const (
sendInputsOperation = "custom.sendjobinputs"
getResultsOperation = "custom.getresults"
zipDatasetArtifactName = "zip_dataset"
jobIDEnvVar = "JOB_ID"
filePathEnvVar = "FILE_PATH"
zipResultAttribute = "zip_result"
)
// DatasetTransferExecution holds properties of a data transfer operation
type DatasetTransferExecution struct {
KV *api.KV
Cfg config.Configuration
DeploymentID string
TaskID string
NodeName string
User string
Operation prov.Operation
OverlayPath string
Artifacts map[string]string
MonitoringTimeInterval time.Duration
EnvInputs []*operations.EnvInput
VarInputsNames []string
}
// ExecuteAsync executes an asynchronous operation - supported to wait for a file and get its content
func (e *DatasetTransferExecution) ExecuteAsync(ctx context.Context) (*prov.Action, time.Duration, error) {
if strings.ToLower(e.Operation.Name) != tosca.RunnableRunOperationName {
return nil, 0, errors.Errorf("Unsupported asynchronous operation %q", e.Operation.Name)
}
jobIDStr := e.getValueFromEnvInputs(jobIDEnvVar)
if jobIDStr == "" {
return nil, 0, errors.Errorf("Failed to get associated job ID")
}
_, err := strconv.ParseInt(jobIDStr, 10, 64)
if err != nil {
err = errors.Wrapf(err, "Unexpected Job ID value %q for deployment %s node %s",
jobIDStr, e.DeploymentID, e.NodeName)
return nil, 0, err
}
data := make(map[string]string)
data["filePath"] = e.getValueFromEnvInputs(filePathEnvVar)
if data["filePath"] == "" {
return nil, 0, errors.Errorf("Failed to get file path property")
}
data["taskID"] = e.TaskID
data["nodeName"] = e.NodeName
data["jobID"] = jobIDStr
data["user"] = e.User
return &prov.Action{ActionType: "heappe-filecontent-monitoring", Data: data}, e.MonitoringTimeInterval, err
}
// Execute executes a synchronous operation
func (e *DatasetTransferExecution) Execute(ctx context.Context) error {
var err error
switch strings.ToLower(e.Operation.Name) {
case installOperation, "standard.create":
// Nothing to do
case uninstallOperation, "standard.delete":
// Nothing to do
case sendInputsOperation:
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, e.DeploymentID).Registerf(
"Sending input to job %q", e.NodeName)
err = e.transferDataset(ctx)
if err != nil {
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, e.DeploymentID).Registerf(
"Dataset transfer %q failed, error %s", e.NodeName, err.Error())
}
case getResultsOperation:
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, e.DeploymentID).Registerf(
"Getting results from job %q", e.NodeName)
err = e.getResultFiles(ctx)
if err != nil {
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, e.DeploymentID).Registerf(
"Getting results from job %q failed, error %s", e.NodeName, err.Error())
}
case tosca.RunnableSubmitOperationName:
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, e.DeploymentID).Registerf(
"Submitting Job %q", e.NodeName)
case tosca.RunnableCancelOperationName:
events.WithContextOptionalFields(ctx).NewLogEntry(events.LogLevelINFO, e.DeploymentID).Registerf(
"Canceling Job %q", e.NodeName)
default:
err = errors.Errorf("Unsupported operation %q on dataset transfer", e.Operation.Name)
}
return err
}
// ResolveExecution resolves inputs and artifacts before the execution of an operation
func (e *DatasetTransferExecution) ResolveExecution(ctx context.Context) error {
log.Debugf("Preparing execution of operation %q on node %q for deployment %q", e.Operation.Name, e.NodeName, e.DeploymentID)
ovPath, err := operations.GetOverlayPath(e.Cfg, e.TaskID, e.DeploymentID)
if err != nil {
return err
}
e.OverlayPath = ovPath
if err = e.resolveInputs(ctx); err != nil {
return err
}
if err = e.resolveArtifacts(ctx); err != nil {
return err
}
return err
}
func (e *DatasetTransferExecution) transferDataset(ctx context.Context) error {
heappeClient, err := getHEAppEClient(ctx, e.Cfg, e.DeploymentID, e.NodeName, e.User)
if err != nil {
return err
}
jobIDStr := e.getValueFromEnvInputs(jobIDEnvVar)
if jobIDStr == "" {
return errors.Errorf("Failed to get associated job ID")
}
jobID, err := strconv.ParseInt(jobIDStr, 10, 64)
if err != nil {
err = errors.Wrapf(err, "Unexpected Job ID value %q for deployment %s node %s",
jobIDStr, e.DeploymentID, e.NodeName)
return err
}
// Get files to transfer
fileNames, err := e.getDatasetFileNames(jobID)
if err != nil {
return err
}
// Get details on destination where to transfer files
transferMethod, err := heappeClient.GetFileTransferMethod(jobID)
if err != nil {
return err
}
defer func() {
_ = heappeClient.EndFileTransfer(jobID, transferMethod)
}()
clientConfig, err := getSSHClientConfig(transferMethod.Credentials.Username,
transferMethod.Credentials.PrivateKey)
if err != nil {
return errors.Wrapf(err, "Failed to create a SSH client using HEAppE file transfer credentials")
}
client := scp.NewClient(transferMethod.ServerHostname+":22", &clientConfig)
// Connect to the remote server
err = client.Connect()
if err != nil {
return errors.Wrapf(err, "Failed to connect to remote server using HEAppE file transfer credentials")
}
defer client.Close()
// Transfer each file in the dataset
for _, fileName := range fileNames {
f, err := os.Open(fileName)
if err != nil {
return errors.Wrapf(err, "Failed to open dataset file %s", fileName)
}
defer f.Close()
baseName := filepath.Base(fileName)
err = client.CopyFile(f, filepath.Join(transferMethod.SharedBasepath, baseName), "0744")
if err != nil {
return errors.Wrapf(err, "Failed to copy dataset file %s to remote server", baseName)
}
}
return err
}
func (e *DatasetTransferExecution) getDatasetFileNames(jobID int64) ([]string, error) {
var fileNames []string
datasetFileName := e.Artifacts[zipDatasetArtifactName]
if datasetFileName == "" {
return fileNames, errors.Errorf("No dataset provided")
}
datasetAbsPath := filepath.Join(e.OverlayPath, datasetFileName)
destDir := filepath.Join(e.OverlayPath, fmt.Sprintf("heappe_dataset_%d", jobID))
os.RemoveAll(destDir)
err := os.MkdirAll(destDir, 0700)
if err != nil {
return fileNames, err
}
fileNames, err = ziputil.Unzip(datasetAbsPath, destDir)
if err != nil {
err = errors.Wrapf(err, "Failed to unzip dataset")
}
return fileNames, err
}
func (e *DatasetTransferExecution) getResultFiles(ctx context.Context) error {
// Get details on remote host where to get result files
heappeClient, err := getHEAppEClient(ctx, e.Cfg, e.DeploymentID, e.NodeName, e.User)
if err != nil {
return err
}
jobIDStr := e.getValueFromEnvInputs(jobIDEnvVar)
if jobIDStr == "" {
return errors.Errorf("Failed to get associated job ID")
}
jobID, err := strconv.ParseInt(jobIDStr, 10, 64)
if err != nil {
err = errors.Wrapf(err, "Unexpected Job ID value %q for deployment %s node %s",
jobIDStr, e.DeploymentID, e.NodeName)
return err
}
// Get list of result files
changedFiles, err := heappeClient.ListChangedFilesForJob(jobID)
if err != nil {
return err
}
log.Debugf("Result files for deployment %s node %s : %+v", e.DeploymentID, e.NodeName, changedFiles)
if len(changedFiles) == 0 {
// Nothing to do
return err
}
transferMethod, err := heappeClient.GetFileTransferMethod(jobID)
if err != nil {
return err
}
defer func() {
_ = heappeClient.EndFileTransfer(jobID, transferMethod)
}()
// go-scp is not yet providing the copy from remote
// see pull request https://github.com/bramvdbogaerde/go-scp/pull/12
// In the meantime using scp command
// Creating the private key file
pkeyFile := filepath.Join(e.OverlayPath, fmt.Sprintf("heappepkey_%d", jobID))
err = ioutil.WriteFile(pkeyFile, []byte(transferMethod.Credentials.PrivateKey), 0400)
if err != nil {
return err
}
defer os.Remove(pkeyFile)
copyDir := filepath.Join(e.OverlayPath, fmt.Sprintf("heappe_results_%d", jobID))
archivePath := copyDir + ".zip"
os.RemoveAll(copyDir)
err = os.MkdirAll(copyDir, 0700)
if err != nil {
return err
}
defer os.RemoveAll(copyDir)
// Transfer each file in the dataset
for _, changedFile := range changedFiles {
remotePath := filepath.Join(transferMethod.SharedBasepath, changedFile.FileName)
localPath := filepath.Join(copyDir, changedFile.FileName)
localDir := filepath.Dir(localPath)
if localDir != "." {
err = os.MkdirAll(localDir, 0700)
if err != nil {
return errors.Wrapf(err, "Failed to create local dir %s", localDir)
}
}
copyCmd := exec.Command("/bin/scp", "-i", pkeyFile,
"-o", "StrictHostKeyChecking=no",
fmt.Sprintf("%s@%s:%s",
transferMethod.Credentials.Username,
transferMethod.ServerHostname,
remotePath),
localPath)
stdoutStderr, err := copyCmd.CombinedOutput()
if err != nil {
log.Printf("Failed to copy remote file: %s - %s", err.Error(), string(stdoutStderr))
return errors.Wrapf(err, "Failed to copy remote file %s", changedFile.FileName)
}
if len(stdoutStderr) > 0 {
log.Debugf("Copy of %s: %s", changedFile.FileName, string(stdoutStderr))
}
}
zippedContent, err := ziputil.ZipPath(copyDir)
if err != nil {
return err
}
err = ioutil.WriteFile(archivePath, zippedContent, 0700)
if err != nil {
return err
}
// Set the corresponding attribute
err = deployments.SetAttributeForAllInstances(ctx, e.DeploymentID, e.NodeName,
zipResultAttribute, archivePath)
if err != nil {
err = errors.Wrapf(err, "Failed to store attribute %s for deployment %s node %s",
zipResultAttribute, e.DeploymentID, e.NodeName)
}
return err
}
func (e *DatasetTransferExecution) resolveInputs(ctx context.Context) error {
var err error
log.Debugf("Get environment inputs for node:%q", e.NodeName)
e.EnvInputs, e.VarInputsNames, err = operations.ResolveInputsWithInstances(
ctx, e.DeploymentID, e.NodeName, e.TaskID, e.Operation, nil, nil)
log.Debugf("Environment inputs: %v", e.EnvInputs)
return err
}
func (e *DatasetTransferExecution) resolveArtifacts(ctx context.Context) error {
var err error
log.Debugf("Get artifacts for node:%q", e.NodeName)
e.Artifacts, err = deployments.GetFileArtifactsForNode(ctx, e.DeploymentID, e.NodeName)
log.Debugf("Resolved artifacts: %v", e.Artifacts)
return err
}
func getSSHClientConfig(username, privateKey string) (ssh.ClientConfig, error) {
var clientConfig ssh.ClientConfig
signer, err := ssh.ParsePrivateKey([]byte(privateKey))
if err == nil {
clientConfig = ssh.ClientConfig{
User: username,
Auth: []ssh.AuthMethod{
ssh.PublicKeys(signer),
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
}
return clientConfig, err
}
func (e *DatasetTransferExecution) getValueFromEnvInputs(envVar string) string {
var result string
for _, envInput := range e.EnvInputs {
if envInput.Name == envVar {
result = envInput.Value
break
}
}
return result
}