コード例 #1
0
        static async Task CallSvcThatUsesReliableCollection()
        {
            var def = new PointDefinition()
            {
                HostTitle = "host2", // this points to host 2 where a different interfaces are exposed
                Binding = new NetTcpBinding(),
                Interfaces = new List<Type>() { typeof(ISomeWcfInterface) }
            };


            FabricClient fc = new FabricClient(); //local cluster

            var resolvedPartitions = await fc.ServiceManager.ResolveServicePartitionAsync(new Uri(FabricServiceName), "P1");
            var ep = resolvedPartitions.Endpoints.SingleOrDefault((endpoint) => endpoint.Role == ServiceEndpointRole.StatefulPrimary);
            var uri = ep.Address; 

            Console.WriteLine(string.Format("working on {0} host", def.HostTitle    ));
                string result;
                
                var channelFactory =
                            new ChannelFactory<ISomeWcfInterface>(new NetTcpBinding(), new EndpointAddress(string.Concat(uri, def.HostTitle, "/", typeof(ISomeWcfInterface).ToString())));

                // data interface 
                var channel = channelFactory.CreateChannel();
                result = channel.SayHello(parameter);
                Console.WriteLine(string.Format("opeartion {0} on interface {1} called with {2} returned {3}", "SayHello", "ISomeWcfInterface", parameter, result));

                var Count = channel.GetHello();
                Console.WriteLine(string.Format("opeartion {0} on interface {1} called with {2} returned {3}", "GetHello", "ISomeWcfInterface", parameter, result));

                ((IClientChannel)channel).Close(); // be kind rewind. 

            }
コード例 #2
0
ファイル: Program.cs プロジェクト: jstuparitz/PizzaShop
        static async Task RunFailoverTestScenarioAsync(string clusterConnection, Uri serviceName)
        {
            TimeSpan maxServiceStabilizationTimeout = TimeSpan.FromSeconds(180);
            PartitionSelector randomPartitionSelector = PartitionSelector.RandomOf(serviceName);

            // Create FabricClient with connection & security information here.
            FabricClient fabricClient = new FabricClient(clusterConnection);

            // The Chaos Test Scenario should run at least 60 minutes or up until it fails.
            TimeSpan timeToRun = TimeSpan.FromMinutes(60);
            FailoverTestScenarioParameters scenarioParameters = new FailoverTestScenarioParameters(
              randomPartitionSelector,
              timeToRun,
              maxServiceStabilizationTimeout);

            // Other related parameters:
            // Pause between two iterations for a random duration bound by this value.
            // scenarioParameters.WaitTimeBetweenIterations = TimeSpan.FromSeconds(30);
            // Pause between concurrent actions for a random duration bound by this value.
            // scenarioParameters.WaitTimeBetweenFaults = TimeSpan.FromSeconds(10);

            // Create the scenario class and execute it asynchronously.
            FailoverTestScenario chaosScenario = new FailoverTestScenario(fabricClient, scenarioParameters);

            try
            {
                await chaosScenario.ExecuteAsync(CancellationToken.None);
            }
            catch (AggregateException ae)
            {
                throw ae.InnerException;
            }
        }
コード例 #3
0
        protected override async Task RunAsync(CancellationToken cancellationToken)
        {
            var activationContext = await FabricRuntime.GetActivationContextAsync(Timeout.InfiniteTimeSpan, cancellationToken);

            var consulServerServiceUri = new Uri($"{activationContext.ApplicationName}/ConsulServer");
            if (cancellationToken.IsCancellationRequested)
                return;

            using (var client = new FabricClient(FabricClientRole.User))
            {
                long? handlerId = null;
                try
                {
                    handlerId = client.ServiceManager.RegisterServicePartitionResolutionChangeHandler(consulServerServiceUri, PartitionResolutionChange);

                    while (true)
                    {
                        if (cancellationToken.IsCancellationRequested)
                            return;
                        await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
                    }
                }
                finally
                {
                    if (handlerId.HasValue)
                        client.ServiceManager.UnregisterServicePartitionResolutionChangeHandler(handlerId.Value);
                }
            }
        }
コード例 #4
0
 private async Task<string[]> GetInstanceEndpoints(string fabricAddress)
 {
     var fabClient = new FabricClient();
     //Get the endpoint for the service
     var serviceEndpoint = await fabClient.ServiceManager.ResolveServicePartitionAsync(new Uri(fabricAddress));
     var addressesDeserialized = serviceEndpoint.Endpoints.Select(x => JsonConvert.DeserializeObject<EndpointServiceFabricModel>(x.Address));
     var simpleEndpoints = addressesDeserialized.SelectMany(x => x.Endpoints.Values);
     return simpleEndpoints.ToArray();
 }
コード例 #5
0
ファイル: Resolver.cs プロジェクト: stuartleeks/blanky
        public Resolver(FabricClient fabClient, ILoggerFactory loggerFactory)
        {
            this.fabClient = fabClient;
            this.logger = loggerFactory.CreateLogger("Service Resolver");

            PopulateServiceCache();

            cacheUpdateTimer = new System.Timers.Timer(TimeSpan.FromSeconds(CACHE_REFRESH_TIME_SECONDS).TotalMilliseconds);
            cacheUpdateTimer.Elapsed += CacheUpdateTimer_UpdateServiceCache;
        }
コード例 #6
0
        public static async Task<string> GetManagementApiEndPointAsync(string FabricEndPoint, string sMgmtAppInstanceName)
        {
            FabricClient fc = new FabricClient(FabricEndPoint);
            ResolvedServicePartition partition = await fc.ServiceManager.ResolveServicePartitionAsync(new Uri(sMgmtAppInstanceName));

            var jsonAddress = JObject.Parse(partition.GetEndpoint().Address);
            var address = (string) jsonAddress["Endpoints"][""];

            return address;
        }
        static DefaultController()
        {
            serviceUri = new Uri(FabricRuntime.GetActivationContext().ApplicationName + "/WordCountService");

            backoffQueryDelay = TimeSpan.FromSeconds(3);

            fabricClient = new FabricClient();

            communicationFactory = new HttpCommunicationClientFactory(new ServicePartitionResolver(() => fabricClient));
        }
コード例 #8
0
ファイル: Startup.cs プロジェクト: stuartleeks/blanky
        public void ConfigureDebugServices(IServiceCollection services)
        {
            var clientName = System.Net.Dns.GetHostName();
            var client = new FabricClient(new FabricClientSettings
            {
                ClientFriendlyName = clientName,
                ConnectionInitializationTimeout = TimeSpan.FromSeconds(3),
                KeepAliveInterval = TimeSpan.FromSeconds(15),
            }, "localhost:19000");

            client.ClientConnected += Client_ClientConnected;
            client.ClientDisconnected += Client_ClientDisconnected;


            services.AddLogging();
            services.AddSingleton<FabricClient>(client);
            services.AddSingleton<Resolver>();
        }
コード例 #9
0
        public void Open()
        {
            string serverUrl = "http://localhost:5001/iot";

            CancellationTokenSource webApiCancellationSource = new CancellationTokenSource();
            FabricClient fabricClient = new FabricClient();

            this.webHost = new WebHostBuilder().UseKestrel()
                .ConfigureServices(
                    services => services
                        .AddSingleton<FabricClient>(fabricClient)
                        .AddSingleton<CancellationTokenSource>(webApiCancellationSource))
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .UseUrls(serverUrl)
                .Build();

            this.webHost.Run();
        }
        public async Task<IEnumerable<string>> AllocateAsync(EventHubClient eventHubClient, FabricClient fabricClient)
        {
            var runtimeInformation = await eventHubClient.GetRuntimeInformationAsync();
            var eventHubPartitions = runtimeInformation.PartitionIds.OrderBy(p => p).ToArray();
            var serviceFabricPartitions = (await fabricClient.QueryManager.GetPartitionListAsync(_serviceName))
                                           .Select(p => p.PartitionInformation.Id.ToString())
                                           .OrderBy(p => p).ToArray();

            // when there are more service fabric partitions then eventhub partitions, 
            // just assign them one by one and the remainder of the partitions will stay dormant

            if (serviceFabricPartitions.Length >= eventHubPartitions.Length)
            {
                var index = Array.IndexOf(serviceFabricPartitions, _partitionId.ToString());

                return new [] { eventHubPartitions[index] };
            }
            else
            {
                // otherwise distribute eventhub partitions evenly across service fabric partitions

                var remainder = eventHubPartitions.Length % serviceFabricPartitions.Length;
                var numberOfEventHubPartitionsPerServiceFabricPartition = eventHubPartitions.Length / serviceFabricPartitions.Length;
                if (remainder > 0)  numberOfEventHubPartitionsPerServiceFabricPartition++;
                var index = Array.IndexOf(serviceFabricPartitions, _partitionId.ToString());

                var allocated = new List<string>();
                for (var i = 0; i < numberOfEventHubPartitionsPerServiceFabricPartition; i++)
                {
                    var idx = (index*numberOfEventHubPartitionsPerServiceFabricPartition) + i;
                    if (eventHubPartitions.Length >= idx)
                    {
                        allocated.Add(eventHubPartitions[idx]);
                    }
                }

                return allocated.ToArray();
            }
        }
        public FabricHealthReporter(string entityIdentifier, HealthState problemHealthState = HealthState.Warning)
        {
            if (string.IsNullOrWhiteSpace(entityIdentifier))
            {
                throw new ArgumentException("entityIdentifier cannot be null or empty", "entityIdentifier");
            }
            this.entityIdentifier = entityIdentifier;

            this.problemHealthState = problemHealthState;

            this.fabricClient = new FabricClient(
                new FabricClientSettings()
                {
                    HealthReportSendInterval = TimeSpan.FromSeconds(5)
                }
                );

            CodePackageActivationContext activationContext = FabricRuntime.GetActivationContext();
            this.applicatioName = new Uri(activationContext.ApplicationName);
            this.serviceManifestName = activationContext.GetServiceManifestName();
            NodeContext nodeContext = FabricRuntime.GetNodeContext();
            this.nodeName = nodeContext.NodeName;
        }
        private async Task<bool> BackupCallbackAsync(BackupInfo backupInfo)
        {
            string backupId = Guid.NewGuid().ToString();


            long totalBackupCount;


            IReliableDictionary<int, long> countDictionary = await this.StateManager.GetOrAddAsync<IReliableDictionary<int, long>>(this.countDictionaryName);
            using (ITransaction txn = this.StateManager.CreateTransaction())
            {
                long count = await countDictionary.AddOrUpdateAsync(txn, 0, 0, (key, oldValue) => { return oldValue + 1; });

                totalBackupCount = count;
                await txn.CommitAsync();
            }

            ServiceEventSource.Current.ServiceMessage(this, "Backup count dictionary updated: " + totalBackupCount);
            ServiceEventSource.Current.Message("Backup count dictionary updated: " + totalBackupCount);

            if ((totalBackupCount%20) == 0)
            {
                //The following limits the number of backups stored to 20 per partition. The actual max might be more than 20 per partition since more backups 
                //could have been created when deletion was taking place. 
                //Also depending on the backup that was restored, the count of backups could be a lot larger.
                this.DeleteBackups(Path.Combine(this.localBackupStore, this.ServicePartition.PartitionInfo.Id.ToString()), 5);
            }

            //Simulate a restore/data loss event randomly. This assumes that all partitions have some state at this point. 
            //Five inventory items must be added for all five partitions to have state.
            if ((totalBackupCount > 19) && (DateTime.Now.Second%20) == 0)
            {
                CancellationToken cancellationToken = default(CancellationToken);

                ServiceEventSource.Current.ServiceMessage(this, "Restore Started");

                using (FabricClient fabricClient = new FabricClient())
                {
                    PartitionSelector partitionSelector = PartitionSelector.PartitionIdOf(
                        this.ServiceInitializationParameters.ServiceName,
                        this.ServiceInitializationParameters.PartitionId);

                    await fabricClient.ServiceManager.InvokeDataLossAsync(partitionSelector, DataLossMode.PartialDataLoss, cancellationToken);
                }
            }

            await
                this.CopyBackupFolderAsync(backupInfo.Directory, this.ServicePartition.PartitionInfo.Id.ToString(), backupId, CancellationToken.None);

            return true;
        }
コード例 #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ObserverManagerController"/> class.
 /// </summary>
 /// <param name="serviceContext">service context.</param>
 /// <param name="fabricClient">FabricClient instance.</param>
 public ObserverManagerController(StatelessServiceContext serviceContext, FabricClient fabricClient)
 {
     this.serviceContext = serviceContext;
     this.fabricClient   = fabricClient;
 }
        private async Task<string[]> getOrderedServicePartitionIds()
        {
            FabricClient fabricClient = new FabricClient();
            ServicePartitionList PartitionList = await fabricClient.QueryManager.GetPartitionListAsync(this.m_InitParams.ServiceName);

            List<string> partitions = new List<string>();

            foreach (Partition p in PartitionList)
            {
                partitions.Add(p.PartitionInformation.Id.ToString());
            }


            return partitions.OrderBy(s => s).ToArray();
        }
コード例 #15
0
 public WebService(StatelessServiceContext context)
     : base(context)
 {
     this.fabricClient = new FabricClient();
 }
コード例 #16
0
 public void ConfigureServices(IServiceCollection services, FabricClient fabricClient, StatelessServiceContext context)
 {
     services.AddScoped(typeof(ObserverBase), s => new SampleNewObserver(fabricClient, context));
 }
コード例 #17
0
        /// <summary>
        /// Initializes a new instance of the reporting type and 
        /// </summary>
        /// <param name="traceId">A unique identifier used to correlate the debugging and diagnostics messages</param>
        /// <param name="logger">An instance used to write debugging and diagnostics information</param>
        /// <param name="componentName">The name of the component for debugging and diagnostics messages</param>
        /// <param name="reportSourceId">A unique id used to represent the source of the health report</param>
        /// <param name="reportCallback">A method to be called when the health data is required</param>
        /// <param name="context">The service fabric context that is assocaited with the entity being reported on</param>
        /// <param name="reportType">The entity type the health report is for</param>
        /// <param name="reportingInterval">How often the report will be sent</param>
        /// <param name="batchInterval">The amount of time to delay before sending for batching purposes, 0 for immediate</param>
        /// <param name="timeout">The timeout for sending a report</param>
        /// <param name="retryInterval">The amount of time to wait before trying to resend a report</param>
        public HealthReporter(Guid traceId, ILogger logger, string componentName, string reportSourceId, ReportGenerator reportCallback, ServiceContext context, ReportTypes reportType, TimeSpan? reportingInterval = null, TimeSpan? batchInterval = null, TimeSpan? timeout = null, TimeSpan? retryInterval = null)
        {
            if (string.IsNullOrEmpty(reportSourceId)) throw new ArgumentException("Parameter cannot be null or empty.", nameof(reportSourceId));
            if (reportCallback == null) throw new ArgumentNullException(nameof(reportCallback));

            this.logger = logger;
            this.componentName = componentName;
            this.logger.Informational(traceId, this.componentName, "Instantiated health reporter");


            this.reportSourceId = reportSourceId;
            this.reportType = reportType;
            this.reportCallback = reportCallback;

            this.client = new FabricClient(new FabricClientSettings
            {
                HealthReportRetrySendInterval = retryInterval ?? TimeSpan.FromSeconds(40),
                HealthReportSendInterval = batchInterval ?? TimeSpan.FromSeconds(0),
                HealthOperationTimeout = timeout ?? TimeSpan.FromSeconds(120)
            });
            
            this.context = context;

            this.interval = reportingInterval ?? TimeSpan.FromSeconds(30);
            if (this.interval < TimeSpan.FromSeconds(5)) this.interval = TimeSpan.FromSeconds(15);

            this.timeToLive = TimeSpan.FromSeconds((this.interval.TotalSeconds * 2.0) + 1.0);
        }
コード例 #18
0
 public TenantsController(FabricClient fabricClient, ServiceCancellation serviceCancellation)
 {
     this.fabricClient = fabricClient;
     this.serviceCancellationToken = serviceCancellation.Token;
 }
コード例 #19
0
 public void SetUp()
 {
     vSessContain = new FabricSessionContainer();
     FabricClient.InitOnce(GetConfig());
 }
コード例 #20
0
 public void TearDown()
 {
     FabricClient.ResetInitialization();
 }
コード例 #21
0
 public GrpcController(IReliableStateManager manager, FabricClient fabricClient, StatefulServiceContext context)
 {
     _manager = manager;
     _client  = fabricClient;
     _context = context;
 }
コード例 #22
0
 internal ServiceGroupManagementClient(FabricClient fabricClient, NativeClient.IFabricServiceGroupManagementClient4 nativeServiceGroupClient)
 {
     this.fabricClient             = fabricClient;
     this.nativeServiceGroupClient = nativeServiceGroupClient;
 }
コード例 #23
0
 public SFBase(FabricClient fabricClient)
 {
     _fabricClient = fabricClient;
 }
コード例 #24
0
 public StatefulBackendServiceController(StatelessServiceContext serviceContext, HttpClient httpClient, FabricClient fabricClient, ConfigSettings settings)
 {
     this.serviceContext = serviceContext;
     this.httpClient     = httpClient;
     this.configSettings = settings;
     this.fabricClient   = fabricClient;
 }
コード例 #25
0
 public HealthMonitor(String sourceId, FabricClient fabricClient)
 {
     SourceId       = sourceId;
     m_fabricClient = fabricClient;
 }
        protected override async Task RunAsync(CancellationToken runAsyncCancellationToken)
        {
            // This is to keep track of exceptions in the validation step at the end of
            // each iteration of the ChaosTestScenario that is being used under the cover 
            //
            bool validationExceptionCaught = false;

            IReliableDictionary<string, CurrentState> chaosServiceState =
                await this.StateManager.GetOrAddAsync<IReliableDictionary<string, CurrentState>>(StringResource.ChaosServiceStateKey);

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                if (!await chaosServiceState.ContainsKeyAsync(tx, StringResource.ChaosServiceStateKey, LockMode.Update))
                {
                    await chaosServiceState.AddAsync(tx, StringResource.ChaosServiceStateKey, CurrentState.Stopped);
                }
                await tx.CommitAsync();
            }


            while (!runAsyncCancellationToken.IsCancellationRequested)
            {
                try
                {
                    // check to see if we're in a "stop" or "start" state.
                    // this continues to poll until we're in a "start" state.
                    // a ReliableDictionary is used to store this information so that if the service
                    //   fails over to another node, the state is preserved and the chaos test will continue to execute.
                    using (ITransaction tx = this.StateManager.CreateTransaction())
                    {
                        ConditionalValue<CurrentState> currentStateResult =
                            await chaosServiceState.TryGetValueAsync(tx, StringResource.ChaosServiceStateKey);

                        if (currentStateResult.HasValue &&
                            (currentStateResult.Value == CurrentState.Stopped ||
                             currentStateResult.Value == CurrentState.None))
                        {
                            await Task.Delay(Constants.IntervalBetweenLoopIteration, runAsyncCancellationToken);
                            continue;
                        }
                    }

                    // this section runs the actual chaos test.
                    // the cancellation token source is linked to the token provided to RunAsync so that we
                    //   can stop the test if the service needs to shut down.
                    using (FabricClient fabricClient = new FabricClient())
                    {
                        using (this.stopEventTokenSource = CancellationTokenSource.CreateLinkedTokenSource(runAsyncCancellationToken))
                        {
                            // when a validation exception is caught, this waits for a while to let the cluster stabilize before continuing.
                            if (validationExceptionCaught)
                            {
                                await Task.Delay(ChaosTestConfigSettings.MaxClusterStabilizationTimeout, this.stopEventTokenSource.Token);
                                validationExceptionCaught = false;
                            }

                            ChaosTestScenarioParameters chaosScenarioParameters =
                                new ChaosTestScenarioParameters(
                                    ChaosTestConfigSettings.MaxClusterStabilizationTimeout,
                                    ChaosTestConfigSettings.MaxConcurrentFaults,
                                    ChaosTestConfigSettings.EnableMoveReplicaFaults,
                                    TimeSpan.MaxValue)
                                {
                                    WaitTimeBetweenFaults =
                                        ChaosTestConfigSettings.WaitTimeBetweenFaults,
                                    WaitTimeBetweenIterations =
                                        ChaosTestConfigSettings.WaitTimeBetweenIterations
                                };

                            ChaosTestScenario chaosTestScenario = new ChaosTestScenario(fabricClient, chaosScenarioParameters);

                            // capture progress events so we can report them back
                            chaosTestScenario.ProgressChanged += this.TestScenarioProgressChanged;

                            // this continuously runs the chaos test until the CancellationToken is signaled.
                            await chaosTestScenario.ExecuteAsync(this.stopEventTokenSource.Token);
                        }
                    }
                }
                catch (TimeoutException e)
                {
                    string message = $"Caught TimeoutException '{e.Message}'. Will wait for cluster to stabilize before continuing test";
                    ServiceEventSource.Current.ServiceMessage(this, message);
                    validationExceptionCaught = true;
                    await this.StoreEventAsync(message);
                }
                catch (FabricValidationException e)
                {
                    string message = $"Caught FabricValidationException '{e.Message}'. Will wait for cluster to stabilize before continuing test";
                    ServiceEventSource.Current.ServiceMessage(this, message);
                    validationExceptionCaught = true;
                    await this.StoreEventAsync(message);
                }
                catch (OperationCanceledException)
                {
                    if (runAsyncCancellationToken.IsCancellationRequested)
                    {
                        // if RunAsync is canceled then we need to quit.
                        throw;
                    }

                    ServiceEventSource.Current.ServiceMessage(
                        this,
                        "Caught OperationCanceledException Exception during test execution. This is expected if test was stopped");
                }
                catch (AggregateException e)
                {
                    if (e.InnerException is OperationCanceledException)
                    {
                        if (runAsyncCancellationToken.IsCancellationRequested)
                        {
                            // if RunAsync is canceled then we need to quit.
                            throw;
                        }

                        ServiceEventSource.Current.ServiceMessage(
                            this,
                            "Caught OperationCanceledException Exception during test execution. This is expected if test was stopped");
                    }
                    else
                    {
                        string message = $"Caught unexpected Exception during test excecution {e.InnerException}";
                        ServiceEventSource.Current.ServiceMessage(this, message);
                        await this.StoreEventAsync(message);
                    }
                }
                catch (Exception e)
                {
                    string message = $"Caught unexpected Exception during test excecution {e}";
                    ServiceEventSource.Current.ServiceMessage(this, message);
                    await this.StoreEventAsync(message);
                }
            }
        }
コード例 #27
0
        public void NewClient_SingleConfig_Default()
        {
            var fab = new FabricClient();

            checkClient(fab, TestConfigKey);
        }
コード例 #28
0
        // using manual resolution
        static async Task doStuffUsingStandardResolve()
        {
            
            FabricClient fc = new FabricClient(); //local cluster

            var resolvedPartitions = await fc.ServiceManager.ResolveServicePartitionAsync(new Uri(FabricServiceName), "P1");
            var ep = resolvedPartitions.Endpoints.SingleOrDefault((endpoint) => endpoint.Role == ServiceEndpointRole.StatefulPrimary);
            var uri = ep.Address;
            foreach (var host in hosts)
            {
                Console.WriteLine(string.Format("working on {0} host", host));
                string result; 
                var channelFactory =
                            new ChannelFactory<SvcInterface1>(new NetTcpBinding(), new EndpointAddress(string.Concat(uri, host, "/" , typeof(SvcInterface1).ToString())));

                // data interface 
                var channel = channelFactory.CreateChannel();
                result = channel.SvcInterface1Op1(parameter);
                Console.WriteLine(string.Format("opeartion {0} on interface {1} called with {2} returned {3}", "SvcInterface1Op1", "SvcInterface1", parameter, result));

                result = channel.SvcInterface1Op2(parameter);
                Console.WriteLine(string.Format("opeartion {0} on interface {1} called with {2} returned {3}", "SvcInterface1Op2", "SvcInterface1", parameter, result));

                ((IClientChannel)channel).Close(); // be kind rewind. 


                var channelFactory2 =
                            new ChannelFactory<SvcInterface2>(new NetTcpBinding(), new EndpointAddress(string.Concat(uri, host, "/", typeof(SvcInterface2).ToString())));

                var channel2 = channelFactory2.CreateChannel();

                result = channel2.SvcInterface2Op1(parameter);
                Console.WriteLine(string.Format("opeartion {0} on interface {1} called with {2} returned {3}", "SvcInterface2Op1", "SvcInterface2", parameter, result));

                result = channel2.SvcInterface2Op2(parameter);
                Console.WriteLine(string.Format("opeartion {0} on interface {1} called with {2} returned {3}", "SvcInterface2Op2", "SvcInterface2", parameter, result));


                ((IClientChannel)channel2).Close(); // be kind rewind. 
            }



        }
コード例 #29
0
 public TenantsController(FabricClient fabricClient, ServiceCancellation serviceCancellation)
 {
     this.fabricClient             = fabricClient;
     this.serviceCancellationToken = serviceCancellation.Token;
 }
コード例 #30
0
 private Program(Options options)
 {
     _options = options;
     _fabricClient = new FabricClient();
 }
コード例 #31
0
 /// <summary>
 /// Constructor for RepairManager helper
 /// </summary>
 /// <param name="fabricClient"></param>
 /// <param name="context"></param>
 internal RepairManagerHelper(FabricClient fabricClient, ServiceContext context)
 {
     this.fabricClient = fabricClient;
     this.context      = context;
 }
コード例 #32
0
 public ClusterNotifier(FabricClient fabricClient, HttpClient httpClient, IBigBrother bb)
 {
     HttpClient   = httpClient;
     _bb          = bb;
     QueryManager = new QueryManagerWrapper(fabricClient);
 }
コード例 #33
0
 /// <summary>
 /// Constructor for Command Processor
 /// </summary>
 /// <param name="fabricClient">Fabric client object used for carrying out service fabric client requests</param>
 /// <param name="serviceEventSource">Eventsource used for logging</param>
 public CommandProcessor(FabricClient fabricClient, IPatchOrchestrationEvents serviceEventSource)
 {
     this.fabricClient            = fabricClient;
     ServiceEventSource.Current   = serviceEventSource;
     this.cancellationTokenSource = new CancellationTokenSource();
 }
コード例 #34
0
 public FabricClientWrapper()
 {
     FabricClient = new FabricClient();
 }
コード例 #35
0
ファイル: generator.cs プロジェクト: mega-hackfest/mycode
        private async Task <SprocAddressStruct> GetOrCreateSproServiceInstanceAsync(string messageSessionType, string messageUserName)
        {
            var urlPath = $"SPROC_{messageSessionType}_{messageUserName}";

            var url          = new ServiceUriBuilder(urlPath).ToUri();
            var fabricClient = new FabricClient();

            ServiceDescription service = null;

            try
            {
                service = await fabricClient.ServiceManager.GetServiceDescriptionAsync(url);
            }
            catch (Exception ex)
            {
                // nothing to do -> exception mean no service with the requested namename
                service = null;
            }
            if (service == null)
            {
                StatelessServiceDescription newGeneratorDescription = new StatelessServiceDescription()
                {
                    ApplicationName            = new Uri(this.Context.CodePackageActivationContext.ApplicationName),
                    ServiceName                = url,
                    InstanceCount              = 1,
                    ServiceTypeName            = "com.mega.SproGuestExeType",
                    PartitionSchemeDescription = new SingletonPartitionSchemeDescription()
                };

                await fabricClient.ServiceManager.CreateServiceAsync(newGeneratorDescription).ConfigureAwait(false);

                service = await fabricClient.ServiceManager.GetServiceDescriptionAsync(url);


                var healthState = HealthState.Unknown;
                var count       = 0;
                while (healthState != HealthState.Ok)
                {
                    if (count++ >= 10)
                    {
                        throw new TimeoutException("Time out waiting for " + url);
                    }

                    var serviceList = await fabricClient.QueryManager.GetServiceListAsync(new Uri(this.Context.CodePackageActivationContext.ApplicationName));

                    healthState = serviceList.Single(services => services.ServiceName == url).HealthState;

                    if (healthState != HealthState.Ok)
                    {
                        await Task.Delay(TimeSpan.FromSeconds(2));
                    }
                }
            }

            ServicePartitionResolver resolver  = ServicePartitionResolver.GetDefault();
            ResolvedServicePartition partition = await resolver.ResolveAsync(service.ServiceName,
                                                                             new ServicePartitionKey(), CancellationToken.None);

            var s = partition.Endpoints.First();
            // s.Address == {"Endpoints":{"com.mega.SproGuestExeTypeEndpoint":"localhost:33039"}}

            // HACK : exytraction fqdn : should using json deserialization instead of this bad hack
            int start = s.Address.IndexOf(":\"") + 2;
            int stop  = s.Address.IndexOf("\"", start);
            var fqdn  = s.Address.Substring(start, stop - start);

            var parts = fqdn.Split(':');

            return(new SprocAddressStruct {
                ServiceName = service.ServiceName, Ip = parts[0], Port = Convert.ToInt32(parts[1])
            });
        }
コード例 #36
0
 public ChessFabrickController(HttpClient httpClient, StatelessServiceContext context, FabricClient fabricClient)
 {
     this.fabricClient = fabricClient;
     this.httpClient   = httpClient;
     this.context      = context;
     this.proxyFactory = new ServiceProxyFactory((c) =>
     {
         return(new FabricTransportServiceRemotingClientFactory());
     });
     this.chessStatefulUri = new Uri($"{context.CodePackageActivationContext.ApplicationName}/ChessFabrickStateful");
     this.playerServiceUri = new Uri($"{context.CodePackageActivationContext.ApplicationName}/ChessFabrickPlayersStateful");
 }
 public ReliableCollectionController(FabricClient fabricClient, HttpClient httpClient)
 {
     _fabricClient = fabricClient;
     _httpClient   = httpClient;
 }
コード例 #38
0
 /// <summary>
 /// Static WatchdogService constructor.
 /// </summary>
 static WatchdogService()
 {
     _client = CreateFabricClient();
 }
コード例 #39
0
        /// <summary>
        /// Allows this controller, which is recreated and destroyed for each call,
        /// to access the contexts it needs to control the behavior wanted.
        /// </summary>
        public RoomController(StatelessServiceContext serviceContext, HttpClient httpClient, FabricClient fabricClient, ConfigSettings settings)
        {
            this.serviceContext = serviceContext;
            this.httpClient     = httpClient;
            this.configSettings = settings;
            this.fabricClient   = fabricClient;

            this.RenewProxy();
        }
コード例 #40
0
ファイル: ServiceDiscovery.cs プロジェクト: Azure/RingMaster
 /// <summary>
 /// Initializes a new instance of the <see cref="ServiceDiscovery"/> class.
 /// </summary>
 /// <param name="fabricClient">Fabric client object</param>
 public ServiceDiscovery(FabricClient fabricClient = null)
 {
     this.fabricClient = fabricClient ?? new FabricClient();
 }
        private FabricClient GetClient(string cluster)
        {
            FabricClient client = this.fabricClients.Get(cluster) as FabricClient;

            if (client == null)
            {
                string clientName = Environment.GetEnvironmentVariable("COMPUTERNAME");
                if (string.IsNullOrWhiteSpace(clientName))
                {
                    try
                    {
                        clientName = System.Net.Dns.GetHostName();
                    }
                    catch (System.Net.Sockets.SocketException)
                    {
                        clientName = "";
                    }
                }

                clientName = clientName + "_" + this.serviceParameters.ReplicaId.ToString();

                client = new FabricClient(
                    new FabricClientSettings
                    {
                        ClientFriendlyName = clientName,
                        ConnectionInitializationTimeout = TimeSpan.FromSeconds(30),
                        KeepAliveInterval = TimeSpan.FromSeconds(15),
                    },
                    cluster);

                this.fabricClients.Add(
                    new CacheItem(cluster, client),
                    new CacheItemPolicy()
                    {
                        SlidingExpiration = this.cacheSlidingExpiration,
                        RemovedCallback = args =>
                        {
                            IDisposable fc = args.CacheItem.Value as IDisposable;
                            if (fc != null)
                            {
                                try
                                {
                                    fc.Dispose();
                                }
                                catch
                                {
                                }
                            }
                        }
                    });
            }

            return client;
        }
コード例 #42
0
        private static void Main(string[] args)
        {
            Console.WriteLine("Enter IoT Hub connection string: ");
            connectionString = Console.ReadLine();

            Console.WriteLine("Enter Service Fabric cluster address where your IoT project is deployed (or blank for local): ");
            clusterAddress = Console.ReadLine();

            registryManager = RegistryManager.CreateFromConnectionString(connectionString);
            fabricClient = String.IsNullOrEmpty(clusterAddress)
                ? new FabricClient()
                : new FabricClient(clusterAddress);

            Task.Run(
                async () =>
                {
                    while (true)
                    {
                        try
                        {
                            devices = await registryManager.GetDevicesAsync(Int32.MaxValue);
                            tenants = (await fabricClient.QueryManager.GetApplicationListAsync())
                                .Where(x => x.ApplicationTypeName == Names.TenantApplicationTypeName)
                                .Select(x => x.ApplicationName.ToString().Replace(Names.TenantApplicationNamePrefix + "/", ""));

                            Console.WriteLine();
                            Console.WriteLine("Devices IDs: ");
                            foreach (Device device in devices)
                            {
                                Console.WriteLine(device.Id);
                            }

                            Console.WriteLine();
                            Console.WriteLine("Tenants: ");
                            foreach (string tenant in tenants)
                            {
                                Console.WriteLine(tenant);
                            }

                            Console.WriteLine();
                            Console.WriteLine("Commands:");
                            Console.WriteLine("1: Register a device");
                            Console.WriteLine("2: Register random devices");
                            Console.WriteLine("3: Send data from a device");
                            Console.WriteLine("4: Send data from all devices");
                            Console.WriteLine("5: Exit");

                            string command = Console.ReadLine();

                            switch (command)
                            {
                                case "1":
                                    Console.WriteLine("Make up a device ID: ");
                                    string deviceId = Console.ReadLine();
                                    await AddDeviceAsync(deviceId);
                                    break;
                                case "2":
                                    Console.WriteLine("How many devices? ");
                                    int num = Int32.Parse(Console.ReadLine());
                                    await AddRandomDevicesAsync(num);
                                    break;
                                case "3":
                                    Console.WriteLine("Tenant: ");
                                    string tenant = Console.ReadLine();
                                    Console.WriteLine("Device id: ");
                                    string deviceKey = Console.ReadLine();
                                    await SendDeviceToCloudMessagesAsync(deviceKey, tenant);
                                    break;
                                case "4":
                                    Console.WriteLine("Tenant: ");
                                    string tenantName = Console.ReadLine();
                                    Console.WriteLine("Iterations: ");
                                    int iterations = Int32.Parse(Console.ReadLine());
                                    await SendAllDevices(tenantName, iterations);
                                    break;
                                case "5":
                                    return;
                                default:
                                    break;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Oops, {0}", ex.Message);
                        }
                    }
                })
                .GetAwaiter().GetResult();
        }
コード例 #43
0
 private void PartitionResolutionChange(FabricClient source, long handlerId, ServicePartitionResolutionChange args)
 {
     if (args.HasException)
         return;
     var ac = FabricRuntime.GetActivationContext();
     var node = FabricRuntime.GetNodeContext();
     var sb = new StringBuilder($"{this.ServiceInitializationParameters.ServiceName}@{node.NodeName} PartitionResolutionChange");
     var i = 0;
     foreach (var endpoint in args.Result.Endpoints)
     {
         sb.AppendFormat($" {++i} {endpoint.Role} ");
         var json = JObject.Parse(endpoint.Address);
         var endpoints = (JObject)json["Endpoints"];
         foreach (var ep in endpoints)
             sb.Append($"{ep.Key}:{ep.Value} ");
     }
     eventSource.Message(sb.ToString());
 }
        private async Task<bool> BackupCallbackAzureAsync(BackupInfo backupInfo)
        {
            string backupId = Guid.NewGuid().ToString();
            CancellationToken cancellationToken = default(CancellationToken);

            long totalBackupCount;


            IReliableDictionary<int, long> countDictionary = await this.StateManager.GetOrAddAsync<IReliableDictionary<int, long>>(this.countDictionaryName);
            using (ITransaction txn = this.StateManager.CreateTransaction())
            {
                long count = await countDictionary.AddOrUpdateAsync(txn, 0, 0, (key, oldValue) => { return oldValue + 1; });

                totalBackupCount = count;
                await txn.CommitAsync();
            }


            ServiceEventSource.Current.Message("Backup count dictionary updated: " + totalBackupCount);


            if ((totalBackupCount%10) == 0)
            {
                //Store no more than 10 backups at a time - the actual max might be a bit more than 10 since more backups could have been created when deletion was taking place. Keeps behind 5 backups.
                await this.backupStore.DeleteBackupsAzureAsync(cancellationToken);
            }

            if ((totalBackupCount > 10) && (DateTime.Now.Second%20) == 0)
            {
                //Let's simulate a data loss every time the time is a multiple of 20 seconds, and a backup just completed.
                ServiceEventSource.Current.ServiceMessage(this, "Restore Started");

                using (FabricClient fabricClient = new FabricClient())
                {
                    PartitionSelector partitionSelector = PartitionSelector.PartitionIdOf(
                        this.ServiceInitializationParameters.ServiceName,
                        this.ServiceInitializationParameters.PartitionId);

                    await fabricClient.ServiceManager.InvokeDataLossAsync(partitionSelector, DataLossMode.PartialDataLoss, cancellationToken);
                }
            }

            ServiceEventSource.Current.Message("Backing up from directory, ID  : " + backupInfo.Directory + " *** " + backupId);
            try
            {
                await this.backupStore.UploadBackupFolderAsync(backupInfo.Directory, backupId, CancellationToken.None);
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.ServiceMessage(this, "Uploading to backup folder failed: " + "{0} {1}" + e.GetType() + e.Message);
            }

            return true;
        }
コード例 #45
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FabricObserverWeb"/> class.
 /// </summary>
 /// <param name="context">service context.</param>
 public FabricObserverWeb(StatelessServiceContext context)
     : base(context)
 {
     this.fabricClient = new FabricClient();
 }
 public EventHubListenerOptions(string currentPartitionId, Uri serviceName, FabricClient fabricClient = null) : this(currentPartitionId) 
 {
     mServiceName  = serviceName;
     mFabricClient = null == fabricClient ? new FabricClient() : fabricClient;
 }
コード例 #47
0
 public ServiceClient(FabricClient fabricClient)
 {
     fabricClient.ThrowIfNull(nameof(fabricClient));
     this.fabricClient = fabricClient;
 }
コード例 #48
0
        /// <summary>
        /// Sends a health report in using a service fabric client for immediate transmission (no batching)
        /// </summary>
        /// <param name="report">The health report to send</param>
        /// <param name="batchDelay">The maximum amount of time to wait before sending in an effort to batch transmission</param>
        /// <param name="timeout">The time to wait before considering the send as timed out</param>
        /// <param name="retryInterval">The amount of time to wait before sending the report again on failure</param>
        public static void SubmitHealthReport(HealthReport report, TimeSpan? batchDelay = null, TimeSpan? timeout = null, TimeSpan? retryInterval = null)
        {
            var client = new FabricClient(new FabricClientSettings
            {
                HealthReportSendInterval = batchDelay ?? TimeSpan.FromSeconds(0),
                HealthOperationTimeout = timeout ?? TimeSpan.FromSeconds(15),
                HealthReportRetrySendInterval = retryInterval ?? TimeSpan.FromSeconds(50)
            });

            client.HealthManager.ReportHealth(report);
        }
コード例 #49
0
 public FabricHelper(FabricClient fabricClient)
 {
     _fabricClient = fabricClient;
 }
コード例 #50
0
 public DevicesController(FabricClient fabricClient, HttpClient httpClient, ServiceCancellation serviceCancellation)
 {
     this.fabricClient = fabricClient;
     this.httpClient = httpClient;
     this.serviceCancellationToken = serviceCancellation.Token;
 }
コード例 #51
0
        /// <summary>
        /// Creates Repair task for a node with executor set as Patch Orchestration Service
        /// </summary>
        /// <param name="fc">Fabric client object used for carrying out service fabric client requests</param>
        /// <param name="nodeName">Node name for which repair task needs to be created</param>
        /// <param name="taskDescription">Description of repair task which needs to be created</param>
        /// <param name="resultDetails">Result details for the completed operation to make the repair task verbose</param>
        /// <param name="executorData">Executor data associated with the repair task</param>
        /// <param name="timeout">Timeout for the async operation</param>
        /// <param name="cancellationToken">The cancellation token to cancel the async operation</param>
        /// <returns>A Task representing the asnyc operation, result of task would be <see cref="NodeAgentSfUtilityExitCodes"/></returns>
        internal static async Task <NodeAgentSfUtilityExitCodes> CreateRepairTaskForNode(FabricClient fc, string nodeName,
                                                                                         string taskDescription, string resultDetails, ExecutorDataForRmTask executorData, TimeSpan timeout,
                                                                                         CancellationToken cancellationToken)
        {
            string            taskIdPrefix = string.Format("{0}_{1}", TaskIdPrefix, nodeName);
            string            taskId       = string.Format("{0}_{1}", taskIdPrefix, Guid.NewGuid());
            ClusterRepairTask repairTask   = new ClusterRepairTask(taskId, RepairAction);

            repairTask.Description   = taskDescription;
            repairTask.State         = RepairTaskState.Claimed;
            repairTask.Executor      = ExecutorName;
            repairTask.ExecutorData  = SerializationUtility.Serialize(executorData);
            repairTask.Target        = new NodeRepairTargetDescription(nodeName);
            repairTask.ResultDetails = resultDetails;

            try
            {
                await fc.RepairManager.CreateRepairTaskAsync(repairTask, timeout, cancellationToken);

                return(NodeAgentSfUtilityExitCodes.Success);
            }
            catch (Exception e)
            {
                ServiceEventSource.Current.ErrorMessage(
                    String.Format("RepairManagerHelper.CreateRepairTaskForNode failed. Exception details {0}", e));
                if (e is FabricTransientException)
                {
                    return(NodeAgentSfUtilityExitCodes.RetryableException);
                }
                else
                {
                    return(NodeAgentSfUtilityExitCodes.Failure);
                }
            }
        }
        protected override async Task RunAsync(CancellationToken runAsyncCancellationToken)
        {
            // This is to keep track of exceptions in the validation step at the end of
            // each iteration of the ChaosTestScenario that is being used under the cover
            //
            bool validationExceptionCaught = false;

            IReliableDictionary <string, CurrentState> chaosServiceState =
                await this.StateManager.GetOrAddAsync <IReliableDictionary <string, CurrentState> >(StringResource.ChaosServiceStateKey);

            using (ITransaction tx = this.StateManager.CreateTransaction())
            {
                if (!await chaosServiceState.ContainsKeyAsync(tx, StringResource.ChaosServiceStateKey, LockMode.Update))
                {
                    await chaosServiceState.AddAsync(tx, StringResource.ChaosServiceStateKey, CurrentState.Stopped);
                }
                await tx.CommitAsync();
            }


            while (!runAsyncCancellationToken.IsCancellationRequested)
            {
                try
                {
                    // check to see if we're in a "stop" or "start" state.
                    // this continues to poll until we're in a "start" state.
                    // a ReliableDictionary is used to store this information so that if the service
                    //   fails over to another node, the state is preserved and the chaos test will continue to execute.
                    using (ITransaction tx = this.StateManager.CreateTransaction())
                    {
                        ConditionalValue <CurrentState> currentStateResult =
                            await chaosServiceState.TryGetValueAsync(tx, StringResource.ChaosServiceStateKey);

                        if (currentStateResult.HasValue &&
                            (currentStateResult.Value == CurrentState.Stopped ||
                             currentStateResult.Value == CurrentState.None))
                        {
                            await Task.Delay(Constants.IntervalBetweenLoopIteration, runAsyncCancellationToken);

                            continue;
                        }
                    }

                    // this section runs the actual chaos test.
                    // the cancellation token source is linked to the token provided to RunAsync so that we
                    //   can stop the test if the service needs to shut down.
                    using (FabricClient fabricClient = new FabricClient())
                    {
                        using (this.stopEventTokenSource = CancellationTokenSource.CreateLinkedTokenSource(runAsyncCancellationToken))
                        {
                            // when a validation exception is caught, this waits for a while to let the cluster stabilize before continuing.
                            if (validationExceptionCaught)
                            {
                                await Task.Delay(ChaosTestConfigSettings.MaxClusterStabilizationTimeout, this.stopEventTokenSource.Token);

                                validationExceptionCaught = false;
                            }

                            ChaosTestScenarioParameters chaosScenarioParameters =
                                new ChaosTestScenarioParameters(
                                    ChaosTestConfigSettings.MaxClusterStabilizationTimeout,
                                    ChaosTestConfigSettings.MaxConcurrentFaults,
                                    ChaosTestConfigSettings.EnableMoveReplicaFaults,
                                    TimeSpan.MaxValue)
                            {
                                WaitTimeBetweenFaults =
                                    ChaosTestConfigSettings.WaitTimeBetweenFaults,
                                WaitTimeBetweenIterations =
                                    ChaosTestConfigSettings.WaitTimeBetweenIterations
                            };

                            ChaosTestScenario chaosTestScenario = new ChaosTestScenario(fabricClient, chaosScenarioParameters);

                            // capture progress events so we can report them back
                            chaosTestScenario.ProgressChanged += this.TestScenarioProgressChanged;

                            // this continuously runs the chaos test until the CancellationToken is signaled.
                            await chaosTestScenario.ExecuteAsync(this.stopEventTokenSource.Token);
                        }
                    }
                }
                catch (TimeoutException e)
                {
                    string message = $"Caught TimeoutException '{e.Message}'. Will wait for cluster to stabilize before continuing test";
                    ServiceEventSource.Current.ServiceMessage(this, message);
                    validationExceptionCaught = true;
                    await this.StoreEventAsync(message);
                }
                catch (FabricValidationException e)
                {
                    string message = $"Caught FabricValidationException '{e.Message}'. Will wait for cluster to stabilize before continuing test";
                    ServiceEventSource.Current.ServiceMessage(this, message);
                    validationExceptionCaught = true;
                    await this.StoreEventAsync(message);
                }
                catch (OperationCanceledException)
                {
                    if (runAsyncCancellationToken.IsCancellationRequested)
                    {
                        // if RunAsync is canceled then we need to quit.
                        throw;
                    }

                    ServiceEventSource.Current.ServiceMessage(
                        this,
                        "Caught OperationCanceledException Exception during test execution. This is expected if test was stopped");
                }
                catch (AggregateException e)
                {
                    if (e.InnerException is OperationCanceledException)
                    {
                        if (runAsyncCancellationToken.IsCancellationRequested)
                        {
                            // if RunAsync is canceled then we need to quit.
                            throw;
                        }

                        ServiceEventSource.Current.ServiceMessage(
                            this,
                            "Caught OperationCanceledException Exception during test execution. This is expected if test was stopped");
                    }
                    else
                    {
                        string message = $"Caught unexpected Exception during test excecution {e.InnerException}";
                        ServiceEventSource.Current.ServiceMessage(this, message);
                        await this.StoreEventAsync(message);
                    }
                }
                catch (Exception e)
                {
                    string message = $"Caught unexpected Exception during test excecution {e}";
                    ServiceEventSource.Current.ServiceMessage(this, message);
                    await this.StoreEventAsync(message);
                }
            }
        }
コード例 #53
0
        public async Task <Dictionary <String, List <List <String> > > > GetApplicationsServices(FabricClient primaryfc, String primarycs, FabricClient secondaryfc, String secondarycs)
        {
            Dictionary <String, List <List <String> > > applicationsServicesMap = new Dictionary <String, List <List <String> > >();

            FabricClient.QueryClient queryClient = primaryfc.QueryManager;
            ApplicationList          appsList    = await queryClient.GetApplicationListAsync();

            HashSet <String> configuredApplications = await GetConfiguredApplications(primarycs, secondarycs);

            HashSet <String> configuredServices = await GetConfiguredServices();

            HashSet <String> secServices = new HashSet <string>();

            foreach (Application application in appsList)
            {
                string applicationName   = application.ApplicationName.ToString();
                string applicationStatus = "NotConfigured";

                ServiceList services = await primaryfc.QueryManager.GetServiceListAsync(new Uri(applicationName));

                ServiceList secondaryServices;

                try
                {
                    secondaryServices = await secondaryfc.QueryManager.GetServiceListAsync(new Uri(applicationName));

                    foreach (Service service in secondaryServices)
                    {
                        secServices.Add(service.ServiceName.ToString());
                    }
                }
                catch (System.Fabric.FabricElementNotFoundException e)
                {
                    ServiceEventSource.Current.Message("Web Service: Could not find application on secondary cluster: {0}", e);
                    applicationStatus = "NotExist";
                }
                catch (Exception e)
                {
                    ServiceEventSource.Current.Message("Web Service: Exception with Fabric Client Query Manager {0}", e);
                    throw;
                }

                if (configuredApplications.Contains(applicationName))
                {
                    applicationStatus = "Configured";
                }

                List <List <String> > serviceList   = new List <List <String> >();
                List <String>         appStatusList = new List <String>();

                appStatusList.Add(applicationName);
                appStatusList.Add(applicationStatus);

                serviceList.Add(appStatusList);

                foreach (Service service in services)
                {
                    List <String> serviceInfo = new List <String>();
                    string        serviceName = service.ServiceName.ToString();

                    if (secServices.Contains(serviceName))
                    {
                        if (configuredServices.Contains(serviceName))
                        {
                            //Configured
                            serviceInfo.Add(serviceName);
                            serviceInfo.Add("Configured");
                        }
                        else if (service.ServiceKind == ServiceKind.Stateless)
                        {
                            //Stateless
                            serviceInfo.Add(serviceName);
                            serviceInfo.Add("Stateless");
                        }
                        else
                        {
                            //NotConfigured
                            serviceInfo.Add(serviceName);
                            serviceInfo.Add("NotConfigured");
                        }
                    }
                    else
                    {
                        //NotExist
                        serviceInfo.Add(serviceName);
                        serviceInfo.Add("NotExist");
                    }


                    serviceList.Add(serviceInfo);
                }

                applicationsServicesMap.Add(applicationName, serviceList);
            }


            return(applicationsServicesMap);
        }
コード例 #54
0
ファイル: Startup.cs プロジェクト: stuartleeks/blanky
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            ILoggerFactory loggerFactory,
            Resolver resolver,
            FabricClient fabClient)
        {
            app.Map("/list/services", subApp =>
            {
                subApp.Run(async h =>
                {
                    var services = await resolver.ListAvailableServices();
                    var jsonResponse = JsonConvert.SerializeObject(services, Formatting.Indented);
                    await h.Response.WriteAsync(jsonResponse);
                });
            });

            app.Map("/list/usage", subApp =>
            {
                subApp.Run(async h =>
                {
                    if (ServiceRouter.RedisConnection == null)
                    {
                        ServiceRouter.RedisConnection = ConnectionMultiplexer.Connect(await resolver.ResolveEndpoint(Constants.RedisServiceAddress));
                    }

                    IDatabase redisDb = ServiceRouter.RedisConnection.GetDatabase();

                    var services = await resolver.ListAvailableServices();
                    var usageStats = new Dictionary<string, long>();
                    foreach (var service in services)
                    {
                        var hitCount = await redisDb.ListLengthAsync($"/{service.ApplicationName}/{service.ServiceName}");
                        usageStats.Add(service.FabricAddress.ToString(), hitCount);
                    }
                    var jsonResponse = JsonConvert.SerializeObject(usageStats, Formatting.Indented);
                    await h.Response.WriteAsync(jsonResponse);
                });
            });

            app.Map("/list/endpoints", subApp =>
            {
                subApp.Run(async h =>
                {
                    var services = await resolver.ListServiceEndpoints();
                    var jsonResponse = JsonConvert.SerializeObject(new { Results = services }, Formatting.Indented);
                    await h.Response.WriteAsync(jsonResponse);
                });
            });

            app.Map("/route", subApp =>
            {
                subApp.UseMiddleware<GatewayMiddleware>(resolver);
            });

            app.Map("/health", subApp =>
            {
                subApp.Run(async hrequest =>
                {
                    await hrequest.Response.WriteAsync("A OK!");
                });
            });

            app.Run(async context =>
            {
                await context.Response.WriteAsync(Constants.HelpText);
            });
        }
コード例 #55
0
        static SF_Services()
        {
            try
            {
                partitions_ = null;

                if (EnvoyDefaults.client_cert_subject_name != null)
                {
                    X509Credentials creds = new X509Credentials();
                    creds.FindType  = X509FindType.FindBySubjectName;
                    creds.FindValue = EnvoyDefaults.client_cert_subject_name;
                    if (EnvoyDefaults.client_cert_issuer_thumbprints != null)
                    {
                        foreach (var issuer in EnvoyDefaults.client_cert_issuer_thumbprints)
                        {
                            creds.IssuerThumbprints.Add(issuer);
                        }
                    }
                    if (EnvoyDefaults.server_cert_common_names != null)
                    {
                        foreach (var commonName in EnvoyDefaults.server_cert_common_names)
                        {
                            creds.RemoteCommonNames.Add(commonName);
                        }
                    }
                    else
                    {
                        creds.RemoteCommonNames.Add(EnvoyDefaults.client_cert_subject_name);
                    }
                    if (EnvoyDefaults.server_cert_issuer_thumbprints != null)
                    {
                        foreach (var issuer in EnvoyDefaults.server_cert_issuer_thumbprints)
                        {
                            creds.RemoteCertThumbprints.Add(issuer);
                        }
                    }
                    else if (EnvoyDefaults.client_cert_issuer_thumbprints != null)
                    {
                        foreach (var issuer in EnvoyDefaults.client_cert_issuer_thumbprints)
                        {
                            creds.RemoteCertThumbprints.Add(issuer);
                        }
                    }
                    creds.StoreLocation = StoreLocation.LocalMachine;
                    creds.StoreName     = "/app/sfcerts";

                    client = new FabricClient(creds, EnvoyDefaults.fabricUri);
                }
                else
                {
                    client = new FabricClient(EnvoyDefaults.fabricUri);
                }
                EnvoyDefaults.LogMessage("Client sucessfully created");

                EnableResolveNotifications.RegisterNotificationFilter("fabric:", client, Handler);
                EnvoyDefaults.LogMessage("Notification handler sucessfully set");
            }
            catch (Exception e)
            {
                EnvoyDefaults.LogMessage(String.Format("Error={0}", e));
            }
        }
コード例 #56
0
 public WebService(StatelessServiceContext context)
     : base(context)
 {
     this.fabricClient = new FabricClient();
 }
コード例 #57
0
 public RoomsController(HttpClient httpClient, StatelessServiceContext context, FabricClient fabricClient)
 {
     this.fabricClient   = fabricClient;
     this.httpClient     = httpClient;
     this.serviceContext = context;
 }