public ServiceFabricWebHost(IWebHost webHost, FabricRuntime fabricRuntime) { Console.WriteLine("ServiceFabricWebHost: Constructor"); if (webHost == null) throw new ArgumentNullException(nameof(webHost)); if (fabricRuntime == null) throw new ArgumentNullException(nameof(fabricRuntime)); _webHost = webHost; _fabricRuntime = fabricRuntime; }
public void ServiceMessage(StatefulServiceInitializationParameters service, string message, params object[] args) { if (this.IsEnabled()) { string finalMessage = string.Format(message, args); ServiceMessage( service.ServiceName.ToString(), service.ServiceTypeName, service.ReplicaId, service.PartitionId, service.CodePackageActivationContext.ApplicationName, service.CodePackageActivationContext.ApplicationTypeName, FabricRuntime.GetNodeContext().NodeName, finalMessage); } }
public async Task <string> OpenAsync(CancellationToken cancellationToken) { Logger.Debug(nameof(this.OpenAsync)); try { EndpointResourceDescription endpoint = this.serviceContext .CodePackageActivationContext.GetEndpoint(this.serviceEndpoint); int port = endpoint.Port; //拼接字符串 this.listeningAddress = string.Format( CultureInfo.InvariantCulture, "http://+:{0}/{1}", port, string.IsNullOrWhiteSpace(this.appRoot) ? string.Empty : this.appRoot.TrimEnd('/') + '/'); if (this.serviceContext is StatefulServiceContext) { StatefulServiceContext sip = (StatefulServiceContext)this.serviceContext; this.listeningAddress += sip.PartitionId + "/" + sip.ReplicaId + "/"; } this.publishAddress = this.listeningAddress.Replace("+", FabricRuntime.GetNodeContext().IPAddressOrFQDN); this.publishAddress = this.publishAddress.Replace("http", "ws"); //websocket启动事件 Logger.Info("Starting websocket listener on {0}", this.listeningAddress); this.webSocketApp = new WebSocketApp(this.createConnectionHandler, this.listeningAddress, port); //websocket设置 this.webSocketApp.Init(); //websocket初始化 使用supersocket初始化 //websocket主循环事件 // this.mainLoop = this.webSocketApp.StartAsync(this.ProcessConnectionAsync); //启动 Logger.Info("Started websocket listener on {0}", this.listeningAddress); return(await Task.FromResult(this.publishAddress)); } catch (Exception ex) { Logger.Error(ex, nameof(this.OpenAsync)); throw; } }
static GatewayController() { WinHttpHandler handler = new WinHttpHandler(); // We need to set timeout for handler first // Setting timeout for httpClient alone is not good enough var timeout = TimeSpan.FromSeconds(_DefaultHttpTimeoutSecs); handler.SendTimeout = timeout; handler.ReceiveDataTimeout = timeout; handler.ReceiveHeadersTimeout = timeout; _HttpClient = new HttpClient(handler) { // Default http timeout is 100s, increase it to 4 min since few key mainline scenarios // can take longer than default 100s Timeout = timeout }; // Attach remote cert validation to ignore self-signed ssl cert error if reverseProxySslThumbprint is specified in the config handler.ServerCertificateValidationCallback = ValidateRemoteCert; _ReverseProxySslThumbprint = GetReverseProxySslThumbprintFromConfig(); _AllowedUserRoles = GetAllowedUserRolesFromConfig(); var serviceKeyvaultName = ServiceFabricUtil.GetServiceKeyVaultName().Result.ToString(); var configPackage = FabricRuntime.GetActivationContext().GetConfigurationPackageObject("Config"); var serviceEnvironmenConfig = configPackage.Settings.Sections["ServiceEnvironment"]; var appInsightsIntrumentationKey = serviceEnvironmenConfig.Parameters["AppInsightsIntrumentationKey"].Value; var testClientId = serviceEnvironmenConfig.Parameters["TestClientId"].Value; _IsUserInfoLoggingEnabled = IsUserInfoLoggingEnabled(); _StaticLogger = new ApplicationInsightsLogger("GatewayILogger", new Microsoft.ApplicationInsights.TelemetryClient(new TelemetryConfiguration(KeyVault.GetSecretFromKeyvault(serviceKeyvaultName, appInsightsIntrumentationKey))), new ApplicationInsightsLoggerOptions()); try { // Each secret needs to be a list of unique Ids in the format {ObjectId}.{TenantId} List <string> userIdList = KeyVault.GetSecretFromKeyvault(serviceKeyvaultName, testClientId).Split(new char[] { ',' }).ToList(); foreach (string userId in userIdList) { _ClientWhitelist.Add(userId); } } catch (Exception e) { // Do nothing in case the TestClientId is not set in the keyvault. This is set for testing purposes. var message = e.Message; _StaticLogger.LogError(e.Message); } }
public WsCommunicationListener(StatefulServiceContext args, string endpointName, string appName, Action <byte[], CancellationToken, Action <byte[]> > callbackHandle) { this.serviceCallbackDelegate = callbackHandle; EndpointResourceDescription endpointDesc = args.CodePackageActivationContext.GetEndpoint(endpointName); appName = appName.Trim(); if (!appName.EndsWith("/")) { appName += "/"; } listeningAddress = $"http://+:{endpointDesc.Port}/{appName}"; publicAddress = listeningAddress.Replace("+", FabricRuntime.GetNodeContext().IPAddressOrFQDN); publicAddress = this.publicAddress.Replace("http", "ws"); }
/// <summary> /// Get ReverseProxySslThumbprint from config /// </summary> /// <returns></returns> private static string GetReverseProxySslThumbprintFromConfig() { string thumbprint = string.Empty; var configPackage = FabricRuntime.GetActivationContext().GetConfigurationPackageObject("Config"); if (configPackage.Settings.Sections.Contains("SslCertsConfig")) { var sslCertsConfig = configPackage.Settings.Sections["SslCertsConfig"]; if (sslCertsConfig.Parameters.Contains("ReverseProxySslThumbprint")) { thumbprint = sslCertsConfig.Parameters["ReverseProxySslThumbprint"].Value; } } return(thumbprint); }
public void Initialize(ServiceInitializationParameters serviceInitializationParameters) { ServiceEventSource.Current.Message("Initialize"); EndpointResourceDescription serviceEndpoint = serviceInitializationParameters.CodePackageActivationContext.GetEndpoint("ServiceEndpoint"); int port = serviceEndpoint.Port; this.listeningAddress = string.Format( CultureInfo.InvariantCulture, "http://+:{0}/{1}", port, string.IsNullOrWhiteSpace(this.appRoot) ? string.Empty : this.appRoot.TrimEnd('/') + '/'); this.publishAddress = this.listeningAddress.Replace("+", FabricRuntime.GetNodeContext().IPAddressOrFQDN); }
public static void Main(string[] args) { try { using (FabricRuntime fabricRuntime = FabricRuntime.Create()) { fabricRuntime.RegisterActor(typeof(StatefulVisualObjectActor)); Thread.Sleep(Timeout.Infinite); } } catch (Exception e) { ActorEventSource.Current.ActorRegistrationFailed(typeof(StatefulVisualObjectActor), e); throw; } }
private static void UpdateEventFlowConfiguration() { string appInsightsKey = Environment.GetEnvironmentVariable("EventFlow:ApplicationInsightsKey"); string logFilter = Environment.GetEnvironmentVariable("EventFlow:LogFilter"); CodePackageActivationContext activationContext = FabricRuntime.GetActivationContext(); ConfigurationPackage configPackage = activationContext.GetConfigurationPackageObject("Config"); string configFilePath = Path.Combine(configPackage.Path, "eventFlowConfig.json"); string content = File.ReadAllText(configFilePath); EventFlowOptions options = JsonConvert.DeserializeObject <EventFlowOptions>(content); options.Outputs[0].InstrumentationKey = appInsightsKey; options.Filters[0].Include = logFilter; File.WriteAllText(configFilePath, JsonConvert.SerializeObject(options)); }
private async Task DestroyValidationDPActorAsync(IValidationDPActor validationDPActor, CancellationToken cancellationToken) { try { ActorId actorId = validationDPActor.GetActorId(); IActorService myActorServiceProxy = ActorServiceProxy.Create( new Uri($"{FabricRuntime.GetActivationContext().ApplicationName}/ValidationActorService"), actorId); await myActorServiceProxy.DeleteActorAsync(actorId, cancellationToken); } catch (Exception ex) { _logger.LogError("Problem deleting actor", ex); } }
public ServiceConfigReader(string configPackageName) { var context = FabricRuntime.GetActivationContext(); if (context.GetConfigurationPackageNames().Contains(configPackageName)) { this.ConfigurationPackage = context.GetConfigurationPackageObject(configPackageName); this.UpdateConfigSettings(); context.ConfigurationPackageModifiedEvent += ConfigPackageChangedEvent; } else { throw new ArgumentException("No Matching Config Package Found"); } }
public void ActorError(ActivityActorCore actor, string message, params object[] args) { if (IsEnabled()) { ActorError( actor.GetType().ToString(), actor.Id.ToString(), actor.ActorService.Context.CodePackageActivationContext.ApplicationTypeName, actor.ActorService.Context.CodePackageActivationContext.ApplicationName, actor.ActorService.Context.ServiceTypeName, actor.ActorService.Context.ServiceName.ToString(), actor.ActorService.Context.PartitionId, actor.ActorService.Context.ReplicaId, FabricRuntime.GetNodeContext().NodeName, string.Format(message, args)); } }
public ServiceFabricWebHostBuilder(string[] args) { Console.WriteLine("ServiceFabricWebHostBuilder: Constructor"); _builder = new WebHostBuilder() .UseDefaultHostingConfiguration(args); RunInServiceFabric = string.Equals(_builder.GetSetting("fabric"), "true", StringComparison.OrdinalIgnoreCase); Console.WriteLine("RunInServiceFabric: " + RunInServiceFabric); if (RunInServiceFabric) { _fabricRuntime = FabricRuntime.Create(); Console.WriteLine("FabricRuntime initialized"); } }
public async Task <CounterStats> IncrementClickCount() { using (var tx = StateManager.CreateTransaction()) { var countDictionary = await this.StateManager.GetOrAddAsync <IReliableDictionary <long, long> >("countDictionary"); var result = await countDictionary.AddOrUpdateAsync(tx, 0, 1, (key, value) => ++ value); await tx.CommitAsync(); return(new CounterStats { ServedBy = FabricRuntime.GetNodeContext().NodeName, ClickCount = result }); } }
public async Task <CounterStats> GetClickCount() { using (var tx = StateManager.CreateTransaction()) { var countDictionary = await this.StateManager.GetOrAddAsync <IReliableDictionary <long, long> >("countDictionary"); var result = await countDictionary.TryGetValueAsync(tx, 0); await tx.CommitAsync(); return(new CounterStats { ServedBy = FabricRuntime.GetNodeContext().NodeName, ClickCount = result.HasValue ? result.Value : 0 }); } }
/* Set up the address that the server will be listening on and start taking requests. */ /* * OpenAsync method starts the web server and returns the address that the server * listens on. Service Fabric registers the returned address with its naming service so that a client * can query for the address by service name. This is necessary because a service instance may get * moved for load balancing or fail over, hence the listening address could change. However, a client * always can use the stable service name to look up the correct address to talk to. */ public Task <string> OpenAsync(CancellationToken cancellationToken) { EndpointResourceDescription serviceEndpoint = parameters.CodePackageActivationContext.GetEndpoint("ServiceEndpoint"); int port = serviceEndpoint.Port; listeningAddress = string.Format( CultureInfo.InvariantCulture, "http://+:{0}/{1}", port, string.IsNullOrWhiteSpace(appRoot) ? string.Empty : appRoot.TrimEnd('/') + '/'); this.serverHandle = WebApp.Start(this.listeningAddress, appBuilder => this.startup.Configuration(appBuilder)); string resultAddress = this.listeningAddress.Replace("+", FabricRuntime.GetNodeContext().IPAddressOrFQDN); ServiceEventSource.Current.Message("Listening on {0}", resultAddress); return(Task.FromResult(resultAddress)); }
public static void Main(string[] args) { try { using (FabricRuntime fabricRuntime = FabricRuntime.Create()) { fabricRuntime.RegisterActor(typeof(TKActorGlobalSum)); Thread.Sleep(Timeout.Infinite); } } catch (Exception e) { ActorEventSource.Current.ActorHostInitializationFailed(e); throw; } }
public Task <string> OpenAsync(CancellationToken cancellationToken) { ServiceEventSource.Current.Message("Initialize"); EndpointResourceDescription serviceEndpoint = this.serviceContext.CodePackageActivationContext.GetEndpoint("ServiceEndpoint"); int port = serviceEndpoint.Port; this.listeningAddress = string.Format(CultureInfo.InvariantCulture, "http://+:{0}/{1}{2}", port, this.appRoot, this.webSocketRoot); this.publishAddress = this.listeningAddress.Replace("+", FabricRuntime.GetNodeContext().IPAddressOrFQDN); this.Start(); ServiceEventSource.Current.Message("Starting web socket server on {0}", this.listeningAddress); return(Task.FromResult(this.publishAddress)); }
public Task <string> OpenAsync(CancellationToken cancellationToken) { EndpointResourceDescription serviceEndpoint = serviceInitializationParameters.CodePackageActivationContext.GetEndpoint("PlantsMonitoringEndpoint"); int port = serviceEndpoint.Port; this.listeningAddress = String.Format( CultureInfo.InvariantCulture, "http://+:{0}/", port); this.serverHandle = WebApp.Start(this.listeningAddress, appBuilder => this.startup.Configuration(appBuilder)); string publishAddress = this.listeningAddress.Replace("+", FabricRuntime.GetNodeContext().IPAddressOrFQDN); ServiceEventSource.Current.Message("Listening on {0}", publishAddress); return(Task.FromResult(publishAddress)); }
public static async Task <Noop> SendMessage(string destinationService, ServiceMessage2 message) { var client = new FabricClient(FabricClientRole.Admin); var resolver = ServicePartitionResolver.GetDefault(); var serviceUri = new Uri(FabricRuntime.GetActivationContext().ApplicationName + "/" + destinationService); var communicationFactory = new GrpcCommunicationClientFactory <Common.Grpc.GrpcMessageService.GrpcMessageServiceClient>(null, resolver); var partitionList = await client.QueryManager.GetPartitionListAsync(serviceUri); foreach (var partition in partitionList) { long partitionKey = ((Int64RangePartitionInformation)partition.PartitionInformation).HighKey; var partitionClient = new ServicePartitionClient <GrpcCommunicationClient <Common.Grpc.GrpcMessageService.GrpcMessageServiceClient> >(communicationFactory, serviceUri, new ServicePartitionKey(partitionKey), listenerName: "grpc"); var reply = partitionClient.InvokeWithRetry((communicationClient) => communicationClient.Client.Send(message)); } return(new Noop()); }
public static void Main(string[] args) { try { // Create a Service Fabric Runtime using (FabricRuntime fabricRuntime = FabricRuntime.Create()) { fabricRuntime.RegisterServiceType(Service.ServiceTypeName, typeof(Service)); Thread.Sleep(Timeout.Infinite); } } catch (Exception e) { ServiceEventSource.Current.ServiceHostInitializationFailed(e); throw; } }
Task <string> ICommunicationListener.OpenAsync(CancellationToken cancellationToken) { var endpoint = FabricRuntime.GetActivationContext().GetEndpoint(_endpointName); string serverUrl = $"{endpoint.Protocol}://{FabricRuntime.GetNodeContext().IPAddressOrFQDN}:{endpoint.Port}"; _webHost = new WebHostBuilder().UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseStartup <Startup>() .UseUrls(serverUrl) .UseContentRoot(Directory.GetCurrentDirectory()) .Build(); _webHost.Start(); return(Task.FromResult(serverUrl)); }
public ServiceFabricWebHost(IWebHost webHost, FabricRuntime fabricRuntime) { Console.WriteLine("ServiceFabricWebHost: Constructor"); if (webHost == null) { throw new ArgumentNullException(nameof(webHost)); } if (fabricRuntime == null) { throw new ArgumentNullException(nameof(fabricRuntime)); } _webHost = webHost; _fabricRuntime = fabricRuntime; }
internal static string GetCurrentFabricApplicationName() { if (ApplicationName == null) { try { var context = FabricRuntime.GetActivationContext(); ApplicationName = context.ApplicationName; } catch (InvalidOperationException) { ApplicationName = string.Empty; } } return(ApplicationName); }
/// <summary> /// This is the entry point of the service host process. /// </summary> private static void Main() { ILogger logger = null; var applicationInsightsKey = FabricRuntime.GetActivationContext() .GetConfigurationPackageObject("Config") .Settings .Sections["ConfigurationSection"] .Parameters["ApplicationInsightsKey"] .Value; try { // The ServiceManifest.XML file defines one or more service type names. // Registering a service maps a service type name to a .NET type. // When Service Fabric creates an instance of this service type, // an instance of the class is created in this host process. ServiceRuntime.RegisterServiceAsync("WebApiType", context => { LogContext.PushProperty(nameof(context.ServiceTypeName), context.ServiceTypeName); LogContext.PushProperty(nameof(context.ServiceName), context.ServiceName); LogContext.PushProperty(nameof(context.PartitionId), context.PartitionId); LogContext.PushProperty(nameof(context.ReplicaOrInstanceId), context.ReplicaOrInstanceId); LogContext.PushProperty(nameof(context.NodeContext.NodeName), context.NodeContext.NodeName); LogContext.PushProperty(nameof(context.CodePackageActivationContext.ApplicationName), context.CodePackageActivationContext.ApplicationName); LogContext.PushProperty(nameof(context.CodePackageActivationContext.ApplicationTypeName), context.CodePackageActivationContext.ApplicationTypeName); LogContext.PushProperty(nameof(context.CodePackageActivationContext.CodePackageVersion), context.CodePackageActivationContext.CodePackageVersion); var loggerFactory = new LoggerFactoryBuilder(context).CreateLoggerFactory(applicationInsightsKey); logger = loggerFactory.CreateLogger <WebApi>(); return(new WebApi(context, logger)); }).GetAwaiter().GetResult(); // Prevents this host process from terminating so services keeps running. Thread.Sleep(Timeout.Infinite); } catch (Exception e) { logger?.LogStatelessServiceInitalizationFailed <WebApi>(e); throw; } }
public void ActorMessage(Actor actor, string message, params object[] args) { if (this.IsEnabled()) { string finalMessage = string.Format(message, args); ActorMessage( actor.GetType().ToString(), actor.Id.ToString(), actor.ActorService.Context.CodePackageActivationContext.ApplicationTypeName, actor.ActorService.Context.CodePackageActivationContext.ApplicationName, actor.ActorService.Context.ServiceTypeName, actor.ActorService.Context.ServiceName.ToString(), actor.ActorService.Context.PartitionId, actor.ActorService.Context.ReplicaId, FabricRuntime.GetNodeContext().NodeName, finalMessage); } }
public void ActorMessage <TState>(Actor <TState> actor, string message, params object[] args) where TState : class { if (this.IsEnabled()) { string finalMessage = string.Format(message, args); ActorMessage( actor.GetType().ToString(), actor.Id.ToString(), actor.Host.ActivationContext.ApplicationTypeName, actor.Host.ActivationContext.ApplicationName, actor.Host.StatefulServiceInitializationParameters.ServiceTypeName, actor.Host.StatefulServiceInitializationParameters.ServiceName.ToString(), actor.Host.StatefulServiceInitializationParameters.PartitionId, actor.Host.StatefulServiceInitializationParameters.ReplicaId, FabricRuntime.GetNodeContext().NodeName, finalMessage); } }
public Uri ToUri() { string applicationInstance = this.ApplicationInstance; if (String.IsNullOrEmpty(applicationInstance)) { try { // the ApplicationName property here automatically prepends "fabric:/" for us applicationInstance = FabricRuntime.GetActivationContext().ApplicationName.Replace("fabric:/", String.Empty); } catch (InvalidOperationException) { } } return(new Uri("fabric:/" + applicationInstance + "/" + this.ServiceInstance)); }
public async Task Post(AddUsage usage) { var activationContext = FabricRuntime.GetActivationContext(); string applicationInstance = "ServiceFabricPoc.BottleFiller"; var serviceUri = new Uri("fabric:/" + applicationInstance + "/" + BottleFillerServiceName); //We create a unique Guid that is associated with a customer order, as well as with the actor that represents that order's state. IBottleFillerActor bottleFiller = ActorProxy.Create <IBottleFillerActor>(new ActorId(Guid.Parse(usage.Id)), serviceUri); var message = new AddUsageMessage() { NumberOfGallons = usage.NumberOfGallons }; await bottleFiller.AddUsage(message); }
public void ServiceMessage(StatelessService service, string message, params object[] args) { if (!this.IsEnabled()) { return; } string finalMessage = string.Format(message, args); this.ServiceMessage( service.Context.ServiceName.ToString(), service.Context.ServiceTypeName, service.Context.InstanceId, service.Context.PartitionId, service.Context.CodePackageActivationContext.ApplicationName, service.Context.CodePackageActivationContext.ApplicationTypeName, FabricRuntime.GetNodeContext().NodeName, finalMessage); }
/// <summary> /// Initializes component version of the telemetry item with the code package version from the Service Fabric runtime activation context. /// </summary> /// <param name="telemetry">The telemetry context to initialize.</param> public void Initialize(ITelemetry telemetry) { if (telemetry == null) { throw new ArgumentNullException(nameof(telemetry)); } if (telemetry.Context?.Component != null && string.IsNullOrEmpty(telemetry.Context.Component.Version)) { if (string.IsNullOrEmpty(codePackageVersion)) { var activationContext = FabricRuntime.GetActivationContext(); codePackageVersion = activationContext.CodePackageVersion; } telemetry.Context.Component.Version = codePackageVersion; } }
public ServiceFabricWebHostBuilder(string[] args) { Console.WriteLine("ServiceFabricWebHostBuilder: Constructor"); var config = new ConfigurationBuilder() .AddCommandLine(args) .Build(); _builder = new WebHostBuilder() .UseConfiguration(config); RunInServiceFabric = string.Equals(_builder.GetSetting("fabric"), "true", StringComparison.OrdinalIgnoreCase); Console.WriteLine("RunInServiceFabric: " + RunInServiceFabric); if (RunInServiceFabric) { _fabricRuntime = FabricRuntime.Create(); Console.WriteLine("FabricRuntime initialized"); } }