Skip to Content
Technical Articles

Observability, monitoring and alerting services offered by SAP Cloud Platform – Part 2

Introduction

This blog post  is a continuation of my previous post where I gave an intro about observability and SAP’s  product portfolio on observability services. In this blog post  we can see how we can focus on the event data which is very important when an app or microservice runs in the production.

SAP Cloud Platform Alert Notification

Alerts are useful when we need to know if there are some changes in the behavior (e.g. connectivity to some external service is down ) or there are some operational changes in an application(e.g. when the app is deployed). We can also configure how we need the stakeholders to be notified. There are various notification channels available starting from email to a slack channel.

SAP Cloud platform alert notification services provides an out of box solution for this. Lets us see how we can setup  alert notification for your application.

Please note that SAP Cloud Platform Alert Notification does not produce any alerts on its own. It acts like a proxy to which different applications and services are sending alerts.  Alert Notification provides you with a catalogue, depending on the environment with which you are working. This catalogue of alerts is going to grow over time and adopt as many SAP Cloud Platform services as possible, regardless of the environment.

Prerequisites 

  1. A cloud foundry Organization to create an instance of alert notification service.
  2. Available service plan and entitlement for the particular subaccount.
  3. you can always check your available services using  ” cf marketpace ” command.

 

Creating Alert Notification using command line

In order to create an alert notification service use

cf create-service alert-notification standard my-alert-notification-instance

Alert Notification supports configuration parameters that can be provided by the -c option of the create-service command. The supported JSON format is the same as the exported configuration format but wrapped in a configuration object: {"configuration":{<<>>}}. For more information, see Exporting or Importing Configurations.

An Example.

 

cf create-service alert-notification standard my-alert-notification-instance -c '{"configuration":{"conditions":[{"name":"demo_condition","propertyKey":"eventType","predicate":"EQUALS","propertyValue":"demo"},
{"name":"demo_condition_2","propertyKey":"eventType","predicate":"EQUALS","propertyValue":"demo_2"}],
"actions":[{"name":"demo_action","state":"ENABLED","destination":"https://ans-test-123.cfapps.eu00.hana.ondemand.com/web-hook/api/v1/events","type":"WEB_HOOK"},{"name":"demo_action_2","state":"ENABLED","type":"STORE"}],
"subscriptions":[{"name":"demo_subscription","conditions":["demo_condition"],"actions":["demo_action"],"state":"ENABLED"},{"name":"demo_subscription_2","conditions":["demo_condition_2"],"actions":["demo_action_2"],"state":"ENABLED"}]}}'

 

Using a Multitarget Application descriptor

  • Create a deployment descriptor as described in Defining MTA Deployment Descriptors for Cloud Foundry. In the resources element of the JSON, enter the Alert Notification configuration data in its exported form. Adapt any values if necessary.
resources:
- name: example-alert-notification
     type: org.cloudfoundry.managed-service
     parameters:
        service: alert-notification
        service-plan: standard
        config:
            {
                "configuration":{
                    "conditions":[
                        {
                            "name":"example_condition",
                            "propertyKey":"eventType",
                            "predicate":"EQUALS",
                            "propertyValue":"demo"
                        },
                        {
                            "name":"example_condition_2",
                            "propertyKey":"eventType",
                            "predicate":"EQUALS",
                            "propertyValue":"demo_2"
                        }
                    ],
                    "actions":[
                        {
                            "name":"example_action",
                            "state":"ENABLED",
                            "destination":"https://ans-test-123.cfapps.eu00.hana.ondemand.com/web-hook/api/v1/events",
                            "type":"WEB_HOOK"
                        },
                        {
                            "name":"example_action_2",
                            "state":"ENABLED",
                            "type":"STORE"
                        }
                    ],
                    "subscriptions":[
                        {
                            "name":"example_subscription",
                            "conditions":[
                                "example_condition"
                            ],
                            "actions":[
                                "example_action"
                            ],
                            "state":"ENABLED"
                        },
                        {
                            "name":"example_subscription_2",
                            "conditions":[
                                "example_condition_2"
                            ],
                            "actions":[
                                "example_action_2"
                            ],
                            "state":"ENABLED"
                        }
                    ]
                }
            }

 

Creating a custom event using cloud platform cockpit and send email notification

  •       Open Alert notifications from service marketplace or navigate from the service-instances.

      Alert%20notification%20cockpit

Alert notification cockpit

  • To create a subscription select subscriptions on the left side of the window and click on   create. A wizard opens.

     

  • Enter the name of the subscription and click on create.

          subscription%20dialog

  • Click on create condition button . You can also select conditions if already specified.
  • Enter a name for the condition and select a condition type, condition and enter an expected  value. For example condition type = eventType contains po.create

 

  • Click on Assign button, this opens the select Actions.

         

  •    Click on create Action button .
  •    Select Action type as Email.

         

  •  Enter the name for your action, optional: Enter a fallback action if required.

         

  • Enter a email address to which notification has to be sent under Additional properties, then      click on create.

         

  • Bind the application to trigger standard notifications using cf bind appname

         cf bind-service APP_NAME SERVICE_INSTANCE -c ‘{“name”:”value”,”name”:”value”}’

  • Create a service key which will contain the url, client_id and client_secret for calling the  alerts  when required in an application.
{
	"url": "https://test-service-api.cfapps.sap.hana.ondemand.com",
	"client_id": "b6a3d917-fk05-49cb-a122-3e34567a5b1",
	"client_secret": "pEJBGTfegTY+DANjfm9cDrhyNNoQNwu"
}
  •  This REST API can be called from the application with POST to trigger notification to the   required source.

 

{
  "eventType": "po.create",
  "resource": {
    "resourceName": "purchase order create",
    "resourceType": "app",
    "tags": {
      "env": "dev"
    }
  },
  "severity": "FATAL",
  "category": "ALERT",
  "subject": "application has crashed",
  "body": "Kindly check the app as something has crashed",
  "tags": {
    "ans:correlationId": "30118",
    "ans:status": "CREATE_OR_UPDATE",
    "customTag": "42"
  }
}

The below code snippets demonstarte how the alert notification can be triggered with                                               NodeJS and java applications

NodeJS

var data = JSON.stringify(json);
        var auth = "xxxxxxxxxxxxxxxxxxxxxxx" + ":" + "xxxxxxxxxxxxxxxxxxxxxxx"
        var buff = Buffer.from(auth);
        var base64auth = "Basic " + buff.toString('base64');

        const options = {
            hostname: xxxxxxxxxxxxx.cfapps.sap.hana.ondemand.com',
            port: 443,
            path: '/cf/producer/v1/resource-events',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': data.length,
                'Authorization': base64auth
            },
        };

        const req = https.request(options, (res) => {
            console.log(`statusCode: ${res.statusCode}`)

            res.on('data', (d) => {
                process.stdout.write(d)
            })
        })

        req.on('error', (error) => {
            console.error(error)
        })

        req.write(data)
        req.end()

        res.writeHead(rc, {
            'Content-Type': 'application/json'
        });
        res.end(JSON.stringify({
            state: 1
        }));

 

 

JAVA

public void triggeralertnotification(HttpServletRequest request, HttpServletResponse response, PrintWriter writer) throws IOException, Exception{
	String auth = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx" + ":" + "xxxxxxxxxxxxxxxxxxxxxxxxxx";
	byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.UTF_8));
	String authHeaderValue = "Basic " + new String(encodedAuth);
	   String path = "https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxcfapps.sap.hana.ondemand.com/cf/producer/v1/resource-events";
		URL targetURL = new URL (path);
		HttpURLConnection con = (HttpURLConnection) targetURL.openConnection();
		con.setRequestMethod("POST");
		con.setRequestProperty("Content-Type", "application/json");
		con.setRequestProperty("Authorization", authHeaderValue);
		con.setRequestProperty( "charset", "utf-8");
		con.setConnectTimeout(5000);
		con.setDoOutput(true);
		
		DataOutputStream postbody = new DataOutputStream(con.getOutputStream());
		postbody.writeBytes(getAlertContent());
		postbody.flush();
		postbody.close();

		LOGGER.info("Alert notification called with service url"  + targetURL );
		int sc = con.getResponseCode();
		LOGGER.info("Returning service code "  + sc );
		con.disconnect();
		response.setStatus(sc);
		response.getWriter().println("<p>Alert notification triggered</p>");

	}

	private String getAlertContent() throws Exception{


	InputStream is = getClass().getResourceAsStream("/json/alert.json");
        String json = new BufferedReader(
                  new InputStreamReader(is, StandardCharsets.UTF_8))
                    .lines()
					.collect(Collectors.joining("\n"));


	 LOGGER.info("Send output mail format" + json);

        return json;
	}

 

  •  Trigger the endpoint, make an action or trigger the use case in the application where you   require the alert notification to be triggered.

 

  •  Within few minutes you will receive a mail to the mailbox with all the parameters you had  specified. which would look similar to the screenshot.

     

 

Conclusion

Hence alert notification allows an application to trigger alerts to a specified channel like Email, slack or workflow. which helps us to know and analyze the behavior of the application in production scenario’s.

In my  upcoming blog posts lets see how we can create a SAP Cloud Platform Logging service for cloud foundry.

 

 

Be the first to leave a comment
You must be Logged on to comment or reply to a post.