forked from lablup/backend.ai-client-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backend.ai-client.js
1868 lines (1742 loc) · 58.7 KB
/
backend.ai-client.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
'use babel';
/*
Backend.AI API Library / SDK for Node.JS / Javascript ES6 (v19.07.2)
====================================================================
(C) Copyright 2016-2019 Lablup Inc.
Licensed under MIT
*/
/*jshint esnext: true */
const fetch = require('node-fetch'); /* Exclude for ES6 */
const Headers = fetch.Headers; /* Exclude for ES6 */
const crypto = require('crypto');
const FormData = require('form-data');
const querystring = require('querystring');
class ClientConfig {
/**
* The client Configuration object.
*
* @param {string} accessKey - access key to connect Backend.AI manager
* @param {string} secretKey - secret key to connect Backend.AI manager
* @param {string} endpoint - endpoint of Backend.AI manager
* @param {string} connectionMode - connection mode. 'API', 'SESSION' is supported. `SESSION` mode requires console-server.
*/
constructor(accessKey, secretKey, endpoint, connectionMode = 'API') {
// fixed configs with this implementation
this._apiVersionMajor = 'v4';
this._apiVersion = 'v4.20190315'; // For compatibility with 19.03 / 1.4
this._hashType = 'sha256';
// dynamic configs
if (accessKey === undefined || accessKey === null)
throw 'You must set accessKey! (either as argument or environment variable)';
if (secretKey === undefined || secretKey === null)
throw 'You must set secretKey! (either as argument or environment variable)';
if (endpoint === undefined || endpoint === null)
endpoint = 'https://api.backend.ai';
this._endpoint = endpoint;
this._endpointHost = endpoint.replace(/^[^:]+:\/\//, '');
this._accessKey = accessKey;
this._secretKey = secretKey;
this._proxyURL = null;
this._connectionMode = connectionMode;
}
get accessKey() {
return this._accessKey;
}
get secretKey() {
return this._secretKey;
}
get endpoint() {
return this._endpoint;
}
get proxyURL() {
return this._proxyURL;
}
get endpointHost() {
return this._endpointHost;
}
get apiVersion() {
return this._apiVersion;
}
get apiVersionMajor() {
return this._apiVersionMajor;
}
get hashType() {
return this._hashType;
}
get connectionMode() {
return this._connectionMode;
}
/**
* Create a ClientConfig object from environment variables.
*/
static createFromEnv() {
return new this(
process.env.BACKEND_ACCESS_KEY,
process.env.BACKEND_SECRET_KEY,
process.env.BACKEND_ENDPOINT
);
}
}
class Client {
/**
* The client API wrapper.
*
* @param {ClientConfig} config - the API client-side configuration
* @param {string} agentSignature - an extra string that will be appended to User-Agent headers when making API requests
*/
constructor(config, agentSignature) {
this.code = null;
this.kernelId = null;
this.kernelType = null;
this.clientVersion = '19.06.0';
this.agentSignature = agentSignature;
if (config === undefined) {
this._config = ClientConfig.createFromEnv();
} else {
this._config = config;
}
this._managerVersion = null;
this._apiVersion = null;
this.is_admin = false;
this.is_superadmin = false;
this.kernelPrefix = '/kernel';
this.resourcePreset = new ResourcePreset(this);
this.vfolder = new VFolder(this);
this.agent = new Agent(this);
this.keypair = new Keypair(this);
this.image = new Image(this);
this.utils = new utils(this);
this.computeSession = new ComputeSession(this);
this.resourcePolicy = new ResourcePolicy(this);
this.user = new User(this);
this.group = new Group(this);
this.resources = new Resources(this);
this.maintenance = new Maintenance(this);
//if (this._config.connectionMode === 'API') {
//this.getManagerVersion();
//}
}
/**
* Return the server-side manager version.
*/
get managerVersion() {
return this._managerVersion;
}
/**
* Promise wrapper for asynchronous request to Backend.AI manager.
*
* @param {Request} rqst - Request object to send
*/
async _wrapWithPromise(rqst, rawFile = false) {
let errorType = Client.ERR_REQUEST;
let errorMsg;
let resp, body;
try {
if (rqst.method == 'GET') {
rqst.body = undefined;
}
if (this._config.connectionMode === 'SESSION') { // Force request to use Public when session mode is enabled
rqst.credentials = 'include';
rqst.mode = 'cors';
}
resp = await fetch(rqst.uri, rqst);
errorType = Client.ERR_RESPONSE;
let contentType = resp.headers.get('Content-Type');
if (rawFile === false && contentType === null) {
if (resp.blob === undefined)
body = await resp.buffer(); // for node-fetch
else
body = await resp.blob();
} else if (rawFile === false && (contentType.startsWith('application/json') ||
contentType.startsWith('application/problem+json'))) {
body = await resp.json();
} else if (rawFile === false && contentType.startsWith('text/')) {
body = await resp.text();
} else {
if (resp.blob === undefined)
body = await resp.buffer(); // for node-fetch
else
body = await resp.blob();
}
errorType = Client.ERR_SERVER;
if (!resp.ok) {
throw body;
}
} catch (err) {
switch (errorType) {
case Client.ERR_REQUEST:
errorMsg = `sending request has failed: ${err}`;
break;
case Client.ERR_RESPONSE:
errorMsg = `reading response has failed: ${err}`;
break;
case Client.ERR_SERVER:
errorMsg = 'server responded failure: '
+ `${resp.status} ${resp.statusText} - ${body.title}`;
break;
}
throw {
type: errorType,
message: errorMsg,
};
}
return body;
}
/**
* Return the server-side API version.
*/
getServerVersion() {
let rqst = this.newPublicRequest('GET', '/', null, '');
return this._wrapWithPromise(rqst);
}
/**
* Get the server-side manager version.
*/
async getManagerVersion() {
if (this._managerVersion === null) {
let v = await this.getServerVersion();
this._managerVersion = v.manager;
this._apiVersion = v.version;
this._config._apiVersion = this._apiVersion; // To upgrade API version with server version
}
return this._managerVersion;
}
/**
* Return if manager is compatible with given version.
*/
isManagerVersionCompatibleWith(version) {
let managerVersion = this._managerVersion;
managerVersion = managerVersion.split('.').map(s => s.padStart(10)).join('.');
version = version.split('.').map(s => s.padStart(10)).join('.');
return version <= managerVersion;
}
/**
* Return if api is compatible with given version.
*/
isAPIVersionCompatibleWith(version) {
let apiVersion = this._apiVersion;
apiVersion = apiVersion.split('.').map(s => s.padStart(10)).join('.');
version = version.split('.').map(s => s.padStart(10)).join('.');
return version <= apiVersion;
}
/**
* Check if console-server is authenticated. This requires additional console-server package.
*
*/
async check_login() {
let rqst = this.newSignedRequest('POST', `/server/login-check`, null);
let result;
try {
result = await this._wrapWithPromise(rqst);
if (result.authenticated === true) {
let data = result.data;
this._config._accessKey = result.data.access_key;
}
} catch (err) {
return false;
}
return result.authenticated;
}
/**
* Login into console-server with given ID/Password. This requires additional console-server package.
*
*/
login() {
let body = {
'username': this._config.accessKey,
'password': this._config.secretKey
};
let rqst = this.newSignedRequest('POST', `/server/login`, body);
return this._wrapWithPromise(rqst);
}
/**
* Logout from console-server. This requires additional console-server package.
*
*/
logout() {
let body = {};
let rqst = this.newSignedRequest('POST', `/server/logout`, body);
return this._wrapWithPromise(rqst);
}
/**
* Return the resource slots.
*/
async getResourceSlots() {
let rqst;
if (this.isAPIVersionCompatibleWith('v4.20190601')) {
rqst = this.newPublicRequest('GET', '/config/resource-slots', null, '');
} else {
rqst = this.newPublicRequest('GET', '/etcd/resource-slots', null, '');
}
return this._wrapWithPromise(rqst);
}
/**
* Create a compute session if the session for the given sessionId does not exists.
* It returns the information for the existing session otherwise, without error.
*
* @param {string} kernelType - the kernel type (usually language runtimes)
* @param {string} sessionId - user-defined session ID
* @param {object} resources - Per-session resource
*/
createIfNotExists(image, sessionId, config, tag = "") {
let params = {
"image": image,
"clientSessionToken": sessionId,
"config": config,
};
if (tag) {
params['tag'] = tag;
}
let rqst = this.newSignedRequest('POST', `${this.kernelPrefix}`, params);
return this._wrapWithPromise(rqst);
}
/**
* Obtain the session information by given sessionId.
*
* @param {string} sessionId - the sessionId given when created
*/
getInformation(sessionId, ownerKey = null) {
let queryString = `${this.kernelPrefix}/${sessionId}`;
if (ownerKey != null) {
queryString = `${queryString}?owner_access_key=${ownerKey}`;
}
let rqst = this.newSignedRequest('GET', queryString, null);
return this._wrapWithPromise(rqst);
}
/**
* Obtain the session information by given sessionId.
*
* @param {string} sessionId - the sessionId given when created
*/
getLogs(sessionId, ownerKey = null) {
let queryString = `${this.kernelPrefix}/${sessionId}/logs`;
if (ownerKey != null) {
queryString = `${queryString}?owner_access_key=${ownerKey}`;
}
let rqst = this.newSignedRequest('GET', queryString, null);
return this._wrapWithPromise(rqst);
}
/**
* Terminate and destroy the kernel session.
*
* @param {string} sessionId - the sessionId given when created
*/
destroy(sessionId, ownerKey = null) {
let queryString = `${this.kernelPrefix}/${sessionId}`;
if (ownerKey != null) {
queryString = `${queryString}?owner_access_key=${ownerKey}`;
}
let rqst = this.newSignedRequest('DELETE', queryString, null);
return this._wrapWithPromise(rqst);
}
/**
* Restart the kernel session keeping its work directory and volume mounts.
*
* @param {string} sessionId - the sessionId given when created
*/
restart(sessionId, ownerKey = null) {
let queryString = `${this.kernelPrefix}/${sessionId}`;
if (ownerKey != null) {
queryString = `${queryString}?owner_access_key=${ownerKey}`;
}
let rqst = this.newSignedRequest('PATCH', queryString, null);
return this._wrapWithPromise(rqst);
}
// TODO: interrupt
// TODO: auto-complete
/**
* Execute a code snippet or schedule batch-mode executions.
*
* @param {string} sessionId - the sessionId given when created
* @param {string} runId - a random ID to distinguish each continuation until finish (the length must be between 8 to 64 bytes inclusively)
* @param {string} mode - either "query", "batch", "input", or "continue"
* @param {string} opts - an optional object specifying additional configs such as batch-mode build/exec commands
*/
execute(sessionId, runId, mode, code, opts) {
let params = {
"mode": mode,
"code": code,
"runId": runId,
"options": opts,
};
let rqst = this.newSignedRequest('POST', `${this.kernelPrefix}/${sessionId}`, params);
return this._wrapWithPromise(rqst);
}
// legacy aliases
createKernel(kernelType, sessionId = undefined, resources = {}) {
return this.createIfNotExists(kernelType, sessionId, resources);
}
destroyKernel(kernelId, ownerKey = null) {
return this.destroy(kernelId, ownerKey);
}
refreshKernel(kernelId, ownerKey = null) {
return this.restart(kernelId, ownerKey);
}
runCode(code, kernelId, runId, mode) {
return this.execute(kernelId, runId, mode, code, {});
}
upload(sessionId, path, fs) {
const formData = new FormData();
formData.append('src', fs, {filepath: path});
let rqst = this.newSignedRequest('POST', `${this.kernelPrefix}/${sessionId}/upload`, formData);
return this._wrapWithPromise(rqst);
}
mangleUserAgentSignature() {
let uaSig = this.clientVersion
+ (this.agentSignature ? ('; ' + this.agentSignature) : '');
return uaSig;
}
/* GraphQL requests */
gql(q, v) {
let query = {
'query': q,
'variables': v
};
let rqst = this.newSignedRequest('POST', `/admin/graphql`, query);
return this._wrapWithPromise(rqst);
}
/**
* Generate a RequestInfo object that can be passed to fetch() API,
* which includes a properly signed header with the configured auth information.
*
* @param {string} method - the HTTP method
* @param {string} queryString - the URI path and GET parameters
* @param {string} body - an object that will be encoded as JSON in the request body
*/
newSignedRequest(method, queryString, body) {
let content_type = "application/json";
let requestBody;
let authBody;
let d = new Date();
if (body === null || body === undefined) {
requestBody = '';
authBody = requestBody;
} else if (typeof body.getBoundary === 'function' || body instanceof FormData) {
// detect form data input from form-data module
requestBody = body;
authBody = '';
content_type = "multipart/form-data";
} else {
requestBody = JSON.stringify(body);
authBody = requestBody;
}
//queryString = '/' + this._config.apiVersionMajor + queryString;
let aStr;
let hdrs;
let uri;
uri = '';
if (this._config.connectionMode === 'SESSION') { // Force request to use Public when session mode is enabled
hdrs = new Headers({
"User-Agent": `Backend.AI Client for Javascript ${this.mangleUserAgentSignature()}`,
"X-BackendAI-Version": this._config.apiVersion,
"X-BackendAI-Date": d.toISOString(),
});
//console.log(queryString.startsWith('/server') ===true);
if (queryString.startsWith('/server') === true) { // Force request to use Public when session mode is enabled
uri = this._config.endpoint + queryString;
} else { // Force request to use Public when session mode is enabled
uri = this._config.endpoint + '/func' + queryString;
}
} else {
if (this._config._apiVersion[1] < 4) {
aStr = this.getAuthenticationString(method, queryString, d.toISOString(), authBody, content_type);
} else {
aStr = this.getAuthenticationString(method, queryString, d.toISOString(), '', content_type);
}
let signKey = this.getSignKey(this._config.secretKey, d);
let rqstSig = this.sign(signKey, 'binary', aStr, 'hex');
hdrs = new Headers({
"User-Agent": `Backend.AI Client for Javascript ${this.mangleUserAgentSignature()}`,
"X-BackendAI-Version": this._config.apiVersion,
"X-BackendAI-Date": d.toISOString(),
"Authorization": `BackendAI signMethod=HMAC-SHA256, credential=${this._config.accessKey}:${rqstSig}`,
});
uri = this._config.endpoint + queryString;
}
if (body != undefined) {
if (typeof body.getBoundary === 'function') {
hdrs.set('Content-Type', body.getHeaders()['content-type']);
}
if (body instanceof FormData) {
} else {
hdrs.set('Content-Type', content_type);
hdrs.set('Content-Length', Buffer.byteLength(authBody));
}
} else {
hdrs.set('Content-Type', content_type);
}
let requestInfo = {
method: method,
headers: hdrs,
cache: 'default',
body: requestBody,
uri: uri
};
return requestInfo;
}
/**
* Same to newRequest() method but it does not sign the request.
* Use this for unauthorized public APIs.
*/
newUnsignedRequest(method, queryString, body) {
return this.newPublicRequest(method, queryString, body, this._config.apiVersionMajor);
}
newPublicRequest(method, queryString, body, urlPrefix) {
let d = new Date();
let hdrs = new Headers({
"Content-Type": "application/json",
"User-Agent": `Backend.AI Client for Javascript ${this.mangleUserAgentSignature()}`,
"X-BackendAI-Version": this._config.apiVersion,
"X-BackendAI-Date": d.toISOString(),
"credentials": 'include',
"mode": 'cors'
});
//queryString = '/' + urlPrefix + queryString;
let requestInfo = {
method: method,
headers: hdrs,
mode: 'cors',
cache: 'default'
};
if (this._config.connectionMode === 'SESSION' && queryString.startsWith('/server') === true) { // Force request to use Public when session mode is enabled
requestInfo.uri = this._config.endpoint + queryString;
} else if (this._config.connectionMode === 'SESSION' && queryString.startsWith('/server') === false) { // Force request to use Public when session mode is enabled
requestInfo.uri = this._config.endpoint + '/func' + queryString;
} else {
requestInfo.uri = this._config.endpoint + queryString;
}
return requestInfo;
}
getAuthenticationString(method, queryString, dateValue, bodyValue, content_type = "application/json") {
let bodyHash = crypto.createHash(this._config.hashType)
.update(bodyValue).digest('hex');
return (method + '\n' + queryString + '\n' + dateValue + '\n'
+ 'host:' + this._config.endpointHost + '\n'
+ 'content-type:' + content_type + '\n'
+ 'x-backendai-version:' + this._config.apiVersion + '\n'
+ bodyHash);
}
getCurrentDate(now) {
let year = (`0000${now.getUTCFullYear()}`).slice(-4);
let month = (`0${now.getUTCMonth() + 1}`).slice(-2);
let day = (`0${now.getUTCDate()}`).slice(-2);
let t = year + month + day;
return t;
}
sign(key, key_encoding, msg, digest_type) {
let kbuf = new Buffer(key, key_encoding);
let hmac = crypto.createHmac(this._config.hashType, kbuf);
hmac.update(msg, 'utf8');
return hmac.digest(digest_type);
}
getSignKey(secret_key, now) {
let k1 = this.sign(secret_key, 'utf8', this.getCurrentDate(now), 'binary');
let k2 = this.sign(k1, 'binary', this._config.endpointHost, 'binary');
return k2;
}
generateSessionId() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 8; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text + "-jsSDK";
}
}
class ResourcePreset {
/**
* Resource Preset API wrapper.
*
* @param {Client} client - the Client API wrapper object to bind
*/
constructor(client) {
this.client = client;
this.urlPrefix = '/resource';
}
/**
* Return the GraphQL Promise object containing resource preset list.
*/
list() {
let rqst = this.client.newSignedRequest('GET', `${this.urlPrefix}/presets`, null);
return this.client._wrapWithPromise(rqst);
}
/**
* Return the GraphQL Promise object containing resource preset checking result.
*/
check() {
let rqst = this.client.newSignedRequest('POST', `${this.urlPrefix}/check-presets`, null);
return this.client._wrapWithPromise(rqst);
}
/**
* add resource preset with given name and fields.
*
* @param {string} name - resource preset name.
* @param {json} input - resource preset specification and data. Required fields are:
* {
* 'resource_slots': JSON.stringify(total_resource_slots), // Resource slot value. should be Stringified JSON.
* };
*/
add(name = null, input) {
let fields = ['name',
'resource_slots'];
if (this.client.is_admin === true && name !== null) {
let q = `mutation($name: String!, $input: CreateResourcePresetInput!) {` +
` create_resource_preset(name: $name, props: $input) {` +
` ok msg ` +
` }` +
`}`;
let v = {
'name': name,
'input': input
};
return this.client.gql(q, v);
} else {
return resolve(false);
}
}
/**
* mutate specified resource preset with given name with new values.
*
* @param {string} name - resource preset name to mutate.
* @param {json} input - resource preset specification and data. Required fields are:
* {
* 'resource_slots': JSON.stringify(total_resource_slots), // Resource slot value. should be Stringified JSON.
* };
*/
mutate(name = null, input) {
let fields = ['name',
'resource_slots'];
if (this.client.is_admin === true && name !== null) {
let q = `mutation($name: String!, $input: ModifyResourcePresetInput!) {` +
` modify_resource_preset(name: $name, props: $input) {` +
` ok msg ` +
` }` +
`}`;
let v = {
'name': name,
'input': input
};
return this.client.gql(q, v);
} else {
return resolve(false);
}
}
}
class VFolder {
/**
* The Virtual Folder API wrapper.
*
* @param {Client} client - the Client API wrapper object to bind
* @param {string} name - Virtual folder name.
*/
constructor(client, name = null) {
this.client = client;
this.name = name;
this.urlPrefix = '/folders'
}
/**
* Create a Virtual folder on specific host.
*
* @param {string} name - Virtual folder name.
* @param {string} host - Host name to create virtual folder in it.
*/
create(name, host = null) {
let body = {
'name': name,
'host': host
};
let rqst = this.client.newSignedRequest('POST', `${this.urlPrefix}`, body);
return this.client._wrapWithPromise(rqst);
}
/**
* List Virtual folders that requested accessKey has permission to.
*/
list() {
let rqst = this.client.newSignedRequest('GET', `${this.urlPrefix}`, null);
return this.client._wrapWithPromise(rqst);
}
/**
* List Virtual folder hosts that requested accessKey has permission to.
*/
list_hosts() {
let rqst = this.client.newSignedRequest('GET', `${this.urlPrefix}/_/hosts`, null);
return this.client._wrapWithPromise(rqst);
}
/**
* Information about specific virtual folder.
*/
info(name = null) {
if (name == null) {
name = this.name;
}
let rqst = this.client.newSignedRequest('GET', `${this.urlPrefix}/${name}`, null);
return this.client._wrapWithPromise(rqst);
}
/**
* Delete a Virtual folder.
*
* @param {string} name - Virtual folder name. If no name is given, use name on this VFolder object.
*/
delete(name = null) {
if (name == null) {
name = this.name;
}
let rqst = this.client.newSignedRequest('DELETE', `${this.urlPrefix}/${name}`, null);
return this.client._wrapWithPromise(rqst);
}
/**
* Upload files to specific Virtual folder.
*
* @param {string} path - Path to upload.
* @param {string} fs - File content to upload.
* @param {string} name - Virtual folder name.
*/
upload(path, fs, name = null) {
if (name == null) {
name = this.name;
}
let formData = new FormData();
formData.append('src', fs, {filepath: path});
let rqst = this.client.newSignedRequest('POST', `${this.urlPrefix}/${name}/upload`, formData);
return this.client._wrapWithPromise(rqst);
}
/**
* Upload file from formData to specific Virtual folder.
*
* @param {string} fss - formData with file specification. formData should contain {src, content, {filePath:filePath}}.
* @param {string} name - Virtual folder name.
*/
uploadFormData(fss, name = null) {
let rqst = this.client.newSignedRequest('POST', `${this.urlPrefix}/${name}/upload`, fss);
return this.client._wrapWithPromise(rqst);
}
/**
* Create directory in specific Virtual folder.
*
* @param {string} path - Directory path to create.
* @param {string} name - Virtual folder name.
*/
mkdir(path, name = null) {
if (name == null) {
name = this.name;
}
let body = {
'path': path
};
let rqst = this.client.newSignedRequest('POST', `${this.urlPrefix}/${name}/mkdir`, body);
return this.client._wrapWithPromise(rqst);
}
/**
* Delete multiple files in a Virtual folder.
*
* @param {string} files - Files to delete.
* @param {boolean} recursive - delete files recursively.
* @param {string} name - Virtual folder name that files are in.
*/
delete_files(files, recursive = null, name = null) {
if (name == null) {
name = this.name;
}
if (recursive == null) {
recursive = false;
}
let body = {
'files': files,
'recursive': recursive,
};
let rqst = this.client.newSignedRequest('DELETE', `${this.urlPrefix}/${name}/delete_files`, body);
return this.client._wrapWithPromise(rqst);
}
/**
* Download file in a Virtual folder.
*
* @param {string} file - File to download. Should contain full path.
* @param {string} name - Virtual folder name that files are in.
*/
download(file, name = false) {
let params = {
'file': file
};
let q = querystring.stringify(params);
let rqst = this.client.newSignedRequest('GET', `${this.urlPrefix}/${name}/download_single?${q}`, null);
return this.client._wrapWithPromise(rqst, true);
}
/**
* List files in specific virtual folder / path.
*
* @param {string} path - Directory path to list.
* @param {string} name - Virtual folder name to look up with.
*/
list_files(path, name = null) {
if (name == null) {
name = this.name;
}
let params = {
'path': path
};
let q = querystring.stringify(params);
let rqst = this.client.newSignedRequest('GET', `${this.urlPrefix}/${name}/files?${q}`, null);
return this.client._wrapWithPromise(rqst);
}
/**
* Invite someone to specific virtual folder with permission.
*
* @param {string} perm - Permission to give to. `rw` or `ro`.
* @param {array} emails - User E-mail to invite.
* @param {string} name - Virtual folder name to invite.
*/
invite(perm, emails, name = null) {
if (name == null) {
name = this.name;
}
let body = {
'perm': perm,
'user_ids': emails
};
let rqst = this.client.newSignedRequest('POST', `${this.urlPrefix}/${name}/invite`, body);
return this.client._wrapWithPromise(rqst);
}
/**
* Show invitations to current API key.
*/
invitations() {
let rqst = this.client.newSignedRequest('GET', `${this.urlPrefix}/invitations/list`, null);
return this.client._wrapWithPromise(rqst);
}
/**
* Accept specific invitation.
*
* @param {string} inv_id - Invitation ID.
*/
accept_invitation(inv_id) {
let body = {
'inv_id': inv_id
};
let rqst = this.client.newSignedRequest('POST', `${this.urlPrefix}/invitations/accept`, body);
return this.client._wrapWithPromise(rqst);
}
/**
* Delete specific invitation.
*
* @param {string} inv_id - Invitation ID to delete.
*/
delete_invitation(inv_id) {
let body = {
'inv_id': inv_id
};
let rqst = this.client.newSignedRequest('DELETE', `${this.urlPrefix}/invitations/delete`, body);
return this.client._wrapWithPromise(rqst);
}
/**
* List invitees(users who accepted an invitation)
*
* @param {string} vfolder_id - vfolder id. If no id is given, all users who accepted the client's invitation will be returned
*/
list_invitees(vfolder_id = null) {
let queryString = '/folders/_/shared';
if (vfolder_id !== null) queryString = `${queryString}?vfolder_id=${vfolder_id}`;
let rqst = this.client.newSignedRequest('GET', queryString, null);
return this.client._wrapWithPromise(rqst);
}
/**
* Modify an invitee's permission to a shared vfolder
*
* @param {json} input - parameters for permission modification
* @param {string} input.perm - invitee's new permission. permission should one of the following: 'ro', 'rw', 'wd'
* @param {string} input.user - invitee's uuid
* @param {string} input.vfolder - id of the vfolder that has been shared to the invitee
*/
modify_invitee_permission(input) {
let rqst = this.client.newSignedRequest('POST', '/folders/_/shared', input);
return this.client._wrapWithPromise(rqst);
}
}
class Agent {
/**
* Agent API wrapper.
*
* @param {Client} client - the Client API wrapper object to bind
*/
constructor(client) {
this.client = client;
}
/**
* List computation agents.
*
* @param {string} status - Status to query. Should be one of 'ALIVE', 'PREPARING', 'TERMINATING' and 'TERMINATED'.
* @param {array} fields - Fields to query. Queryable fields are: 'id', 'status', 'region', 'first_contact', 'cpu_cur_pct', 'mem_cur_bytes', 'available_slots', 'occupied_slots'.
*/
list(status = 'ALIVE', fields = ['id', 'status', 'region', 'first_contact', 'cpu_cur_pct', 'mem_cur_bytes', 'available_slots', 'occupied_slots']) {
if (['ALIVE', 'TERMINATED'].includes(status) === false) {
return resolve(false);
}
let q = `query($status: String) {` +
` agents(status: $status) {` +
` ${fields.join(" ")}` +
` }` +
`}`;
let v = {'status': status};
return this.client.gql(q, v);
}
}
class Keypair {
/**
* Keypair API wrapper.
*
* @param {Client} client - the Client API wrapper object to bind
*/
constructor(client, name = null) {
this.client = client;
this.name = name;
}
/**
* Information of specific Keypair.
*
* @param {string} accessKey - Access key to query information. If client is not authorized as admin, this will be ignored and current API key infomation will be returned.
* @param {array} fields - Fields to query. Queryable fields are: 'access_key', 'secret_key', 'is_active', 'is_admin', 'user_id', 'created_at', 'last_used',
'concurrency_limit', 'concurrency_used', 'rate_limit', 'num_queries', 'resource_policy'.
*/
info(accessKey, fields = ['access_key', 'secret_key', 'is_active', 'is_admin', 'user_id', 'created_at', 'last_used',
'concurrency_limit', 'concurrency_used', 'rate_limit', 'num_queries', 'resource_policy']) {
let q, v;
if (this.client.is_admin) {
q = `query($access_key: String!) {` +
` keypair(access_key: $access_key) {` +
` ${fields.join(" ")}` +
` }` +
`}`;
v = {
'access_key': accessKey
};
} else {
q = `query {` +
` keypair {` +
` ${fields.join(" ")}` +
` }` +
`}`;
v = {};
}
return this.client.gql(q, v);
}
/**