write log to Application insights from local service fabric - azure-service-fabric

I am trying to integrate Azure App insights service into the service fabric app for logging and instrumentation. I am running fabric code on my local VM. I exactly followed the document here [scenario 2]. Other resources on learn.microsoft.com also seem to indicate the same steps. [ex: https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-diagnostics-event-aggregation-eventflow
For some reason, I don’t see any event entries in App insights. No errors in code when I do this:
ServiceEventSource.Current.ProcessedCountMetric("synced",sw.ElapsedMilliseconds, crc.DataTable.Rows.Count);
eventflowconfig.json contents
{
"inputs": [
{
"type": "EventSource",
"sources": [
{ "providerName": "Microsoft-ServiceFabric-Services" },
{ "providerName": "Microsoft-ServiceFabric-Actors" },
{ "providerName": "mystatefulservice" }
]
}
],
"filters": [
{
"type": "drop",
"include": "Level == Verbose"
}
],
"outputs": [
{
"type": "ApplicationInsights",
// (replace the following value with your AI resource's instrumentation key)
"instrumentationKey": "XXXXXXXXXXXXXXXXXXXXXX",
"filters": [
{
"type": "metadata",
"metadata": "metric",
"include": "ProviderName == mystatefulservice && EventName == ProcessedCountMetric",
"operationProperty": "operation",
"elapsedMilliSecondsProperty": "elapsedMilliSeconds",
"recordCountProperty": "recordCount"
}
]
}
],
"schemaVersion": "2016-08-11"
}
In ServiceEventSource.cs
[Event(ProcessedCountMetricEventId, Level = EventLevel.Informational)]
public void ProcessedCountMetric(string operation, long elapsedMilliSeconds, int recordCount)
{
if (IsEnabled())
WriteEvent(ProcessedCountMetricEventId, operation, elapsedMilliSeconds, recordCount);
}
EDIT
Adding diagnostics pipeline code from "Program.cs in fabric stateful service
using (var diagnosticsPipeline =
ServiceFabricDiagnosticPipelineFactory.CreatePipeline($"{ServiceFabricGlobalConstants.AppName}-mystatefulservice-DiagnosticsPipeline")
)
{
ServiceRuntime.RegisterServiceAsync("mystatefulserviceType",
context => new mystatefulservice(context)).GetAwaiter().GetResult();
ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id,
typeof(mystatefulservice).Name);
// Prevents this host process from terminating so services keep running.
Thread.Sleep(Timeout.Infinite);
}

Event Source is a tricky technology, I have been working with it for a while and always have problems. The configuration looks good, It is very hard to investigate without access to the environments, so I will make my suggestions.
There are a few catches you must be aware of:
If you are listening etw events from a different process, your process must be running with a user with permissions on 'Performance Log Users. Check which identity your service is running on and if it is part of performance log users, who has permissions to create event sessions to listen for these events.
Ensure the events are being emitted correctly and you can listen to them from Diagnostics Events Window, if it is not showing there, there is a problem in the provider.
For testing purposes, comment out the line if (IsEnabled()). it is an internal check to validate if your events should be emitted. I had situations where it is always false and skip the emit of events, probably it cache the results for a while, the docs are not clear how it should work.
Whenever possible, use the EventSource from the nuget package instead of the framework one, the framework version is full of bugs and lack fixes found in the nuget version.
Application Insights are not RealTime, sometimes it might take a few minutes to process your events, I would recommend to output the events to a console or file and check if it is listening correctly, afterwards, enable the AppInsights.

The link you provide is quite outdated and there's actually a much better way to log application error and exception info to Application insights. For example, the above won't help with tracking the call hierarchy of an incoming request between multiple services.
Have a look at the Microsoft App Insights Service Fabric nuget packages. It works great for:
Sending error and exception info
Populating the application map with all your services and their dependencies (including database)
Reporting on app performance metrics,
Tracing service call dependencies end-to-end,
Integrating with native as well as non-native SF applications

Related

Azure Service Fabric gets terminated in local cluster when running tests

So we are using Azure Service Fabric and gets a weird behavior when trying to run API tests against my local development cluster.
Every time I start the test the app gets terminated, sometimes it gets restarted again but most often it just stays terminated (and even deleted from the cluster).
I guess its somehow connected against that when I run the API test it will run and build stuff that the service fabric is using, but since the outcome is different depending on something (maybe the sun?) it feels like I am either missing something or experience a bug with service fabric.
Do anyone have any idea? Consider me as a noob and assume that I have done something wrong myself (I am doing that atleast).
UPDATE
There was a question on how we do run our tests:
Starts 2 instances of Visual Studio
Open the same .sln in both of them
Start the Service Fabric project.
Wait until cluster reports OK.
Run api test through a unit test (both service bus tests and REST tests) with Resharper test runner
Now we get the messages that is attached in diagnostics.
Diagnostics:
Event #1
{
"Timestamp": "2018-10-16T08:14:03.0590414+02:00",
"ProviderName": "Microsoft-ServiceFabric",
"Id": 23083,
"Message": ApplicationHostTerminated: ApplicationId=fabric:/<MyService>, ServiceName=fabric:/<MyService>, ServicePackageName=<MyPackage>, ServicePackageActivationId=8f36ac97-9271-4a49-94ce-dd296aebffa5, IsExclusive=True, CodePackageName=Code, EntryPointType=Exe, ExeName=MyExe, ProcessId=24568, HostId=d2a820b5-5b4d-42af-ae87-350028a3fa72, ExitCode=3221225786, UnexpectedTermination=False, StartTime=10/16/2018 08:12:14. ",
"ProcessId": 22660,
"Level": "Informational",
"Keywords": "0x4000000000000001",
"EventName": "Hosting",
"ActivityID": null,
"RelatedActivityID": null,
"Payload": {
"eventInstanceId": "\"07f15452-2f75-49e3-ad5d-d16ea49bdc8f\"",
"applicationName": "MyAppName",
"ServiceName": "fabric:/MyServiceName",
"ServicePackageName": "MyPackageName",
"ServicePackageActivationId": "8f36ac97-9271-4a49-94ce-dd296aebffa5",
"IsExclusive": true,
"CodePackageName": "Code",
"EntryPointType": 1,
"ExeName": "MyExe",
"ProcessId": 24568,
"HostId": "d2a820b5-5b4d-42af-ae87-350028a3fa72",
"ExitCode": 3221225786,
"UnexpectedTermination": false,
"StartTime": "\"\/Date(1539670334917)\/\""
}
}
Event #2
{
"Timestamp": "2018-10-16T08:14:02.3557708+02:00",
"ProviderName": "Microsoft-ServiceFabric",
"Id": 29625,
"Message": "Application deleted: Application = fabric:/MyApp, Application Type = MyServiceType ",
"ProcessId": 22660,
"Level": "Informational",
"Keywords": "0x4000000000000001",
"EventName": "CM",
"ActivityID": null,
"RelatedActivityID": null,
"Payload": {
"eventInstanceId": "\"ca608cec-8d55-4606-a331-8ebfcfff8fa6\"",
"applicationName": "fabric:/MyAppName",
"applicationTypeName": "MyAppTypeName",
"applicationTypeVersion": "1.0.0"
}
}
I think you can experience a side effect of Application Debug Mode set for your .sfproj.
By default Application Debug Mode is set to Refresh Application (which if you are using 5-node cluster is automatically changed to Remove Application) or Remove Application debug mode. This instructs Visual Studio to recreate the application for each debugging session and remove it when session ends.
Changing it to Keep Application should prevent the Visual Studio from recreating the application during debugging session.

How to implement a serviceworker in SFCC (Demandware)

I was wondering if anyone here has experience with implementing a service worker in SFCC/Demandware.
I generate a service worker with Webpack with sw-precache-webpack-plugin
The problem is: a service worker should be available from the root of the domain. so site.com/sw.js.
JS files will come normally in the static/ folder.
Anyone an idea how to serve this JS file from the root of the project in Demandware/SFCC?
Unfortunately, registering a service worker under an scope that is in an upper path than the service worker file itself does not work (as stated in MDN):
The service worker will only catch requests from clients under the service worker's scope.
The max scope for a service worker is the location of the worker.
(Source: https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers)
Solution
Here is a suggestion for a working approach for serving "/sw.js" in Demandware (Sales Force):
Create a new controller (or pipeline), e.g. "ServiceWorker-GetFile"; the response should be a file content, which can be read from whatever source you wish:
Content asset (dw.content.ContentMgr.getContent());
Library file (dw.content.ContentMgr.getContent() or directly reading a file with dw.io.File / dw.io.FileReader);
even Site preference (although I wouldn't recommend it);
Create an entry in Business Manager / Merchant Tools / SEO / Aliases to route "/sw.js" to "ServiceWorker-GetFile", i.e. use something along:
{
...
"your-host" : [
...,
{
"if-site-path": "/sw.js",
"pipeline": "ServiceWorker-GetFile"
}
]
}
This may seem like an unnecessary overhead, but it was the only way I could findfor serving files with root path in the URI.
Serving other root files as well
By expanding the controller (renaming it to, say, "Content-GetFile" and adding GET/POST parameters like "name" and/or "source") this could be conveniently used for other files as well ("/manifest.json", "/.well-known/assetlinks.json" etc.). In the next example of Business Manager / ... / Aliases, let Content-GetFile accept two parameters: "name" (which would be a file name in the content library or a content asset ID) and "source" (which would be "file" or "asset"):
...
{
"if-site-path": "/sw.js",
"pipeline": "Content-GetFile",
"params": {
"name": "/ServiceWorker/sw.js",
"source": "file"
}
},
{
"if-site-path": "/manifest.json",
"pipeline": "Content-GetFile",
"params": {
"name": "MANIFEST_JSON",
"source": "asset"
}
}
Note that your code should handle appropriately the base paths of the resources (e.g. "/ServiceWorker/sw.js" from the above example does not speak much; you should know whether this is a path in a content library or a path relative to "cartridges//static/default/js/").
Dynamic content
Since the suggested approach uses a controller, you can dynamically process the content before serving it to the user (e.g. if you need to add/remove the "/v12435145145/" part from DMW links). Sky is your limits. :)
I'm currently messing around with the service workers on DW as well.
In my case I have directly added the script inside a footer.isml file like this:
<script>
//init service worker
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker
.register("${URLUtils.staticURL('/lib/sw/sw.js')}")
.then(registration => {
console.log(
`Service Worker registered! Scope: ${registration.scope}`
);
})
.catch(err => {
console.log(`Service Worker registration failed: ${err}`);
});
});
}
</script>
This works for me, well at least I can see the Service Worker registered message.
I also had some issues due to the SSL certificate since my development environment doesn't have a proper SSL but it's using HTTPs routes, so chrome was complaining about it, I needed to run chrome via terminal using this command:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --user-data-dir=/tmp/foo --ignore-certificate-errors --unsafely-treat-insecure-origin-as-secure=[YOUR DOMAIN]
Unfortunately I'm not able to make work any line of code inside that service worker file, even I tried on Safari, since it has a Service Workers option in the develop menu, but it's not showing any service worker running.
I Hope it will helps you.

Service Fabric and Application Insights Performance Counters

Where can I find a list of performance counter names to be used with a Service Fabric cluster? There is a list published here, but I would need the actual exact names to be used in the cluster's ARM template. Currently I have the following configuration in the template :
"WadCfg": {
"DiagnosticMonitorConfiguration": {
"overallQuotaInMB": "1000",
"sinks": "applicationInsights",
"DiagnosticInfrastructureLogs": {},
"PerformanceCounters": {
"PerformanceCounterConfiguration": [
{
"counterSpecifier": "\\Processor(_Total)\\% Processor Time",
"sampleRate": "PT3M"
},
{
"counterSpecifier": "\\Memory\\Available MBytes",
"sampleRate": "PT3M"
}
]
}
But only the "Memory\Available MBytes" actually shows up in Application Insights.
Those counters are the actual windows performance counters. So you just need to look for them. Some examples:
http://techgenix.com/Key-Performance-Monitor-Counters/
http://www.appadmintools.com/documents/windows-performance-counters-explained/
Judging by all this information, the performance counters all follow the same pattern:
first column\second column
\\Processor(_Total)\\% Processor Time
\\Memory\\Available MBytes
\\Network Interface(*)\\Bytes Received/sec
...
You might be able to find some more counters by running typeperf directly on the service fabric VM and capturing the output. You can also run it locally to get an idea of what is possible.
http://defaultreasoning.com/2009/06/25/list-all-performance-counters-on-a-windows-computer-and-export-it-to-a-file/
C:>TypePerf.exe –q > counters.txt

How to initiate a workflow in Activiti using REST API

I have created a Activit Process using Service Tasks etc with eclipse and deployed the .bar to Activiti which is running on tomcat. It was successfully deployed I can start my process using activiti-explorer without any issue. The deployed process name is "My process" and it is listed under Processes->Deployed Process Definitions in the Activiti-Explorer as well. In the diagram it has the name "myProcess:1:1473"
But I have two questions.
I need to start my process using REST call. (i.e. Without using Activiti-explorer) . What is the URL for that? I tried several variations of (http://localhost:8080/activiti-rest/service/runtime/process-instances) but none of them working.
When I restart the tomcat my process instance is not shown in the Activit -explorer. Each time I restart I need to redeploy the process .bar file. Is that the natural behavior of the engine?
For your first question check this guide for further details:
POST runtime/process-instances should be your endpoint (Be sure to make a POST request, with application/jsonas your content type)
The payload on the other hand should be formatted in one of three templates:
Request body (start by process definition id):
{
"processDefinitionId":"oneTaskProcess:1:158",
"businessKey":"myBusinessKey",
"variables": [
{
"name":"myVar",
"value":"This is a variable",
}
]
}
Request body (start by process definition key):
{
"processDefinitionKey":"oneTaskProcess",
"businessKey":"myBusinessKey",
"tenantId": "tenant1",
"variables": [
{
"name":"myVar",
"value":"This is a variable",
}
]
}
Request body (start by message):
{
"message":"newOrderMessage",
"businessKey":"myBusinessKey",
"tenantId": "tenant1",
"variables": [
{
"name":"myVar",
"value":"This is a variable",
}
]
}
As for your second issue, you should be aware that the OOTB (Out Of The Box) config may involve automatic DB cleaning upon each and every restart, you need to locate that config and override it with values of your choice! Check this section for further info, the databaseSchemaUpdate param might be exactly what you are looking for!

BAM 2.5.0 - Monitoring realtime traffic - Error when creating a new execution plan "Imported streams cannot be empty"

New user of the BAM with CEP integration, I'm currently following the "Monitoring Realtime Traffic" sample from WSo2 Doc and block when creating the Execution-plan step. Link to doc
The doc requires to
4. Under Import Stream select org.wso2.sample.rt.traffic for Import Stream, and enter traffic for As.
Unfortunatly when I click "import" nothing happens (in the doc it shows we should get //imported from org.wso2.sample.rt.traffic:1.0.0)
When I try to add the execution plan I get the "Imported streams cannot be empty"
Am I making a mistake ?
Regards
Vpl
I was able to solve the issue of this UI problem by creating the event stream directly into the registry table. For that I've created the following resource
/_system/governance/StreamDefinitions/org.wso2.sample.rt.traffic/1.0.0
containing
{
"streamId": "org.wso2.sample.rt.traffic:1.0.0",
"name": "org.wso2.sample.rt.traffic",
"version": "1.0.0",
"payloadData": [
{
"name": "entry",
"type": "STRING"
}
]
}
With a Media Type: application/json
Then creating the execution plan I could import the event stream and continue the use-case/ / tutorial
Regards