-
Notifications
You must be signed in to change notification settings - Fork 20
/
utils.js
2179 lines (2028 loc) · 77.8 KB
/
utils.js
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2019 Adobe Inc. All rights reserved.
This file is licensed to you 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 REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
const fs = require('fs-extra')
const sha1 = require('sha1')
const cloneDeep = require('lodash.clonedeep')
const aioLogger = require('@adobe/aio-lib-core-logging')('@adobe/aio-lib-runtime:utils', { provider: 'debug', level: process.env.LOG_LEVEL })
const yaml = require('js-yaml')
const { createFetch } = require('@adobe/aio-lib-core-networking')
const fetch = createFetch()
const globby = require('globby')
const path = require('path')
const archiver = require('archiver')
// this is a static list that comes from here: https://developer.adobe.com/runtime/docs/guides/reference/runtimes/
const SupportedRuntimes = ['nodejs:10', 'nodejs:12', 'nodejs:14', 'nodejs:16']
/**
*
* The entry point to the information read from the manifest, this can be extracted using
* [setPaths](#setpaths).
*
* @typedef {Array<ManifestPackage>} ManifestPackages
*/
/**
*
* The manifest package definition
*
* @typedef {object} ManifestPackage
* @property {string} version the manifest package version
* @property {string} [license] the manifest package license, e.g. Apache-2.0
* @property {Array<ManifestAction>} [actions] Actions in the manifest package
* @property {Array<ManifestSequence>} [sequences] Sequences in the manifest package
* @property {Array<ManifestTrigger>} [triggers] Triggers in the manifest package
* @property {Array<ManifestRule>} [rules] Rules in the manifest package
* @property {Array<ManifestDependency>} [dependencies] Dependencies in the manifest package
* @property {Array<object>} [apis] Apis in the manifest package
*/
/**
*
* The manifest action definition
*
* @typedef {object} ManifestAction
* @property {string} [version] the manifest action version
* @property {string} function the path to the action code
* @property {string} runtime the runtime environment or kind in which the action
* executes, e.g. 'nodejs:12'
* @property {string} [main] the entry point to the function
* @property {object} [inputs] the list of action default parameters
* @property {Array<object>} [limits] limits for the action
* @property {string} [web] indicate if an action should be exported as web, can take the
* value of: true | false | yes | no | raw
* @property {string} [web-export] same as web
* @property {boolean} [raw-http] indicate if an action should be exported as raw web action, this
* option is only valid if `web` or `web-export` is set to true
* @property {string} [docker] the docker container to run the action into
* @property {Array<object>} [annotations] the manifest action annotations
*/
/**
* @typedef IncludeEntry
* @type {object}
* @property {string} dest - destination for included files
* @property {Array} sources - list of files that matched pattern
*/
/**
* Gets the list of files matching the patterns defined by action.include
*
* @param {ManifestAction} action - action object from manifest which defines includes
* @returns {Promise<Array<IncludeEntry>>} list of files matching the patterns defined by action.include
*/
async function getIncludesForAction (action) {
const includeFiles = []
if (action.include) {
// include is array of [ src, dest ] : dest is optional
const files = await Promise.all(action.include.map(async elem => {
if (elem.length === 0) {
throw new Error('Invalid manifest `include` entry: Empty')
} else if (elem.length === 1) {
// src glob only, dest is root of action
elem.push('./')
} else if (elem.length === 2) {
// src glob + dest path both defined
} else {
throw new Error('Invalid manifest `include` entry: ' + elem.toString())
}
const globbyPattern = elem[0].split('\\').join('/')
const pair = {
dest: elem[1],
sources: await globby(globbyPattern)
}
return pair
}))
includeFiles.push(...files)
}
return includeFiles
}
/**
* The manifest sequence definition
* TODO: see https://github.com/apache/openwhisk-wskdeploy/blob/master/specification/html/spec_sequences.md
*
* @typedef {object} ManifestSequence
* @property {string} actions Comma separated list of actions in the sequence
*/
/**
* The manifest trigger definition
* TODO: see https://github.com/apache/openwhisk-wskdeploy/blob/master/specification/html/spec_triggers.md
*
* @typedef {object} ManifestTrigger
* @property {object} [inputs] inputs like cron and trigger_payload
* @property {string} [feed] feed associated with the trigger.
* @property {object} [annotations] annotations
*/
/**
* The manifest rule definition
* TODO: see https://github.com/apache/openwhisk-wskdeploy/blob/master/specification/html/spec_rules.md
*
* @typedef {object} ManifestRule
* @property {string} trigger trigger name
* @property {string} action action name
*/
/**
* The manifest dependency definition
* TODO
*
* @typedef {object} ManifestDependency
* @property {string} location package to bind to
* @property {object} [inputs] package parameters
*/
/**
*
* The OpenWhisk entities definitions, which are compatible with the `openwhisk` node
* client module. Can be obtained using (processpackage)[#processpackage] (with `onlyNames=true` for un-deployment)
*
* @typedef {object} OpenWhiskEntities
* @property {Array<OpenWhiskEntitiesRoute>} apis the array of route entities
* @property {Array<OpenWhiskEntitiesAction>} actions the array of action entities
* @property {Array<OpenWhiskEntitiesTrigger>} triggers the array of trigger entities
* @property {Array<OpenWhiskEntitiesRule>} rules the array of rule entities
* @property {Array<OpenWhiskEntitiesPackage>} pkgAndDeps the array of package entities
*/
/**
*
* The api entity definition
*
* @typedef {object} OpenWhiskEntitiesRoute
* @property {string} name the api name
* @property {string} basepath the api basepath
* @property {string} relpath the api relpath
* @property {string} action the action name behind the api
* @property {string} responsettype the response type, e.g. 'json'
* @property {string} operation the http method, e.g 'get'
*/
/**
* The action entity definition
* TODO
*
* @typedef {object} OpenWhiskEntitiesAction
* @property {string} action blank
* @property {string} name name
* @property {object} exec exec object
*/
/**
* The rule entity definition
* TODO
*
* @typedef {object} OpenWhiskEntitiesRule
* @property {string} trigger trigger name
* @property {string} action action name
*/
/**
* The trigger entity definition
* TODO
*
* @typedef {object} OpenWhiskEntitiesTrigger
* @property {string} [feed] feed associated with the trigger
* @property {object} [annotations] annotations
* @property {object} [parameters] parameters
*/
/**
* The package entity definition
* TODO
*
* @typedef {object} OpenWhiskEntitiesPackage
* @property {boolean} [publish] true for shared package
* @property {object} [parameters] parameters
*/
/**
*
* The entry point to the information read from the deployment file, this can be extracted using
* [setPaths](#setpaths).
* TODO
*
* @typedef {Array<object>} DeploymentPackages
*/
/**
* @typedef {object} DeploymentFileComponents
* @property {ManifestPackages} packages Packages in the manifest
* @property {object} deploymentTriggers Trigger names and their inputs in the deployment manifest
* @property {DeploymentPackages} deploymentPackages Packages in the deployment manifest
* @property {string} manifestPath Path to manifest
* @property {object} manifestContent Parsed manifest object
* @property {string} projectName Name of the project
*/
// for lines starting with date-time-string followed by stdout|stderr a ':' and a log-line, return only the logline
const dtsRegex = /\d{4}-[01]{1}\d{1}-[0-3]{1}\d{1}T[0-2]{1}\d{1}:[0-6]{1}\d{1}:[0-6]{1}\d{1}.\d+Z( *(stdout|stderr):)?\s(.*)/
const stripLog = (elem) => {
// `2019-10-11T19:08:57.298Z stdout: login-success :: { code: ...`
// should become: `login-success :: { code: ...`
const found = elem.match(dtsRegex)
if (found && found.length > 3) {
return found[3]
}
return elem
}
/**
* Prints activation logs messages.
*
* @param {object} activation the activation
* @param {boolean} strip if true, strips the timestamp which prefixes every log line
* @param {object} logger an instance of a logger to emit messages to
*/
function printLogs (activation, strip, logger) {
if (activation.logs) {
activation.logs.forEach(elem => {
if (strip) {
logger(stripLog(elem))
} else {
logger(elem)
}
})
}
}
/**
* Filters and prints action logs.
*
* @param {object} runtime runtime (openwhisk) object
* @param {object} logger an instance of a logger to emit messages to (may optionally provide logFunc and bannerFunc to customize logging)
* @param {number} limit maximum number of activations to fetch logs from
* @param {Array} filterActions array of actions to fetch logs from
* ['pkg1/'] = logs of all deployed actions under package pkg1
* ['pkg1/action'] = logs of action 'action' under package 'pkg1'
* [] = logs of all actions in the namespace
* @param {boolean} strip if true, strips the timestamp which prefixes every log line
* @param {number} startTime time in milliseconds. Only logs after this time will be fetched
* @returns {object} activation timestamp of the last retrieved activation or null
*/
async function printFilteredActionLogs (runtime, logger, limit, filterActions = [], strip = false, startTime = 0) {
// Get activations
const listOptions = { limit: limit, skip: 0, since: startTime }
const logFunc = logger ? logger.logFunc || logger : console.log
// This will narrow down the activation list to specific action
if (filterActions.length === 1 && !filterActions[0].endsWith('/')) {
listOptions.name = filterActions[0]
}
let activations = await runtime.activations.list(listOptions)
let lastActivationTime = 0
// Filter the activations
const actionFilterFunc = (actionPath, annotationValue) => {
// For logs of all deployed actions under a package
if (actionPath.endsWith('/')) {
const actionPathStrLookUp = actionPath.startsWith('/') ? actionPath : '/' + actionPath
return annotationValue.includes(actionPathStrLookUp)
}
// For actions with full path (pkg/actionName) specified in filterActions
return annotationValue.endsWith(actionPath)
}
if (filterActions.length > 0) {
activations = activations.filter((activation) => {
let includeActivation = false
activation.annotations.forEach((annotation) => {
if (annotation.key === 'path' && filterActions.some(actionPath => actionFilterFunc(actionPath, annotation.value))) {
includeActivation = true
}
})
return includeActivation
})
}
const activationsLogged = []
// Getting and printing activation logs
for (let i = (activations.length - 1); i >= 0; i--) {
const activation = activations[i]
lastActivationTime = activation.start
if (lastActivationTime > startTime) {
await printLogs(activation, runtime)
}
}
return { lastActivationTime }
/**
* Check if an activation entry is for a sequence.
*
* @param {*} activation activation log entry
* @returns {boolean} isSequenceActivation
*/
function isSequenceActivation (activation) {
if (activation.annotations && activation.annotations.length) {
return activation.annotations.some(item => (item.key === 'kind' && item.value === 'sequence'))
}
return false
}
/**
* Print activation logs
*
* @param {object} activation activation object
* @param {object} runtime runtime object
*/
async function printActivationLogs (activation, runtime) {
let retValue
try {
if (activationsLogged.includes(activation.activationId)) {
// Happens when this activation is already covered through a sequence
return
} else {
activationsLogged.push(activation.activationId)
}
retValue = await runtime.activations.logs({ activationId: activation.activationId })
// allow banners to be customized
if (logger && logger.bannerFunc) {
logger.bannerFunc(activation, retValue.logs)
} else {
activationLogBanner(logFunc, activation, retValue.logs)
}
if (retValue.logs.length > 0) {
retValue.logs.sort()
retValue.logs.forEach(function (logMsg) {
if (strip) {
logFunc(stripLog(logMsg))
} else {
logFunc(logMsg)
}
})
}
} catch (err) { // Happens in some cases such as trying to get logs of a trigger activation
// TODO: Trigger logs can be obtained from activation result but will need some formatting for the timestamp
// retValue = await runtime.activations.get({ activationId: activation.activationId })
}
}
/**
* Print sequence logs
*
* @param {object} activation sequence activation
* @param {object} runtime runtime object
*/
async function printSequenceLogs (activation, runtime) {
try {
const seqActivation = await runtime.activations.get(activation.activationId)
for (const seqItemActivationId of seqActivation.logs) {
const seqItemActivation = await runtime.activations.get(seqItemActivationId)
await printLogs(seqItemActivation, runtime)
}
} catch (err) {
// Happens when either the sequence or one of the actions in the sequence fails with 'application error'
// Ignore
}
}
/**
* Print logs
*
* @param {object} activation activation
* @param {object} runtime runtime
*/
async function printLogs (activation, runtime) {
if (isSequenceActivation(activation)) {
await printSequenceLogs(activation, runtime)
} else {
await printActivationLogs(activation, runtime)
}
}
}
/**
* returns path to main function as defined in package.json OR default of index.js
* note: file MUST exist, caller's responsibility, this method will throw if it does not exist
*
* @param {string} pkgJsonPath : path to a package.json file
* @returns {string} path to the entry file
*/
function getActionEntryFile (pkgJsonPath) {
try {
const pkgJsonContent = fs.readJsonSync(pkgJsonPath)
if (pkgJsonContent.main) {
return pkgJsonContent.main
}
} catch (err) {
aioLogger.debug(`File not found or does not define 'main' : ${pkgJsonPath}`)
}
return 'index.js'
}
/**
* Zip a file/folder using archiver
*
* @param {string} filePath path of file.folder to zip
* @param {string} out output path
* @param {boolean} pathInZip internal path in zip
* @returns {Promise} returns with a blank promise when done
*/
function zip (filePath, out, pathInZip = false) {
aioLogger.debug(`Creating zip of file/folder ${filePath}`)
const stream = fs.createWriteStream(out)
const archive = archiver('zip', { zlib: { level: 9 } })
return new Promise((resolve, reject) => {
stream.on('close', () => resolve())
archive.pipe(stream)
archive.on('error', err => reject(err))
let stats
try {
stats = fs.lstatSync(filePath) // throws if enoent
} catch (e) {
archive.destroy()
reject(e)
}
if (stats.isDirectory()) {
archive.directory(filePath, pathInZip)
} else { // if (stats.isFile()) {
archive.file(filePath, { name: pathInZip || path.basename(filePath) })
}
archive.finalize()
})
}
/**
* @description returns key value pairs in an object from the key value array supplied. Used to create parameters object.
* @returns {object} An object of key value pairs in this format : {Your key1 : 'Your Value 1' , Your key2: 'Your value 2'}
* @param {Array} inputsArray Array in the form of [{'key':'key1', 'value': 'value1'}]
*/
function createKeyValueObjectFromArray (inputsArray = []) {
const tempObj = {}
inputsArray.forEach((input) => {
if (input && input.key !== undefined && input.key !== null && input.key !== '') {
tempObj[input.key] = safeParse(input.value)
} else {
throw (new Error('Please provide correct input array with key and value params in each array item'))
}
})
return tempObj
}
/**
* @description returns key value array from the object supplied.
* @param {object} object JSON object
* @returns {Array} An array of key value pairs in this format : [{key : 'Your key 1' , value: 'Your value 1'}, {key : 'Your key 2' , value: 'Your value 2'} ]
*/
function createKeyValueArrayFromObject (object) {
return Object.keys(object).map(key => ({ key, value: object[key] }))
}
/**
* @description returns JSON.parse of passed object, but handles exceptions, and numeric strings
* @param {string} val value to parse
* @returns {object} the parsed object
*/
function safeParse (val) {
let resultVal = val
if (typeof val === 'string') {
if ((['true', 'false'].indexOf(val) > -1) ||
(['{', '['].indexOf(val.charAt(0)) > -1)) {
try {
resultVal = JSON.parse(val)
} catch (ex) {
aioLogger.debug(`JSON parse threw exception for value ${val}`)
}
}
}
return resultVal
}
/**
* @description returns key value array from the parameters supplied. Used to create --param and --annotation key value pairs
* @param {Array} flag value from flags.param or flags.annotation
* @returns {Array} An array of key value pairs in this format : [{key : 'Your key 1' , value: 'Your value 1'}, {key : 'Your key 2' , value: 'Your value 2'} ]
*/
function createKeyValueArrayFromFlag (flag) {
if (flag.length % 2 === 0) {
const tempArray = []
for (let i = 0; i < flag.length; i += 2) {
const obj = { key: flag[i] }
obj.value = safeParse(flag[i + 1])
tempArray.push(obj)
}
return tempArray
} else {
throw (new Error('Please provide correct values for flags'))
}
}
/**
* @description returns key value array from the json file supplied. Used to create --param-file and annotation-file key value pairs
* @param {string} file from flags['param-file'] or flags['annotation-file]
* @returns {Array} An array of key value pairs in this format : [{key : 'Your key 1' , value: 'Your value 1'}, {key : 'Your key 2' , value: 'Your value 2'} ]
*/
function createKeyValueArrayFromFile (file) {
const jsonParams = fs.readJsonSync(file)
const tempArray = []
Object.entries(jsonParams).forEach(
([key, value]) => {
tempArray.push({ key, value })
}
)
return tempArray
}
/**
* @description returns key value pairs in an object from the parameters supplied. Used to create --param and --annotation key value pairs
* @param {Array} flag from flags.param or flags.annotation
* @returns {object} An object of key value pairs in this format : {Your key1 : 'Your Value 1' , Your key2: 'Your value 2'}
*/
function createKeyValueObjectFromFlag (flag) {
if (flag.length % 2 === 0) {
let i
const tempObj = {}
for (i = 0; i < flag.length; i += 2) {
tempObj[flag[i]] = safeParse(flag[i + 1])
}
return tempObj
} else {
throw (new Error('Please provide correct values for flags'))
}
}
/**
* @description parses a package name string and returns the namespace and entity name for a package
* @param {string} name package name
* @returns {object} An object { namespace: string, name: string }
*/
function parsePackageName (name) {
const delimiter = '/'
const parts = name.split(delimiter)
let n = parts.length
const leadingSlash = name[0] === delimiter
// accept no more than [/]ns/p
// these are all valid entries [/]ns/p, p, [/]_/p
if (n < 1 || n > 3 || (leadingSlash && n === 2) || (!leadingSlash && n === 3)) throw (new Error('Package name is not valid'))
// skip leading slash, all parts must be non empty (could tighten this check to match EntityName regex)
parts.forEach(function (part, i) { if (i > 0 && part.trim().length === 0) throw (new Error('Package name is not valid')) })
if (leadingSlash) {
parts.shift() // drop leading slash
n--
}
return {
namespace: n === 2 ? parts[0] : '_',
name: n === 1 ? parts[0] : parts[1]
}
}
/**
* @description returns key value array from the params and/or param-file supplied with more precendence to params.
* @param {Array} params from flags.param or flags.annotation
* @param {string} paramFilePath from flags['param-file'] or flags['annotation-file']
* @returns {Array} An array of key value pairs in this format : [{key : 'Your key 1' , value: 'Your value 1'}, {key : 'Your key 2' , value: 'Your value 2'} ]
*/
function getKeyValueArrayFromMergedParameters (params, paramFilePath) {
const paramsActionObj = getKeyValueObjectFromMergedParameters(params, paramFilePath)
if (Object.keys(paramsActionObj).length > 0) {
return createKeyValueArrayFromObject(paramsActionObj)
} else {
return undefined
}
}
/**
* @description returns key value object from the params and/or param-file supplied with more precendence to params.
* @param {Array} params from flags.param or flags.annotation
* @param {string} paramFilePath from flags['param-file'] or flags['annotation-file']
* @returns {object} An object of key value pairs in this format : {Your key1 : 'Your Value 1' , Your key2: 'Your value 2'}
*/
function getKeyValueObjectFromMergedParameters (params, paramFilePath) {
let paramsActionObj = {}
if (paramFilePath) {
paramsActionObj = createKeyValueObjectFromFile(paramFilePath)
}
if (params) {
Object.assign(paramsActionObj, createKeyValueObjectFromFlag(params))
}
return paramsActionObj
}
/**
* @description returns key value pairs from the parameters supplied. Used to create --param-file and --annotation-file key value pairs
* @param {string} file from flags['param-file'] or flags['annotation-file']
* @returns {object} An object of key value pairs in this format : {Your key1 : 'Your Value 1' , Your key2: 'Your value 2'}
*/
function createKeyValueObjectFromFile (file) {
return fs.readJSONSync(file)
}
/**
* @description Creates an object representation of a sequence.
* @param {Array} sequenceAction the sequence action array
* @returns {object} the object representation of the sequence
*/
function createComponentsFromSequence (sequenceAction) {
const fqn = require('openwhisk-fqn')
const objSequence = {}
objSequence.kind = 'sequence'
// The components array requires fully qualified names [/namespace/package_name/action_name] of all the actions passed as sequence
objSequence.components = sequenceAction.map(component => {
return fqn(component)
})
return objSequence
}
/* istanbul ignore next */
/**
* @alias createComponentsFromSequence
* @deprecated use `createComponentsFromSequence`
* @param {Array} sequenceAction the sequence action array
* @returns {object} the object representation of the sequence
*/
function createComponentsfromSequence (sequenceAction) {
return createComponentsFromSequence(sequenceAction)
}
/**
* @description Creates a union of two objects
* @param {object} firstObject the object to merge into
* @param {object} secondObject the object to merge from
* @returns {object} the union of both objects
*/
function returnUnion (firstObject, secondObject) {
return Object.assign(firstObject, secondObject)
}
/**
* @description Parse a path pattern
* @param {string} path the path to parse
* @returns {Array} array of matches
*/
function parsePathPattern (path) {
const pattern = /^\/(.+)\/(.+)$/i
const defaultMatch = [null, null, path]
return (pattern.exec(path) || defaultMatch)
}
/**
* @param {string} inputString the string that may have env vars
* @returns {string} output the string with $vars/${vars} replaced
* @access private
*/
function replaceIfEnvKey (inputString) {
const getEnvKey = (env) => {
let val = env
/* istanbul ignore else */
if (val.startsWith('$')) {
val = val.substr(1)
}
/* istanbul ignore else */
if (val.startsWith('{')) {
val = val.slice(1, -1).trim()
}
return val
}
let match
let output = inputString
// eslint-disable-next-line prefer-regex-literals
const envKeyMatch = RegExp(/(\${|\${ +|\$)\w+( +}|}|)/, 'g')
while ((match = envKeyMatch.exec(inputString)) !== null) {
// eslint-disable-next-line no-param-reassign
output = output.replace(match[0], process.env[getEnvKey(match[0])] || '')
}
return output
}
/**
* @description Process inputs
* @param {object} input the input object to process
* @param {object} params the parameters for the input to process
* @returns {object} the processed inputs
*/
function processInputs (input, params) {
if (typeof input === 'object') {
const output = cloneDeep(input)
const dictDataTypes = {
string: '',
integer: 0,
number: 0
}
const recursiveProcess = (output) => {
/* eslint-disable no-param-reassign */
for (const key in output) {
if (typeof output[key] === 'string') {
if (Object.prototype.hasOwnProperty.call(dictDataTypes, output[key])) {
output[key] = dictDataTypes[output[key]]
} else {
output[key] = replaceIfEnvKey(output[key])
}
}
if (typeof output[key] === 'object') {
const defaultKeys = ['value', 'default']
for (const someKey in output[key]) {
if (defaultKeys.includes(someKey)) {
output[key] = replaceIfEnvKey(output[key][someKey])
} else {
recursiveProcess(output[key])
}
}
}
}
}
// replace with param values if any params.
for (const key in input) {
if (Object.prototype.hasOwnProperty.call(params, key)) {
output[key] = params[key]
}
}
recursiveProcess(output)
return output
} else {
aioLogger.debug('processInputs::Invalid input')
return undefined
}
}
/**
* @description Create a key-value object from the input
* @param {object} input the input to process
* @returns {object} the processed input as a key-value object
*/
function createKeyValueInput (input) {
const arrayInput = Object.keys(input).map(function (k) {
return { key: k, value: input[k] }
})
return arrayInput
}
/**
* @description Get the deployment yaml file path
* @returns {string} the deployment yaml path
*/
function getDeploymentPath () {
let deploymentPath
if (fs.existsSync('./deployment.yaml')) {
deploymentPath = 'deployment.yaml'
} else if (fs.existsSync('./deployment.yml')) {
deploymentPath = 'deployment.yml'
}
return deploymentPath
}
/**
* @description Get the manifest yaml file path
* @returns {string} the manifest yaml path
*/
function getManifestPath () {
let manifestPath
if (fs.existsSync('./manifest.yaml')) {
manifestPath = 'manifest.yaml'
} else if (fs.existsSync('./manifest.yml')) {
manifestPath = 'manifest.yml'
} else {
throw (new Error('Manifest file not found'))
}
return manifestPath
}
/**
* @description Get the deployment trigger inputs.
* @param {DeploymentPackages} deploymentPackages the deployment packages
* @returns {object} the deployment trigger inputs
*/
function returnDeploymentTriggerInputs (deploymentPackages) {
const deploymentTriggers = {}
Object.keys(deploymentPackages).forEach((key) => {
if (deploymentPackages[key].triggers) {
Object.keys(deploymentPackages[key].triggers).forEach((trigger) => {
deploymentTriggers[trigger] = deploymentPackages[key].triggers[trigger].inputs || {}
})
}
})
return deploymentTriggers
}
/**
* @description Get the annotations for an action
* @param {ManifestAction} action the action manifest object
* @returns {object} the action annotation entities
*/
function returnAnnotations (action) {
const annotationParams = action && action.annotations ? cloneDeep(action.annotations) : {}
// common annotations
if (action.annotations && action.annotations.conductor !== undefined) {
annotationParams.conductor = action.annotations.conductor
}
// web related annotations
if (action.web !== undefined) {
Object.assign(annotationParams, checkWebFlags(action.web))
} else if (action['web-export'] !== undefined) {
Object.assign(annotationParams, checkWebFlags(action['web-export']))
} else {
annotationParams['web-export'] = false
annotationParams['raw-http'] = false
}
if (action.annotations && annotationParams['web-export'] === true) {
if (action.annotations['require-whisk-auth'] !== undefined) {
annotationParams['require-whisk-auth'] = action.annotations['require-whisk-auth']
}
if (action.annotations['raw-http'] !== undefined) {
annotationParams['raw-http'] = action.annotations['raw-http']
}
if (action.annotations.final !== undefined) {
annotationParams.final = action.annotations.final
}
}
return annotationParams
}
/**
* Creates an array of route definitions from the given manifest-based package.
* See https://github.com/apache/openwhisk-wskdeploy/blob/master/parsers/manifest_parser.go#L1187
*
* @param {ManifestPackage} pkg The package definition from the manifest.
* @param {string} pkgName The name of the package.
* @param {string} apiName The name of the HTTP API definition from the manifest.
* @param {Array} allowedActions List of action names allowed to be used in routes.
* @param {Array} allowedSequences List of sequence names allowed to be used in routes.
* @param {boolean} pathOnly Skip action, method and response type in route definitions.
* @returns {Array<OpenWhiskEntitiesRoute>} the array of route entities
*/
function createApiRoutes (pkg, pkgName, apiName, allowedActions, allowedSequences, pathOnly) {
const actions = pkg.actions
const sequences = pkg.sequences
const basePaths = pkg.apis[apiName]
if (!basePaths) {
throw new Error('Arguments to create API not provided')
}
const routes = []
Object.keys(basePaths).forEach((basePathName) => {
const basePath = basePaths[basePathName]
Object.keys(basePath).forEach((resourceName) => {
const resource = basePath[resourceName]
Object.keys(resource).forEach((actionName) => {
const route = {
name: apiName,
basepath: `/${basePathName}`,
relpath: `/${resourceName}`
}
// only name/path based information is requested
// add basic route and skip
if (pathOnly) {
routes.push(route)
return
}
// if action name is among allowed set, get from package actions
let actionDefinition = allowedActions.includes(actionName)
? actions[actionName]
: null
// no action of that name, fall back to sequences if available
if (!actionDefinition) {
actionDefinition = allowedSequences.includes(actionName)
? sequences[actionName]
: null
}
// neither action nor sequence found, abort
if (!actionDefinition) {
throw new Error('Action provided in the api not present in the package')
}
// ensure action or sequence has the web annotation
if (!actionDefinition.web && !actionDefinition['web-export']) {
throw new Error('Action or sequence provided in api is not a web action')
}
const action = resource[actionName]
routes.push({
...route,
action: `${pkgName}/${actionName}`,
operation: action.method,
responsetype: action.response || 'json'
})
})
})
})
return routes
}
/**
* @description Create a sequence object that is compatible with the OpenWhisk API from a parsed manifest object
* @param {string} fullName the full sequence name prefixed with the package, e.g. `pkg/sequence`
* @param {ManifestSequence} manifestSequence a sequence object as defined in a valid manifest file
* @param {string} packageName the package name of the sequence, which will be set to for actions in the sequence
* @returns {OpenWhiskEntitiesAction} a sequence object describing the action entity
*/
function createSequenceObject (fullName, manifestSequence, packageName) {
let actionArray = []
if (manifestSequence.actions) {
actionArray = manifestSequence.actions.split(',')
actionArray = actionArray.map((action) => {
// remove space between two actions after split
const actionItem = action.replace(/\s+/g, '')
if (actionItem.split('/').length > 1) {
return actionItem
} else {
return `${packageName}/${actionItem}`
}
})
} else {
throw new Error('Actions for the sequence not provided.')
}
const execObj = {}
execObj.kind = 'sequence'
execObj.components = actionArray
return { action: '', name: fullName, exec: execObj }
}
/**
* @description Check the web flags
* @param {string|boolean} flag the flag to check
* @returns {object} object with the appropriate web flags for an action
*/
function checkWebFlags (flag) {
const tempObj = {}
switch (flag) {
case true:
case 'yes' :
tempObj['web-export'] = true
break
case 'raw' :
tempObj['web-export'] = true
tempObj['raw-http'] = true
break
case false:
case 'no':
tempObj['web-export'] = false
tempObj['raw-http'] = false
}
return tempObj
}
/**
* Create an action object compatible with the OpenWhisk API from an action object parsed from the manifest.
*
* @param {string} fullName the full action name prefixed with the package, e.g. `pkg/action`
* @param {ManifestAction} manifestAction the action object as parsed from the manifest
* @returns {OpenWhiskEntitiesAction} the action entity object
*/
function createActionObject (fullName, manifestAction) {
const objAction = { name: fullName }
if (manifestAction.function.endsWith('.zip')) {
if (!manifestAction.runtime && !manifestAction.docker) {
throw (new Error(`Invalid or missing property "runtime" in the manifest for this action: ${objAction && objAction.name}`))
}
objAction.action = fs.readFileSync(manifestAction.function)
} else {
objAction.action = fs.readFileSync(manifestAction.function, { encoding: 'utf8' })
}
if (manifestAction.main || manifestAction.docker || manifestAction.runtime) {
objAction.exec = {}
if (manifestAction.main) {