Name

sn_agent.AgentStaticImport

Description

No description available

Script

var AgentStaticImport = Class.create();
AgentStaticImport.prototype = {

  IMPORT_MARKER: "SNCImport:",

  initialize: function() {},

  staticImport: function(importRecord) {
      // Get attachment from import record
      var attachmentAPI = new GlideSysAttachment();
      var attachmentGr = attachmentAPI.getAttachments(importRecord.getTableName(), importRecord.getUniqueValue());
      if (!attachmentGr.next()) {
          gs.addErrorMessage(gs.getMessage("There is not attachment for this import. An attachment is required for import"));
          return;
      }

      // Stream in the content line by line until we have our JSON
      var contentStream = attachmentAPI.getContentStream(attachmentGr.getUniqueValue());
      var reader = new GlideTextReader(contentStream);
      var lines = [];
      var charCount = 0;
      var sizeProp = gs.getProperty('sn_agent.agent_static_import_char_read_limit', 1000000);
      while ((ln = reader.readLine()) != null) {
          charCount = charCount + ln.length;
          if (charCount > sizeProp) {
              this._createErrorCiHistory(importRecord, gs.getMessage("Payload character count: {0}", charCount), gs.getMessage("This payload is too large to process, adjust property to compensate or incrementally import the CI."));
              lines = [];
              charCount = 0;
          }

          if (ln.contains(this.IMPORT_MARKER)) {
              if (lines && lines.length > 0) {
                  this._processJsonPayload(importRecord, lines.join(""));
              }
              lines = [];
              charCount = 0;
              continue;
          }
          lines.push(ln);
          charCount = charCount + ln.length;
      }
      // Process the last CI in the attachment
      if (lines && lines.length > 0)
          this._processJsonPayload(importRecord, lines.join(""));
      importRecord.state = 'Processed';
      importRecord.update();
  },

  /*
   * The structure of idOutput is an IRE payload
   * {
   * "expected_output": {
   *    "items": [
   *       {"className":"cmdb_ci_computer",
   *        "operation":null,
   *        "sysId":null,
   *        "partialSysIds":null,
   *        "incompleteSysIds":null,
   *        "relatedSysIds":null,
   *        "relatedItems":null,
   *        "additionalRelatedItems":null,
   *        "maskedAttributes":null,
   *        "identifierEntrySysId":"556eb250c3400200d8d4bea192d3ae92",
   *        "errors":[
   *           {
   *              "error":"UPDATE_FAILED",
   *              "message":"Update failed with error: commit failed or was not attempted due to other errors."
   *           }
   *        ],
   *        "warnings":null,
   *        "identificationAttempts":[],
   *        "duplicateIndices":null,
   *        "duplicateLookupIndices":null,
   *        "duplicateRelatedIndices":null,
   *        "warningCount":0,
   *        "errorCount":1,
   *        "markers":[],
   *        "inputIndices":[0],
   *       "mergedPayloadIds":[]}
   *    ]
   *  },
   *  "additionalCommittedItems": [],
   *  "relation": [],
   *  "additionalCommittedRelations": [],
   *  "summary": "null",
   *  "hasError": "true",
   *  "hasWarning": "true",
   *  "logContextId": "ID of log"
   * }
   */
  processErrorMessage: function(idOutput) {
      var errorMessage;
      for (var j = 0; j < idOutput['idOutput']['items'].length; j++) {

          if (idOutput['idOutput']['items'][j]['errorCount'] != '0' && idOutput['idOutput']['items'][j]['errors']) {
              var errors = idOutput['idOutput']['items'][j]['errors'];
              for (var k = 0; k < errors.length; k++) {
                  errorMessage = errorMessage +
                      "\n" +
                      JSON.stringify(errors[k]['message']);
              }
          }
      }
      return errorMessage;
  },

  _processJsonPayload: function(importRecord, ciJsonPayload) {
      importRecord.total_cis = parseInt(importRecord.total_cis) + 1;
      try {
          var payload = JSON.stringify(JSON.parse(ciJsonPayload));
          var ciHistory = new GlideRecord('sn_agent_import_ci_history');
          ciHistory.initialize();
          ciHistory.setValue('status', 'Ready');
          ciHistory.setValue('import', importRecord.getUniqueValue());
          ciHistory.setValue('payload', payload);
          ciHistory.insert();

          //Conditionally execute script include for handling incoming data
          var uniqueTransactionId = "ASI_" + ciHistory.getUniqueValue();
          var handlerResult = this.callHandler(payload, uniqueTransactionId);

          var ciInfo = handlerResult['ciInfo'];
          var ireOutput = handlerResult['ireOutput'];

          if (ireOutput && ireOutput['hasError'] && ireOutput['hasError'] == 'true') {
              //Iterate through the items to check for errors
              ciHistory.setValue('error_message', this.processErrorMessage(ireOutput));
              importRecord.error_cis = parseInt(importRecord.error_cis) + 1;
              ciHistory.setValue('status', 'Error');
              ciHistory.update();
              return;
          }

          if (ciInfo) {
              ciHistory.setValue('cmdb_ci', ciInfo);
          } else {
              ciHistory.setValue('error_message', gs.getMessage("Did not recieve CI sys_id from processing payload."));
              importRecord.error_cis = parseInt(importRecord.error_cis) + 1;
              ciHistory.setValue('status', 'Error');
              ciHistory.update();
              return;
          }

          importRecord.success_cis = parseInt(importRecord.success_cis) + 1;
          ciHistory.setValue('status', 'Success');
          ciHistory.update();
      } catch (e) {
          var message = gs.getMessage("An exception occurred during JSON processing. Exception: {0}", e.message);
          if (!ciHistory) {
              this._createErrorCiHistory(importRecord, JSON.stringify(ciJsonPayload), message);
              return;
          }
          // ciHistory exists so set to Error and increment importRecord error count
          ciHistory.setValue('error_message', message);
          ciHistory.setValue('status', 'Error');
          importRecord.error_cis = parseInt(importRecord.error_cis) + 1;
          ciHistory.update();
          return;
      }
  },

  _createErrorCiHistory: function(importRecord, payload, message) {
      importRecord.error_cis = parseInt(importRecord.error_cis) + 1;
      var ciHistory = new GlideRecord('sn_agent_import_ci_history');
      ciHistory.initialize();
      ciHistory.setValue('status', 'Error');
      ciHistory.setValue('import', importRecord.getUniqueValue());
      ciHistory.setValue('payload', JSON.stringify(payload));
      ciHistory.setValue('error_message', message);
      ciHistory.insert();
  },

  callHandler: function(payload, uniqueTransactionId) {
      var ciInfo;
      var ireOutput;
      if (GlidePluginManager.isActive('sn_acc_visibility')) {
          var accv = new sn_acc_visibility.EnhancedDiscoveryHandler();
          accv.agentId = uniqueTransactionId;
          accv.setLog();
          ciInfo = accv.addDataIntoCMDB(payload);
          ireOutput = accv.ireOutput;
      } else {
          var accf = new MainDiscoveryHandler();
          accf.agentId = uniqueTransactionId;
          accf.setLog();
          ciInfo = accf.addDataIntoCMDB(payload);
          ireOutput = accf.ireOutput;
      }
      return {
          ciInfo: ciInfo,
          ireOutput: ireOutput
      };
  },

  type: 'AgentStaticImport'
};

Sys ID

5194076207e10110b736783eced30097

Offical Documentation

Official Docs: