-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathcompute_engine_docker.ts
More file actions
1294 lines (1237 loc) · 42.9 KB
/
compute_engine_docker.ts
File metadata and controls
1294 lines (1237 loc) · 42.9 KB
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
/* eslint-disable security/detect-non-literal-fs-filename */
import { Readable } from 'stream'
import { C2DStatusNumber, C2DStatusText } from '../../@types/C2D/C2D.js'
import type {
C2DClusterInfo,
ComputeEnvironment,
ComputeAlgorithm,
ComputeAsset,
ComputeJob,
ComputeOutput,
DBComputeJob,
DBComputeJobPayment,
ComputeResult,
RunningPlatform,
ComputeEnvFeesStructure,
ComputeResourceRequest,
ComputeEnvFees
} from '../../@types/C2D/C2D.js'
import { getConfiguration } from '../../utils/config.js'
import { C2DEngine } from './compute_engine_base.js'
import { C2DDatabase } from '../database/C2DDatabase.js'
import { Escrow } from '../core/utils/escrow.js'
import { create256Hash } from '../../utils/crypt.js'
import { Storage } from '../storage/index.js'
import Dockerode from 'dockerode'
import type { ContainerCreateOptions, HostConfig, VolumeCreateOptions } from 'dockerode'
import * as tar from 'tar'
import {
createWriteStream,
existsSync,
mkdirSync,
rmSync,
writeFileSync,
statSync,
createReadStream
} from 'fs'
import { pipeline } from 'node:stream/promises'
import { CORE_LOGGER } from '../../utils/logging/common.js'
import { AssetUtils } from '../../utils/asset.js'
import { FindDdoHandler } from '../core/handler/ddoHandler.js'
import { OceanNode } from '../../OceanNode.js'
import { decryptFilesObject, omitDBComputeFieldsFromComputeJob } from './index.js'
import * as drc from 'docker-registry-client'
import { ValidateParams } from '../httpRoutes/validateCommands.js'
import { Service } from '@oceanprotocol/ddo-js'
import { getOceanTokenAddressForChain } from '../../utils/address.js'
export class C2DEngineDocker extends C2DEngine {
private envs: ComputeEnvironment[] = []
public docker: Dockerode
private cronTimer: any
private cronTime: number = 2000
public constructor(clusterConfig: C2DClusterInfo, db: C2DDatabase, escrow: Escrow) {
super(clusterConfig, db, escrow)
this.docker = null
if (clusterConfig.connection.socketPath) {
try {
this.docker = new Dockerode({ socketPath: clusterConfig.connection.socketPath })
} catch (e) {
CORE_LOGGER.error('Could not create Docker container: ' + e.message)
}
}
if (
clusterConfig.connection.protocol &&
clusterConfig.connection.host &&
clusterConfig.connection.port
) {
try {
this.docker = new Dockerode({
protocol: clusterConfig.connection.protocol,
host: clusterConfig.connection.host,
port: clusterConfig.connection.port
})
} catch (e) {
CORE_LOGGER.error('Could not create Docker container: ' + e.message)
}
}
// TO DO C2D - create envs
try {
if (!existsSync(clusterConfig.tempFolder))
mkdirSync(clusterConfig.tempFolder, { recursive: true })
} catch (e) {
CORE_LOGGER.error(
'Could not create Docker container temporary folders: ' + e.message
)
}
// envs are build on start function
}
public override async start() {
// let's build the env. Swarm and k8 will build multiple envs, based on arhitecture
const config = await getConfiguration()
const envConfig = await this.getC2DConfig().connection
let sysinfo = null
try {
sysinfo = await this.docker.info()
} catch (e) {
CORE_LOGGER.error('Could not get docker info: ' + e.message)
// since we cannot connect to docker, we cannot start the engine -> no envs
return
}
// console.log(sysinfo)
let fees: ComputeEnvFeesStructure = null
const supportedChains: number[] = []
for (const chain of Object.keys(config.supportedNetworks)) {
supportedChains.push(parseInt(chain))
}
for (const feeChain of Object.keys(envConfig.fees)) {
// for (const feeConfig of envConfig.fees) {
// console.log(feeChain)
if (supportedChains.includes(parseInt(feeChain))) {
if (fees === null) fees = {}
if (!(feeChain in fees)) fees[feeChain] = []
const tmpFees: ComputeEnvFees[] = []
for (let i = 0; i < envConfig.fees[feeChain].length; i++) {
if (
envConfig.fees[feeChain][i].prices &&
envConfig.fees[feeChain][i].prices.length > 0
) {
if (!envConfig.fees[feeChain][i].feeToken) {
const tokenAddress = await getOceanTokenAddressForChain(parseInt(feeChain))
if (tokenAddress) {
envConfig.fees[feeChain][i].feeToken = tokenAddress
tmpFees.push(envConfig.fees[feeChain][i])
} else {
CORE_LOGGER.error(
`Unable to find Ocean token address for chain ${feeChain} and no custom token provided`
)
}
} else {
tmpFees.push(envConfig.fees[feeChain][i])
}
} else {
CORE_LOGGER.error(
`Unable to find prices for fee ${JSON.stringify(
envConfig.fees[feeChain][i]
)} on chain ${feeChain}`
)
}
}
fees[feeChain] = tmpFees
}
/* for (const chain of Object.keys(config.supportedNetworks)) {
const chainId = parseInt(chain)
if (task.chainId && task.chainId !== chainId) continue
result[chainId] = await computeEngines.fetchEnvironments(chainId)
} */
}
this.envs.push({
id: '', // this.getC2DConfig().hash + '-' + create256Hash(JSON.stringify(this.envs[i])),
runningJobs: 0,
consumerAddress: config.keys.ethAddress,
platform: {
architecture: sysinfo.Architecture,
os: sysinfo.OperatingSystem
},
fees
})
if (`storageExpiry` in envConfig) this.envs[0].storageExpiry = envConfig.storageExpiry
if (`maxJobDuration` in envConfig)
this.envs[0].maxJobDuration = envConfig.maxJobDuration
if (`maxJobs` in envConfig) this.envs[0].maxJobs = envConfig.maxJobs
// let's add resources
this.envs[0].resources = []
this.envs[0].resources.push({
id: 'cpu',
total: sysinfo.NCPU,
max: sysinfo.NCPU,
min: 1
})
this.envs[0].resources.push({
id: 'ram',
total: sysinfo.MemTotal,
max: sysinfo.MemTotal,
min: 1e9
})
if (envConfig.resources) {
for (const res of envConfig.resources) {
// allow user to add other resources
if (res.id !== 'cpu' && res.id !== 'ram') {
if (!res.max) res.max = res.total
if (!res.min) res.min = 0
this.envs[0].resources.push(res)
}
}
}
// limits for free env
if ('free' in envConfig) {
this.envs[0].free = {}
if (`storageExpiry` in envConfig.free)
this.envs[0].free.storageExpiry = envConfig.free.storageExpiry
if (`maxJobDuration` in envConfig.free)
this.envs[0].free.maxJobDuration = envConfig.free.maxJobDuration
if (`maxJobs` in envConfig.free) this.envs[0].free.maxJobs = envConfig.free.maxJobs
if ('resources' in envConfig.free) {
// TO DO - check if resource is also listed in this.envs[0].resources, if not, ignore it
this.envs[0].free.resources = envConfig.free.resources
}
}
this.envs[0].id =
this.getC2DConfig().hash + '-' + create256Hash(JSON.stringify(this.envs[0]))
}
// eslint-disable-next-line require-await
public override async getComputeEnvironments(
chainId?: number
): Promise<ComputeEnvironment[]> {
/**
* Returns all cluster's compute environments, filtered by a specific chainId if needed. Env's id already contains the cluster hash
*/
if (!this.docker) return []
const filteredEnvs = []
for (const computeEnv of this.envs) {
if (
!chainId ||
(computeEnv.fees && Object.hasOwn(computeEnv.fees, String(chainId)))
) {
const { totalJobs, totalFreeJobs, usedResources, usedFreeResources } =
await this.getUsedResources(computeEnv)
computeEnv.runningJobs = totalJobs
computeEnv.runningfreeJobs = totalFreeJobs
for (let i = 0; i < computeEnv.resources.length; i++) {
if (computeEnv.resources[i].id in usedResources)
computeEnv.resources[i].inUse = usedResources[computeEnv.resources[i].id]
else computeEnv.resources[i].inUse = 0
}
if (computeEnv.free && computeEnv.free.resources) {
for (let i = 0; i < computeEnv.free.resources.length; i++) {
if (computeEnv.free.resources[i].id in usedFreeResources)
computeEnv.free.resources[i].inUse =
usedFreeResources[computeEnv.free.resources[i].id]
else computeEnv.free.resources[i].inUse = 0
}
}
filteredEnvs.push(computeEnv)
}
}
return filteredEnvs
}
/**
* Checks the docker image by looking at the manifest
* @param image name or tag
* @returns boolean
*/
public static async checkDockerImage(
image: string,
platform?: RunningPlatform
): Promise<ValidateParams> {
try {
const info = drc.default.parseRepoAndRef(image)
/**
* info: {
index: { name: 'docker.io', official: true },
official: true,
remoteName: 'library/node',
localName: 'node',
canonicalName: 'docker.io/node',
digest: 'sha256:1155995dda741e93afe4b1c6ced2d01734a6ec69865cc0997daf1f4db7259a36'
}
*/
const client = drc.createClientV2({ name: info.localName })
const tagOrDigest = info.tag || info.digest
// try get manifest from registry
return await new Promise<any>((resolve, reject) => {
client.getManifest(
{ ref: tagOrDigest, maxSchemaVersion: 2 },
function (err: any, manifest: any) {
client.close()
if (manifest) {
return resolve({
valid: checkManifestPlatform(manifest.platform, platform)
})
}
if (err) {
CORE_LOGGER.error(
`Unable to get Manifest for image ${image}: ${err.message}`
)
reject(err)
}
}
)
})
} catch (err) {
// show all aggregated errors, if present
const aggregated = err.errors && err.errors.length > 0
aggregated ? CORE_LOGGER.error(JSON.stringify(err.errors)) : CORE_LOGGER.error(err)
return {
valid: false,
status: 404,
reason: aggregated ? JSON.stringify(err.errors) : err.message
}
}
}
// eslint-disable-next-line require-await
public override async startComputeJob(
assets: ComputeAsset[],
algorithm: ComputeAlgorithm,
output: ComputeOutput,
environment: string,
owner: string,
maxJobDuration: number,
resources: ComputeResourceRequest[],
payment: DBComputeJobPayment,
jobId: string
): Promise<ComputeJob[]> {
if (!this.docker) return []
const isFree: boolean = !(payment && payment.lockTx)
// C2D - Check image, check arhitecture, etc
const image = getAlgorithmImage(algorithm)
// ex: node@sha256:1155995dda741e93afe4b1c6ced2d01734a6ec69865cc0997daf1f4db7259a36
if (!image) {
// send a 500 with the error message
throw new Error(
`Unable to extract docker image ${image} from algoritm: ${JSON.stringify(
algorithm
)}`
)
}
const envIdWithHash = environment && environment.indexOf('-') > -1
const env = await this.getComputeEnvironment(
payment && payment.chainId ? payment.chainId : null,
envIdWithHash ? environment : null,
environment
)
if (!env) {
throw new Error(`Invalid environment ${environment}`)
}
const validation = await C2DEngineDocker.checkDockerImage(image, env.platform)
if (!validation.valid)
throw new Error(`Unable to validate docker image ${image}: ${validation.reason}`)
const job: DBComputeJob = {
clusterHash: this.getC2DConfig().hash,
containerImage: image,
owner,
jobId,
dateCreated: String(Date.now() / 1000),
dateFinished: null,
status: C2DStatusNumber.JobStarted,
statusText: C2DStatusText.JobStarted,
results: [],
algorithm,
assets,
maxJobDuration,
environment,
configlogURL: null,
publishlogURL: null,
algologURL: null,
outputsURL: null,
stopRequested: false,
isRunning: true,
isStarted: false,
resources,
isFree,
algoStartTimestamp: '0',
algoStopTimestamp: '0',
payment
}
await this.makeJobFolders(job)
// make sure we actually were able to insert on DB
const addedId = await this.db.newJob(job)
if (!addedId) {
return []
}
// only now set the timer
if (!this.cronTimer) {
this.setNewTimer()
}
const cjob: ComputeJob = omitDBComputeFieldsFromComputeJob(job)
// we add cluster hash to user output
cjob.jobId = this.getC2DConfig().hash + '-' + cjob.jobId
// cjob.jobId = jobId
return [cjob]
}
// eslint-disable-next-line require-await
public override async stopComputeJob(
jobId: string,
owner: string,
agreementId?: string
): Promise<ComputeJob[]> {
return null
}
// eslint-disable-next-line require-await
protected async getResults(jobId: string): Promise<ComputeResult[]> {
const res: ComputeResult[] = []
let index = 0
try {
const logStat = statSync(
this.getC2DConfig().tempFolder + '/' + jobId + '/data/logs/algorithm.log'
)
if (logStat) {
res.push({
filename: 'algorithm.log',
filesize: logStat.size,
type: 'algorithmLog',
index
})
index = index + 1
}
} catch (e) {}
try {
const outputStat = statSync(
this.getC2DConfig().tempFolder + '/' + jobId + '/data/outputs/outputs.tar'
)
if (outputStat) {
res.push({
filename: 'outputs.tar',
filesize: outputStat.size,
type: 'output',
index
})
index = index + 1
}
} catch (e) {}
return res
}
// eslint-disable-next-line require-await
public override async getComputeJobStatus(
consumerAddress?: string,
agreementId?: string,
jobId?: string
): Promise<ComputeJob[]> {
const jobs = await this.db.getJob(jobId, agreementId, consumerAddress)
if (jobs.length === 0) {
return []
}
const statusResults = []
for (const job of jobs) {
const res: ComputeJob = omitDBComputeFieldsFromComputeJob(job)
// add results for algoLogs
res.results = await this.getResults(job.jobId)
statusResults.push(res)
}
return statusResults
}
// eslint-disable-next-line require-await
public override async getComputeJobResult(
consumerAddress: string,
jobId: string,
index: number
): Promise<{ stream: Readable; headers: any }> {
const jobs = await this.db.getJob(jobId, null, consumerAddress)
if (jobs.length === 0) {
return null
}
const results = await this.getResults(jobId)
for (const i of results) {
if (i.index === index) {
if (i.type === 'algorithmLog') {
return {
stream: createReadStream(
this.getC2DConfig().tempFolder + '/' + jobId + '/data/logs/algorithm.log'
),
headers: {
'Content-Type': 'text/plain'
}
}
}
if (i.type === 'output') {
return {
stream: createReadStream(
this.getC2DConfig().tempFolder + '/' + jobId + '/data/outputs/outputs.tar'
),
headers: {
'Content-Type': 'application/octet-stream'
}
}
}
}
}
return null
}
// eslint-disable-next-line require-await
public override async getStreamableLogs(jobId: string): Promise<NodeJS.ReadableStream> {
const jobRes: DBComputeJob[] = await this.db.getJob(jobId)
if (jobRes.length === 0) return null
if (!jobRes[0].isRunning) return null
try {
const job = jobRes[0]
const container = await this.docker.getContainer(job.jobId + '-algoritm')
const details = await container.inspect()
if (details.State.Running === false) return null
return await container.logs({
stdout: true,
stderr: true,
follow: true
})
} catch (e) {
return null
}
}
private async setNewTimer() {
// don't set the cron if we don't have compute environments
if ((await this.getComputeEnvironments()).length > 0)
this.cronTimer = setInterval(this.InternalLoop.bind(this), this.cronTime)
}
private async InternalLoop() {
// this is the internal loop of docker engine
// gets list of all running jobs and process them one by one
clearInterval(this.cronTimer)
this.cronTimer = null
// get all running jobs
const jobs = await this.db.getRunningJobs(this.getC2DConfig().hash)
if (jobs.length === 0) {
CORE_LOGGER.info('No C2D jobs found for engine ' + this.getC2DConfig().hash)
return
} else {
CORE_LOGGER.info(`Got ${jobs.length} jobs for engine ${this.getC2DConfig().hash}`)
CORE_LOGGER.debug(JSON.stringify(jobs))
}
const promises: any = []
for (const job of jobs) {
promises.push(this.processJob(job))
}
// wait for all promises, there is no return
await Promise.all(promises)
// set the cron again
this.setNewTimer()
}
private async createDockerContainer(
containerInfo: ContainerCreateOptions,
retry: boolean = false
): Promise<Dockerode.Container> | null {
try {
const container = await this.docker.createContainer(containerInfo)
console.log('container: ', container)
return container
} catch (e) {
CORE_LOGGER.error(`Unable to create docker container: ${e.message}`)
if (
e.message
.toLowerCase()
.includes('--storage-opt is supported only for overlay over xfs') &&
retry
) {
delete containerInfo.HostConfig.StorageOpt
CORE_LOGGER.info('Retrying again without HostConfig.StorageOpt options...')
// Retry without that option because it does not work
return this.createDockerContainer(containerInfo)
}
return null
}
}
private async createDockerVolume(
volume: VolumeCreateOptions,
retry: boolean = false
): Promise<boolean> {
try {
await this.docker.createVolume(volume)
return true
} catch (e) {
CORE_LOGGER.error(`Unable to create docker volume: ${e.message}`)
if (
e.message.toLowerCase().includes('quota size requested but no quota support') &&
retry
) {
delete volume.DriverOpts
CORE_LOGGER.info('Retrying again without DriverOpts options...')
return this.createDockerVolume(volume)
}
return false
}
}
// eslint-disable-next-line require-await
private async processJob(job: DBComputeJob) {
console.log(`Process job started: [STATUS: ${job.status}: ${job.statusText}]`)
console.log(job)
// has to :
// - monitor running containers and stop them if over limits
// - monitor disc space and clean up
/* steps:
- instruct docker to pull image
- create volume
- after image is ready, create the container
- download assets & algo into temp folder
- download DDOS
- tar and upload assets & algo to container
- start the container
- check if container is exceeding validUntil
- if yes, stop it
- download /data/outputs and store it locally (or upload it somewhere)
- delete the container
- delete the volume
*/
if (job.status === C2DStatusNumber.JobStarted) {
// pull docker image
try {
const pullStream = await this.docker.pull(job.containerImage)
await new Promise((resolve, reject) => {
let wroteStatusBanner = false
this.docker.modem.followProgress(
pullStream,
(err: any, res: any) => {
// onFinished
if (err) return reject(err)
CORE_LOGGER.info('############# Pull docker image complete ##############')
resolve(res)
},
(progress: any) => {
// onProgress
if (!wroteStatusBanner) {
wroteStatusBanner = true
CORE_LOGGER.info('############# Pull docker image status: ##############')
}
// only write the status banner once, its cleaner
CORE_LOGGER.info(progress.status)
}
)
})
} catch (err) {
CORE_LOGGER.error(
`Unable to pull docker image: ${job.containerImage}: ${err.message}`
)
job.status = C2DStatusNumber.PullImageFailed
job.statusText = C2DStatusText.PullImageFailed
job.isRunning = false
job.dateFinished = String(Date.now() / 1000)
await this.db.updateJob(job)
await this.cleanupJob(job)
return
}
job.status = C2DStatusNumber.PullImage
job.statusText = C2DStatusText.PullImage
await this.db.updateJob(job)
return // now we wait until image is ready
}
if (job.status === C2DStatusNumber.PullImage) {
try {
const imageInfo = await this.docker.getImage(job.containerImage)
console.log('imageInfo', imageInfo)
const details = await imageInfo.inspect()
console.log('details:', details)
job.status = C2DStatusNumber.ConfiguringVolumes
job.statusText = C2DStatusText.ConfiguringVolumes
await this.db.updateJob(job)
// now we can move forward
} catch (e) {
// not ready yet
CORE_LOGGER.error(`Unable to inspect docker image: ${e.message}`)
}
return
}
if (job.status === C2DStatusNumber.ConfiguringVolumes) {
// create the volume & create container
// TO DO C2D: Choose driver & size
// get env info
// const environment = await this.getJobEnvironment(job)
const volume: VolumeCreateOptions = {
Name: job.jobId + '-volume'
}
// volume
const diskSize = this.getResourceRequest(job.resources, 'disk')
if (diskSize && diskSize > 0) {
volume.DriverOpts = {
o: 'size=' + String(diskSize)
}
}
const volumeCreated = await this.createDockerVolume(volume, true)
if (!volumeCreated) {
job.status = C2DStatusNumber.VolumeCreationFailed
job.statusText = C2DStatusText.VolumeCreationFailed
job.isRunning = false
job.dateFinished = String(Date.now() / 1000)
await this.db.updateJob(job)
await this.cleanupJob(job)
return
}
// create the container
const mountVols: any = { '/data': {} }
const hostConfig: HostConfig = {
Mounts: [
{
Type: 'volume',
Source: volume.Name,
Target: '/data',
ReadOnly: false
}
]
}
// disk
if (diskSize && diskSize > 0) {
hostConfig.StorageOpt = {
size: String(diskSize)
}
}
// ram
const ramSize = this.getResourceRequest(job.resources, 'ram')
if (ramSize && ramSize > 0) {
hostConfig.Memory = ramSize
// set swap to same memory value means no swap (otherwise it use like 2X mem)
hostConfig.MemorySwap = hostConfig.Memory
}
const cpus = this.getResourceRequest(job.resources, 'cpu')
if (cpus && cpus > 0) {
const systemInfo = this.docker ? await this.docker.info() : null
hostConfig.CpuPeriod = 100000 // 100 miliseconds is usually the default
hostConfig.CpuQuota = Math.floor((cpus / systemInfo.NCPU) * hostConfig.CpuPeriod)
}
const containerInfo: ContainerCreateOptions = {
name: job.jobId + '-algoritm',
Image: job.containerImage,
AttachStdin: false,
AttachStdout: true,
AttachStderr: true,
Tty: true,
OpenStdin: false,
StdinOnce: false,
Volumes: mountVols,
HostConfig: hostConfig
}
if (job.algorithm.meta.container.entrypoint) {
const newEntrypoint = job.algorithm.meta.container.entrypoint.replace(
'$ALGO',
'data/transformations/algorithm'
)
containerInfo.Entrypoint = newEntrypoint.split(' ')
}
console.log('CREATING CONTAINER')
console.log(containerInfo)
const container = await this.createDockerContainer(containerInfo, true)
if (container) {
console.log('container: ', container)
job.status = C2DStatusNumber.Provisioning
job.statusText = C2DStatusText.Provisioning
await this.db.updateJob(job)
} else {
job.status = C2DStatusNumber.ContainerCreationFailed
job.statusText = C2DStatusText.ContainerCreationFailed
job.isRunning = false
job.dateFinished = String(Date.now() / 1000)
await this.db.updateJob(job)
await this.cleanupJob(job)
return
}
return
}
if (job.status === C2DStatusNumber.Provisioning) {
// download algo & assets
const ret = await this.uploadData(job)
console.log('Upload data')
console.log(ret)
job.status = ret.status
job.statusText = ret.statusText
if (job.status !== C2DStatusNumber.RunningAlgorithm) {
// failed, let's close it
job.isRunning = false
job.dateFinished = String(Date.now() / 1000)
await this.db.updateJob(job)
await this.cleanupJob(job)
} else {
await this.db.updateJob(job)
}
}
if (job.status === C2DStatusNumber.RunningAlgorithm) {
const container = await this.docker.getContainer(job.jobId + '-algoritm')
const details = await container.inspect()
console.log('Container inspect')
console.log(details)
if (job.isStarted === false) {
// make sure is not started
if (details.State.Running === false) {
try {
await container.start()
job.isStarted = true
job.algoStartTimestamp = String(Date.now() / 1000)
await this.db.updateJob(job)
return
} catch (e) {
// container failed to start
job.algoStartTimestamp = String(Date.now() / 1000)
job.algoStopTimestamp = String(Date.now() / 1000)
try {
const algoLogFile =
this.getC2DConfig().tempFolder +
'/' +
job.jobId +
'/data/logs/algorithm.log'
writeFileSync(algoLogFile, String(e.message))
} catch (e) {
console.log('Failed to write')
console.log(e)
}
console.error('could not start container: ' + e.message)
console.log(e)
job.status = C2DStatusNumber.AlgorithmFailed
job.statusText = C2DStatusText.AlgorithmFailed
job.isRunning = false
job.dateFinished = String(Date.now() / 1000)
await this.db.updateJob(job)
await this.cleanupJob(job)
return
}
}
} else {
// is running, we need to stop it..
console.log('running, need to stop it?')
const timeNow = Date.now() / 1000
const expiry = parseFloat(job.algoStartTimestamp) + job.maxJobDuration
console.log('timeNow: ' + timeNow + ' , Expiry: ' + expiry)
if (timeNow > expiry || job.stopRequested) {
// we need to stop the container
// make sure is running
console.log('We need to stop')
console.log(details.State.Running)
if (details.State.Running === true) {
try {
await container.stop()
} catch (e) {
// we should never reach this, unless the container is already stopped or deleted by someone else
console.log(e)
}
}
console.log('Stopped')
job.isStarted = false
job.status = C2DStatusNumber.PublishingResults
job.statusText = C2DStatusText.PublishingResults
job.algoStopTimestamp = String(Date.now() / 1000)
job.isRunning = false
await this.db.updateJob(job)
return
} else {
if (details.State.Running === false) {
job.isStarted = false
job.status = C2DStatusNumber.PublishingResults
job.statusText = C2DStatusText.PublishingResults
job.algoStopTimestamp = String(Date.now() / 1000)
job.isRunning = false
await this.db.updateJob(job)
return
}
}
}
}
if (job.status === C2DStatusNumber.PublishingResults) {
// get output
job.status = C2DStatusNumber.JobFinished
job.statusText = C2DStatusText.JobFinished
const container = await this.docker.getContainer(job.jobId + '-algoritm')
const outputsArchivePath =
this.getC2DConfig().tempFolder + '/' + job.jobId + '/data/outputs/outputs.tar'
try {
await pipeline(
await container.getArchive({ path: '/data/outputs' }),
createWriteStream(outputsArchivePath)
)
} catch (e) {
console.log(e)
job.status = C2DStatusNumber.ResultsUploadFailed
job.statusText = C2DStatusText.ResultsUploadFailed
}
job.isRunning = false
job.dateFinished = String(Date.now() / 1000)
await this.db.updateJob(job)
await this.cleanupJob(job)
}
}
// eslint-disable-next-line require-await
private async cleanupJob(job: DBComputeJob) {
// cleaning up
// - claim payment or release lock
// - get algo logs
// - delete volume
// - delete container
// payments
if (!job.isFree && job.payment) {
let txId = null
const env = await this.getComputeEnvironment(job.payment.chainId, job.environment)
let minDuration = 0
if (env && `minJobDuration` in env && env.minJobDuration) {
minDuration = env.minJobDuration
}
const algoRunnedTime =
parseFloat(job.algoStopTimestamp) - parseFloat(job.algoStartTimestamp)
if (algoRunnedTime < 0) minDuration += algoRunnedTime * -1
else minDuration += algoRunnedTime
if (minDuration > 0) {
// we need to claim
const cost = this.getTotalCostOfJob(job.resources, minDuration)
const proof = JSON.stringify(omitDBComputeFieldsFromComputeJob(job))
try {
txId = await this.escrow.claimLock(
job.payment.chainId,
job.jobId,
job.payment.token,
job.owner,
cost,
proof
)
} catch (e) {
console.log(e)
}
} else {
// release the lock, we are not getting paid
try {
txId = await this.escrow.cancelExpiredLocks(
job.payment.chainId,
job.jobId,
job.payment.token,
job.owner
)
} catch (e) {
console.log(e)
}
}
if (txId) {
job.payment.claimTx = txId
await this.db.updateJob(job)
}
}
try {
const container = await this.docker.getContainer(job.jobId + '-algoritm')
if (container) {
if (job.status !== C2DStatusNumber.AlgorithmFailed) {
writeFileSync(
this.getC2DConfig().tempFolder + '/' + job.jobId + '/data/logs/algorithm.log',
await container.logs({
stdout: true,
stderr: true,
follow: false
})
)
}
await container.remove()
}
const volume = await this.docker.getVolume(job.jobId + '-volume')
if (volume) {
try {
await volume.remove()
} catch (e) {
console.log(e)
}
}
// remove folders
rmSync(this.getC2DConfig().tempFolder + '/' + job.jobId + '/data/inputs', {
recursive: true,
force: true
})
rmSync(this.getC2DConfig().tempFolder + '/' + job.jobId + '/data/transformations', {
recursive: true,
force: true
})
} catch (e) {
console.log(e)
}
}
private deleteOutputFolder(job: DBComputeJob) {
rmSync(this.getC2DConfig().tempFolder + '/' + job.jobId + '/data/outputs/', {
recursive: true,
force: true
})
}
private async uploadData(
job: DBComputeJob
): Promise<{ status: C2DStatusNumber; statusText: C2DStatusText }> {
const config = await getConfiguration()
const ret = {
status: C2DStatusNumber.RunningAlgorithm,
statusText: C2DStatusText.RunningAlgorithm
}
// for testing purposes
// if (!job.algorithm.fileObject) {
// console.log('no file object')
// const file: UrlFileObject = {
// type: 'url',
// url: 'https://raw.githubusercontent.com/oceanprotocol/test-algorithm/master/javascript/algo.js',
// method: 'get'
// }
// job.algorithm.fileObject = file