Create an alarm from a script

🟢 Beginner

alarm script

In this tutorial, you will learn how to create a script that periodically creates a health-check alarm and logs the result of the insertion.

  • Configure a detached script with a scheduled execution (every hour).

  • Write a JavaScript script that calls the alarms API to create an alarm.

  • Log the result of the alarm insertion using the OnSphere logging API.

git checkout origin/osp-alarms-configuration .
git checkout origin/osp-web-configuration .
git checkout origin/osp-scripts-configuration .
git checkout origin/example-alarms-created-from-script .

Configuration structure

@startuml
skinparam backgroundColor transparent

package "root/.../alarm-generator" {
    [detached.scripts] as trigger
}

node ospscripts as "osp-scripts"
node ospalarms as "osp-alarms"

ospscripts -[#black]> trigger : <size:11><color:black> **executes**
trigger -[#firebrick]r-> ospalarms : <size:11><color:firebrick> **Create alarm**
@enduml

Steps

1. Create a detached script that will be executed every hour

root/alarm-generator/detached.scripts

{
    "moduleId": "modules.scripts.scripts-1",
    "scheduledExecutions": ["0/10 * * ? * * *"],
    "accessedValues": [],
    "sourceFile": "root/alarm-generator/script.js"
}

2. Write a script that creates an alarm and logs the result of the insertion

root/alarm-generator/script.js

const CLEAR_SEVERITY = 100;

main();

function main() {
    const timestamp = trigger.content;
    if (!!timestamp) {
        const alarm = alarms.newAlarmBuilder("" + timestamp, CLEAR_SEVERITY)
            .setSummary("Healtcheck alarm " + timestamp)
            .setLocation("Internal")
            .setSource("localhost")
            .addTag("Healthcheck")
            .build();
        const result = alarms.create(alarm);
        if (result.success) {
            log.info("Healthcheck alarm successfully inserted at [{}].", timestamp);
        } else {
            log.error("Healthcheck alarm failed to be inserted at [{}].", timestamp);
        }
    }
}