Repository navigation
Expand file tree
/
Copy pathdocker_head.ts
More file actions
2882 lines (2607 loc) · 90.4 KB
/
Copy pathdocker_head.ts
File metadata and controls
2882 lines (2607 loc) · 90.4 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
import fs from 'node:fs';
import path from 'node:path';
import axios from 'axios';
import Dockerode from 'dockerode';
import Joi from 'joi';
import JoiCronExpression from 'joi-cron-expression';
import RE2 from 're2';
const joi = JoiCronExpression(Joi);
import debounceImport from 'just-debounce';
import cron from 'node-cron';
import parse from 'parse-docker-image-name';
const debounce: typeof import('just-debounce').default =
(debounceImport as any).default || (debounceImport as any);
import * as event from '../../../event/index.js';
import log from '../../../log/index.js';
import {
type Container,
type ContainerImage,
fullName,
validate as validateContainer,
} from '../../../model/container.js';
import { getMaintenanceSkipCounter, getWatchContainerGauge } from '../../../prometheus/watcher.js';
import type { ComponentConfiguration } from '../../../registry/Component.js';
import * as registry from '../../../registry/index.js';
import { resolveConfiguredPath } from '../../../runtime/paths.js';
import * as storeContainer from '../../../store/container.js';
import {
isGreater as isGreaterSemver,
parse as parseSemver,
transform as transformTag,
} from '../../../tag/index.js';
import Watcher from '../../Watcher.js';
import {
ddComposeAuto,
ddComposeBackup,
ddComposeDigestpin,
ddComposeDryrun,
ddComposeFile,
ddComposeNative,
ddComposeOnce,
ddComposePrune,
ddComposeThreshold,
ddDisplayIcon,
ddDisplayName,
ddInspectTagPath,
ddLinkTemplate,
ddRegistryLookupImage,
ddRegistryLookupUrl,
ddTagExclude,
ddTagInclude,
ddTagTransform,
ddTriggerExclude,
ddTriggerInclude,
ddWatch,
ddWatchDigest,
wudComposeAuto,
wudComposeBackup,
wudComposeDigestpin,
wudComposeDryrun,
wudDisplayIcon,
wudDisplayName,
wudComposeFile,
wudComposeNative,
wudComposeOnce,
wudComposePrune,
wudComposeThreshold,
wudInspectTagPath,
wudLinkTemplate,
wudRegistryLookupImage,
wudRegistryLookupUrl,
wudTagExclude,
wudTagInclude,
wudTagTransform,
wudTriggerExclude,
wudTriggerInclude,
wudWatch,
wudWatchDigest,
} from './label.js';
import { getNextMaintenanceWindow, isInMaintenanceWindow } from './maintenance.js';
export interface DockerWatcherConfiguration extends ComponentConfiguration {
socket: string;
host?: string;
protocol?: 'http' | 'https' | 'ssh';
port: number;
auth?: {
type?: 'basic' | 'bearer' | 'oidc';
user?: string;
password?: string;
bearer?: string;
oidc?: any;
};
cafile?: string;
certfile?: string;
keyfile?: string;
cron: string;
jitter: number;
watchbydefault: boolean;
watchall: boolean;
watchdigest?: any;
watchevents: boolean;
watchatstart: boolean;
maintenancewindow?: string;
maintenancewindowtz: string;
compose?: {
backup?: boolean;
prune?: boolean;
dryrun?: boolean;
auto?: boolean;
once?: boolean;
digestpin?: boolean;
native?: boolean;
threshold?: string;
};
imgset?: Record<string, any>;
}
/**
* Get a label value, preferring the dd.* key over the wud.* fallback.
*/
function getLabel(labels: Record<string, string>, ddKey: string, wudKey?: string) {
return labels[ddKey] ?? (wudKey ? labels[wudKey] : undefined);
}
/**
* Safely compile a user-supplied regex pattern.
* Returns null (and logs a warning) when the pattern is invalid.
* Uses RE2, which is inherently immune to ReDoS backtracking attacks.
*/
function safeRegExp(pattern: string, logger: any): RE2 | null {
const MAX_PATTERN_LENGTH = 1024;
if (pattern.length > MAX_PATTERN_LENGTH) {
logger.warn(`Regex pattern exceeds maximum length of ${MAX_PATTERN_LENGTH} characters`);
return null;
}
try {
return new RE2(pattern);
} catch (e: any) {
logger.warn(`Invalid regex pattern "${pattern}": ${e.message}`);
return null;
}
}
// The delay before starting the watcher when the app is started
const START_WATCHER_DELAY_MS = 1000;
// Debounce delay used when performing a watch after a docker event has been received
const DEBOUNCED_WATCH_CRON_MS = 5000;
const MAINTENANCE_WINDOW_QUEUE_POLL_MS = 60 * 1000;
const SWARM_SERVICE_ID_LABEL = 'com.docker.swarm.service.id';
const COMPOSE_PROJECT_CONFIG_FILES_LABEL = 'com.docker.compose.project.config_files';
const COMPOSE_PROJECT_WORKING_DIR_LABEL = 'com.docker.compose.project.working_dir';
const OIDC_ACCESS_TOKEN_REFRESH_WINDOW_MS = 30 * 1000;
const OIDC_DEFAULT_ACCESS_TOKEN_TTL_MS = 5 * 60 * 1000;
const OIDC_DEFAULT_TIMEOUT_MS = 5000;
const OIDC_TOKEN_ENDPOINT_PATHS = [
'tokenurl',
'tokenendpoint',
'token_url',
'token_endpoint',
'token.url',
'token.endpoint',
];
const OIDC_CLIENT_ID_PATHS = ['clientid', 'client_id', 'client.id'];
const OIDC_CLIENT_SECRET_PATHS = ['clientsecret', 'client_secret', 'client.secret'];
const OIDC_SCOPE_PATHS = ['scope'];
const OIDC_RESOURCE_PATHS = ['resource'];
const OIDC_AUDIENCE_PATHS = ['audience'];
const OIDC_GRANT_TYPE_PATHS = ['granttype', 'grant_type'];
const OIDC_ACCESS_TOKEN_PATHS = ['accesstoken', 'access_token'];
const OIDC_REFRESH_TOKEN_PATHS = ['refreshtoken', 'refresh_token'];
const OIDC_EXPIRES_IN_PATHS = ['expiresin', 'expires_in'];
const OIDC_TIMEOUT_PATHS = ['timeout'];
const OIDC_DEVICE_URL_PATHS = [
'deviceurl',
'deviceendpoint',
'device_url',
'device_endpoint',
'device.url',
'device.endpoint',
'device_authorization_endpoint',
];
const OIDC_DEVICE_POLL_INTERVAL_MS = 5000;
const OIDC_DEVICE_POLL_TIMEOUT_MS = 5 * 60 * 1000;
function appendTriggerId(triggerInclude: string | undefined, triggerId: string | undefined): string | undefined {
if (!triggerId) {
return triggerInclude;
}
const triggersIncluded = triggerInclude ? triggerInclude.split(/\s*,\s*/) : [];
if (triggersIncluded.includes(triggerId)) {
return triggerInclude;
}
if (!triggerInclude) {
return triggerId;
}
return `${triggerInclude},${triggerId}`;
}
function removeTriggerId(triggerInclude: string | undefined, triggerId: string | undefined) {
if (!triggerInclude || !triggerId) {
return triggerInclude;
}
const triggersIncluded = triggerInclude
.split(/\s*,\s*/)
.map((trigger) => trigger.trim())
.filter((trigger) => trigger !== '' && trigger !== triggerId);
return triggersIncluded.length > 0 ? triggersIncluded.join(',') : undefined;
}
function normalizeComposeDefaultValue(value: string | boolean | undefined) {
if (value === undefined) {
return undefined;
}
return `${value}`;
}
function getDockercomposeTriggerConfigurationFromLabels(
labels: Record<string, string>,
composeDefaults: DockerWatcherConfiguration['compose'] = {},
) {
const dockercomposeConfig: Record<string, string> = {};
const backup =
getLabel(labels, ddComposeBackup, wudComposeBackup) ||
normalizeComposeDefaultValue(composeDefaults.backup);
if (backup !== undefined) {
dockercomposeConfig.backup = backup;
}
const prune =
getLabel(labels, ddComposePrune, wudComposePrune) ||
normalizeComposeDefaultValue(composeDefaults.prune);
if (prune !== undefined) {
dockercomposeConfig.prune = prune;
}
const dryrun =
getLabel(labels, ddComposeDryrun, wudComposeDryrun) ||
normalizeComposeDefaultValue(composeDefaults.dryrun);
if (dryrun !== undefined) {
dockercomposeConfig.dryrun = dryrun;
}
const auto =
getLabel(labels, ddComposeAuto, wudComposeAuto) ||
normalizeComposeDefaultValue(composeDefaults.auto);
if (auto !== undefined) {
dockercomposeConfig.auto = auto;
}
const once =
getLabel(labels, ddComposeOnce, wudComposeOnce) ||
normalizeComposeDefaultValue(composeDefaults.once);
if (once !== undefined) {
dockercomposeConfig.once = once;
}
const digestpin =
getLabel(labels, ddComposeDigestpin, wudComposeDigestpin) ||
normalizeComposeDefaultValue(composeDefaults.digestpin);
if (digestpin !== undefined) {
dockercomposeConfig.digestpin = digestpin;
}
const threshold =
getLabel(labels, ddComposeThreshold, wudComposeThreshold) ||
normalizeConfigStringValue(composeDefaults.threshold);
if (threshold !== undefined) {
dockercomposeConfig.threshold = threshold;
}
return dockercomposeConfig;
}
function isAutoComposeEnabled(
labels: Record<string, string>,
composeNativeEnabledByWatcher: boolean,
): boolean {
const autoComposeLabelValue = getLabel(labels, ddComposeNative, wudComposeNative);
if (autoComposeLabelValue !== undefined) {
const normalizedAutoComposeLabelValue = autoComposeLabelValue.trim();
if (normalizedAutoComposeLabelValue !== '') {
return normalizedAutoComposeLabelValue.toLowerCase() === 'true';
}
}
return composeNativeEnabledByWatcher;
}
function getComposeNativeFilePathFromLabels(labels: Record<string, string>) {
const composeConfigFiles = labels[COMPOSE_PROJECT_CONFIG_FILES_LABEL];
if (!composeConfigFiles || composeConfigFiles.trim() === '') {
return undefined;
}
const composeProjectWorkingDir = labels[COMPOSE_PROJECT_WORKING_DIR_LABEL];
const configFiles = composeConfigFiles
.split(',')
.map((configFile) => configFile.trim())
.filter((configFile) => configFile !== '');
// Only the first entry is used if multiple config files are present ("first file wins").
const configFile = configFiles[0];
if (!configFile) {
return undefined;
}
if (path.isAbsolute(configFile)) {
return configFile;
}
const trimmedWorkingDir = composeProjectWorkingDir?.trim();
if (trimmedWorkingDir) {
return path.join(trimmedWorkingDir, configFile);
}
return configFile;
}
function getComposeFilePathFromLabels(
labels: Record<string, string>,
composeNativeEnabledByWatcher: boolean,
) {
const composeFilePathFromLabel = getLabel(labels, ddComposeFile, wudComposeFile);
if (composeFilePathFromLabel) {
return composeFilePathFromLabel;
}
if (!isAutoComposeEnabled(labels, composeNativeEnabledByWatcher)) {
return undefined;
}
return getComposeNativeFilePathFromLabels(labels);
}
interface ResolvedImgset {
name: string;
includeTags?: string;
excludeTags?: string;
transformTags?: string;
linkTemplate?: string;
displayName?: string;
displayIcon?: string;
triggerInclude?: string;
triggerExclude?: string;
registryLookupImage?: string;
registryLookupUrl?: string;
watchDigest?: string;
inspectTagPath?: string;
}
interface ContainerLabelOverrides {
includeTags?: string;
excludeTags?: string;
transformTags?: string;
linkTemplate?: string;
displayName?: string;
displayIcon?: string;
triggerInclude?: string;
triggerExclude?: string;
registryLookupImage?: string;
registryLookupUrl?: string;
}
type ContainerLabelOverrideKey = Exclude<
keyof ContainerLabelOverrides,
'registryLookupImage' | 'registryLookupUrl'
>;
interface ResolvedContainerLabelOverrides {
includeTags?: string;
excludeTags?: string;
transformTags?: string;
linkTemplate?: string;
displayName?: string;
displayIcon?: string;
triggerInclude?: string;
triggerExclude?: string;
lookupImage?: string;
}
const containerLabelOverrideMappings = [
{ key: 'includeTags', ddKey: ddTagInclude, wudKey: wudTagInclude },
{ key: 'excludeTags', ddKey: ddTagExclude, wudKey: wudTagExclude },
{ key: 'transformTags', ddKey: ddTagTransform, wudKey: wudTagTransform },
{ key: 'linkTemplate', ddKey: ddLinkTemplate, wudKey: wudLinkTemplate },
{ key: 'displayName', ddKey: ddDisplayName, wudKey: wudDisplayName },
{ key: 'displayIcon', ddKey: ddDisplayIcon, wudKey: wudDisplayIcon },
{ key: 'triggerInclude', ddKey: ddTriggerInclude, wudKey: wudTriggerInclude },
{ key: 'triggerExclude', ddKey: ddTriggerExclude, wudKey: wudTriggerExclude },
] as const satisfies ReadonlyArray<{
key: ContainerLabelOverrideKey;
ddKey: string;
wudKey: string;
}>;
interface DeviceCodeFlowOptions {
tokenEndpoint: string;
clientId?: string;
clientSecret?: string;
scope?: string;
audience?: string;
resource?: string;
timeout?: number;
}
interface OidcRequestParameters {
clientId?: string;
clientSecret?: string;
scope?: string;
audience?: string;
resource?: string;
}
interface DeviceCodeTokenPollOptions {
tokenEndpoint: string;
deviceCode: string;
clientId?: string;
clientSecret?: string;
timeout?: number;
pollIntervalMs: number;
pollTimeoutMs: number;
}
interface ImgsetMatchCandidate {
specificity: number;
imgset: ResolvedImgset;
}
/**
* Return all supported registries
* @returns {*}
*/
function getRegistries() {
return registry.getState().registry;
}
/**
* Apply include/exclude regex filters to tags.
* Returns the filtered tags and whether include-filter recovery mode is active.
*/
function applyIncludeExcludeFilters(
container: Container,
tags: string[],
logContainer: any,
): { filteredTags: string[]; allowIncludeFilterRecovery: boolean } {
let filteredTags = tags;
let allowIncludeFilterRecovery = false;
if (container.includeTags) {
const includeTagsRegex = safeRegExp(container.includeTags, logContainer);
if (includeTagsRegex) {
filteredTags = filteredTags.filter((tag) => includeTagsRegex.test(tag));
if (container.image.tag.semver && !includeTagsRegex.test(container.image.tag.value)) {
logContainer.warn(
`Current tag "${container.image.tag.value}" does not match includeTags regex "${container.includeTags}". Trying best-effort semver upgrade within filtered tags.`,
);
allowIncludeFilterRecovery = true;
}
}
} else {
filteredTags = filteredTags.filter((tag) => !tag.startsWith('sha'));
}
if (container.excludeTags) {
const excludeTagsRegex = safeRegExp(container.excludeTags, logContainer);
if (excludeTagsRegex) {
filteredTags = filteredTags.filter((tag) => !excludeTagsRegex.test(tag));
}
}
filteredTags = filteredTags.filter((tag) => !tag.endsWith('.sig'));
return { filteredTags, allowIncludeFilterRecovery };
}
/**
* Filter tags by prefix to match the current tag's prefix convention.
*/
function isDigitCode(charCode: number | undefined): boolean {
return charCode !== undefined && charCode >= 48 && charCode <= 57;
}
function getFirstDigitIndex(value: string): number {
for (let i = 0; i < value.length; i += 1) {
if (isDigitCode(value.codePointAt(i))) {
return i;
}
}
return -1;
}
function getCurrentPrefix(value: string): string {
const firstDigitIndex = getFirstDigitIndex(value);
return firstDigitIndex >= 0 ? value.slice(0, firstDigitIndex) : '';
}
function startsWithDigit(value: string): boolean {
return isDigitCode(value.codePointAt(0));
}
function getPrefixFilterWarning(currentPrefix: string): string {
if (currentPrefix) {
return `No tags found with existing prefix: '${currentPrefix}'; check your regex filters`;
}
return 'No tags found starting with a number (no prefix); check your regex filters';
}
function filterByCurrentPrefix(tags: string[], container: Container, logContainer: any): string[] {
const currentTag = container.image.tag.value;
const currentPrefix = getCurrentPrefix(currentTag);
const filtered = tags.filter((tag) =>
currentPrefix ? tag.startsWith(currentPrefix) : startsWithDigit(tag),
);
if (filtered.length === 0) {
logContainer.warn(getPrefixFilterWarning(currentPrefix));
}
return filtered;
}
/**
* Filter tags to only those with the same number of numeric segments as the current tag.
*/
function filterBySegmentCount(tags: string[], container: Container): string[] {
const numericPart = /(\d+(\.\d+)*)/.exec(
transformTag(container.transformTags, container.image.tag.value),
);
if (!numericPart) {
return tags;
}
const referenceGroups = numericPart[0].split('.').length;
return tags.filter((tag) => {
const tagNumericPart = /(\d+(\.\d+)*)/.exec(transformTag(container.transformTags, tag));
if (!tagNumericPart) return false;
return tagNumericPart[0].split('.').length === referenceGroups;
});
}
/**
* Sort tags by semver in descending order (mutates the array).
*/
function sortSemverDescending(tags: string[], transformTags: string | undefined): void {
tags.sort((t1, t2) => {
const greater = isGreaterSemver(
transformTag(transformTags, t2),
transformTag(transformTags, t1),
);
return greater ? 1 : -1;
});
}
/**
* Keep only tags that are valid semver.
*/
function filterSemverOnly(tags: string[], transformTags: string | undefined): string[] {
return tags.filter((tag) => parseSemver(transformTag(transformTags, tag)) !== null);
}
/**
* Filter candidate tags (based on tag name).
* @param container
* @param tags
* @returns {*}
*/
function getTagCandidates(container: Container, tags: string[], logContainer: any) {
const { filteredTags: baseTags, allowIncludeFilterRecovery } = applyIncludeExcludeFilters(
container,
tags,
logContainer,
);
if (!container.image.tag.semver && !container.includeTags) {
return [];
}
if (!container.image.tag.semver) {
// Non-semver tag with includeTags filter: advise best semver tag
logContainer.warn(
`Current tag "${container.image.tag.value}" is not semver but includeTags filter "${container.includeTags}" is set. Advising best semver tag from filtered candidates.`,
);
const semverTags = filterSemverOnly(baseTags, container.transformTags);
sortSemverDescending(semverTags, container.transformTags);
return semverTags;
}
// Semver image -> find higher semver tag
let filteredTags = baseTags;
if (filteredTags.length === 0) {
logContainer.warn('No tags found after filtering; check you regex filters');
}
if (!container.includeTags) {
filteredTags = filterByCurrentPrefix(filteredTags, container, logContainer);
}
filteredTags = filterSemverOnly(filteredTags, container.transformTags);
filteredTags = filterBySegmentCount(filteredTags, container);
if (!allowIncludeFilterRecovery) {
filteredTags = filteredTags.filter((tag) =>
isGreaterSemver(
transformTag(container.transformTags, tag),
transformTag(container.transformTags, container.image.tag.value),
),
);
}
sortSemverDescending(filteredTags, container.transformTags);
return filteredTags;
}
function normalizeContainer(container: Container) {
const containerWithNormalizedImage = container;
const imageForMatching = getImageForRegistryLookup(container.image);
const registryProvider = Object.values(getRegistries()).find((provider) =>
provider.match(imageForMatching),
);
if (registryProvider) {
containerWithNormalizedImage.image = registryProvider.normalizeImage(imageForMatching);
containerWithNormalizedImage.image.registry.name = registryProvider.getId();
} else {
log.warn(`${fullName(container)} - No Registry Provider found`);
containerWithNormalizedImage.image.registry.name = 'unknown';
}
return validateContainer(containerWithNormalizedImage);
}
/**
* Build an image candidate used for registry matching and tag lookups.
* The lookup value can be:
* - an image reference (preferred): ghcr.io/user/image or library/nginx
* - a legacy registry url: https://registry-1.docker.io
*/
function getImageForRegistryLookup(image: ContainerImage) {
const lookupImage = image.registry.lookupImage || image.registry.lookupUrl || '';
const lookupImageTrimmed = lookupImage.trim();
if (lookupImageTrimmed === '') {
return image;
}
// Legacy fallback: support plain registry URL values from older experiments.
if (/^https?:\/\//i.test(lookupImageTrimmed)) {
try {
const lookupUrl = new URL(lookupImageTrimmed).hostname;
return {
...image,
registry: {
...image.registry,
url: lookupUrl,
},
};
} catch (e) {
log.debug(`Invalid registry lookup URL "${lookupImageTrimmed}" - using image defaults`);
return image;
}
}
const parsedLookupImage = parse(lookupImageTrimmed);
const parsedPath = parsedLookupImage.path;
const parsedDomain = parsedLookupImage.domain;
// If only a registry hostname was provided, keep the original image name.
if (parsedPath && !parsedDomain && !lookupImageTrimmed.includes('/')) {
return {
...image,
registry: {
...image.registry,
url: parsedPath,
},
};
}
if (!parsedPath) {
return image;
}
return {
...image,
registry: {
...image.registry,
url: parsedDomain || 'registry-1.docker.io',
},
name: parsedPath,
};
}
/**
* Get the Docker Registry by name.
* @param registryName
*/
function getRegistry(registryName: string) {
const registryToReturn = getRegistries()[registryName];
if (!registryToReturn) {
throw new Error(`Unsupported Registry ${registryName}`);
}
return registryToReturn;
}
/**
* Get old containers to prune.
* @param newContainers
* @param containersFromTheStore
* @returns {*[]|*}
*/
function getOldContainers(newContainers: Container[], containersFromTheStore: Container[]) {
if (!containersFromTheStore || !newContainers) {
return [];
}
return containersFromTheStore.filter((containerFromStore) => {
return !newContainers.some((newContainer) => newContainer.id === containerFromStore.id);
});
}
/**
* Prune old containers from the store.
* Containers that still exist in Docker (e.g. stopped) get their status updated
* instead of being removed, so the UI can still show them with a start button.
* @param newContainers
* @param containersFromTheStore
* @param dockerApi
*/
async function pruneOldContainers(
newContainers: Container[],
containersFromTheStore: Container[],
dockerApi: any,
) {
const containersToRemove = getOldContainers(newContainers, containersFromTheStore);
for (const containerToRemove of containersToRemove) {
try {
const inspectResult = await dockerApi.getContainer(containerToRemove.id).inspect();
const newStatus = inspectResult?.State?.Status;
if (newStatus) {
storeContainer.updateContainer({ ...containerToRemove, status: newStatus });
}
} catch {
// Container no longer exists in Docker — remove from store
storeContainer.deleteContainer(containerToRemove.id);
}
}
}
function getContainerName(container: any) {
let containerName = '';
const names = container.Names;
if (names && names.length > 0) {
[containerName] = names;
}
// Strip ugly forward slash
containerName = containerName.replace(/\//, '');
return containerName;
}
function getContainerDisplayName(
containerName: string,
parsedImagePath: string,
displayName?: string,
) {
if (displayName && displayName.trim() !== '') {
return displayName;
}
const normalizedImagePath = (parsedImagePath || '').toLowerCase();
if (normalizedImagePath === 'drydock' || normalizedImagePath.endsWith('/drydock')) {
return 'drydock';
}
return containerName;
}
function normalizeConfigStringValue(value: any) {
if (typeof value !== 'string') {
return undefined;
}
const valueTrimmed = value.trim();
return valueTrimmed === '' ? undefined : valueTrimmed;
}
function getNestedValue(value: any, path: string) {
return path
.split('.')
.filter((item) => item !== '')
.reduce((nestedValue, item) => {
if (nestedValue === undefined || nestedValue === null || typeof nestedValue !== 'object') {
return undefined;
}
return nestedValue[item];
}, value);
}
function getFirstConfigString(value: any, paths: string[]) {
for (const path of paths) {
const pathValue = normalizeConfigStringValue(getNestedValue(value, path));
if (pathValue !== undefined) {
return pathValue;
}
}
return undefined;
}
function getImageReferenceCandidates(path: string, domain?: string) {
const pathNormalized = normalizeConfigStringValue(path)?.toLowerCase();
if (!pathNormalized) {
return [];
}
const domainNormalized = normalizeConfigStringValue(domain)?.toLowerCase();
const pathWithoutLibraryPrefix = pathNormalized.startsWith('library/')
? pathNormalized.substring('library/'.length)
: pathNormalized;
const candidates = new Set<string>([
pathNormalized,
pathWithoutLibraryPrefix,
`docker.io/${pathNormalized}`,
`docker.io/${pathWithoutLibraryPrefix}`,
`registry-1.docker.io/${pathNormalized}`,
`registry-1.docker.io/${pathWithoutLibraryPrefix}`,
]);
if (domainNormalized) {
candidates.add(`${domainNormalized}/${pathNormalized}`);
candidates.add(`${domainNormalized}/${pathWithoutLibraryPrefix}`);
}
return Array.from(candidates).filter((candidate) => candidate !== '');
}
function getImageReferenceCandidatesFromPattern(pattern: string) {
const patternNormalized = normalizeConfigStringValue(pattern);
if (!patternNormalized) {
return [];
}
try {
const parsedPattern = parse(patternNormalized.toLowerCase());
if (!parsedPattern.path) {
return [patternNormalized.toLowerCase()];
}
return getImageReferenceCandidates(parsedPattern.path, parsedPattern.domain);
} catch (e) {
log.debug(`Invalid imgset image pattern "${patternNormalized}" - using normalized value`);
return [patternNormalized.toLowerCase()];
}
}
function getImageReferenceCandidatesFromParsedImage(parsedImage: any) {
return getImageReferenceCandidates(parsedImage?.path, parsedImage?.domain);
}
function getImgsetSpecificity(imagePattern: string, parsedImage: any) {
const patternCandidates = getImageReferenceCandidatesFromPattern(imagePattern);
if (patternCandidates.length === 0) {
return -1;
}
const imageCandidates = getImageReferenceCandidatesFromParsedImage(parsedImage);
if (imageCandidates.length === 0) {
return -1;
}
const hasMatch = patternCandidates.some((patternCandidate) =>
imageCandidates.includes(patternCandidate),
);
if (!hasMatch) {
return -1;
}
return patternCandidates.reduce(
(maxSpecificity, patternCandidate) => Math.max(maxSpecificity, patternCandidate.length),
0,
);
}
function getResolvedImgsetConfiguration(name: string, imgsetConfiguration: any) {
return {
name,
includeTags: getFirstConfigString(imgsetConfiguration, [
'tag.include',
'includeTags',
'include',
]),
excludeTags: getFirstConfigString(imgsetConfiguration, [
'tag.exclude',
'excludeTags',
'exclude',
]),
transformTags: getFirstConfigString(imgsetConfiguration, [
'tag.transform',
'transformTags',
'transform',
]),
linkTemplate: getFirstConfigString(imgsetConfiguration, ['link.template', 'linkTemplate']),
displayName: getFirstConfigString(imgsetConfiguration, ['display.name', 'displayName']),
displayIcon: getFirstConfigString(imgsetConfiguration, ['display.icon', 'displayIcon']),
triggerInclude: getFirstConfigString(imgsetConfiguration, [
'trigger.include',
'triggerInclude',
]),
triggerExclude: getFirstConfigString(imgsetConfiguration, [
'trigger.exclude',
'triggerExclude',
]),
registryLookupImage: getFirstConfigString(imgsetConfiguration, [
'registry.lookup.image',
'registryLookupImage',
'lookupImage',
]),
registryLookupUrl: getFirstConfigString(imgsetConfiguration, [
'registry.lookup.url',
'registryLookupUrl',
'lookupUrl',
]),
watchDigest: getFirstConfigString(imgsetConfiguration, ['watch.digest', 'watchDigest']),
inspectTagPath: getFirstConfigString(imgsetConfiguration, [
'inspect.tag.path',
'inspectTagPath',
]),
} as ResolvedImgset;
}
function getContainerConfigValue(labelValue: string | undefined, imgsetValue: string | undefined) {
return normalizeConfigStringValue(labelValue) || normalizeConfigStringValue(imgsetValue);
}
function normalizeConfigNumberValue(value: any) {
if (typeof value === 'number' && Number.isFinite(value)) {
return value;
}
if (typeof value === 'string' && value.trim() !== '') {
const parsedNumber = Number(value);
if (Number.isFinite(parsedNumber)) {
return parsedNumber;
}
}
return undefined;
}
function getFirstConfigNumber(value: any, paths: string[]) {
for (const path of paths) {
const pathValue = normalizeConfigNumberValue(getNestedValue(value, path));
if (pathValue !== undefined) {
return pathValue;
}
}
return undefined;
}
/**
* Get image repo digest.
* @param containerImage
* @returns {*} digest
*/
function getRepoDigest(containerImage: any) {
if (!containerImage.RepoDigests || containerImage.RepoDigests.length === 0) {
return undefined;
}
const fullDigest = containerImage.RepoDigests[0];
const digestSplit = fullDigest.split('@');
return digestSplit[1];
}
/**
* Resolve a value in a Docker inspect payload from a slash-separated path.
* Example: Config/Labels/org.opencontainers.image.version
*/
function getInspectValueByPath(containerInspect: any, path: string) {
if (!path) {
return undefined;
}
const pathSegments = path.split('/').filter((segment) => segment !== '');
return pathSegments.reduce((value, key) => {
if (value === undefined || value === null) {
return undefined;
}
return value[key];
}, containerInspect);
}
/**
* Try to derive a semver tag from a Docker inspect path.
*/
function getSemverTagFromInspectPath(
containerInspect: any,
inspectPath: string,
transformTags: string,
) {
const inspectValue = getInspectValueByPath(containerInspect, inspectPath);
if (inspectValue === undefined || inspectValue === null) {
return undefined;
}
const tagValue = `${inspectValue}`.trim();
if (tagValue === '') {
return undefined;
}
const parsedTag = parseSemver(transformTag(transformTags, tagValue));
return parsedTag?.version;
}
/**