cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

[Unlock Workflow Power] only with one Running.JS scheduled Task

uros_djukic1
Dynatrace Mentor
Dynatrace Mentor

In our customer context, we used the Workflow to collect the availability rate on a specific scenario in a solution composed of external APIs. In order to feed the main dashboard of availability of "critical" applications. Thus meeting a functional need.

Valid and compliant for Dynatrace SaaS platform version 1.296.

*** client context 

Formerly we had to use a Python script and implement a V1 extension, here the simple use of the Workflow with a little knowledge via Javascript makes our work easier!


*** WORKAROUND OVERVIEW

Before sharing my "only one Task JS" please find main lines of my running.JS :

   1 .  // Retrieve credentials from the credential vault for External API
   2.  // fetching bearer Token value
   3.  // collect APIs parameters from external endpoints
   4 . // ingest metric to Dynatrace 

Find my script lightened but with the important steps, all-in-one running.JS task as depicted below :

import { credentialVaultClient } from "@dynatrace-sdk/client-classic-environment-v2";
import { executionsClient } from '@dynatrace-sdk/client-automation';
import { execution } from '@dynatrace-sdk/automation-utils';
import { metricsClient } from "@dynatrace-sdk/client-classic-environment-v2";
 
           // Main()
export default async function ({ execution_id }) { ==>  Main function 
  try {
    // Retrieve credentials from the credential vault for External endpoint API
    const External endpointCredentials = await credentialVaultClient.getCredentialsDetails(
      { id: "CREDENTIALS_VAULT-XXX" }
    );
    const External endpointUsername = External endpointCredentials.username;
    const External endpointPassword = External endpointCredentials.password;
 
    if (!External endpointUsername || !External endpointPassword) {
      throw new Error('External endpoint credentials are not defined.');
    }
 
// fetching bearer Token value
    async function fetchBearerToken() { ==> function 1 : getToken from External endpoint
 
      try {
        const response = await fetch('https://api.External endpoint.XXX/auth/login', {
          method: 'POST',
          body: JSON.stringify({ email: External endpointUsername, password: External endpointPassword }),
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
          },
        });
 
        // Parse response body as JSON
 
    }
 
// collect APIs parameters from External endpoint
    async function fetchData(bearerToken) { ==> function 2 : get parameters/data from External endpoint (i.e. scenarioName)
 
      try {
        console.log('Bearer Token:', bearerToken);
 
// make dates dynamic
 
function formatDate(date) {
var d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();
 
if (month.length < 2) 
        month = '0' + month;
if (day.length < 2) 
        day = '0' + day;
 
return [year, month, day].join('-');
};
 
var today = new Date();
var firstDay = new Date(today.getFullYear(),today.getMonth()-1,1);
firstDay.setDate(Math.min(today.getDate(),firstDay.getDate()));
var lastDay = formatDate(new Date(today.getFullYear(),today.getMonth(),0))+ ' 00:00:00';
firstDay=formatDate(firstDay.getFullYear()+'-'+(firstDay.getMonth()+1)+'-'+firstDay.getDate())+ ' 00:00:00';
console.log(firstDay);
console.log(lastDay);
 
        const body = {
          "dates": {
            "from": firstDay,
            "to": lastDay
          }
        };
 
 
        // Define the endpoint to fetch data from
        const apiEndpoint = 'https://api.External endpoint.XXX.net/results/avail/XXX'; // Replace with the actual endpoint
 
 
        // Try to parse response as JSON if needed
 
    }
 
    // Fetch bearer token and data
    const bearerToken = await fetchBearerToken();
    const scenarioData = await fetchData(bearerToken);
 
    // Assuming the scenarioData contains the relevant fields directly
    const get_scenario_name = scenarioData.scenarioName;
    const get_scenario_rate = scenarioData.ratePercent;
 
 
    // Send the metrics to Dynatrace ==>  Ingest metrics via Dynatrace API 
 
    const environment = "/platform/classic/environment-api/v2/metrics/ingest";
    try {
      const response = await fetch(environment, {
        method: 'POST',
        headers: {
          'Content-Type': 'text/plain; charset=utf-8',
        },
        body: `External endpoint.availability.rate,scenario.name=${get_scenario_name} ${get_scenario_rate}`,
      });
 
      // Try to parse response as JSON if needed
 
 
  } catch (error) {
    console.error('Error in script execution:', error);
    throw error;
  }


 I hope it helps,

Thanks



 

0 REPLIES 0

Featured Posts