-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathcompute_engine_docker.ts
More file actions
executable file
·3403 lines (3168 loc) · 114 KB
/
compute_engine_docker.ts
File metadata and controls
executable file
·3403 lines (3168 loc) · 114 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, PassThrough } from 'stream'
import os from 'os'
import path from 'path'
import {
C2DStatusNumber,
C2DStatusText,
DBComputeJobMetadata
} from '../../@types/C2D/C2D.js'
import type {
C2DClusterInfo,
ComputeEnvironment,
ComputeAlgorithm,
ComputeOutput,
ComputeAsset,
ComputeJob,
DBComputeJob,
DBComputeJobPayment,
ComputeResult,
RunningPlatform,
ComputeEnvFeesStructure,
ComputeResourceRequest,
ComputeEnvFees,
ComputeResource,
C2DEnvironmentConfig,
ComputeResourcesPricingInfo
} from '../../@types/C2D/C2D.js'
import {
BASE_CHAIN_ID,
getConfiguration,
USDC_TOKEN_ADDRESS_BASE
} 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 * as tarStream from 'tar-stream'
import {
createWriteStream,
existsSync,
mkdirSync,
chmodSync,
rmSync,
writeFileSync,
appendFileSync,
statSync,
statfsSync,
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 { KeyManager } from '../KeyManager/index.js'
import { decryptFilesObject, omitDBComputeFieldsFromComputeJob } from './index.js'
import { ValidateParams } from '../httpRoutes/validateCommands.js'
import { Service } from '@oceanprotocol/ddo-js'
import { getOceanTokenAddressForChain } from '../../utils/address.js'
import { dockerRegistrysAuth, dockerRegistryAuth } from '../../@types/OceanNode.js'
import { EncryptMethod } from '../../@types/fileObject.js'
import { getAddress, ZeroAddress } from 'ethers'
import { AccessList } from '../../@types/AccessList.js'
const C2D_CONTAINER_UID = 1000
const C2D_CONTAINER_GID = 1000
const trivyImage = 'aquasec/trivy:0.69.3' // Use pinned versions for safety
export class C2DEngineDocker extends C2DEngine {
private envs: ComputeEnvironment[] = []
public docker: Dockerode
private cronTimer: any
private cronTime: number = 2000
private jobImageSizes: Map<string, number> = new Map()
private isInternalLoopRunning: boolean = false
private imageCleanupTimer: NodeJS.Timeout | null = null
private paymentClaimTimer: NodeJS.Timeout | null = null
private scanDBUpdateTimer: NodeJS.Timeout | null = null
private static DEFAULT_DOCKER_REGISTRY = 'https://registry-1.docker.io'
private retentionDays: number
private cleanupInterval: number
private paymentClaimInterval: number
private scanImages: boolean
private scanImageDBUpdateInterval: number
private trivyCachePath: string
private cpuAllocations: Map<string, number[]> = new Map()
private envCpuCoresMap: Map<string, number[]> = new Map()
public constructor(
clusterConfig: C2DClusterInfo,
db: C2DDatabase,
escrow: Escrow,
keyManager: KeyManager,
dockerRegistryAuths: dockerRegistrysAuth
) {
super(clusterConfig, db, escrow, keyManager, dockerRegistryAuths)
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)
}
}
this.retentionDays = clusterConfig.connection.imageRetentionDays || 7
this.cleanupInterval = clusterConfig.connection.imageCleanupInterval
this.paymentClaimInterval = clusterConfig.connection.paymentClaimInterval || 3600 // 1 hour
this.scanImages = clusterConfig.connection.scanImages || false // default is not to scan images for now, until it's prod ready
this.scanImageDBUpdateInterval = clusterConfig.connection.scanImageDBUpdateInterval
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)
}
}
// trivy cache is the same for all engines
this.trivyCachePath = path.join(
process.cwd(),
this.getC2DConfig().tempFolder,
'trivy_cache'
)
try {
if (!existsSync(this.getStoragePath()))
mkdirSync(this.getStoragePath(), { recursive: true })
if (!existsSync(this.trivyCachePath))
mkdirSync(this.trivyCachePath, { recursive: true })
} catch (e) {
CORE_LOGGER.error(
'Could not create Docker container temporary folders: ' + e.message
)
}
// envs are build on start function
}
private processFeesForEnvironment(
rawFees: ComputeEnvFeesStructure | undefined,
supportedChains: number[]
): ComputeEnvFeesStructure | null {
if (!rawFees || Object.keys(rawFees).length === 0) return null
let fees: ComputeEnvFeesStructure = null
for (const feeChain of Object.keys(rawFees)) {
if (!supportedChains.includes(parseInt(feeChain))) continue
if (fees === null) fees = {}
if (!(feeChain in fees)) fees[feeChain] = []
const tmpFees: ComputeEnvFees[] = []
for (const feeEntry of rawFees[feeChain]) {
if (!feeEntry.prices || feeEntry.prices.length === 0) {
CORE_LOGGER.error(
`Unable to find prices for fee ${JSON.stringify(feeEntry)} on chain ${feeChain}`
)
continue
}
if (!feeEntry.feeToken) {
const tokenAddress = getOceanTokenAddressForChain(parseInt(feeChain))
if (tokenAddress) {
feeEntry.feeToken = tokenAddress
tmpFees.push(feeEntry)
} else {
CORE_LOGGER.error(
`Unable to find Ocean token address for chain ${feeChain} and no custom token provided`
)
}
} else {
tmpFees.push(feeEntry)
}
}
fees[feeChain] = tmpFees
}
return fees
}
public getStoragePath(): string {
return this.getC2DConfig().tempFolder + this.getC2DConfig().hash
}
private createBenchmarkEnvironment(sysinfo: any, envConfig: any): void {
const ramGB = this.physicalLimits.get('ram') || 0
const physicalDiskGB = this.physicalLimits.get('disk') || 0
const gpuMap = new Map<string, ComputeResource>()
for (const env of envConfig.environments) {
if (env.resources) {
for (const res of env.resources) {
if (res.id !== 'cpu' && res.id !== 'ram' && res.id !== 'disk') {
if (!gpuMap.has(res.id)) {
gpuMap.set(res.id, res)
}
}
}
}
}
const gpuResources: ComputeResource[] = Array.from(gpuMap.values())
const benchmarkPrices: ComputeResourcesPricingInfo[] = gpuResources.map((gpu) => ({
id: gpu.id,
price: 1
}))
const benchmarkFees: ComputeEnvFeesStructure = {
[BASE_CHAIN_ID]: [{ feeToken: USDC_TOKEN_ADDRESS_BASE, prices: benchmarkPrices }]
}
const benchmarkEnv: C2DEnvironmentConfig = {
description: 'Auto-generated benchmark environment',
storageExpiry: 604800,
maxJobDuration: 180,
minJobDuration: 60,
resources: [
{ id: 'cpu', total: sysinfo.NCPU, min: 1, max: sysinfo.NCPU },
{ id: 'ram', total: ramGB, min: 1, max: ramGB },
{ id: 'disk', total: physicalDiskGB, min: 0, max: physicalDiskGB },
...gpuResources
],
access: {
addresses: [],
accessLists: [
{ [BASE_CHAIN_ID]: [getAddress('0xcb7Db55Ca9Aa9C3b25F5Bc266da63317fa02086a')] }
]
},
fees: benchmarkFees,
enableNetwork: true
}
envConfig.environments.push(benchmarkEnv)
}
public override async start() {
const config = await getConfiguration()
const envConfig = await this.getC2DConfig().connection
if (!envConfig?.environments?.length) {
CORE_LOGGER.warn(
`Skipping C2D Engine ${this.getC2DConfig().hash}: no environments configured`
)
return
}
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
}
this.physicalLimits.set('cpu', sysinfo.NCPU)
this.physicalLimits.set('ram', Math.floor(sysinfo.MemTotal / 1024 / 1024 / 1024))
try {
const diskStats = statfsSync(this.getC2DConfig().tempFolder)
const diskGB = Math.floor((diskStats.bsize * diskStats.blocks) / 1024 / 1024 / 1024)
this.physicalLimits.set('disk', diskGB)
} catch (e) {
CORE_LOGGER.warn('Could not detect physical disk size: ' + e.message)
}
// Determine supported chains
const supportedChains: number[] = []
if (config.supportedNetworks) {
for (const chain of Object.keys(config.supportedNetworks)) {
supportedChains.push(parseInt(chain))
}
}
const platform: RunningPlatform = {
architecture: sysinfo.Architecture,
os: sysinfo.OSType
}
const consumerAddress = this.getKeyManager().getEthAddress()
if (config.enableBenchmark) {
if (supportedChains.includes(parseInt(BASE_CHAIN_ID))) {
this.createBenchmarkEnvironment(sysinfo, envConfig)
} else {
CORE_LOGGER.warn(
`Skipping benchmark environment: Base chain (${BASE_CHAIN_ID}) is not in supportedNetworks`
)
}
}
for (let envIdx = 0; envIdx < envConfig.environments.length; envIdx++) {
const envDef: C2DEnvironmentConfig = envConfig.environments[envIdx]
const fees = this.processFeesForEnvironment(envDef.fees, supportedChains)
const envResources: ComputeResource[] = []
const cpuResources = {
id: 'cpu',
type: 'cpu',
total: sysinfo.NCPU,
max: sysinfo.NCPU,
min: 1,
description: os.cpus()[0].model
}
const ramResources = {
id: 'ram',
type: 'ram',
total: Math.floor(sysinfo.MemTotal / 1024 / 1024 / 1024),
max: Math.floor(sysinfo.MemTotal / 1024 / 1024 / 1024),
min: 1
}
const physicalDiskGB = this.physicalLimits.get('disk') || 0
const diskResources = {
id: 'disk',
type: 'disk',
total: physicalDiskGB,
max: physicalDiskGB,
min: 0
}
if (envDef.resources) {
for (const res of envDef.resources) {
// allow user to add other resources
if (res.id === 'cpu') {
if (res.total) cpuResources.total = res.total
if (res.max) cpuResources.max = res.max
if (res.min) cpuResources.min = res.min
}
if (res.id === 'ram') {
if (res.total) ramResources.total = res.total
if (res.max) ramResources.max = res.max
if (res.min) ramResources.min = res.min
}
if (res.id === 'disk') {
if (res.total) diskResources.total = res.total
if (res.max) diskResources.max = res.max
if (res.min !== undefined) diskResources.min = res.min
}
if (res.id !== 'cpu' && res.id !== 'ram' && res.id !== 'disk') {
if (!res.max) res.max = res.total
if (!res.min) res.min = 0
envResources.push(res)
}
}
}
envResources.push(cpuResources)
envResources.push(ramResources)
envResources.push(diskResources)
const env: ComputeEnvironment = {
id: '',
runningJobs: 0,
consumerAddress,
platform,
access: envDef.access || { addresses: [], accessLists: null },
fees,
resources: envResources,
queuedJobs: 0,
queuedFreeJobs: 0,
queMaxWaitTime: 0,
queMaxWaitTimeFree: 0,
runMaxWaitTime: 0,
runMaxWaitTimeFree: 0,
enableNetwork: envDef.enableNetwork
}
if (envDef.storageExpiry !== undefined) env.storageExpiry = envDef.storageExpiry
if (envDef.minJobDuration !== undefined) env.minJobDuration = envDef.minJobDuration
if (envDef.maxJobDuration !== undefined) env.maxJobDuration = envDef.maxJobDuration
if (envDef.maxJobs !== undefined) env.maxJobs = envDef.maxJobs
if (envDef.description !== undefined) env.description = envDef.description
// Free tier config for this environment
if (envDef.free) {
env.free = {
access: envDef.free.access || { addresses: [], accessLists: null }
}
if (envDef.free.storageExpiry !== undefined)
env.free.storageExpiry = envDef.free.storageExpiry
if (envDef.free.minJobDuration !== undefined)
env.free.minJobDuration = envDef.free.minJobDuration
if (envDef.free.maxJobDuration !== undefined)
env.free.maxJobDuration = envDef.free.maxJobDuration
if (envDef.free.maxJobs !== undefined) env.free.maxJobs = envDef.free.maxJobs
if (envDef.free.resources) env.free.resources = envDef.free.resources
}
const envIdSuffix = envDef.id || String(envIdx)
env.id =
this.getC2DConfig().hash +
'-' +
create256Hash(JSON.stringify(env.fees) + envIdSuffix)
this.envs.push(env)
CORE_LOGGER.info(
`Engine ${this.getC2DConfig().hash}: created environment ${env.id} (index=${envIdx}, resources=${envResources.map((r) => r.id).join(',')})`
)
}
const physicalCpuCount = this.physicalLimits.get('cpu') || 0
let cpuOffset = 0
for (const env of this.envs) {
const cpuRes = this.getResource(env.resources ?? [], 'cpu')
if (cpuRes && cpuRes.total > 0) {
let isBenchmarkEnv = false
if (env.access?.accessLists) {
const baseAccessList = env.access?.accessLists?.[0] as AccessList
if (baseAccessList && baseAccessList[BASE_CHAIN_ID]) {
isBenchmarkEnv = baseAccessList[BASE_CHAIN_ID].includes(
getAddress('0xcb7Db55Ca9Aa9C3b25F5Bc266da63317fa02086a')
)
}
}
if (isBenchmarkEnv) {
const total = physicalCpuCount > 0 ? physicalCpuCount : cpuRes.total
const cores = Array.from({ length: total }, (_, i) => i)
this.envCpuCoresMap.set(env.id, cores)
CORE_LOGGER.info(
`CPU affinity: benchmark environment ${env.id} cores 0-${cores[cores.length - 1]}`
)
} else {
const cores = Array.from({ length: cpuRes.total }, (_, i) => cpuOffset + i)
this.envCpuCoresMap.set(env.id, cores)
CORE_LOGGER.info(
`CPU affinity: environment ${env.id} cores ${cores[0]}-${cores[cores.length - 1]}`
)
cpuOffset += cpuRes.total
}
}
}
// Rebuild CPU allocations from running containers (handles node restart)
await this.rebuildCpuAllocations()
// only now set the timer
if (!this.cronTimer) {
this.setNewTimer()
}
this.startCrons()
}
public startCrons() {
if (!this.docker) {
CORE_LOGGER.debug('Docker not available, skipping crons')
return
}
// Start image cleanup timer
if (this.cleanupInterval) {
if (this.imageCleanupTimer) {
return // Already running
}
// Run initial cleanup after a short delay
setTimeout(() => {
this.cleanupOldImages().catch((e) => {
CORE_LOGGER.error(`Initial image cleanup failed: ${e.message}`)
})
}, 60000) // Wait 1 minute after start
// Set up periodic cleanup
this.imageCleanupTimer = setInterval(() => {
this.cleanupOldImages().catch((e) => {
CORE_LOGGER.error(`Periodic image cleanup failed: ${e.message}`)
})
}, this.cleanupInterval * 1000)
CORE_LOGGER.info(
`Image cleanup timer started (interval: ${this.cleanupInterval / 60} minutes)`
)
}
// start payments cron
if (this.paymentClaimInterval) {
if (this.paymentClaimTimer) {
return // Already running
}
// Run initial cleanup after a short delay
setTimeout(() => {
this.claimPayments().catch((e) => {
CORE_LOGGER.error(`Initial payments claim failed: ${e.message}`)
})
}, 60000) // Wait 1 minute after start
// Set up periodic cleanup
this.paymentClaimTimer = setInterval(() => {
this.claimPayments().catch((e) => {
CORE_LOGGER.error(`Periodic payments claim failed: ${e.message}`)
})
}, this.paymentClaimInterval * 1000)
CORE_LOGGER.info(
`Payments claim timer started (interval: ${this.paymentClaimInterval / 60} minutes)`
)
}
// scan db updater cron
if (this.scanImageDBUpdateInterval) {
if (this.scanDBUpdateTimer) {
return // Already running
}
// Run initial db cache
setTimeout(() => {
this.scanDBUpdate().catch((e) => {
CORE_LOGGER.error(`scan DB Update Initial failed: ${e.message}`)
})
}, 30000) // Wait 30 seconds
// Set up periodic cleanup
this.scanDBUpdateTimer = setInterval(() => {
this.scanDBUpdate().catch((e) => {
CORE_LOGGER.error(`Periodic scan DB update failed: ${e.message}`)
})
}, this.scanImageDBUpdateInterval * 1000)
CORE_LOGGER.info(
`scan DB update timer started (interval: ${this.scanImageDBUpdateInterval / 60} minutes)`
)
}
}
public override stop(): Promise<void> {
// Clear the timer and reset the flag
if (this.cronTimer) {
clearTimeout(this.cronTimer)
this.cronTimer = null
}
this.isInternalLoopRunning = false
// Stop image cleanup timer
if (this.imageCleanupTimer) {
clearInterval(this.imageCleanupTimer)
this.imageCleanupTimer = null
CORE_LOGGER.debug('Image cleanup timer stopped')
}
if (this.paymentClaimTimer) {
clearInterval(this.paymentClaimTimer)
this.paymentClaimTimer = null
CORE_LOGGER.debug('Payment claim timer stopped')
}
return Promise.resolve()
}
public async updateImageUsage(image: string): Promise<void> {
try {
await this.db.updateImage(image)
} catch (e) {
CORE_LOGGER.error(`Failed to update image usage for ${image}: ${e.message}`)
}
}
private async claimPayments(): Promise<void> {
const currentTimestamp = BigInt(Math.floor(Date.now() / 1000))
const envs: string[] = []
const envsChains: string[] = []
// Group jobs by operation type and chain for batch processing
const jobsToClaim: Array<{
job: DBComputeJob
cost: number
proof: string
}> = []
const jobsToCancel: DBComputeJob[] = []
const jobsWithoutLock: DBComputeJob[] = []
for (const env of this.envs) {
envs.push(env.id)
for (const chain in env.fees) {
if (!envsChains.includes(chain)) envsChains.push(chain)
}
}
// get all jobs that needs to be paid
const jobs = await this.db.getJobsByStatus(envs, [
C2DStatusNumber.AlgorithmFailed,
C2DStatusNumber.DiskQuotaExceeded,
C2DStatusNumber.ResultsFetchFailed,
C2DStatusNumber.ResultsUploadFailed,
C2DStatusNumber.JobSettle
])
CORE_LOGGER.info(`ClaimPayments: Got ${jobs.length} jobs to check`)
if (jobs.length > 0) {
const providerAddress = this.getKeyManager().getEthAddress()
const chains: Set<number> = new Set()
// get all unique chains
for (const job of jobs) {
if (job.payment && job.payment.token) {
chains.add(job.payment.chainId)
}
}
// Get all locks for all chains
const locks: any[] = []
for (const chain of chains) {
try {
const contractLocks = await this.escrow.getLocks(
chain,
ZeroAddress,
ZeroAddress,
providerAddress
)
if (contractLocks) {
locks.push(...contractLocks)
}
} catch (e) {
CORE_LOGGER.error(`Failed to get locks for chain ${chain}: ${e.message}`)
}
}
// Process each job to determine what operation is needed
let duration
for (const job of jobs) {
// Calculate algo duration
duration = parseFloat(job.algoStopTimestamp) - parseFloat(job.algoStartTimestamp)
duration += this.getValidBuildDurationSeconds(job)
// Free jobs or jobs without payment info - mark as finished
if (job.isFree || !job.payment) {
jobsWithoutLock.push(job)
continue
}
// Find matching lock
const lock = locks.find(
(lock) => BigInt(lock.jobId.toString()) === BigInt(job.jobIdHash)
)
if (!lock) {
// No lock found, mark as finished
jobsWithoutLock.push(job)
continue
}
// Check if lock is expired
const lockExpiry = BigInt(lock.expiry.toString())
if (currentTimestamp > lockExpiry) {
// Lock expired, cancel it
jobsToCancel.push(job)
continue
}
// Get environment to calculate cost
const env = await this.getComputeEnvironment(job.payment.chainId, job.environment)
if (!env) {
CORE_LOGGER.warn(
`Environment not found for job ${job.jobId}, skipping payment claim`
)
continue
}
let minDuration = Math.abs(duration)
if (minDuration > job.maxJobDuration) {
minDuration = job.maxJobDuration
}
if (
`minJobDuration` in env &&
env.minJobDuration &&
minDuration < env.minJobDuration
) {
minDuration = env.minJobDuration
}
if (minDuration > 0) {
// We need to claim payment
const fee = env.fees?.[job.payment.chainId]?.find(
(fee) => fee.feeToken === job.payment.token
)
if (!fee) {
CORE_LOGGER.warn(
`Fee not found for job ${job.jobId}, token ${job.payment.token}, skipping`
)
continue
}
const cost = this.getTotalCostOfJob(job.resources, minDuration, fee)
const proof = JSON.stringify(omitDBComputeFieldsFromComputeJob(job))
jobsToClaim.push({ job, cost, proof })
} else {
// No payment due, cancel the lock
jobsToCancel.push(job)
}
}
// Batch process claims by chain
const claimsByChain = new Map<
number,
Array<{ job: DBComputeJob; cost: number; proof: string }>
>()
for (const claim of jobsToClaim) {
const { chainId } = claim.job.payment!
if (!claimsByChain.has(chainId)) {
claimsByChain.set(chainId, [])
}
claimsByChain.get(chainId)!.push(claim)
}
// Process batch claims
for (const [chainId, claims] of claimsByChain.entries()) {
if (claims.length === 0) continue
try {
const jobs = claims.map((c) => c.job)
const tokens = jobs.map((j) => j.payment!.token)
const payers = jobs.map((j) => j.owner)
const amounts = claims.map((c) => c.cost)
const proofs = claims.map((c) => c.proof)
const txId = await this.escrow.claimLocks(
chainId,
jobs.map((j) => j.jobId),
tokens,
payers,
amounts,
proofs
)
if (txId) {
// Update all jobs with the transaction ID
for (const claim of claims) {
if (claim.job.payment) {
claim.job.payment.claimTx = txId
claim.job.payment.cost = claim.cost
}
claim.job.status = C2DStatusNumber.JobFinished
claim.job.statusText = C2DStatusText.JobFinished
await this.db.updateJob(claim.job)
}
CORE_LOGGER.info(
`Successfully claimed ${claims.length} locks in batch transaction ${txId}`
)
}
} catch (e) {
CORE_LOGGER.error(
`Failed to batch claim locks for chain ${chainId}: ${e.message}`
)
// Fallback to individual processing on batch failure
for (const claim of claims) {
try {
const txId = await this.escrow.claimLock(
chainId,
claim.job.jobId,
claim.job.payment!.token,
claim.job.owner,
claim.cost,
claim.proof
)
if (txId) {
if (claim.job.payment) {
claim.job.payment.claimTx = txId
claim.job.payment.cost = claim.cost
}
claim.job.status = C2DStatusNumber.JobFinished
claim.job.statusText = C2DStatusText.JobFinished
await this.db.updateJob(claim.job)
}
} catch (err) {
CORE_LOGGER.error(
`Failed to claim lock for job ${claim.job.jobId}: ${err.message}`
)
}
}
}
}
// Batch process cancellations by chain
const cancellationsByChain = new Map<number, DBComputeJob[]>()
for (const job of jobsToCancel) {
const { chainId } = job.payment!
if (!cancellationsByChain.has(chainId)) {
cancellationsByChain.set(chainId, [])
}
cancellationsByChain.get(chainId)!.push(job)
}
// Process batch cancellations
for (const [chainId, jobsToCancelBatch] of cancellationsByChain.entries()) {
if (jobsToCancelBatch.length === 0) continue
try {
const jobIds = jobsToCancelBatch.map((j) => j.jobId)
const tokens = jobsToCancelBatch.map((j) => j.payment!.token)
const payers = jobsToCancelBatch.map((j) => j.owner)
const txId = await this.escrow.cancelExpiredLocks(
chainId,
jobIds,
tokens,
payers
)
if (txId) {
// Update all jobs
for (const job of jobsToCancelBatch) {
if (job.payment) job.payment.cancelTx = txId
job.status = C2DStatusNumber.JobFinished
job.statusText = C2DStatusText.JobFinished
await this.db.updateJob(job)
}
CORE_LOGGER.info(
`Successfully cancelled ${jobsToCancelBatch.length} expired locks in batch transaction ${txId}`
)
}
} catch (e) {
CORE_LOGGER.error(
`Failed to batch cancel locks for chain ${chainId}: ${e.message}`
)
// Fallback to individual processing on batch failure
for (const job of jobsToCancelBatch) {
try {
const txId = await this.escrow.cancelExpiredLock(
chainId,
job.jobId,
job.payment!.token,
job.owner
)
if (txId) {
if (job.payment) job.payment.cancelTx = txId
job.status = C2DStatusNumber.JobFinished
job.statusText = C2DStatusText.JobFinished
await this.db.updateJob(job)
}
} catch (err) {
CORE_LOGGER.error(
`Failed to cancel lock for job ${job.jobId}: ${err.message}`
)
}
}
}
}
// Mark jobs without locks as finished
for (const job of jobsWithoutLock) {
job.status = C2DStatusNumber.JobFinished
job.statusText = C2DStatusText.JobFinished
if (job.payment) {
job.payment.cancelTx = 'nolock'
job.payment.claimTx = 'nolock'
}
await this.db.updateJob(job)
}
}
// force clean of locks without jobs
// ideally, we should never have locks without jobs in db
// (handled above). This means somehow that db got deleted
for (const chain of envsChains) {
this.cleanUpUnknownLocks(chain, currentTimestamp)
}
}
private async cleanUpUnknownLocks(chain: string, currentTimestamp: bigint) {
try {
const nodeAddress = this.getKeyManager().getEthAddress()
const jobIds: any[] = []
const tokens: string[] = []
const payer: string[] = []
const balocks = await this.escrow.getLocks(
parseInt(chain),
'0x0000000000000000000000000000000000000000',
'0x0000000000000000000000000000000000000000',
nodeAddress
)
if (!balocks || balocks.length === 0) {
CORE_LOGGER.warn(`Could not find any locks for chain ${chain}, skipping cleanup`)
return
}
for (const lock of balocks) {
const lockExpiry = BigInt(lock.expiry.toString())
if (currentTimestamp > lockExpiry) {
jobIds.push(lock.jobId.toString())
tokens.push(lock.token)
payer.push(lock.payer)
}
}
if (jobIds.length > 0) {
try {
const tx = await this.escrow.cancelExpiredLocks(
parseInt(chain),
jobIds,
tokens,
payer,
false
)
CORE_LOGGER.warn(` Canceled locks on chain ${chain}, tx:${tx}`)
} catch (e) {
// not critical, since we will try to cancel them at next run
CORE_LOGGER.warn(`Tried to cancel some locks, errored: ${e.message}`)
}
}
} catch (e) {
CORE_LOGGER.error(`Error during cleanup of unknown locks: ${e.message}`)
}
}
private async cleanupOldImages(): Promise<void> {
if (!this.docker) return
try {
const oldImages = await this.db.getOldImages(this.retentionDays)
if (oldImages.length === 0) {
CORE_LOGGER.debug('No old images to clean up')
return
}
CORE_LOGGER.info(`Starting cleanup of ${oldImages.length} old Docker images`)
let cleaned = 0
let failed = 0
for (const image of oldImages) {
try {
const dockerImage = this.docker.getImage(image)
await dockerImage.remove({ force: true })
await this.db.deleteImage(image)
cleaned++
CORE_LOGGER.info(`Successfully removed old image: ${image}`)
} catch (e) {
failed++
// Image might be in use or already deleted - log but don't throw
CORE_LOGGER.debug(`Could not remove image ${image}: ${e.message}`)
}
}
CORE_LOGGER.info(
`Image cleanup completed: ${cleaned} removed, ${failed} failed (may be in use)`
)
} catch (e) {
CORE_LOGGER.error(`Error during image cleanup: ${e.message}`)
}
}
// 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 = []
// const systemInfo = this.docker ? await this.docker.info() : null
for (const env of this.envs) {
if (!chainId || (env.fees && Object.hasOwn(env.fees, String(chainId)))) {
const computeEnv = JSON.parse(JSON.stringify(env))
// TO DO - At some point in time we need to handle multiple runtimes
// console.log('********************************')
// console.log(systemInfo.GenericResources)
// console.log('********************************')
// if (systemInfo.Runtimes) computeEnv.runtimes = systemInfo.Runtimes
// if (systemInfo.DefaultRuntime)
// computeEnv.defaultRuntime = systemInfo.DefaultRuntime
const {
totalJobs,
totalFreeJobs,
usedResources,
usedFreeResources,
queuedJobs,
queuedFreeJobs,
maxWaitTime,
maxWaitTimeFree,
maxRunningTime,
maxRunningTimeFree
} = await this.getUsedResources(computeEnv)
computeEnv.runningJobs = totalJobs
computeEnv.runningfreeJobs = totalFreeJobs
computeEnv.queuedJobs = queuedJobs
computeEnv.queuedFreeJobs = queuedFreeJobs
computeEnv.queMaxWaitTime = maxWaitTime
computeEnv.queMaxWaitTimeFree = maxWaitTimeFree
computeEnv.runMaxWaitTime = maxRunningTime
computeEnv.runMaxWaitTimeFree = maxRunningTimeFree
if (computeEnv.resources) {
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
}
private parseImage(image: string) {