Example #1
0
        public void SetUp()
        {
            fakeDependenciesLayerConfiguration =
                MakeLayerConfiguration(
                    "core/application/dependencies", EXTRACTION_PATH_ROOT.Resolve("libs"));
            fakeSnapshotDependenciesLayerConfiguration =
                MakeLayerConfiguration(
                    "core/application/snapshot-dependencies", EXTRACTION_PATH_ROOT.Resolve("libs"));
            fakeResourcesLayerConfiguration =
                MakeLayerConfiguration(
                    "core/application/resources", EXTRACTION_PATH_ROOT.Resolve("resources"));
            fakeClassesLayerConfiguration =
                MakeLayerConfiguration("core/application/classes", EXTRACTION_PATH_ROOT.Resolve("classes"));
            fakeExtraFilesLayerConfiguration =
                LayerConfiguration.CreateBuilder()
                .AddEntry(
                    Paths.Get(TestResources.GetResource("core/fileA").ToURI()),
                    EXTRA_FILES_LAYER_EXTRACTION_PATH.Resolve("fileA"))
                .AddEntry(
                    Paths.Get(TestResources.GetResource("core/fileB").ToURI()),
                    EXTRA_FILES_LAYER_EXTRACTION_PATH.Resolve("fileB"))
                .Build();
            emptyLayerConfiguration = LayerConfiguration.CreateBuilder().Build();

            cache = LayersCache.WithDirectory(temporaryFolder.NewFolder().ToPath());

            Mock.Get(mockBuildConfiguration).Setup(m => m.GetEventHandlers()).Returns(mockEventHandlers);

            Mock.Get(mockBuildConfiguration).Setup(m => m.GetApplicationLayersCache()).Returns(cache);
        }
Example #2
0
        public async Task TestFromFileAsync()
        {
            SystemPath fileA    = Paths.Get(TestResources.GetResource("core/fileA").ToURI());
            string     expected = Encoding.UTF8.GetString(Files.ReadAllBytes(fileA));

            await VerifyBlobWriteToAsync(expected, Blobs.From(fileA)).ConfigureAwait(false);
        }
        public void TestReadJsonWithLock()
        {
            SystemPath jsonFile = Paths.Get(TestResources.GetResource("core/json/basic.json").ToURI());

            // Deserializes into a metadata JSON object.
            TestJson testJson = JsonTemplateMapper.ReadJsonFromFileWithLock <TestJson>(jsonFile);

            Assert.AreEqual(testJson.Number, 54);
            Assert.AreEqual(testJson.Text, "crepecake");
            Assert.AreEqual(
                testJson.Digest,
                DescriptorDigest.FromDigest(
                    "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad"));
            Assert.IsInstanceOf <TestJson.InnerObjectClass>(testJson.InnerObject);
            Assert.AreEqual(testJson.InnerObject.Number, 23);

            Assert.AreEqual(
                testJson.InnerObject.Texts, new[] { "first text", "second text" });

            Assert.AreEqual(testJson.InnerObject.Digests, new[]
            {
                DescriptorDigest.FromDigest("sha256:91e0cae00b86c289b33fee303a807ae72dd9f0315c16b74e6ab0cdbe9d996c10"),
                DescriptorDigest.FromHash("4945ba5011739b0b98c4a41afe224e417f47c7c99b2ce76830999c9a0861b236")
            });

            // ignore testJson.list
        }
        public void TestAddEntryRecursive_defaults()
        {
            SystemPath testDirectory = TestResources.GetResource("core/layer");
            SystemPath testFile      = TestResources.GetResource("core/fileA");

            ILayerConfiguration layerConfiguration =
                LayerConfiguration.CreateBuilder()
                .AddEntryRecursive(testDirectory, AbsoluteUnixPath.Get("/app/layer/"))
                .AddEntryRecursive(testFile, AbsoluteUnixPath.Get("/app/fileA"))
                .Build();

            ImmutableHashSet <LayerEntry> expectedLayerEntries =
                ImmutableHashSet.Create(
                    DefaultLayerEntry(testDirectory, AbsoluteUnixPath.Get("/app/layer/")),
                    DefaultLayerEntry(testDirectory.Resolve("a"), AbsoluteUnixPath.Get("/app/layer/a/")),
                    DefaultLayerEntry(
                        testDirectory.Resolve("a/b"), AbsoluteUnixPath.Get("/app/layer/a/b/")),
                    DefaultLayerEntry(
                        testDirectory.Resolve("a/b/bar"), AbsoluteUnixPath.Get("/app/layer/a/b/bar/")),
                    DefaultLayerEntry(testDirectory.Resolve("c/"), AbsoluteUnixPath.Get("/app/layer/c")),
                    DefaultLayerEntry(
                        testDirectory.Resolve("c/cat/"), AbsoluteUnixPath.Get("/app/layer/c/cat")),
                    DefaultLayerEntry(testDirectory.Resolve("foo"), AbsoluteUnixPath.Get("/app/layer/foo")),
                    DefaultLayerEntry(testFile, AbsoluteUnixPath.Get("/app/fileA")));

            CollectionAssert.AreEquivalent(
                expectedLayerEntries, ImmutableHashSet.CreateRange(layerConfiguration.LayerEntries));
        }
        public void TestReadListOfJson()
        {
            SystemPath jsonFile = Paths.Get(TestResources.GetResource("core/json/basic_list.json").ToURI());

            string           jsonString  = Encoding.UTF8.GetString(Files.ReadAllBytes(jsonFile));
            IList <TestJson> listofJsons = JsonTemplateMapper.ReadListOfJson <TestJson>(jsonString);
            TestJson         json1       = listofJsons[0];
            TestJson         json2       = listofJsons[1];

            DescriptorDigest digest1 =
                DescriptorDigest.FromDigest(
                    "sha256:91e0cae00b86c289b33fee303a807ae72dd9f0315c16b74e6ab0cdbe9d996c10");
            DescriptorDigest digest2 =
                DescriptorDigest.FromDigest(
                    "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad");

            Assert.AreEqual(1, json1.Number);
            Assert.AreEqual(2, json2.Number);
            Assert.AreEqual("text1", json1.Text);
            Assert.AreEqual("text2", json2.Text);
            Assert.AreEqual(digest1, json1.Digest);
            Assert.AreEqual(digest2, json2.Digest);
            Assert.AreEqual(10, json1.InnerObject.Number);
            Assert.AreEqual(20, json2.InnerObject.Number);
            Assert.AreEqual(2, json1.List.Count);
            Assert.IsTrue(json2.List.Count == 0);
        }
Example #6
0
        public void Test_fromJson()
        {
            // Loads the JSON string.
            SystemPath jsonFile = Paths.Get(TestResources.GetResource("core/json/dockerconfig.json").ToURI());

            // Deserializes into a docker config JSON object.
            DockerConfig dockerConfig =
                new DockerConfig(JsonTemplateMapper.ReadJsonFromFile <DockerConfigTemplate>(jsonFile));

            Assert.AreEqual("some:auth", DecodeBase64(dockerConfig.GetAuthFor("some registry")));
            Assert.AreEqual(
                "some:other:auth", DecodeBase64(dockerConfig.GetAuthFor("some other registry")));
            Assert.AreEqual("token", DecodeBase64(dockerConfig.GetAuthFor("registry")));
            Assert.AreEqual("token", DecodeBase64(dockerConfig.GetAuthFor("https://registry")));
            Assert.IsNull(dockerConfig.GetAuthFor("just registry"));

            Assert.AreEqual(
                Paths.Get("docker-credential-some credential store"),
                dockerConfig.GetCredentialHelperFor("some registry").GetCredentialHelper());
            Assert.AreEqual(
                Paths.Get("docker-credential-some credential store"),
                dockerConfig.GetCredentialHelperFor("some other registry").GetCredentialHelper());
            Assert.AreEqual(
                Paths.Get("docker-credential-some credential store"),
                dockerConfig.GetCredentialHelperFor("just registry").GetCredentialHelper());
            Assert.AreEqual(
                Paths.Get("docker-credential-some credential store"),
                dockerConfig.GetCredentialHelperFor("with.protocol").GetCredentialHelper());
            Assert.AreEqual(
                Paths.Get("docker-credential-another credential helper"),
                dockerConfig.GetCredentialHelperFor("another registry").GetCredentialHelper());
            Assert.IsNull(dockerConfig.GetCredentialHelperFor("unknonwn registry"));
        }
        public void TestToJson()
        {
            // Loads the expected JSON string.
            SystemPath jsonFile     = Paths.Get(TestResources.GetResource("core/json/containerconfig.json").ToURI());
            string     expectedJson = Encoding.UTF8.GetString(Files.ReadAllBytes(jsonFile));

            // Creates the JSON object to serialize.
            ContainerConfigurationTemplate containerConfigJson = new ContainerConfigurationTemplate
            {
                Created      = "1970-01-01T00:00:20Z",
                Architecture = "wasm",
                Os           = "js"
            };

            containerConfigJson.SetContainerEnvironment(new[] { "VAR1=VAL1", "VAR2=VAL2" });
            containerConfigJson.SetContainerEntrypoint(new[] { "some", "entrypoint", "command" });
            containerConfigJson.SetContainerCmd(new[] { "arg1", "arg2" });
            containerConfigJson.SetContainerHealthCheckTest(new[] { "CMD-SHELL", "/checkhealth" });
            containerConfigJson.SetContainerHealthCheckInterval(3000000000L);
            containerConfigJson.SetContainerHealthCheckTimeout(1000000000L);
            containerConfigJson.SetContainerHealthCheckStartPeriod(2000000000L);
            containerConfigJson.SetContainerHealthCheckRetries(3);
            containerConfigJson.SetContainerExposedPorts(
                new Dictionary <string, IDictionary <object, object> >
            {
                ["1000/tcp"] =
                    ImmutableDictionary.Create <object, object>(),
                ["2000/tcp"] =
                    ImmutableDictionary.Create <object, object>(),
                ["3000/udp"] =
                    ImmutableDictionary.Create <object, object>()
            }.ToImmutableSortedDictionary());
            containerConfigJson.SetContainerLabels(ImmutableDic.Of("key1", "value1", "key2", "value2"));
            containerConfigJson.SetContainerVolumes(
                ImmutableDic.Of <string, IDictionary <object, object> >(
                    "/var/job-result-data", ImmutableDictionary.Create <object, object>(), "/var/log/my-app-logs", ImmutableDictionary.Create <object, object>()));
            containerConfigJson.SetContainerWorkingDir("/some/workspace");
            containerConfigJson.SetContainerUser("tomcat");

            containerConfigJson.AddLayerDiffId(
                DescriptorDigest.FromDigest(
                    "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad"));
            containerConfigJson.AddHistoryEntry(
                HistoryEntry.CreateBuilder()
                .SetCreationTimestamp(Instant.FromUnixTimeSeconds(0))
                .SetAuthor("Bazel")
                .SetCreatedBy("bazel build ...")
                .SetEmptyLayer(true)
                .Build());
            containerConfigJson.AddHistoryEntry(
                HistoryEntry.CreateBuilder()
                .SetCreationTimestamp(Instant.FromUnixTimeSeconds(20))
                .SetAuthor("Fib")
                .SetCreatedBy("fib")
                .Build());

            // Serializes the JSON object.
            Assert.AreEqual(expectedJson, JsonTemplateMapper.ToUtf8String(containerConfigJson));
        }
Example #8
0
        private static void SetupCachedMetadataV21(SystemPath cacheDirectory)
        {
            SystemPath imageDirectory = cacheDirectory.Resolve("images/test/image!tag");

            Files.CreateDirectories(imageDirectory);
            Files.Copy(
                Paths.Get(TestResources.GetResource("core/json/v21manifest.json").ToURI()),
                imageDirectory.Resolve("manifest.json"));
        }
        public void TestToBlob_listOfJson()
        {
            SystemPath jsonFile = Paths.Get(TestResources.GetResource("core/json/basic_list.json").ToURI());

            string          jsonString = Encoding.UTF8.GetString(Files.ReadAllBytes(jsonFile));
            List <TestJson> listOfJson = JsonTemplateMapper.ReadListOfJson <TestJson>(jsonString);

            Assert.AreEqual(jsonString, JsonTemplateMapper.ToUtf8String(listOfJson));
        }
Example #10
0
        public void TestGetAuthFor_correctSuffixMatching()
        {
            SystemPath json =
                Paths.Get(TestResources.GetResource("core/json/dockerconfig_extra_matches.json").ToURI());

            DockerConfig dockerConfig =
                new DockerConfig(JsonTemplateMapper.ReadJsonFromFile <DockerConfigTemplate>(json));

            Assert.IsNull(dockerConfig.GetAuthFor("example"));
        }
Example #11
0
        public void TestGetCredentialHelperFor_withProtocolAndSuffix()
        {
            SystemPath json = Paths.Get(TestResources.GetResource("core/json/dockerconfig.json").ToURI());

            DockerConfig dockerConfig =
                new DockerConfig(JsonTemplateMapper.ReadJsonFromFile <DockerConfigTemplate>(json));

            Assert.AreEqual(
                Paths.Get("docker-credential-some credential store"),
                dockerConfig.GetCredentialHelperFor("with.protocol.and.suffix").GetCredentialHelper());
        }
        public void Setup()
        {
            testTarStreamBuilder = new TarStreamBuilder();
            // Gets the test resource files.
            fileA      = Paths.Get(TestResources.GetResource("core/fileA").ToURI());
            fileB      = Paths.Get(TestResources.GetResource("core/fileB").ToURI());
            directoryA = Paths.Get(TestResources.GetResource("core/directoryA").ToURI());

            fileAContents = Files.ReadAllBytes(fileA);
            fileBContents = Files.ReadAllBytes(fileB);
        }
        public void TestFromJson()
        {
            // Loads the JSON string.
            SystemPath jsonFile = Paths.Get(TestResources.GetResource("core/json/containerconfig.json").ToURI());

            // Deserializes into a manifest JSON object.
            ContainerConfigurationTemplate containerConfigJson =
                JsonTemplateMapper.ReadJsonFromFile <ContainerConfigurationTemplate>(jsonFile);

            Assert.AreEqual("1970-01-01T00:00:20Z", containerConfigJson.Created);
            Assert.AreEqual("wasm", containerConfigJson.Architecture);
            Assert.AreEqual("js", containerConfigJson.Os);
            Assert.AreEqual(
                new[] { "VAR1=VAL1", "VAR2=VAL2" }, containerConfigJson.GetContainerEnvironment());
            Assert.AreEqual(
                new[] { "some", "entrypoint", "command" },
                containerConfigJson.GetContainerEntrypoint());
            Assert.AreEqual(new[] { "arg1", "arg2" }, containerConfigJson.GetContainerCmd());

            Assert.AreEqual(
                new[] { "CMD-SHELL", "/checkhealth" }, containerConfigJson.GetContainerHealthTest());
            Assert.IsNotNull(containerConfigJson.GetContainerHealthInterval());
            Assert.AreEqual(3000000000L, containerConfigJson.GetContainerHealthInterval().GetValueOrDefault());
            Assert.IsNotNull(containerConfigJson.GetContainerHealthTimeout());
            Assert.AreEqual(1000000000L, containerConfigJson.GetContainerHealthTimeout().GetValueOrDefault());
            Assert.IsNotNull(containerConfigJson.GetContainerHealthStartPeriod());
            Assert.AreEqual(
                2000000000L, containerConfigJson.GetContainerHealthStartPeriod().GetValueOrDefault());
            Assert.IsNotNull(containerConfigJson.GetContainerHealthRetries());
            Assert.AreEqual(3, containerConfigJson.GetContainerHealthRetries().GetValueOrDefault());

            Assert.AreEqual(
                ImmutableDic.Of("key1", "value1", "key2", "value2"),
                containerConfigJson.GetContainerLabels());
            Assert.AreEqual("/some/workspace", containerConfigJson.GetContainerWorkingDir());
            Assert.AreEqual(
                DescriptorDigest.FromDigest(
                    "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad"),
                containerConfigJson.GetLayerDiffId(0));
            Assert.AreEqual(
                ImmutableArray.Create(
                    HistoryEntry.CreateBuilder()
                    .SetCreationTimestamp(Instant.FromUnixTimeSeconds(0))
                    .SetAuthor("Bazel")
                    .SetCreatedBy("bazel build ...")
                    .SetEmptyLayer(true)
                    .Build(),
                    HistoryEntry.CreateBuilder()
                    .SetCreationTimestamp(Instant.FromUnixTimeSeconds(20))
                    .SetAuthor("Fib")
                    .SetCreatedBy("fib")
                    .Build()),
                containerConfigJson.History);
        }
Example #14
0
        public void TestRetrieveGCR()
        {
            new Command("docker-credential-gcr", "store")
            .Run(Files.ReadAllBytes(Paths.Get(TestResources.GetResource("credentials.json").ToURI())));

            DockerCredentialHelper dockerCredentialHelper = new DockerCredentialHelper("myregistry", "gcr");

            Credential credentials = dockerCredentialHelper.Retrieve();

            Assert.AreEqual("myusername", credentials.GetUsername());
            Assert.AreEqual("mysecret", credentials.GetPassword());
        }
Example #15
0
        public async Task TestBuildAsync()
        {
            SystemPath layerDirectory = Paths.Get(TestResources.GetResource("core/layer").ToURI());
            SystemPath blobA          = Paths.Get(TestResources.GetResource("core/blobA").ToURI());

            ReproducibleLayerBuilder layerBuilder =
                new ReproducibleLayerBuilder(
                    LayerConfiguration.CreateBuilder()
                    .AddEntryRecursive(
                        layerDirectory, AbsoluteUnixPath.Get("/extract/here/apple/layer"))
                    .AddEntry(blobA, AbsoluteUnixPath.Get("/extract/here/apple/blobA"))
                    .AddEntry(blobA, AbsoluteUnixPath.Get("/extract/here/banana/blobA"))
                    .Build()
                    .LayerEntries);

            // Writes the layer tar to a temporary file.
            IBlob      unwrittenBlob = layerBuilder.Build();
            SystemPath temporaryFile = temporaryFolder.NewFile().ToPath();

            using (Stream temporaryFileOutputStream =
                       new BufferedStream(Files.NewOutputStream(temporaryFile)))
            {
                await unwrittenBlob.WriteToAsync(temporaryFileOutputStream).ConfigureAwait(false);
            }

            // Reads the file back.
            TarInputStream tarArchiveInputStream =
                new TarInputStream(Files.NewInputStream(temporaryFile));

            VerifyNextTarArchiveEntryIsDirectory(tarArchiveInputStream, "extract/");
            VerifyNextTarArchiveEntryIsDirectory(tarArchiveInputStream, "extract/here/");
            VerifyNextTarArchiveEntryIsDirectory(tarArchiveInputStream, "extract/here/apple/");
            VerifyNextTarArchiveEntry(tarArchiveInputStream, "extract/here/apple/blobA", blobA);
            VerifyNextTarArchiveEntryIsDirectory(tarArchiveInputStream, "extract/here/apple/layer/");
            VerifyNextTarArchiveEntryIsDirectory(tarArchiveInputStream, "extract/here/apple/layer/a/");
            VerifyNextTarArchiveEntryIsDirectory(tarArchiveInputStream, "extract/here/apple/layer/a/b/");
            VerifyNextTarArchiveEntry(
                tarArchiveInputStream,
                "extract/here/apple/layer/a/b/bar",
                Paths.Get(TestResources.GetResource("core/layer/a/b/bar").ToURI()));
            VerifyNextTarArchiveEntryIsDirectory(tarArchiveInputStream, "extract/here/apple/layer/c/");
            VerifyNextTarArchiveEntry(
                tarArchiveInputStream,
                "extract/here/apple/layer/c/cat",
                Paths.Get(TestResources.GetResource("core/layer/c/cat").ToURI()));
            VerifyNextTarArchiveEntry(
                tarArchiveInputStream,
                "extract/here/apple/layer/foo",
                Paths.Get(TestResources.GetResource("core/layer/foo").ToURI()));
            VerifyNextTarArchiveEntryIsDirectory(tarArchiveInputStream, "extract/here/banana/");
            VerifyNextTarArchiveEntry(tarArchiveInputStream, "extract/here/banana/blobA", blobA);
        }
        public void TestGetContainerConfiguration()
        {
            SetUp(ManifestFormat.V22);

            // Loads the expected JSON string.
            SystemPath jsonFile     = Paths.Get(TestResources.GetResource("core/json/containerconfig.json").ToURI());
            string     expectedJson = Encoding.UTF8.GetString(Files.ReadAllBytes(jsonFile));

            // Translates the image to the container configuration and writes the JSON string.
            ContainerConfigurationTemplate containerConfiguration = imageToJsonTranslator.GetContainerConfiguration();

            Assert.AreEqual(expectedJson, JsonTemplateMapper.ToUtf8String(containerConfiguration));
        }
Example #17
0
        public void SetUp()
        {
            mockEventHandlers    = Mock.Of <IEventHandlers>();
            v22manifestJsonFile  = Paths.Get(TestResources.GetResource("core/json/v22manifest.json").ToURI());
            fakeManifestTemplate =
                JsonTemplateMapper.ReadJsonFromFile <V22ManifestTemplate>(v22manifestJsonFile);

            testManifestPusher =
                new ManifestPusher(
                    new RegistryEndpointRequestProperties("someServerUrl", "someImageName"),
                    fakeManifestTemplate,
                    "test-image-tag",
                    mockEventHandlers);
        }
        public void TestRetrieve_suffixMatchingFromAlias()
        {
            SystemPath dockerConfigFile =
                Paths.Get(TestResources.GetResource("core/json/dockerconfig_index_docker_io_v1.json").ToURI());

            DockerConfigCredentialRetriever dockerConfigCredentialRetriever =
                new DockerConfigCredentialRetriever("registry.hub.docker.com", dockerConfigFile);

            Maybe <Credential> credentials = dockerConfigCredentialRetriever.Retrieve(mockLogger);

            Assert.IsTrue(credentials.IsPresent());
            Assert.AreEqual("token for", credentials.Get().GetUsername());
            Assert.AreEqual(" index.docker.io/v1/", credentials.Get().GetPassword());
        }
        public void TestWriteJson()
        {
            SystemPath jsonFile     = Paths.Get(TestResources.GetResource("core/json/basic.json").ToURI());
            string     expectedJson = Encoding.UTF8.GetString(Files.ReadAllBytes(jsonFile));

            TestJson testJson = new TestJson
            {
                Number = 54,
                Text   = "crepecake",
                Digest =
                    DescriptorDigest.FromDigest(
                        "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad"),
                InnerObject = new TestJson.InnerObjectClass
                {
                    Number = 23,
                    Texts  = new List <string> {
                        "first text", "second text"
                    },
                    Digests = new[]
                    {
                        DescriptorDigest.FromDigest(
                            "sha256:91e0cae00b86c289b33fee303a807ae72dd9f0315c16b74e6ab0cdbe9d996c10"),
                        DescriptorDigest.FromHash(
                            "4945ba5011739b0b98c4a41afe224e417f47c7c99b2ce76830999c9a0861b236")
                    }
                }
            };

            TestJson.InnerObjectClass innerObject1 = new TestJson.InnerObjectClass
            {
                Number = 42,
                Texts  = new List <string>()
            };
            TestJson.InnerObjectClass innerObject2 = new TestJson.InnerObjectClass
            {
                Number = 99,
                Texts  = new List <string> {
                    "some text"
                },
                Digests =
                    new List <DescriptorDigest> {
                    DescriptorDigest.FromDigest(
                        "sha256:d38f571aa1c11e3d516e0ef7e513e7308ccbeb869770cb8c4319d63b10a0075e")
                }
            };
            testJson.List = new[] { innerObject1, innerObject2 };

            Assert.AreEqual(expectedJson, JsonTemplateMapper.ToUtf8String(testJson));
        }
Example #20
0
 /**
  * Lists the files in the {@code resourcePath} resources directory and builds a {@link
  * LayerConfiguration} from those files.
  */
 private static ILayerConfiguration MakeLayerConfiguration(
     string resourcePath, string pathInContainer)
 {
     IEnumerable <SystemPath> fileStream =
         Files.List(Paths.Get(TestResources.GetResource(resourcePath).ToURI()));
     {
         LayerConfiguration.Builder layerConfigurationBuilder = LayerConfiguration.CreateBuilder();
         foreach (SystemPath i in fileStream)
         {
             ((Func <SystemPath, LayerConfiguration.Builder>)(sourceFile =>
                                                              layerConfigurationBuilder.AddEntry(
                                                                  sourceFile, AbsoluteUnixPath.Get(pathInContainer + sourceFile.GetFileName()))))(i);
         }
         return(layerConfigurationBuilder.Build());
     }
 }
Example #21
0
        public void TestGetAuthFor_orderOfMatchPreference()
        {
            SystemPath json =
                Paths.Get(TestResources.GetResource("core/json/dockerconfig_extra_matches.json").ToURI());

            DockerConfig dockerConfig =
                new DockerConfig(JsonTemplateMapper.ReadJsonFromFile <DockerConfigTemplate>(json));

            Assert.AreEqual("my-registry: exact match", dockerConfig.GetAuthFor("my-registry"));
            Assert.AreEqual("cool-registry: with https", dockerConfig.GetAuthFor("cool-registry"));
            Assert.AreEqual(
                "awesome-registry: starting with name", dockerConfig.GetAuthFor("awesome-registry"));
            Assert.AreEqual(
                "dull-registry: starting with name and with https",
                dockerConfig.GetAuthFor("dull-registry"));
        }
        /** Tests translation of image to {@link BuildableManifestTemplate}. */
        private async Task TestGetManifestAsync(
            ManifestFormat manifestTemplateClass, string translatedJsonFilename)
        {
            // Loads the expected JSON string.
            SystemPath jsonFile     = Paths.Get(TestResources.GetResource(translatedJsonFilename).ToURI());
            string     expectedJson = Encoding.UTF8.GetString(Files.ReadAllBytes(jsonFile));

            // Translates the image to the manifest and writes the JSON string.
            ContainerConfigurationTemplate containerConfiguration = imageToJsonTranslator.GetContainerConfiguration();
            BlobDescriptor blobDescriptor = await Digests.ComputeJsonDescriptorAsync(containerConfiguration).ConfigureAwait(false);

            IBuildableManifestTemplate manifestTemplate =
                imageToJsonTranslator.GetManifestTemplate(manifestTemplateClass, blobDescriptor);

            Assert.AreEqual(expectedJson, JsonTemplateMapper.ToUtf8String(manifestTemplate));
        }
Example #23
0
        public async Task TestHandleResponse_v22Async()
        {
            SystemPath v22ManifestFile = Paths.Get(TestResources.GetResource("core/json/v22manifest.json").ToURI());
            Stream     v22Manifest     = new MemoryStream(Files.ReadAllBytes(v22ManifestFile));

            mockResponse = new HttpResponseMessage
            {
                Content = new StreamContent(v22Manifest)
            };

            IManifestTemplate manifestTemplate =
                await new ManifestPuller <V22ManifestTemplate>(
                    fakeRegistryEndpointRequestProperties, "test-image-tag")
                .HandleResponseAsync(mockResponse).ConfigureAwait(false);

            Assert.IsInstanceOf <V22ManifestTemplate>(manifestTemplate);
        }
Example #24
0
        private static void CreateFilesInDirectory(SystemPath directory)
        {
            SystemPath testFilesDirectory = Paths.Get(TestResources.GetResource("core/layer").ToURI());

            new DirectoryWalker(testFilesDirectory)
            .FilterRoot()
            .Walk(path =>
            {
                if (File.Exists(path))
                {
                    Files.Copy(path, directory.Resolve(testFilesDirectory.Relativize(path)));
                }
                else if (Directory.Exists(path))
                {
                    Directory.CreateDirectory(directory.Resolve(testFilesDirectory.Relativize(path)));
                }
            });
        }
        public async Task TestWriteMetadata_v21Async()
        {
            SystemPath manifestJsonFile =
                Paths.Get(TestResources.GetResource("core/json/v21manifest.json").ToURI());
            V21ManifestTemplate manifestTemplate =
                JsonTemplateMapper.ReadJsonFromFile <V21ManifestTemplate>(manifestJsonFile);
            ImageReference imageReference = ImageReference.Parse("image.reference/project/thing:tag");

            await new CacheStorageWriter(cacheStorageFiles).WriteMetadataAsync(imageReference, manifestTemplate).ConfigureAwait(false);

            SystemPath savedManifestPath =
                cacheRoot.Resolve("images/image.reference/project/thing!tag/manifest.json");

            Assert.IsTrue(Files.Exists(savedManifestPath));

            V21ManifestTemplate savedManifest =
                JsonTemplateMapper.ReadJsonFromFile <V21ManifestTemplate>(savedManifestPath);

            Assert.AreEqual("amd64", savedManifest.GetContainerConfiguration().Get().Architecture);
        }
        public void TestToJson()
        {
            // Loads the expected JSON string.
            SystemPath jsonFile     = Paths.Get(TestResources.GetResource("core/json/loadmanifest.json").ToURI());
            string     expectedJson = Encoding.UTF8.GetString(Files.ReadAllBytes(jsonFile));

            DockerLoadManifestEntryTemplate template = new DockerLoadManifestEntryTemplate();

            template.SetRepoTags(
                ImageReference.Of("testregistry", "testrepo", "testtag").ToStringWithTag());
            template.AddLayerFile("layer1.tar.gz");
            template.AddLayerFile("layer2.tar.gz");
            template.AddLayerFile("layer3.tar.gz");

            List <DockerLoadManifestEntryTemplate> loadManifest = new List <DockerLoadManifestEntryTemplate> {
                template
            };

            Assert.AreEqual(expectedJson, JsonTemplateMapper.ToUtf8String(loadManifest));
        }
Example #27
0
        private async Task Serve200Async()
        {
            threadStarted.Release();
            serverSocket.Start();
            using (var socket = await serverSocket.AcceptTcpClientAsync().ConfigureAwait(false))
            {
                socket.NoDelay = true;

                using (NetworkStream socketStream = socket.GetStream())
                {
                    Stream authorizedStream;
                    if (https)
                    {
                        var              sslStream         = new SslStream(socketStream, true);
                        SystemPath       certFile          = TestResources.GetResource("localhost.2.pfx");
                        X509Certificate2 serverCertificate = new X509Certificate2(certFile, "password");

                        await sslStream.AuthenticateAsServerAsync(serverCertificate, false, false).ConfigureAwait(false);

                        authorizedStream = sslStream;
                    }
                    else
                    {
                        authorizedStream = socket.GetStream();
                    }
                    const string response  = "HTTP/1.1 200 OK\nContent-Length:12\n\nHello World!";
                    var          writeTask = authorizedStream.WriteAsync(Encoding.UTF8.GetBytes(response));

                    using (TextReader reader = new StreamReader(authorizedStream))
                    {
                        string line;
                        while (!string.IsNullOrWhiteSpace(line = await reader.ReadLineAsync().ConfigureAwait(false)))
                        {
                            inputRead.AppendLine(line);
                        }
                        await writeTask.ConfigureAwait(false);
                    }
                }
            }
        }
Example #28
0
        public void TestCopy()
        {
            SystemPath destDir  = temporaryFolder.NewFolder().ToPath();
            SystemPath libraryA =
                Paths.Get(TestResources.GetResource("core/application/dependencies/libraryA.jar").ToURI());
            SystemPath libraryB =
                Paths.Get(TestResources.GetResource("core/application/dependencies/libraryB.jar").ToURI());
            SystemPath dirLayer = Paths.Get(TestResources.GetResource("core/layer").ToURI());

            FileOperations.Copy(ImmutableArray.Create(libraryA, libraryB, dirLayer), destDir);

            AssertFilesEqual(libraryA, destDir.Resolve("libraryA.jar"));
            AssertFilesEqual(libraryB, destDir.Resolve("libraryB.jar"));
            Assert.IsTrue(Files.Exists(destDir.Resolve("layer").Resolve("a").Resolve("b")));
            Assert.IsTrue(Files.Exists(destDir.Resolve("layer").Resolve("c")));
            AssertFilesEqual(
                dirLayer.Resolve("a").Resolve("b").Resolve("bar"),
                destDir.Resolve("layer").Resolve("a").Resolve("b").Resolve("bar"));
            AssertFilesEqual(
                dirLayer.Resolve("c").Resolve("cat"), destDir.Resolve("layer").Resolve("c").Resolve("cat"));
            AssertFilesEqual(dirLayer.Resolve("foo"), destDir.Resolve("layer").Resolve("foo"));
        }
        public void TestToJson()
        {
            // Loads the expected JSON string.
            SystemPath jsonFile     = Paths.Get(TestResources.GetResource("core/json/ocimanifest.json").ToURI());
            string     expectedJson = Encoding.UTF8.GetString(Files.ReadAllBytes(jsonFile));

            // Creates the JSON object to serialize.
            OCIManifestTemplate manifestJson = new OCIManifestTemplate();

            manifestJson.SetContainerConfiguration(
                1000,
                DescriptorDigest.FromDigest(
                    "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad"));

            manifestJson.AddLayer(
                1000_000,
                DescriptorDigest.FromHash(
                    "4945ba5011739b0b98c4a41afe224e417f47c7c99b2ce76830999c9a0861b236"));

            // Serializes the JSON object.
            Assert.AreEqual(expectedJson, JsonTemplateMapper.ToUtf8String(manifestJson));
        }
        public void TestFromJson()
        {
            // Loads the JSON string.
            SystemPath jsonFile = Paths.Get(TestResources.GetResource("core/json/ocimanifest.json").ToURI());

            // Deserializes into a manifest JSON object.
            OCIManifestTemplate manifestJson =
                JsonTemplateMapper.ReadJsonFromFile <OCIManifestTemplate>(jsonFile);

            Assert.AreEqual(
                DescriptorDigest.FromDigest(
                    "sha256:8c662931926fa990b41da3c9f42663a537ccd498130030f9149173a0493832ad"),
                manifestJson.GetContainerConfiguration().Digest);

            Assert.AreEqual(1000, manifestJson.GetContainerConfiguration().Size);

            Assert.AreEqual(
                DescriptorDigest.FromHash(
                    "4945ba5011739b0b98c4a41afe224e417f47c7c99b2ce76830999c9a0861b236"),
                manifestJson.Layers[0].Digest);

            Assert.AreEqual(1000_000, manifestJson.Layers[0].Size);
        }