Exemplo n.º 1
0
 internal static void Initialize(
     StatelessServiceInitializationParameters initializationParameters,
     MonitoringAgentServiceEvent trace)
 {
     codePkgActivationCtx = initializationParameters.CodePackageActivationContext;
     serviceTrace         = trace;
 }
Exemplo n.º 2
0
 private static void ParseEndPoints(CodePackageActivationContext context, ServiceManifest manifest)
 {
     foreach (EndpointResourceDescription description in context.GetEndpoints())
     {
         manifest.Endpoints.Add(description);
     }
 }
Exemplo n.º 3
0
        public static DiagnosticPipeline CreatePipeline(string healthEntityName, string configurationFileName = "eventFlowConfig.json")
        {
            // TODO: dynamically re-configure the pipeline when configuration changes, without stopping the service

            Requires.NotNullOrWhiteSpace(healthEntityName, nameof(healthEntityName));

            var healthReporter = new ServiceFabricHealthReporter(healthEntityName);

            CodePackageActivationContext activationContext = FabricRuntime.GetActivationContext();
            ConfigurationPackage         configPackage     = activationContext.GetConfigurationPackageObject("Config");
            string configFilePath = Path.Combine(configPackage.Path, configurationFileName);

            if (!File.Exists(configFilePath))
            {
                string errorMessage = $"{nameof(ServiceFabricDiagnosticPipelineFactory)}: configuration file '{configFilePath}' is missing or inaccessible";
                healthReporter.ReportProblem(errorMessage, EventFlowContextIdentifiers.Configuration);
                throw new Exception(errorMessage);
            }

            ConfigurationBuilder configBuilder = new ConfigurationBuilder();

            configBuilder.AddJsonFile(configFilePath);
            IConfigurationRoot configurationRoot = configBuilder.Build();

            return(DiagnosticPipelineFactory.CreatePipeline(configurationRoot, new ServiceFabricHealthReporter(healthEntityName)));
        }
Exemplo n.º 4
0
        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;
        }
        /// <summary>
        /// This is used by Kvs and Volatile actor state provider.
        /// </summary>
        /// <param name="codePackage"></param>
        /// <param name="actorImplType"></param>
        /// <returns></returns>
        internal static ReplicatorSettings GetActorReplicatorSettings(CodePackageActivationContext codePackage, Type actorImplType)
        {
            var settings = ReplicatorSettings.LoadFrom(
                codePackage,
                ActorNameFormat.GetConfigPackageName(actorImplType),
                ActorNameFormat.GetFabricServiceReplicatorConfigSectionName(actorImplType));

            settings.SecurityCredentials = SecurityCredentials.LoadFrom(
                codePackage,
                ActorNameFormat.GetConfigPackageName(actorImplType),
                ActorNameFormat.GetFabricServiceReplicatorSecurityConfigSectionName(actorImplType));

            var nodeContext = FabricRuntime.GetNodeContext();
            var endpoint    = codePackage.GetEndpoint(ActorNameFormat.GetFabricServiceReplicatorEndpointName(actorImplType));

            settings.ReplicatorAddress = string.Format(
                CultureInfo.InvariantCulture,
                "{0}:{1}",
                nodeContext.IPAddressOrFQDN,
                endpoint.Port);

            if (!settings.MaxPrimaryReplicationQueueSize.HasValue)
            {
                settings.MaxPrimaryReplicationQueueSize = DefaultMaxPrimaryReplicationQueueSize;
            }

            if (!settings.MaxSecondaryReplicationQueueSize.HasValue)
            {
                settings.MaxSecondaryReplicationQueueSize = DefaultMaxSecondaryReplicationQueueSize;
            }

            return(settings);
        }
        private void ChangeNotificationTestHelper <TPackageInfo, TPackage>(
            ChangeNotificationTestData <TPackageInfo, TPackage> data,
            TPackageInfo oldPackage,
            TPackageInfo newPackage,
            Action <EventArgs> validator)
            where TPackageInfo : IPackageInfo
            where TPackage : class
        {
            var stub = new CodePackageActivationContextStub();

            // create the context
            var context = new CodePackageActivationContext(stub);

            EventArgs packageChangedArgs = null;

            // create a delegate for handling the event
            Action <object, EventArgs> eventHandler = (sender, args) =>
            {
                Assert.AreSame(context, sender);

                packageChangedArgs = args;
            };

            // hookup the delegate as the event handler
            data.EventHookupFunction(context, eventHandler);

            // invoke the event
            data.EventInvoker(stub, oldPackage, newPackage);

            // validate that the event was invoked
            Assert.IsNotNull(packageChangedArgs);

            validator(packageChangedArgs);
        }
Exemplo n.º 7
0
        /// <summary>
        ///     Configure and run a new ServiceHost
        /// </summary>
        public static void Run(Action <ServiceHost> configure)
        {
            CodePackageActivationContext packageActivationContext = FabricRuntime.GetActivationContext();

            try
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                ServicePointManager.CheckCertificateRevocationList = true;
                JsonConvert.DefaultSettings =
                    () => new JsonSerializerSettings {
                    TypeNameHandling = TypeNameHandling.None
                };
                var host = new ServiceHost();
                configure(host);
                host.Start();
                packageActivationContext.ReportDeployedServicePackageHealth(
                    new HealthInformation("ServiceHost", "ServiceHost.Run", HealthState.Ok));
                Thread.Sleep(Timeout.Infinite);
            }
            catch (Exception ex)
            {
                packageActivationContext.ReportDeployedServicePackageHealth(
                    new HealthInformation("ServiceHost", "ServiceHost.Run", HealthState.Error)
                {
                    Description = $"Unhandled Exception: {ex}"
                },
                    new HealthReportSendOptions {
                    Immediate = true
                });
                Thread.Sleep(5000);
                Environment.Exit(-1);
            }
        }
Exemplo n.º 8
0
        internal TraceConfig(string eventSourceName, string packageName)
        {
            this.traceEventsSectionName = string.Concat(TraceEventsSectionPrefix, eventSourceName);
            this.packageName            = packageName;
            ConfigurationSettings        configurationSettings = null;
            CodePackageActivationContext context = null;

            try
            {
                context = FabricRuntime.GetActivationContext();
            }
            catch (Exception)
            {
                // We want to handle the standalone case
            }

            if (context != null)
            {
                // Handle scenario for System Servcies as they dont have config package.
                // System Services like Fault Analysis Service & Update Orchestration Service depends on Microsoft.ServiceFabric.Services.dll which depends on
                // Microsoft.ServiceFabric.Diagnostics.dll
                if (context.GetConfigurationPackageNames().Contains(packageName))
                {
                    var configPackage = context.GetConfigurationPackageObject(packageName);
                    context.ConfigurationPackageModifiedEvent += this.OnConfigurationPackageModified;

                    if (configPackage != null)
                    {
                        configurationSettings = configPackage.Settings;
                    }
                }
            }

            this.UpdateSettings(configurationSettings, true);
        }
Exemplo n.º 9
0
 /// <summary>
 /// Convenience method to create an instance of this class initialized with property values loaded from the application configuration package.
 /// </summary>
 /// <param name="codePackageActivationContext">The activation context under which this code is running. Retrieved from <see cref="System.Fabric.FabricRuntime"/>.</param>
 /// <param name="configPackageName">The name of the configuration package (specified in the Service Manifest) containing the settings to load.</param>
 /// <param name="sectionName">The name of the section in Settings.xml within the specified configuration package containing the settings to load.</param>
 /// <returns>The initialized settings object.</returns>
 public static LocalEseStoreSettings LoadFrom(
     CodePackageActivationContext codePackageActivationContext,
     string configPackageName,
     string sectionName)
 {
     return(Utility.WrapNativeSyncInvokeInMTA <LocalEseStoreSettings>(
                () => InternalLoadFrom(codePackageActivationContext, configPackageName, sectionName), "LocalEseStoreSettings::LoadFrom"));
 }
        private void OneHandlerRegistrationTestHelper(Func <CodePackageActivationContextStub, int> handlerCountFunc)
        {
            var stub = new CodePackageActivationContextStub();

            var context = new CodePackageActivationContext(stub);

            Assert.AreEqual <int>(1, handlerCountFunc(stub));
        }
Exemplo n.º 11
0
        public static string GetConfigValue(string sectionName, string paramName)
        {
            CodePackageActivationContext activationContext = FabricRuntime.GetActivationContext();
            var configurationPackage = activationContext.GetConfigurationPackageObject("Config");

            string configValue = configurationPackage.Settings.Sections[sectionName].Parameters[paramName].Value;

            return(configValue);
        }
Exemplo n.º 12
0
        private static void ParseDataPackages(CodePackageActivationContext context, ServiceManifest manifest)
        {
            IList <string> names = context.GetDataPackageNames();

            foreach (string name in names)
            {
                manifest.DataPackages.Add(context.GetDataPackageObject(name));
            }
        }
 public ServiceFabricConfigurationProvider(string packageName)
 {
     this.packageName = packageName;
     this.context     = FabricRuntime.GetActivationContext();
     this.context.ConfigurationPackageModifiedEvent += (sender, e) => {
         this.LoadPackage(e.NewPackage, reload: true);
         this.OnReload();
     };
 }
Exemplo n.º 14
0
        public void ServiceInitializationParameters_NonNullActivationContextReturnsObject()
        {
            var obj = new CodePackageActivationContext(new Stubs.CodePackageActivationContextStub());

            Action <ServiceInitializationParameters> action = (initParams) => Assert.AreSame(obj, initParams.CodePackageActivationContext);

            action(new StatelessServiceInitializationParameters(obj));
            action(new StatefulServiceInitializationParameters(obj));
        }
Exemplo n.º 15
0
        public static string GetCertThumbprint()
        {
            CodePackageActivationContext activationContext = FabricRuntime.GetActivationContext();
            var configurationPackage = activationContext.GetConfigurationPackageObject("Config");

            string policyStorageCertThumbprint = configurationPackage.Settings.Sections["PolicyStorageSecurityConfig"].Parameters["PolicyStorageCertThumbprint"].Value;

            return(policyStorageCertThumbprint);
        }
Exemplo n.º 16
0
        public AppConfigStore(CodePackageActivationContext activationCtx, string configPackageName)
        {
            this.activationCtx     = activationCtx;
            this.configPackageName = configPackageName;

            activationCtx.ConfigurationPackageModifiedEvent += this.OnConfigurationPackageModified;

            this.RefreshConfigPackage();
        }
Exemplo n.º 17
0
        // internal for test hook
        internal void ActivateCodePackageInternal(
            string activationContextId,
            string codePackageName,
            CodePackageActivationContext activationContext,
            NativeRuntime.IFabricRuntime fabricRuntimePointer)
        {
            this.ThrowIfDisposed();

            CodePackage codePackage;

            try
            {
                codePackage = activationContext.GetCodePackageObject(codePackageName);
            }
            catch (KeyNotFoundException)
            {
                AppTrace.TraceSource.WriteError("FabricHostEntryPoint.ActivateCodePackageInternal", "The code package {0} to activate was not found", codePackageName);
                throw new ArgumentException(StringResources.Error_CodePackageNotFound);
            }

            DllHostEntryPointDescription description = codePackage.Description.EntryPoint as DllHostEntryPointDescription;

            if (description == null)
            {
                AppTrace.TraceSource.WriteError("FabricHostEntryPoint.ActivateCodePackageInternal", "Code package {0} does not have a FabricHostEntryPoint", codePackageName);
                throw new ArgumentException(StringResources.Error_FabricHostEntryPoint_No_EntryPoint_Found);
            }

            AppTrace.TraceSource.WriteNoise("FabricHostEntryPoint.ActivateCodePackageInternal", "Adding assembly resolver path: {0}", codePackage.Path);
            this.assemblyResolver.AddApplicationBinariesPath(codePackage.Path);

            var workerEntryPoints = description.HostedDlls
                                    .Where(i => i.Kind == DllHostHostedDllKind.Managed)
                                    .Select(FabricWorkerEntryPoint.CreateFromAssemblyDescription)
                                    .ToArray();

            var fabricRuntime = new FabricRuntime(fabricRuntimePointer, activationContext);
            ActivatedCodePackage activatedCodePackage = new ActivatedCodePackage(fabricRuntime, workerEntryPoints);

            bool activateSucceeded = false;

            try
            {
                workerEntryPoints.ForEach(wep => wep.InvokeActivate(fabricRuntime, activationContext));

                this.activeCodePackages[activationContextId] = activatedCodePackage;
                activateSucceeded = true;
            }
            finally
            {
                if (!activateSucceeded)
                {
                    activatedCodePackage.Dispose();
                }
            }
        }
Exemplo n.º 18
0
        public static string ReadValue(string sectionName, string parameterName)
        {
            CodePackageActivationContext context        = FabricRuntime.GetActivationContext();
            ConfigurationSettings        configSettings = context.GetConfigurationPackageObject("Config").Settings;
            ConfigurationSection         configSection  = configSettings.Sections.FirstOrDefault(s => (s.Name == sectionName));

            ConfigurationProperty configurationProperty = configSection?.Parameters.FirstOrDefault(p => (p.Name == parameterName));

            return(configurationProperty?.Value);
        }
        public ServiceFabricHealthReporter(string entityIdentifier)
        {
            if (string.IsNullOrWhiteSpace(entityIdentifier))
            {
                throw new ArgumentException("entityIdentifier cannot be null or empty", "entityIdentifier");
            }
            this.entityIdentifier = entityIdentifier;

            this.activationContext = FabricRuntime.GetActivationContext();
        }
Exemplo n.º 20
0
 private void RegisterSyncTestHelper_DefaultServiceFactory(CodePackageActivationContext context, Type implementationType, bool isStateful)
 {
     this.RegisterTestHelper(
         context,
         isStateful,
         0,
         true,
         (s, rt, stub) => rt.RegisterServiceType(s, implementationType),
         (broker) => this.DefaultServiceFactoryRegistrationValidator(broker, implementationType));
 }
Exemplo n.º 21
0
 private void RegisterSyncTestHelper_CustomServiceFactory(CodePackageActivationContext context, Action <string, FabricRuntime, object> registerFunc, object serviceFactory, bool isStateful)
 {
     this.RegisterTestHelper(
         context,
         isStateful,
         0,
         true,
         (s, rt, stub) => registerFunc(s, rt, serviceFactory),
         (broker) => Assert.AreSame(serviceFactory, broker.ServiceFactory));
 }
 public StatefulServiceParameters(
     CodePackageActivationContext codePackageActivationContext, byte[] initializationData, Guid partitionId, Uri serviceName, string serviceTypeName,
     long replicaId)
 {
     this.CodePackageActivationContext = codePackageActivationContext;
     this.InitializationData           = initializationData;
     this.PartitionId     = partitionId;
     this.ServiceName     = serviceName;
     this.ServiceTypeName = serviceTypeName;
     this.ReplicaId       = replicaId;
 }
 public StatefulServiceParameters(
     CodePackageActivationContext codePackageActivationContext, byte[] initializationData, Guid partitionId, Uri serviceName, string serviceTypeName,
     long replicaId)
 {
     this.CodePackageActivationContext = codePackageActivationContext;
     this.InitializationData = initializationData;
     this.PartitionId = partitionId;
     this.ServiceName = serviceName;
     this.ServiceTypeName = serviceTypeName;
     this.ReplicaId = replicaId;
 }
        private void ParametersArePassedToServiceFactoryTestHelper(
            byte[] initializationData,
            object returnValue,
            CodePackageActivationContext context,
            Func <ServiceFactoryBroker, IntPtr, IntPtr, uint, IntPtr, Guid, long, object> factoryFunc,
            Func <object, ServiceInitializationParameters> initParamGetterFunc,
            Func <object, long> idGetterFunc)
        {
            ParameterSavingStub stub = new ParameterSavingStub
            {
                InstanceToReturn = returnValue
            };

            var broker = new ServiceFactoryBroker(stub, context);

            // the service factory returns byte[0]
            byte[] initializationDataExpected = initializationData == null ? new byte[0] : initializationData;

            using (var pin = new PinBlittable(initializationData))
            {
                var instance = factoryFunc(
                    broker,
                    ServiceFactoryBrokerTest.PtrDefaultServiceType,
                    ServiceFactoryBrokerTest.PtrDefaultServiceUri,
                    initializationData == null ? 0 : (uint)initializationData.Length,
                    pin.AddrOfPinnedObject(),
                    ServiceFactoryBrokerTest.DefaultPartitionId,
                    ServiceFactoryBrokerTest.DefaultInstanceId);

                // the correct values must be passed into the service factory
                Assert.AreEqual <long>(ServiceFactoryBrokerTest.DefaultInstanceId, stub.InstanceId);
                Assert.AreEqual(ServiceFactoryBrokerTest.DefaultServiceTypeName, stub.ServiceType);
                Assert.AreEqual(new Uri(ServiceFactoryBrokerTest.DefaultServiceUri).ToString().ToLower(), stub.ServiceName.ToString().ToLower());

                MiscUtility.CompareEnumerables(initializationDataExpected, stub.InitializationData);

                Assert.AreSame(returnValue, instance);

                // the values must be set on the initialization parameters (initialize must have been called)
                ServiceInitializationParameters actualInitParams = initParamGetterFunc(instance);
                long actualId = idGetterFunc(instance);
                Assert.AreEqual <long>(ServiceFactoryBrokerTest.DefaultInstanceId, actualId);
                Assert.AreEqual(ServiceFactoryBrokerTest.DefaultServiceTypeName, actualInitParams.ServiceTypeName);
                Assert.AreEqual(new Uri(ServiceFactoryBrokerTest.DefaultServiceUri).ToString().ToLower(), actualInitParams.ServiceName.ToString().ToLower());
                Assert.AreEqual(ServiceFactoryBrokerTest.DefaultPartitionId, actualInitParams.PartitionId);

                if (context != null)
                {
                    Assert.AreSame(context, actualInitParams.CodePackageActivationContext);
                }

                MiscUtility.CompareEnumerables(initializationDataExpected, actualInitParams.InitializationData);
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Create and configure a Serilog logger that writes to Elasticsearch, enriching
        /// with properties about the Service Fabric environment.
        /// </summary>
        public static ILogger CreateLogger(NodeContext nodeContext, CodePackageActivationContext activationContext)
        {
            var config = new LoggerConfiguration()
                         .Enrich.WithCommonProperties()
                         .Enrich.With(new PropertyEnricher("NodeId", nodeContext.NodeId))
                         .Enrich.With(new PropertyEnricher("NodeName", nodeContext.NodeName))
                         .Enrich.With(new PropertyEnricher("ApplicationName", activationContext.ApplicationName))
                         .Enrich.With(new PropertyEnricher("ApplicationTypeName", activationContext.ApplicationTypeName))
                         .WriteTo.Elasticsearch(GetElasticsearchOptions());

            return(Log.Logger = config.CreateLogger());
        }
Exemplo n.º 26
0
        private MessageBrokerEnvironment GetEnvironment()
        {
            CodePackageActivationContext context        = FabricRuntime.GetActivationContext();
            ConfigurationPackage         packageContext = context.GetConfigurationPackageObject("Config");

            string environment = packageContext.Settings.Sections["ConfigSection"].Parameters["Environment"].Value;

            Verify.IsNotEmpty(nameof(environment), environment);

            ServiceEventSource.Current.ServiceMessage(Context, $"Environment selected: {environment}");
            return((MessageBrokerEnvironment)Enum.Parse(typeof(MessageBrokerEnvironment), environment, true));
        }
Exemplo n.º 27
0
        public ServiceFactoryBroker(object serviceFactory, CodePackageActivationContext codePackageActivationContext)
        {
            Requires.Argument <object>("serviceFactory", serviceFactory).NotNull();
            this.serviceFactory = serviceFactory;
            this.codePackageActivationContext = codePackageActivationContext;

            if (!(serviceFactory is IStatelessServiceFactory) && !(serviceFactory is IStatefulServiceFactory))
            {
                AppTrace.TraceSource.WriteError("ServiceFactoryBroker.ServiceFactoryBroker", "Tried to construct a service factory with an invalid type. this indicates a coding error, {0}", serviceFactory.GetType().FullName);
                throw new ArgumentException(StringResources.Error_ServiceFactoryBroker_Coding_Error_Invalid_Type);
            }
        }
Exemplo n.º 28
0
        public FabricConfigurationProvider(string configurationSectionName)
        {
            if (string.IsNullOrWhiteSpace(configurationSectionName))
            {
                throw new ArgumentNullException("configurationSectionName");
            }

            CodePackageActivationContext activationContext = FabricRuntime.GetActivationContext();
            ConfigurationPackage         configPackage     = activationContext.GetConfigurationPackageObject("Config");

            this.UseConfiguration(configPackage, configurationSectionName);
        }
        public ServiceFabricConfigurationProvider(string configurationPackageName = DefaultConfigurationPackageName)
        {
            Requires.NotNullOrEmpty(configurationPackageName, nameof(configurationPackageName));

            this.configurationPackageName = configurationPackageName;
            CodePackageActivationContext activationContext = FabricRuntime.GetActivationContext();

            activationContext.ConfigurationPackageModifiedEvent += (sender, e) => {
                this.Load(e.NewPackage, reload: true);
                this.OnReload();
            };
        }
        public void CodePackageActivationContextTest_GetServiceManifestTest()
        {
            ServiceManifestInfo manifest = ServiceManifestTest.HelperInstance.CreateDefaultInfo();

            var context = CodePackageActivationContext.CreateFromNative(new CodePackageActivationContextStub()
            {
                ServiceManifestInfo_Internal = manifest,
                CodePackageName_Internal     = manifest.CodePackages.ElementAt(0).Name
            });

            ServiceManifestTest.HelperInstance.Compare(ServiceManifestTest.HelperInstance.CreateDefaultDescription(), ServiceManifest.CreateFromCodePackageActivationContext(context));
        }
Exemplo n.º 31
0
        public ServiceFabricConfigurationProvider(string packageName)
        {
            _packageName = packageName;
            _context     = FabricRuntime.GetActivationContext();

            //It's possible to upgrade a service's configuration package without changing the code package. In that case, Service Fabric does not restart the service. Instead, the service receives a ConfigurationPackageModifiedEvent event to notify it that the package changed.
            _context.ConfigurationPackageModifiedEvent += (sender, e) =>
            {
                this.LoadPackage(e.NewPackage, reload: true);
                this.OnReload();
            };
        }