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

Is it possible to create a Workflow to call Dynatrace Objects API?

dannemca
DynaMight Guru
DynaMight Guru

Hi team, good day.

The idea is to create a Workflow to disable CPU monitoring for some hosts in a crontab way (we do downsize some machines for $aving purpose) to avoid unneeded alerts/problems, since the Maintenance Window does not allow us to suppres a specific event type, yet.

I know I can call a Workflow in a crontab way, what I don't know is how to properly call the api/v2/settings/objects API as a task. I was expecting something we have for ingest data, for example.

Any clue/help on this?

Thanks.

Site Reliability Engineer @ Kyndryl
4 REPLIES 4

rkdy
Dynatrace Helper
Dynatrace Helper

A possible suggestion is creating two Workflows, one where you disable monitoring and one where you enable it based on your schedule, both with the same JavaScript task but different payloads for the PUT call. 

Following is some basic JavaScript code that could be used in the workflow; just meant as a starting point; it needs both `settings.read` and `settings.write` scopes for the access token

const https://{environmentid}.live.dynatrace.com/api/v2/";
const api_token = "dt0c01.XXXXXXXXXXXXXXXXXXXXXXXX.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

// Step 1: Get all Object Ids for HOST schema
const options = {
  method: 'GET',
  headers: {
    'Authorization': `Api-Token ${api_token}`
  }
};

https.get(`${base_url}settings/objects?schemaIds=builtin:host.monitoring&fields=objectId,value,scope`, options, (response) => {
  let data = '';

  response.on('data', (chunk) => {
    data += chunk;
  });

  response.on('end', () => {
    const hostObjects = JSON.parse(data);
    if ("error" in hostObjects) {
      console.log(`Error occurred: ${hostObjects.error.message}`);
      process.exit(1);
    }

    // Extracting host IDs and object IDs from the response
    const hostIds = hostObjects.items.map(item => item.scope);
    const objectIds = hostObjects.items.map(item => item.objectId);

    // Step 2: Modify monitoring settings for all hosts
    const payload = {
      value: {
        enabled: true, // or false
        autoInjection: true // or false
      }
    };

    hostIds.forEach(hostId => {
      const objectId = objectIds[hostIds.indexOf(hostId)];
      const requestOptions = {
        method: 'PUT',
        headers: {
          'Authorization': `Api-Token ${api_token}`,
          'Content-Type': 'application/json'
        }
      };

      const req = https.request(`${base_url}settings/objects/${objectId}`, requestOptions, (res) => {
        let responseData = '';
        res.on('data', (chunk) => {
          responseData += chunk;
        });

        res.on('end', () => {
          if (res.statusCode === 200) {
            console.log(`Modified monitoring settings for host ID: ${hostId} (Object ID: ${objectId})`);
          } else {
            console.log(`Failed to modify monitoring settings for host ID: ${hostId} (Object ID: ${objectId})`);
          }
        });
      });

      req.write(JSON.stringify(payload));
      req.end();
    });
  });

}).on("error", (error) => {
  console.error(`Error: ${error.message}`);
});




dannemca
DynaMight Guru
DynaMight Guru

Thanks, @rkdy , it was really helpful.

That's the final javascript code for the purpose I need, to disable the CPU monitoring for a specific host only:

 

var https = require('https');

const base_url = "https://myenv.live.dynatrace.com/api/v2/";
const api_token = "dt0c01.XXXXXXXXXXXXXXXXXXXXXXXX.XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";

// Step 1: Get all Object Ids for HOST schema
const options = {
  method: 'GET',
  headers: {
    'Authorization': `Api-Token ${api_token}`
  }
};

https.get(`${base_url}settings/objects?pageSize=500&scopes=HOST-XXXXXXXXXXXXXXX&schemaIds=builtin:anomaly-detection.infrastructure-hosts&fields=objectId,value,scope`, options, (response) => {
  let data = '';

  response.on('data', (chunk) => {
    data += chunk;
  });

  response.on('end', () => {
    const hostObjects = JSON.parse(data);
    if ("error" in hostObjects) {
      console.log(`Error occurred: ${hostObjects.error.message}`);
      process.exit(1);
    }

    // Extracting host IDs and object IDs from the response
    const hostIds = hostObjects.items.map(item => item.scope);
    const objectIds = hostObjects.items.map(item => item.objectId);

    // Step 2: Modify monitoring settings for all hosts
    const payload = {
		value: {
                "host": {
                    "connectionLostDetection": {
                        "enabled": true,
                        "onGracefulShutdowns": "DONT_ALERT_ON_GRACEFUL_SHUTDOWN"
                    },
                    "highCpuSaturationDetection": {
                        "enabled": false
                    },
                    "highSystemLoadDetection": {
                        "enabled": false
                    },
                    "highMemoryDetection": {
                        "enabled": true,
                        "detectionMode": "auto"
                    },
                    "highGcActivityDetection": {
                        "enabled": true,
                        "detectionMode": "auto"
                    },
                    "outOfMemoryDetection": {
                        "enabled": true,
                        "detectionMode": "auto"
                    },
                    "outOfThreadsDetection": {
                        "enabled": true,
                        "detectionMode": "auto"
                    }
                },
                "network": {
                    "networkDroppedPacketsDetection": {
                        "enabled": true,
                        "detectionMode": "auto"
                    },
                    "networkErrorsDetection": {
                        "enabled": true,
                        "detectionMode": "auto"
                    },
                    "highNetworkDetection": {
                        "enabled": false
                    },
                    "networkTcpProblemsDetection": {
                        "enabled": false
                    },
                    "networkHighRetransmissionDetection": {
                        "enabled": false
                    }
                }
            }
    };

    hostIds.forEach(hostId => {
      const objectId = objectIds[hostIds.indexOf(hostId)];
      const requestOptions = {
        method: 'PUT',
        headers: {
          'Authorization': `Api-Token ${api_token}`,
          'Content-Type': 'application/json'
        }
      };

      const req = https.request(`${base_url}settings/objects/${objectId}`, requestOptions, (res) => {
        let responseData = '';
        res.on('data', (chunk) => {
          responseData += chunk;
        });

        res.on('end', () => {
          if (res.statusCode === 200) {
            console.log(`Modified monitoring settings for host ID: ${hostId} (Object ID: ${objectId})`);
          } else {
            console.log(`Failed to modify monitoring settings for host ID: ${hostId} (Object ID: ${objectId})`);
          }
        });
      });

      req.write(JSON.stringify(payload));
      req.end();
    });
  });

}).on("error", (error) => {
  console.error(`Error: ${error.message}`);
});

 

Regards.

Site Reliability Engineer @ Kyndryl

dannemca
DynaMight Guru
DynaMight Guru

I completely missed the native option that runs http requests into workflow :facepalm:

Screenshot 2023-11-08 143936.png

Javascript code is required to run batch executions, but in my case, it was simple run in two hosts only.

Anyway, I learned, and I am happy. 😅

Site Reliability Engineer @ Kyndryl

rkdy
Dynatrace Helper
Dynatrace Helper

That was an oversite on my end, too :facepalm_pickard:; one improvement if you were to have gone down the route of using JavaScript for future reference would be to use the SDK for Typescript - SDK for TypeScript | Dynatrace Developer

Featured Posts