Example #1
0
        protected static async Task TearDownAsync(params PackageInfo[] packages)
        {
            try
            {
                var builder = new ServiceFabricClientBuilder();
                builder.UseEndpoints(new Uri(TestInfo.Connection));
                var fabricClient = await builder.BuildAsync();

                foreach (var package in packages)
                {
                    await DeleteExistingApplicationAsync(fabricClient, package.AppId);
                    await RemoveApplicationTypeAsync(fabricClient, package.AppTypeName);
                }
            }
            catch (Exception)
            {
                // Ignore
            }
            finally
            {
                foreach (var package in packages)
                {
                    Directory.Delete(package.TempDir, true);
                }
            }
        }
        protected override void ProcessRecord()
        {
            PartitionSchemeDescription partitionSchemeDescription;
            ServiceDescription         serviceDescription;
            var client = new ServiceFabricClientBuilder().ConnectAsync(ClusterEndPoint, ThumbPrint).Result;

            if (PartitionSchemeUniformInt64)
            {
                partitionSchemeDescription = new UniformInt64RangePartitionSchemeDescription(PartitionCount, LowKey.ToString(), HighKey.ToString());
            }
            else if (PartitionSchemeNamed)
            {
                partitionSchemeDescription = new NamedPartitionSchemeDescription(PartitionCount, PartitionNames);
            }
            else
            {
                partitionSchemeDescription = new SingletonPartitionSchemeDescription();
            }

            if (Stateless.IsPresent)
            {
                serviceDescription = new StatelessServiceDescription(new ServiceName(ServiceName), ServiceType, partitionSchemeDescription, InstanceCount, initializationData: InitializationData);
            }
            else
            {
                serviceDescription = new StatefulServiceDescription(new ServiceName(ServiceName), ServiceType, partitionSchemeDescription, TargetReplicaSetSize, MinReplicaSetSize, PersistedState, initializationData: InitializationData);
            }

            client.Services.CreateServiceAsync(ApplicationId, serviceDescription).Wait();
        }
Example #3
0
        /// <summary>
        /// Creates and initializes a new instance of the <see cref="ServiceFabricHttpClient"/> class.
        /// </summary>
        /// <param name="builder">Builder isntance to create ServiceFabricHttpClient from.</param>
        /// <param name="cancellationToken">A cancellation token to cancel the async operation.</param>
        /// <returns><see cref="ServiceFabricHttpClient"/> instance.</returns>
        internal static async Task <IServiceFabricClient> CreateAsync(
            ServiceFabricClientBuilder builder,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            var obj = new ServiceFabricHttpClient(builder);
            await obj.InitializeAsync(cancellationToken);

            return(obj);
        }
        public static Task <IServiceFabricClient> BuildAsyncDirect(this ServiceFabricClientBuilder serviceFabricClientBuilder)
        {
            object[] parameters = new object[2]
            {
                serviceFabricClientBuilder,
                default(CancellationToken)
            };

            return((Task <IServiceFabricClient>) typeof(ServiceFabricHttpClient).GetMethod("CreateAsync", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, parameters));
        }
Example #5
0
 private void AppendSecurity(ServiceFabricClientBuilder builder, Manifest manifest)
 {
     if (!string.IsNullOrWhiteSpace(manifest.ClusterDetails.FindByValue))
     {
         builder.UseX509Security(_ =>
         {
             var certificate    = FindCertificate(manifest.ClusterDetails);
             var remoteSettings = new RemoteX509SecuritySettings(
                 new List <string>(new[] { certificate.Thumbprint }));
             var settings = new X509SecuritySettings(certificate, remoteSettings);
             return(Task.FromResult <SecuritySettings>(settings));
         });
     }
 }
Example #6
0
        public async Task <IServiceFabricClient> BuildAsync(Manifest manifest)
        {
            try
            {
                var builder = new ServiceFabricClientBuilder();
                AppendSecurity(builder, manifest);
                AppendClusterEndpoint(builder, manifest);
                return(await builder.BuildAsync());
            }
            catch (Exception error)
            {
                _logger.Log(new LogMessage(StageTypes.Preparation, error.Message, LogLevelTypes.Error));
            }

            return(null);
        }
Example #7
0
        /// <summary>
        /// Configure IServiceFabricClientBuilder to create IServiceFabricClient implementation which communicates with Service Fabric cluster via the REST http gateway using the provided HttpClientHandler and DelegatingHandlers.
        /// </summary>
        /// <param name="builder">Builder </param>
        /// <param name="innerHandler">The inner handler which is responsible for processing the HTTP response messages. When null or not provided, <see cref="System.Net.Http.HttpClientHandler"/> will be used as last handler in channel.</param>
        /// <param name="delegateHandlers">An ordered list of <see cref="System.Net.Http.DelegatingHandler"/> instances to be invoked in HTTP message channel as message flows to and from the last handler in the channel.</param>
        /// <returns>IServiceFabricClientBuilder instance.</returns>
        public static ServiceFabricClientBuilder ConfigureHttpClientSettings(
            this ServiceFabricClientBuilder builder,
            HttpClientHandler innerHandler,
            params DelegatingHandler[] delegateHandlers)
        {
            if (innerHandler == null)
            {
                throw new ArgumentNullException(nameof(innerHandler));
            }

            if (delegateHandlers.Any(handler => handler == null))
            {
                throw new ArgumentException(SR.ErrorNullDelegateHandler);
            }

            builder.Container[typeof(HttpClientHandler)]   = innerHandler;
            builder.Container[typeof(DelegatingHandler[])] = delegateHandlers;
            return(builder);
        }
Example #8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceFabricHttpClient"/> class.
        /// </summary>
        /// <param name="builder">Builder isntance to create ServiceFabricHttpClient from.</param>
        private ServiceFabricHttpClient(ServiceFabricClientBuilder builder)
            : base(builder.Endpoints, builder.SecuritySettings, builder.ClientSettings)
        {
            this.CreateManagementClients();

            // Validate when Security Settings is null, url can't be https
            if (this.SecuritySettingsFunc == null)
            {
                var scheme = Uri.UriSchemeHttp;
                var invalidClusterEndpoint = this.ClusterEndpoints.FirstOrDefault(url => !string.Equals(url.Scheme, scheme, StringComparison.OrdinalIgnoreCase));

                if (invalidClusterEndpoint != null)
                {
                    throw new InvalidOperationException(string.Format(SR.ErrorUrlScheme, invalidClusterEndpoint.Scheme, scheme));
                }
            }
            else
            {
                // Url validation for secured cluster will be done after SecuritySettings is invoked in Initialize, it can be https only for Claims and X509.
            }

            var seed = (int)DateTime.Now.Ticks;

            this.randomizedEndpoints = new RandomizedList <Uri>(this.ClusterEndpoints, new Random(seed));
            this.ClientId            = Guid.NewGuid().ToString();

            // Get information from DI container in ServiceFabricClientBuilder
            this.innerHandler = new HttpClientHandler();
            if (builder.Container.ContainsKey(typeof(HttpClientHandler)))
            {
                this.innerHandler = (HttpClientHandler)builder.Container[typeof(HttpClientHandler)];
            }

            if (builder.Container.ContainsKey(typeof(DelegatingHandler[])))
            {
                this.delegateHandlers = (DelegatingHandler[])builder.Container[typeof(DelegatingHandler[])];
            }

            this.refreshSecuritySettingsFunc = this.SecuritySettingsFunc;
            this.httpClientHandlerWrapper    = new HttpClientHandlerWrapper(this.innerHandler);
            this.ClientTypeHeaderValue       = Constants.ClientlibClientTypeHeaderValue;
        }
        public async Task Init()
        {
            Process.Start(new ProcessStartInfo {
                FileName = "dotnet", Arguments = "publish", WorkingDirectory = basePath
            }).WaitForExit();
            var client = new ServiceFabricClientBuilder().UseEndpoints(new Uri("http://localhost:19080")).BuildAsync().Result;
            var apps   = await client.Applications.GetApplicationInfoListAsync();

            foreach (var app in apps.Data)
            {
                await client.Applications.DeleteApplicationAsync(app.Id);
            }

            var apptypes = await client.ApplicationTypes.GetApplicationTypeInfoListAsync();

            foreach (var type in apptypes.Data)
            {
                await client.ApplicationTypes.UnprovisionApplicationTypeAsync(type.Name, new UnprovisionApplicationTypeDescriptionInfo(type.Version));
            }
        }
        public static Task <IServiceFabricClient> ConnectAsync(this ServiceFabricClientBuilder serviceFabricClientBuilder, string ClusterEndPoint, string ThumbPrint, StoreLocation storeLocation = StoreLocation.CurrentUser)
        {
            var builder = serviceFabricClientBuilder.UseEndpoints(new Uri(ClusterEndPoint));

            if (!string.IsNullOrWhiteSpace(ThumbPrint))
            {
                Func <CancellationToken, Task <SecuritySettings> > GetSecurityCredentials = (ct) =>
                {
                    var store = new X509Store(StoreName.My, storeLocation);
                    store.Open(OpenFlags.ReadOnly);
                    var clientCert             = store.Certificates.Find(X509FindType.FindByThumbprint, ThumbPrint, false)[0];
                    var remoteSecuritySettings = new RemoteX509SecuritySettings(new List <string> {
                        ThumbPrint
                    });
                    return(Task.FromResult <SecuritySettings>(new X509SecuritySettings(clientCert, remoteSecuritySettings)));
                };

                builder = builder.UseX509Security(GetSecurityCredentials);
            }

            builder.ClientSettings.ClientTimeout = TimeSpan.FromMinutes(15);

            return(builder.BuildAsyncDirect());
        }
Example #11
0
 private static void AppendClusterEndpoint(ServiceFabricClientBuilder builder, Manifest manifest)
 {
     builder.UseEndpoints(new Uri(manifest.ClusterDetails.Connection));
 }
Example #12
0
 internal static ServiceFabricClientBuilder AddClientTypeIdentity(
     this ServiceFabricClientBuilder builder,
     string clientType)
 {
     return(builder);
 }
Example #13
0
        /// <inheritdoc />
        protected override void ProcessRecordInternal()
        {
            if (this.ConnectionEndpoint == null)
            {
                if (!this.TryConfiguringDefaultConnect())
                {
                    throw new InvalidOperationException("Cluster Connection Information is not provided. Please try connecting again with correct connection information.");
                }
            }

            // Create Builder
            var builder = new ServiceFabricClientBuilder()
                          .UseEndpoints(this.ConnectionEndpoint.Select(e => new Uri(e)).ToArray());

            // Configure Security for builder
            if (this.WindowsCredential.IsPresent)
            {
                builder.UseWindowsSecurity();
            }
            else if (this.X509Credential.IsPresent)
            {
                var remoteX509SecuritySettings = this.GetServerX509SecuritySettings();
                Func <CancellationToken, Task <SecuritySettings> > securitySettings;

                if (this.ClientCertificate == null)
                {
                    var clientCert = CredentialsUtil.GetCertificate(this.StoreLocation, this.StoreName, this.FindValue, this.FindType);

                    if (clientCert == null)
                    {
                        throw new PSInvalidOperationException(Resource.ErrorLoadingClientCertificate);
                    }

                    securitySettings = (ct) => Task.FromResult <SecuritySettings>(new X509SecuritySettings(clientCert, remoteX509SecuritySettings));
                }
                else
                {
                    securitySettings = (ct) => Task.FromResult <SecuritySettings>(new X509SecuritySettings(this.ClientCertificate, remoteX509SecuritySettings));
                }

                builder.UseX509Security(securitySettings);
            }
            else if (this.AzureActiveDirectory.IsPresent)
            {
                var remoteX509SecuritySettings = this.GetServerX509SecuritySettings();
                Func <CancellationToken, Task <SecuritySettings> > securitySettings;

                if (this.GetMetadata.IsPresent)
                {
                    securitySettings = (ct) => Task.FromResult <SecuritySettings>(new AzureActiveDirectorySecuritySettings("DummyTokenToGetMetadata", remoteX509SecuritySettings));
                }
                else
                {
                    if (this.SecurityToken != null)
                    {
                        securitySettings = (ct) => Task.FromResult <SecuritySettings>(new AzureActiveDirectorySecuritySettings(this.SecurityToken, remoteX509SecuritySettings));
                    }
                    else
                    {
                        securitySettings = (ct) => Task.FromResult <SecuritySettings>(new AzureActiveDirectorySecuritySettings(CredentialsUtil.GetAccessTokenAsync, remoteX509SecuritySettings));
                    }
                }

                builder.UseAzureActiveDirectorySecurity(securitySettings);
            }
            else if (this.DSTS.IsPresent)
            {
                var remoteX509SecuritySettings = this.GetServerX509SecuritySettings();
                Func <CancellationToken, Task <SecuritySettings> > securitySettings =
                    (ct) => Task.FromResult <SecuritySettings>(new DstsClaimsSecuritySettings(CredentialsUtil.GetAccessTokenDstsAsync, remoteX509SecuritySettings));

                builder.UseClaimsSecurity(securitySettings);
            }

            // build the client
            var client = builder.BuildAsync(cancellationToken: this.CancellationToken).GetAwaiter().GetResult() as ServiceFabricHttpClient;

            // set the client type for Telemetry on HttpGateway.
            client.ClientTypeHeaderValue = Constants.PowershellClientTypeHeaderValue;

            if (this.GetMetadata.IsPresent)
            {
                var aadMetadata = client.Cluster.GetAadMetadataAsync(cancellationToken: this.CancellationToken).GetAwaiter().GetResult().Metadata;
                var result      = new PSObject();

                result.Properties.Add(new PSNoteProperty(nameof(aadMetadata.Authority), aadMetadata.Authority));
                result.Properties.Add(new PSNoteProperty(nameof(aadMetadata.Client), aadMetadata.Client));
                result.Properties.Add(new PSNoteProperty(nameof(aadMetadata.Cluster), aadMetadata.Cluster));
                result.Properties.Add(new PSNoteProperty(nameof(aadMetadata.Login), aadMetadata.Login));
                result.Properties.Add(new PSNoteProperty(nameof(aadMetadata.Redirect), aadMetadata.Redirect));
                result.Properties.Add(new PSNoteProperty(nameof(aadMetadata.Tenant), aadMetadata.Tenant));

                this.WriteObject(result);
            }
            else
            {
                client.Cluster.GetClusterManifestAsync(cancellationToken: this.CancellationToken).GetAwaiter().GetResult();
                Console.WriteLine(Resource.MsgConnectSuccess);
                this.SetClusterConnection(client);
            }
        }