Example #1
0
        /// <summary>
        /// Tries to read the tags for a repository with the given credentials.
        /// If authentication failed, returns null.
        /// If any other error occured, throws an exception.
        /// </summary>
        public async Task <Tuple <string, HttpStatusCode, string> > ListTags(RegistryCredential cred, string repoName, string queryString)
        {
            try
            {
                string             endpoint = $"/v2/{repoName}/tags/list{queryString}";
                HttpRequestMessage message  = new HttpRequestMessage(HttpMethod.Get,
                                                                     new Uri(new Uri("https://" + cred.Registry), endpoint));

                message.Headers.Authorization = new AuthenticationHeaderValue("Basic", cred.BasicAuth);

                var resp = await client.SendAsync(message);

                if (resp.StatusCode == HttpStatusCode.Unauthorized)
                {
                    return(null);
                }

                return(Tuple.Create(await resp.Content.ReadAsStringAsync(), resp.StatusCode,
                                    resp.Headers.Contains("Link") ? resp.Headers.GetValues("Link").First() : null));
            }
            catch (HttpRequestException)
            {
                return(null);
            }
        }
Example #2
0
        public async Task <IActionResult> Get()
        {
            RegistryCredential cred = GetDockerCredential();

            if (cred == null)
            {
                return(new UnauthorizedResult());
            }

            if (cred.Registry == null)
            {
                return(new UnauthorizedResult());
            }

            if (!cred.Registry.Contains("."))
            {
                return(new UnauthorizedResult());
            }

            if (await _service.TestCredentials(cred.Registry, cred.BasicAuth))
            {
                return(new OkResult());
            }

            return(new UnauthorizedResult());
        }
Example #3
0
        /// <summary>
        /// Reads a manifest.
        /// </summary>
        public async Task <Tuple <string, HttpStatusCode> > Manifest(RegistryCredential cred, string repo, string tag)
        {
            try
            {
                HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Get,
                                                                    new Uri(new Uri("https://" + cred.Registry), $"/v2/{repo}/manifests/{tag}"));

                message.Headers.Authorization = new AuthenticationHeaderValue("Basic", cred.BasicAuth);
                message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(
                                               "application/vnd.docker.distribution.manifest.v1+json", 0.5));
                message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(
                                               "application/vnd.docker.distribution.manifest.v2+json", 0.6));

                var resp = await client.SendAsync(message);

                if (resp.StatusCode == HttpStatusCode.Unauthorized)
                {
                    return(null);
                }

                return(Tuple.Create(await resp.Content.ReadAsStringAsync(), resp.StatusCode));
            }
            catch (HttpRequestException)
            {
                return(null);
            }
        }
Example #4
0
        public async Task <IActionResult> Catalog([FromQuery(Name = "n")] int n = 10, [FromQuery(Name = "last")] string last = "")
        {
            RegistryCredential cred = GetDockerCredential();

            if (cred == null)
            {
                return(new UnauthorizedResult());
            }

            var base64EncodedBytes = System.Convert.FromBase64String(cred.BasicAuth);
            var decodedAuth        = System.Text.Encoding.UTF8.GetString(base64EncodedBytes);

            var user     = decodedAuth.Split(":")[0];
            var password = decodedAuth.Split(":")[1];

            int timeoutInMilliseconds = 1500000;
            CancellationToken ct      = new CancellationTokenSource(timeoutInMilliseconds).Token;
            var client = LoginBasic(ct, user, password, cred.Registry);

            try
            {
                var repositories = await client.GetRepositoriesAsync(last, n);

                var jsonString = JsonConvert.SerializeObject(repositories);
                if (repositories.Names != null && repositories.Names.Count > 0)
                {
                    var lastRepo   = repositories.Names[repositories.Names.Count - 1];
                    var linkHeader = $"</v2/_catalog?last={last}&n={n}&orderby=>; rel=\"next\"";
                    Response.Headers.Add("Link", linkHeader);
                }
                return(new ContentResult()
                {
                    Content = jsonString,
                    ContentType = "application/json",
                    StatusCode = 200
                });
            }
            catch (AcrErrorsException e)
            {
                return(new ContentResult()
                {
                    Content = e.Response.Content,
                    ContentType = "application/json",
                    StatusCode = (int)e.Response.StatusCode
                });
            }
        }
        /// <inheritdoc/>
        protected override void ProcessRecordInternal()
        {
            var registryCredential = new RegistryCredential(
                registryUserName: this.RegistryUserName,
                registryPassword: this.RegistryPassword,
                passwordEncrypted: this.PasswordEncrypted);

            var monitoringPolicyDescription = new MonitoringPolicyDescription(
                failureAction: this.FailureAction,
                healthCheckWaitDurationInMilliseconds: this.HealthCheckWaitDurationInMilliseconds,
                healthCheckStableDurationInMilliseconds: this.HealthCheckStableDurationInMilliseconds,
                healthCheckRetryTimeoutInMilliseconds: this.HealthCheckRetryTimeoutInMilliseconds,
                upgradeTimeoutInMilliseconds: this.UpgradeTimeoutInMilliseconds,
                upgradeDomainTimeoutInMilliseconds: this.UpgradeDomainTimeoutInMilliseconds);

            var serviceTypeHealthPolicy = new ServiceTypeHealthPolicy(
                maxPercentUnhealthyPartitionsPerService: this.MaxPercentUnhealthyPartitionsPerService,
                maxPercentUnhealthyReplicasPerPartition: this.MaxPercentUnhealthyReplicasPerPartition,
                maxPercentUnhealthyServices: this.MaxPercentUnhealthyServices);

            var applicationHealthPolicy = new ApplicationHealthPolicy(
                considerWarningAsError: this.ConsiderWarningAsError,
                maxPercentUnhealthyDeployedApplications: this.MaxPercentUnhealthyDeployedApplications,
                defaultServiceTypeHealthPolicy: serviceTypeHealthPolicy,
                serviceTypeHealthPolicyMap: this.ServiceTypeHealthPolicyMap);

            var composeDeploymentUpgradeDescription = new ComposeDeploymentUpgradeDescription(
                deploymentName: this.DeploymentName,
                composeFileContent: this.ComposeFileContent,
                upgradeKind: this.UpgradeKind,
                registryCredential: registryCredential,
                rollingUpgradeMode: this.RollingUpgradeMode,
                upgradeReplicaSetCheckTimeoutInSeconds: this.UpgradeReplicaSetCheckTimeoutInSeconds,
                forceRestart: this.ForceRestart,
                monitoringPolicy: monitoringPolicyDescription,
                applicationHealthPolicy: applicationHealthPolicy);

            this.ServiceFabricClient.ComposeDeployments.StartComposeDeploymentUpgradeAsync(
                deploymentName: this.DeploymentName,
                composeDeploymentUpgradeDescription: composeDeploymentUpgradeDescription,
                serverTimeout: this.ServerTimeout,
                cancellationToken: this.CancellationToken).GetAwaiter().GetResult();

            Console.WriteLine("Success!");
        }
Example #6
0
        public async Task <IActionResult> VerifyCredential()
        {
            RegistryCredential cred = GetDockerCredential();

            if (cred == null)
            {
                return(new UnauthorizedResult());
            }

            if (cred.Registry == null)
            {
                return(new UnauthorizedResult());
            }

            if (!cred.Registry.Contains("."))
            {
                return(new UnauthorizedResult());
            }

            var base64EncodedBytes = System.Convert.FromBase64String(cred.BasicAuth);
            var decodedAuth        = System.Text.Encoding.UTF8.GetString(base64EncodedBytes);

            var user     = decodedAuth.Split(":")[0];
            var password = decodedAuth.Split(":")[1];

            int timeoutInMilliseconds = 1500000;
            CancellationToken ct      = new CancellationTokenSource(timeoutInMilliseconds).Token;
            var client = LoginBasic(ct, user, password, cred.Registry);

            try
            {
                await client.GetDockerRegistryV2SupportAsync();

                return(new OkResult());
            }
            catch (AcrErrorsException e)
            {
                return(new ContentResult()
                {
                    Content = e.Response.Content,
                    ContentType = "application/json",
                    StatusCode = (int)e.Response.StatusCode
                });
            }
        }
Example #7
0
        /// <inheritdoc/>
        protected override void ProcessRecordInternal()
        {
            var registryCredential = new RegistryCredential(
                registryUserName: this.RegistryUserName,
                registryPassword: this.RegistryPassword,
                passwordEncrypted: this.PasswordEncrypted);

            var createComposeDeploymentDescription = new CreateComposeDeploymentDescription(
                deploymentName: this.DeploymentName,
                composeFileContent: this.ComposeFileContent,
                registryCredential: registryCredential);

            this.ServiceFabricClient.ComposeDeployments.CreateComposeDeploymentAsync(
                createComposeDeploymentDescription: createComposeDeploymentDescription,
                serverTimeout: this.ServerTimeout,
                cancellationToken: this.CancellationToken).GetAwaiter().GetResult();

            Console.WriteLine("Success!");
        }
Example #8
0
        public async Task <IActionResult> Manifest(string repo, string tag)
        {
            RegistryCredential cred = GetDockerCredential();

            if (cred == null)
            {
                return(new UnauthorizedResult());
            }

            var base64EncodedBytes = System.Convert.FromBase64String(cred.BasicAuth);
            var decodedAuth        = System.Text.Encoding.UTF8.GetString(base64EncodedBytes);

            var user     = decodedAuth.Split(":")[0];
            var password = decodedAuth.Split(":")[1];

            int timeoutInMilliseconds = 1500000;
            CancellationToken ct      = new CancellationTokenSource(timeoutInMilliseconds).Token;
            var client = LoginBasic(ct, user, password, cred.Registry);

            try
            {
                var acceptString = MediaTypeHelper.ManifestAcceptMediaTypes;
                var manifest     = await client.GetManifestAsync(repo, tag, acceptString);

                var jsonString = JsonConvert.SerializeObject(manifest);

                return(new ContentResult()
                {
                    Content = jsonString,
                    ContentType = "application/json",
                    StatusCode = 200
                });
            }
            catch (AcrErrorsException e)
            {
                return(new ContentResult()
                {
                    Content = e.Response.Content,
                    ContentType = "application/json",
                    StatusCode = (int)e.Response.StatusCode
                });
            }
        }
Example #9
0
        /// <summary>
        /// Serializes the object to JSON.
        /// </summary>
        /// <param name="writer">The <see cref="T: Newtonsoft.Json.JsonWriter" /> to write to.</param>
        /// <param name="obj">The object to serialize to JSON.</param>
        internal static void Serialize(JsonWriter writer, RegistryCredential obj)
        {
            // Required properties are always serialized, optional properties are serialized when not null.
            writer.WriteStartObject();
            if (obj.RegistryUserName != null)
            {
                writer.WriteProperty(obj.RegistryUserName, "RegistryUserName", JsonWriterExtensions.WriteStringValue);
            }

            if (obj.RegistryPassword != null)
            {
                writer.WriteProperty(obj.RegistryPassword, "RegistryPassword", JsonWriterExtensions.WriteStringValue);
            }

            if (obj.PasswordEncrypted != null)
            {
                writer.WriteProperty(obj.PasswordEncrypted, "PasswordEncrypted", JsonWriterExtensions.WriteBoolValue);
            }

            writer.WriteEndObject();
        }