forked from oras-project/oras-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegistry.java
More file actions
1199 lines (1061 loc) · 47.6 KB
/
Copy pathRegistry.java
File metadata and controls
1199 lines (1061 loc) · 47.6 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
/*-
* =LICENSE=
* ORAS Java SDK
* ===
* Copyright (C) 2024 - 2025 ORAS
* ===
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =LICENSEEND=
*/
package land.oras;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import land.oras.auth.AuthProvider;
import land.oras.auth.AuthStoreAuthenticationProvider;
import land.oras.auth.BearerTokenProvider;
import land.oras.auth.NoAuthProvider;
import land.oras.auth.UsernamePasswordProvider;
import land.oras.exception.OrasException;
import land.oras.utils.ArchiveUtils;
import land.oras.utils.Const;
import land.oras.utils.JsonUtils;
import land.oras.utils.OrasHttpClient;
import land.oras.utils.SupportedAlgorithm;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/**
* A registry is the main entry point for interacting with a container registry
*/
@NullMarked
public final class Registry extends OCI<ContainerRef> {
/**
* The chunk size for uploading blobs (5MB)
* This is a standard chunk size commonly used in cloud storage systems to balance
* network performance with memory usage. The actual chunk size used may be larger
* if the registry specifies a minimum chunk size via the OCI-Chunk-Min-Length header.
*/
private static final int CHUNK_SIZE = 5 * 1024 * 1024;
/**
* The digest calculation limit (16MB)
* For files smaller than this size, we compute the digest before starting the upload
* to check if the blob already exists in the registry, potentially avoiding unnecessary uploads.
*/
private static final int DIGEST_CALCULATION_LIMIT = 16 * 1024 * 1024;
/**
* The HTTP client
*/
private OrasHttpClient client;
/**
* The auth provider
*/
private AuthProvider authProvider;
/**
* Insecure. Use HTTP instead of HTTPS
*/
private boolean insecure;
/**
* Skip TLS verification
*/
private boolean skipTlsVerify;
/**
* Constructor
*/
private Registry() {
this.authProvider = new NoAuthProvider();
this.client = OrasHttpClient.Builder.builder().build();
}
/**
* Return this registry with insecure flag
* @param insecure Insecure
*/
private void setInsecure(boolean insecure) {
this.insecure = insecure;
}
/**
* Return this registry with skip TLS verification
* @param skipTlsVerify Skip TLS verification
*/
private void setSkipTlsVerify(boolean skipTlsVerify) {
this.skipTlsVerify = skipTlsVerify;
}
/**
* Return this registry with auth provider
* @param authProvider The auth provider
*/
private void setAuthProvider(AuthProvider authProvider) {
this.authProvider = authProvider;
client.updateAuthentication(authProvider);
}
/**
* Build the provider
* @return The provider
*/
private Registry build() {
client = OrasHttpClient.Builder.builder()
.withAuthentication(authProvider)
.withSkipTlsVerify(skipTlsVerify)
.build();
return this;
}
/**
* Get the HTTP scheme depending on the insecure flag
* @return The scheme
*/
public String getScheme() {
return insecure ? "http" : "https";
}
/**
* Get the tags of a container
* @param containerRef The container
* @return The tags
*/
public List<String> getTags(ContainerRef containerRef) {
URI uri = URI.create("%s://%s".formatted(getScheme(), containerRef.getTagsPath()));
OrasHttpClient.ResponseWrapper<String> response =
client.get(uri, Map.of(Const.ACCEPT_HEADER, Const.DEFAULT_JSON_MEDIA_TYPE));
if (switchTokenAuth(containerRef, response)) {
response = client.get(uri, Map.of(Const.ACCEPT_HEADER, Const.DEFAULT_JSON_MEDIA_TYPE));
}
handleError(response);
return JsonUtils.fromJson(response.response(), Tags.class).tags();
}
/**
* Get the referrers of a container
* @param containerRef The container
* @param artifactType The optional artifact type
* @return The referrers
*/
public Referrers getReferrers(ContainerRef containerRef, @Nullable ArtifactType artifactType) {
if (containerRef.getDigest() == null) {
throw new OrasException("Digest is required to get referrers");
}
URI uri = URI.create("%s://%s".formatted(getScheme(), containerRef.getReferrersPath(artifactType)));
OrasHttpClient.ResponseWrapper<String> response =
client.get(uri, Map.of(Const.ACCEPT_HEADER, Const.DEFAULT_INDEX_MEDIA_TYPE));
if (switchTokenAuth(containerRef, response)) {
response = client.get(uri, Map.of(Const.ACCEPT_HEADER, Const.DEFAULT_INDEX_MEDIA_TYPE));
}
handleError(response);
return JsonUtils.fromJson(response.response(), Referrers.class);
}
/**
* Delete a manifest
* @param containerRef The artifact
*/
public void deleteManifest(ContainerRef containerRef) {
URI uri = URI.create("%s://%s".formatted(getScheme(), containerRef.getManifestsPath()));
OrasHttpClient.ResponseWrapper<String> response = client.delete(uri, Map.of());
logResponse(response);
if (switchTokenAuth(containerRef, response)) {
response = client.delete(uri, Map.of());
logResponse(response);
}
handleError(response);
}
@Override
public Manifest pushManifest(ContainerRef containerRef, Manifest manifest) {
Map<String, String> annotations = manifest.getAnnotations();
if (!annotations.containsKey(Const.ANNOTATION_CREATED) && containerRef.getDigest() == null) {
Map<String, String> manifestAnnotations = new HashMap<>(annotations);
manifestAnnotations.put(Const.ANNOTATION_CREATED, Const.currentTimestamp());
manifest = manifest.withAnnotations(manifestAnnotations);
}
URI uri = URI.create("%s://%s".formatted(getScheme(), containerRef.getManifestsPath()));
byte[] manifestData = manifest.getJson() != null
? manifest.getJson().getBytes()
: manifest.toJson().getBytes();
OrasHttpClient.ResponseWrapper<String> response =
client.put(uri, manifestData, Map.of(Const.CONTENT_TYPE_HEADER, Const.DEFAULT_MANIFEST_MEDIA_TYPE));
if (switchTokenAuth(containerRef, response)) {
response =
client.put(uri, manifestData, Map.of(Const.CONTENT_TYPE_HEADER, Const.DEFAULT_MANIFEST_MEDIA_TYPE));
}
logResponse(response);
handleError(response);
if (manifest.getSubject() != null) {
// https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pushing-manifests-with-subject
if (!response.headers().containsKey(Const.OCI_SUBJECT_HEADER.toLowerCase())) {
throw new OrasException(
"Subject was set on manifest but not OCI subject header was returned. Legecy flow not implemented");
}
}
return getManifest(containerRef);
}
/**
* Push a manifest
* @param containerRef The container
* @param index The index
* @return The location
*/
public Index pushIndex(ContainerRef containerRef, Index index) {
URI uri = URI.create("%s://%s".formatted(getScheme(), containerRef.getManifestsPath()));
OrasHttpClient.ResponseWrapper<String> response = client.put(
uri,
JsonUtils.toJson(index).getBytes(),
Map.of(Const.CONTENT_TYPE_HEADER, Const.DEFAULT_INDEX_MEDIA_TYPE));
if (switchTokenAuth(containerRef, response)) {
response = client.put(
uri,
JsonUtils.toJson(index).getBytes(),
Map.of(Const.CONTENT_TYPE_HEADER, Const.DEFAULT_INDEX_MEDIA_TYPE));
}
logResponse(response);
handleError(response);
return getIndex(containerRef);
}
/**
* Delete a blob
* @param containerRef The container
*/
public void deleteBlob(ContainerRef containerRef) {
URI uri = URI.create("%s://%s".formatted(getScheme(), containerRef.getBlobsPath()));
OrasHttpClient.ResponseWrapper<String> response = client.delete(uri, Map.of());
logResponse(response);
// Switch to bearer auth if needed and retry first request
if (switchTokenAuth(containerRef, response)) {
response = client.delete(uri, Map.of());
logResponse(response);
}
handleError(response);
}
@Override
public void pullArtifact(ContainerRef containerRef, Path path, boolean overwrite) {
// Only collect layer that are files
String contentType = getContentType(containerRef);
List<Layer> layers = collectLayers(containerRef, contentType, false);
if (layers.isEmpty()) {
LOG.info("Skipped pulling layers without file name in '{}'", Const.ANNOTATION_TITLE);
return;
}
for (Layer layer : layers) {
try (InputStream is = fetchBlob(containerRef.withDigest(layer.getDigest()))) {
// Unpack or just copy blob
if (Boolean.parseBoolean(layer.getAnnotations().getOrDefault(Const.ANNOTATION_ORAS_UNPACK, "false"))) {
LOG.debug("Extracting blob to: {}", path);
// Uncompress the tar.gz archive and verify digest if present
LocalPath tempArchive = ArchiveUtils.uncompress(is, layer.getMediaType());
String expectedDigest = layer.getAnnotations().get(Const.ANNOTATION_ORAS_CONTENT_DIGEST);
if (expectedDigest != null) {
LOG.trace("Expected digest: {}", expectedDigest);
String actualDigest = containerRef.getAlgorithm().digest(tempArchive.getPath());
LOG.trace("Actual digest: {}", actualDigest);
if (!expectedDigest.equals(actualDigest)) {
throw new OrasException(
"Digest mismatch: expected %s but got %s".formatted(expectedDigest, actualDigest));
}
}
// Extract the tar
ArchiveUtils.untar(Files.newInputStream(tempArchive.getPath()), path);
} else {
Path targetPath = path.resolve(
layer.getAnnotations().getOrDefault(Const.ANNOTATION_TITLE, layer.getDigest()));
LOG.debug("Copying blob to: {}", targetPath);
Files.copy(
is,
targetPath,
overwrite ? StandardCopyOption.REPLACE_EXISTING : StandardCopyOption.ATOMIC_MOVE);
}
} catch (IOException e) {
throw new OrasException("Failed to pull artifact", e);
}
}
}
@Override
public Manifest pushArtifact(
ContainerRef containerRef,
ArtifactType artifactType,
Annotations annotations,
@Nullable Config config,
LocalPath... paths) {
Manifest manifest = Manifest.empty().withArtifactType(artifactType);
Map<String, String> manifestAnnotations = new HashMap<>(annotations.manifestAnnotations());
if (!manifestAnnotations.containsKey(Const.ANNOTATION_CREATED) && containerRef.getDigest() == null) {
manifestAnnotations.put(Const.ANNOTATION_CREATED, Const.currentTimestamp());
}
manifest = manifest.withAnnotations(manifestAnnotations);
if (config != null) {
config = config.withAnnotations(annotations);
manifest = manifest.withConfig(config);
}
// Push layers
List<Layer> layers = pushLayers(containerRef, false, paths);
// Push the config like any other blob
Config pushedConfig = pushConfig(containerRef, config != null ? config : Config.empty());
// Add layer and config
manifest = manifest.withLayers(layers).withConfig(pushedConfig);
// Push the manifest
manifest = pushManifest(containerRef, manifest);
LOG.debug(
"Manifest pushed to: {}",
containerRef.withDigest(manifest.getDescriptor().getDigest()));
return manifest;
}
/**
* Copy an artifact from one container to another
* @param targetRegistry The target registry
* @param sourceContainer The source container
* @param targetContainer The target container
*/
public void copy(Registry targetRegistry, ContainerRef sourceContainer, ContainerRef targetContainer) {
throw new OrasException("Not implemented");
}
/**
* Attach file to an existing manifest
* @param containerRef The container
* @param artifactType The artifact type
* @param paths The paths
* @return The manifest of the new artifact
*/
public Manifest attachArtifact(ContainerRef containerRef, ArtifactType artifactType, LocalPath... paths) {
return attachArtifact(containerRef, artifactType, Annotations.empty(), paths);
}
/**
* Attach file to an existing manifest
* @param containerRef The container
* @param artifactType The artifact type
* @param annotations The annotations
* @param paths The paths
* @return The manifest of the new artifact
*/
public Manifest attachArtifact(
ContainerRef containerRef, ArtifactType artifactType, Annotations annotations, LocalPath... paths) {
// Push layers
List<Layer> layers = pushLayers(containerRef, false, paths);
// Get the subject from the manifest
Subject subject = getManifest(containerRef).getDescriptor().toSubject();
// Add created annotation if not present since we push with digest
Map<String, String> manifestAnnotations = annotations.manifestAnnotations();
if (!manifestAnnotations.containsKey(Const.ANNOTATION_CREATED)) {
manifestAnnotations.put(Const.ANNOTATION_CREATED, Const.currentTimestamp());
}
// assemble manifest
Manifest manifest = Manifest.empty()
.withArtifactType(artifactType)
.withAnnotations(manifestAnnotations)
.withLayers(layers)
.withSubject(subject);
return pushManifest(
containerRef.withDigest(
SupportedAlgorithm.SHA256.digest(manifest.toJson().getBytes(StandardCharsets.UTF_8))),
manifest);
}
@Override
public Layer pushBlob(ContainerRef containerRef, Path blob, Map<String, String> annotations) {
String digest = containerRef.getAlgorithm().digest(blob);
LOG.debug("Digest: {}", digest);
if (hasBlob(containerRef.withDigest(digest))) {
LOG.info("Blob already exists: {}", digest);
return Layer.fromFile(blob, containerRef.getAlgorithm()).withAnnotations(annotations);
}
URI uri = URI.create(
"%s://%s".formatted(getScheme(), containerRef.withDigest(digest).getBlobsUploadDigestPath()));
OrasHttpClient.ResponseWrapper<String> response = client.upload(
"POST", uri, Map.of(Const.CONTENT_TYPE_HEADER, Const.APPLICATION_OCTET_STREAM_HEADER_VALUE), blob);
logResponse(response);
// Switch to bearer auth if needed and retry first request
if (switchTokenAuth(containerRef, response)) {
response = client.upload(
"POST", uri, Map.of(Const.CONTENT_TYPE_HEADER, Const.APPLICATION_OCTET_STREAM_HEADER_VALUE), blob);
logResponse(response);
}
// Accepted single POST push
if (response.statusCode() == 201) {
return Layer.fromFile(blob, containerRef.getAlgorithm()).withAnnotations(annotations);
}
// We need to push via PUT
if (response.statusCode() == 202) {
String location = response.headers().get(Const.LOCATION_HEADER.toLowerCase());
// Ensure location is absolute URI
if (!location.startsWith("http") && !location.startsWith("https")) {
location = "%s://%s/%s"
.formatted(getScheme(), containerRef.getApiRegistry(), location.replaceFirst("^/", ""));
}
LOG.debug("Location header: {}", location);
response = client.upload(
"PUT",
URI.create("%s&digest=%s".formatted(location, digest)),
Map.of(Const.CONTENT_TYPE_HEADER, Const.APPLICATION_OCTET_STREAM_HEADER_VALUE),
blob);
if (response.statusCode() == 201) {
LOG.debug("Successful push: {}", response.response());
} else {
throw new OrasException("Failed to push layer: %s".formatted(response.response()));
}
}
handleError(response);
return Layer.fromFile(blob, containerRef.getAlgorithm()).withAnnotations(annotations);
}
@Override
public Layer pushBlob(ContainerRef containerRef, byte[] data) {
String digest = containerRef.getAlgorithm().digest(data);
if (containerRef.getDigest() != null) {
ensureDigest(containerRef, data);
}
if (hasBlob(containerRef.withDigest(digest))) {
LOG.info("Blob already exists: {}", digest);
return Layer.fromData(containerRef, data);
}
URI uri = URI.create(
"%s://%s".formatted(getScheme(), containerRef.withDigest(digest).getBlobsUploadDigestPath()));
OrasHttpClient.ResponseWrapper<String> response =
client.post(uri, data, Map.of(Const.CONTENT_TYPE_HEADER, Const.APPLICATION_OCTET_STREAM_HEADER_VALUE));
logResponse(response);
// Switch to bearer auth if needed and retry first request
if (switchTokenAuth(containerRef, response)) {
response = client.post(
uri, data, Map.of(Const.CONTENT_TYPE_HEADER, Const.APPLICATION_OCTET_STREAM_HEADER_VALUE));
logResponse(response);
}
// Accepted single POST push
if (response.statusCode() == 201) {
return Layer.fromData(containerRef, data);
}
// We need to push via PUT
if (response.statusCode() == 202) {
String location = response.headers().get(Const.LOCATION_HEADER.toLowerCase());
// Ensure location is absolute URI
if (!location.startsWith("http") && !location.startsWith("https")) {
location = "%s://%s/%s"
.formatted(getScheme(), containerRef.getApiRegistry(), location.replaceFirst("^/", ""));
}
LOG.debug("Location header: {}", location);
response = client.put(
URI.create("%s&digest=%s".formatted(location, digest)),
data,
Map.of(Const.CONTENT_TYPE_HEADER, Const.APPLICATION_OCTET_STREAM_HEADER_VALUE));
if (response.statusCode() == 201) {
LOG.debug("Successful push: {}", response.response());
} else {
throw new OrasException("Failed to push layer: %s".formatted(response.response()));
}
}
handleError(response);
return Layer.fromData(containerRef, data);
}
/**
* Return if the registry contains already the blob
* @param containerRef The container
* @return True if the blob exists
*/
private boolean hasBlob(ContainerRef containerRef) {
OrasHttpClient.ResponseWrapper<String> response = headBlob(containerRef);
return response.statusCode() == 200;
}
private OrasHttpClient.ResponseWrapper<String> headBlob(ContainerRef containerRef) {
URI uri = URI.create("%s://%s".formatted(getScheme(), containerRef.getBlobsPath()));
OrasHttpClient.ResponseWrapper<String> response =
client.head(uri, Map.of(Const.ACCEPT_HEADER, Const.APPLICATION_OCTET_STREAM_HEADER_VALUE));
logResponse(response);
// Switch to bearer auth if needed and retry first request
if (switchTokenAuth(containerRef, response)) {
response = client.head(uri, Map.of(Const.ACCEPT_HEADER, Const.APPLICATION_OCTET_STREAM_HEADER_VALUE));
logResponse(response);
}
return response;
}
/**
* Get the blob for the given digest. Not be suitable for large blobs
* @param containerRef The container
* @return The blob as bytes
*/
@Override
public byte[] getBlob(ContainerRef containerRef) {
try (InputStream is = fetchBlob(containerRef)) {
return ensureDigest(containerRef, is.readAllBytes());
} catch (IOException e) {
throw new OrasException("Failed to get blob", e);
}
}
@Override
public void fetchBlob(ContainerRef containerRef, Path path) {
if (!hasBlob(containerRef)) {
throw new OrasException(new OrasHttpClient.ResponseWrapper<>("", 404, Map.of()));
}
URI uri = URI.create("%s://%s".formatted(getScheme(), containerRef.getBlobsPath()));
OrasHttpClient.ResponseWrapper<Path> response =
client.download(uri, Map.of(Const.ACCEPT_HEADER, Const.APPLICATION_OCTET_STREAM_HEADER_VALUE), path);
logResponse(response);
handleError(response);
}
@Override
public InputStream fetchBlob(ContainerRef containerRef) {
if (!hasBlob(containerRef)) {
throw new OrasException(new OrasHttpClient.ResponseWrapper<>("", 404, Map.of()));
}
URI uri = URI.create("%s://%s".formatted(getScheme(), containerRef.getBlobsPath()));
OrasHttpClient.ResponseWrapper<InputStream> response =
client.download(uri, Map.of(Const.ACCEPT_HEADER, Const.APPLICATION_OCTET_STREAM_HEADER_VALUE));
logResponse(response);
handleError(response);
return response.response();
}
@Override
public Descriptor fetchBlobDescriptor(ContainerRef containerRef) {
OrasHttpClient.ResponseWrapper<String> response = headBlob(containerRef);
handleError(response);
String size = response.headers().get(Const.CONTENT_LENGTH_HEADER.toLowerCase());
String digest = response.headers().get(Const.DOCKER_CONTENT_DIGEST_HEADER.toLowerCase());
return Descriptor.of(digest, Long.parseLong(size), Const.DEFAULT_DESCRIPTOR_MEDIA_TYPE);
}
/**
* Get the manifest of a container
* @param containerRef The container
* @return The manifest and it's associated descriptor
*/
public Manifest getManifest(ContainerRef containerRef) {
OrasHttpClient.ResponseWrapper<String> response = getManifestResponse(containerRef);
logResponse(response);
handleError(response);
String contentType = response.headers().get(Const.CONTENT_TYPE_HEADER.toLowerCase());
if (!isManifestMediaType(contentType)) {
throw new OrasException(
"Expected manifest but got index. Probably a multi-platform image instead of artifact");
}
String size = response.headers().get(Const.CONTENT_LENGTH_HEADER.toLowerCase());
String digest = response.headers().get(Const.DOCKER_CONTENT_DIGEST_HEADER.toLowerCase());
ManifestDescriptor descriptor =
ManifestDescriptor.of(contentType, digest, size == null ? 0 : Long.parseLong(size));
return Manifest.fromJson(response.response()).withDescriptor(descriptor);
}
/**
* Get the index of a container
* @param containerRef The container
* @return The index and it's associated descriptor
*/
public Index getIndex(ContainerRef containerRef) {
OrasHttpClient.ResponseWrapper<String> response = getManifestResponse(containerRef);
logResponse(response);
handleError(response);
String contentType = response.headers().get(Const.CONTENT_TYPE_HEADER.toLowerCase());
if (!isIndexMediaType(contentType)) {
throw new OrasException("Expected index but got %s".formatted(contentType));
}
String size = response.headers().get(Const.CONTENT_LENGTH_HEADER.toLowerCase());
String digest = response.headers().get(Const.DOCKER_CONTENT_DIGEST_HEADER.toLowerCase());
ManifestDescriptor descriptor =
ManifestDescriptor.of(contentType, digest, size == null ? 0 : Long.parseLong(size));
return Index.fromJson(response.response()).withDescriptor(descriptor);
}
/**
* Get a manifest response
* @param containerRef The container
* @return The response
*/
private OrasHttpClient.ResponseWrapper<String> getManifestResponse(ContainerRef containerRef) {
URI uri = URI.create("%s://%s".formatted(getScheme(), containerRef.getManifestsPath()));
OrasHttpClient.ResponseWrapper<String> response =
client.head(uri, Map.of(Const.ACCEPT_HEADER, Const.MANIFEST_ACCEPT_TYPE));
logResponse(response);
// Switch to bearer auth if needed and retry first request
if (switchTokenAuth(containerRef, response)) {
response = client.head(uri, Map.of(Const.ACCEPT_HEADER, Const.MANIFEST_ACCEPT_TYPE));
logResponse(response);
}
handleError(response);
return client.get(uri, Map.of("Accept", Const.MANIFEST_ACCEPT_TYPE));
}
private byte[] ensureDigest(ContainerRef ref, byte[] data) {
if (ref.getDigest() == null) {
throw new OrasException("Missing digest");
}
SupportedAlgorithm algorithm = SupportedAlgorithm.fromDigest(ref.getDigest());
String dataDigest = algorithm.digest(data);
if (!ref.getDigest().equals(dataDigest)) {
throw new OrasException("Digest mismatch: %s != %s".formatted(ref.getTag(), dataDigest));
}
return data;
}
/**
* Switch the current authentication to token auth
* @param response The response
*/
private boolean switchTokenAuth(ContainerRef containerRef, OrasHttpClient.ResponseWrapper<String> response) {
if (response.statusCode() == 401 && !(authProvider instanceof BearerTokenProvider)) {
LOG.debug("Requesting token with token flow");
setAuthProvider(new BearerTokenProvider(authProvider).refreshToken(containerRef, client, response));
return true;
}
// Need token refresh (expired or wrong scope)
if ((response.statusCode() == 401 || response.statusCode() == 403)
&& authProvider instanceof BearerTokenProvider) {
LOG.debug("Requesting new token with username password flow");
setAuthProvider(((BearerTokenProvider) authProvider).refreshToken(containerRef, client, response));
return true;
}
return false;
}
/**
* Handle an error response
* @param responseWrapper The response
*/
@SuppressWarnings("unchecked")
private void handleError(OrasHttpClient.ResponseWrapper<?> responseWrapper) {
if (responseWrapper.statusCode() >= 400) {
if (responseWrapper.response() instanceof String) {
LOG.debug("Response: {}", responseWrapper.response());
throw new OrasException((OrasHttpClient.ResponseWrapper<String>) responseWrapper);
}
throw new OrasException(new OrasHttpClient.ResponseWrapper<>("", responseWrapper.statusCode(), Map.of()));
}
}
/**
* Log the response
* @param response The response
*/
private void logResponse(OrasHttpClient.ResponseWrapper<?> response) {
LOG.debug("Status Code: {}", response.statusCode());
LOG.debug("Headers: {}", response.headers());
// Only log non-binary responses
if (response.response() instanceof String) {
LOG.debug("Response: {}", response.response());
}
}
/**
* Push a blob using input stream in chunks to avoid loading the whole blob in memory.
* This method is recommended for large files to prevent excessive memory usage.
* For smaller blobs, consider using {@link #pushBlob(ContainerRef, Path)} which may be more efficient
* as it uses fewer HTTP requests.
*
* This method complies with the OCI Distribution Specification for chunked uploads and will
* respect the minimum chunk size requirements specified by the registry.
*
* @param containerRef the container ref
* @param input the input stream
* @param size the size of the blob
* @return The Layer containing the uploaded blob information
* @throws OrasException if upload fails or digest calculation fails
* @see <a href="https://github.com/opencontainers/distribution-spec/blob/main/spec.md#pushing-a-blob-in-chunks">OCI Distribution Spec: Pushing a blob in chunks</a>
*/
public Layer pushChunks(ContainerRef containerRef, InputStream input, long size) {
// INITIALIZATION PHASE
// Initialize the Message Digest
MessageDigest digest;
try {
digest = MessageDigest.getInstance(containerRef.getAlgorithm().getAlgorithmName());
} catch (NoSuchAlgorithmException e) {
throw new OrasException("Failed to get message digest", e);
}
byte[] buffer = new byte[CHUNK_SIZE];
ByteArrayOutputStream firstChunk = new ByteArrayOutputStream();
int bytesRead;
long totalBytesRead = 0;
String contentDigest = null;
try {
// FIRST CHUNK PROCESSING
// Read first chunk to buffer for initial PATCH request
while ((bytesRead = input.read(buffer)) != -1 && totalBytesRead < CHUNK_SIZE) {
digest.update(buffer, 0, bytesRead);
firstChunk.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
}
// Handle small blobs that fit in one chunk
if (bytesRead == -1) {
contentDigest = createDigestString(containerRef, digest.digest());
// Check if blob already exists, return early if it does
if (hasBlob(containerRef.withDigest(contentDigest))) {
LOG.info("Blob already exists: {}", contentDigest);
return Layer.fromDigest(contentDigest, totalBytesRead);
}
}
// UPLOAD SESSION INITIALIZATION
URI uploadUri = URI.create("%s://%s".formatted(getScheme(), containerRef.getBlobsUploadPath()));
OrasHttpClient.ResponseWrapper<String> response = client.post(uploadUri, new byte[0], Map.of());
// Handle authentication if needed
if (switchTokenAuth(containerRef, response)) {
response = client.post(uploadUri, new byte[0], Map.of());
}
handleError(response);
if (response.statusCode() != 202) {
throw new OrasException("Failed to initiate blob upload: " + response.statusCode());
}
// Get upload location URL
String location = response.headers().get(Const.LOCATION_HEADER.toLowerCase());
if (location == null) {
throw new OrasException("No location header in response");
}
// Handle minimum chunk size requirements from registry
int chunkSize = adjustChunkSizeIfNeeded(response, buffer.length);
if (buffer.length < chunkSize) {
buffer = new byte[chunkSize];
}
// Ensure location is an absolute URL
location = ensureAbsoluteUri(location, containerRef);
LOG.debug("Initial location URL: {}", location);
// UPLOAD FIRST CHUNK
long startRange = 0;
long endRange = totalBytesRead - 1;
if (totalBytesRead > 0) {
// Prepare headers for first chunk
Map<String, String> firstChunkHeaders = new HashMap<>();
firstChunkHeaders.put(Const.CONTENT_TYPE_HEADER, Const.APPLICATION_OCTET_STREAM_HEADER_VALUE);
firstChunkHeaders.put(Const.CONTENT_RANGE_HEADER, startRange + "-" + endRange);
// Upload first chunk
response = client.patch(URI.create(location), firstChunk.toByteArray(), firstChunkHeaders);
handleError(response);
if (response.statusCode() != 202) {
throw new OrasException("Failed to upload first chunk: " + response.statusCode());
}
// Update location for next request
location = getLocationHeader(response);
location = ensureAbsoluteUri(location, containerRef);
LOG.debug("Location after first chunk: {}", location);
// Update range information for next chunk
endRange = getEndRangeFromHeader(response, endRange);
startRange = endRange + 1;
// PROCESS TRANSITION BYTES
// Handle bytes read during the last iteration of first chunk loop
if (bytesRead > 0) {
LOG.debug("Processing transition bytes: {} bytes", bytesRead);
digest.update(buffer, 0, bytesRead);
// Prepare headers for transition bytes
Map<String, String> transitionHeaders = new HashMap<>();
long transitionEndRange = startRange + bytesRead - 1;
transitionHeaders.put(Const.CONTENT_TYPE_HEADER, Const.APPLICATION_OCTET_STREAM_HEADER_VALUE);
transitionHeaders.put(Const.CONTENT_RANGE_HEADER, startRange + "-" + transitionEndRange);
// Upload transition bytes
response = client.patch(URI.create(location), Arrays.copyOf(buffer, bytesRead), transitionHeaders);
handleError(response);
if (response.statusCode() != 202) {
throw new OrasException("Failed to upload transition bytes: " + response.statusCode());
}
// Update location for next chunk
location = getLocationHeader(response);
location = ensureAbsoluteUri(location, containerRef);
LOG.debug("Location after transition chunk: {}", location);
// Update range information for next chunk
endRange = getEndRangeFromHeader(response, transitionEndRange);
startRange = endRange + 1;
totalBytesRead += bytesRead;
}
}
// UPLOAD REMAINING CHUNKS
while ((bytesRead = input.read(buffer)) != -1) {
// Update digest with current chunk
digest.update(buffer, 0, bytesRead);
// Prepare headers for chunk
Map<String, String> chunkHeaders = new HashMap<>();
endRange = startRange + bytesRead - 1;
chunkHeaders.put(Const.CONTENT_TYPE_HEADER, Const.APPLICATION_OCTET_STREAM_HEADER_VALUE);
chunkHeaders.put(Const.CONTENT_RANGE_HEADER, startRange + "-" + endRange);
// Upload chunk
response = client.patch(URI.create(location), Arrays.copyOf(buffer, bytesRead), chunkHeaders);
handleError(response);
if (response.statusCode() != 202) {
throw new OrasException("Failed to upload chunk: " + response.statusCode());
}
// Update location for next chunk
location = getLocationHeader(response);
location = ensureAbsoluteUri(location, containerRef);
// Update range information for next chunk
endRange = getEndRangeFromHeader(response, endRange);
startRange = endRange + 1;
totalBytesRead += bytesRead;
}
// FINALIZE UPLOAD
// Calculate final digest if not already done
if (contentDigest == null) {
contentDigest = createDigestString(containerRef, digest.digest());
LOG.debug("Calculated content digest: {}", contentDigest);
}
// Prepare final upload URI
URI finalizeUri = constructFinalizeUri(location, contentDigest, containerRef);
// Complete the upload with final PUT
Map<String, String> finalHeaders = new HashMap<>();
finalHeaders.put(Const.CONTENT_TYPE_HEADER, Const.APPLICATION_OCTET_STREAM_HEADER_VALUE);
// Log finalization details for debugging
LOG.debug("Final PUT URL: {}", finalizeUri);
LOG.debug("Content Digest: {}", contentDigest);
response = client.put(finalizeUri, new byte[0], finalHeaders);
logFinalResponse(response);
handleError(response);
if (response.statusCode() != 201) {
throw new OrasException("Failed to complete blob upload: " + response.statusCode());
}
return Layer.fromDigest(contentDigest, totalBytesRead);
} catch (IOException e) {
throw new OrasException("Failed to push blob", e);
}
}
/**
* Get blob as stream to avoid loading into memory
* @param containerRef The container ref
* @return The input stream
*/
public InputStream getBlobStream(ContainerRef containerRef) {
// Similar to fetchBlob()
return fetchBlob(containerRef);
}
// Helper method to convert bytes to hex
private static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
/**
* Creates a properly formatted digest string.
*/
private String createDigestString(ContainerRef containerRef, byte[] digestBytes) {
return containerRef.getAlgorithm().getPrefix() + ":" + bytesToHex(digestBytes);
}
/**
* Gets and validates the location header.
*/
private String getLocationHeader(OrasHttpClient.ResponseWrapper<String> response) {
String location = response.headers().get(Const.LOCATION_HEADER.toLowerCase());
if (location == null) {
throw new OrasException("No location header in response");
}
return location;
}
/**
* Makes sure the location URI has a scheme.
*/
private String ensureAbsoluteUri(String location, ContainerRef containerRef) {
if (!location.startsWith("http:") && !location.startsWith("https:")) {
return "%s://%s/%s".formatted(getScheme(), containerRef.getRegistry(), location.replaceFirst("^/", ""));
}
return location;
}
/**
* Extracts the end range value from response headers.
*/
private long getEndRangeFromHeader(OrasHttpClient.ResponseWrapper<String> response, long defaultEndRange) {
String rangeHeader = response.headers().get(Const.RANGE_HEADER.toLowerCase());
if (rangeHeader != null) {
String[] parts = rangeHeader.split("-");
if (parts.length == 2) {
return Long.parseLong(parts[1]);
}
}
return defaultEndRange;
}
/**
* Adjusts chunk size based on registry requirements.
*/
private int adjustChunkSizeIfNeeded(OrasHttpClient.ResponseWrapper<String> response, int currentChunkSize) {
String minChunkSizeHeader = response.headers().get("OCI-Chunk-Min-Length".toLowerCase());
if (minChunkSizeHeader == null) {
return currentChunkSize;
}
try {
int registryMinChunkSize = Integer.parseInt(minChunkSizeHeader);
if (registryMinChunkSize > currentChunkSize) {
LOG.debug(
"Registry requires minimum chunk size of {} bytes, adjusting from default {} bytes",
registryMinChunkSize,
currentChunkSize);
return registryMinChunkSize;
}
} catch (NumberFormatException e) {
LOG.warn("Invalid OCI-Chunk-Min-Length header value: {}", minChunkSizeHeader);
}
return currentChunkSize;
}
/**