Name

sn_agent.AgentSingleLineInstallerCommands

Description

No description available

Script

var AgentSingleLineInstallerCommands = Class.create();
AgentSingleLineInstallerCommands.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {

  /**
   *
   * Build one-line installer commands
   *
   **/
  getSingleLineInstallCmd: function() {
      var type = this.getParameter('sysparm_type');
      var apiKeySysId = this.getParameter('sysparm_apiKeySysId');

      var endpointUrl = this.getEndpointUrlList();
      var apiKey = this.getApiKeyBySysId(apiKeySysId);

      var apiKeyAndEndPoint = "ACC_API_KEY=" + apiKey + " ACC_MID=\"" + endpointUrl + "\"";
      if (type == "windows")
          return "msiexec /i <msi_file_path> /quiet /qn /norestart " + apiKeyAndEndPoint;

      var installScriptLoc = this.getInstallScriptUrl();

      if (this.isDevMode() == 'true')
          apiKeyAndEndPoint += " DEV_MODE=1";

      return apiKeyAndEndPoint + " bash -c \"$(curl -L " + installScriptLoc + ")\"";
  },

  getSingleLineInstallCmdWithoutMid: function() {
      var type = this.getParameter('sysparm_type');

      // Adding the Cloud Services endpoint to hardcoded US value
      var command = "CONNECT_WITHOUT_MID=\"true\" ACC_CNC=\"<gateway_endpoint>\" ";

      // get Registration key
      var regGr = new GlideRecord("sn_agent_registration_key");
      regGr.query();
      if (!regGr.next()) {
          gs.warn("Unable to get registration key for single line command");
          command = command + "REGISTRATION_KEY=\"<registration_key>\" ";
      } else
          command = command + "REGISTRATION_KEY=\"" + regGr.getValue("registration_key") + "\" ";

      // Add instance URL
      var commandInstanceUrl = gs.getProperty("glide.servlet.uri");

      if (gs.nil(commandInstanceUrl))
          commandInstanceUrl = "https://" + gs.getProperty('instance_name') + ".service-now.com/";

      command = command + "INSTANCE_URL=\"" + commandInstanceUrl + "\" ";

      if (type == "windows")
          return "msiexec /i <msi_file_path> /quiet /qn /norestart " + command;

      var installScriptEndpoint = this.getInstallScriptUrl();

      if (this.isDevMode() == 'true')
          command += " DEV_MODE=1";

      return command + " bash -c \"$(curl -L " + installScriptEndpoint + ")\"";
  },

  /*
  	Returns all active keys as an array of objects.
  	Each object has the following attributes:
  	- expires - The expiration data of the API Key - "never" indicate the key never expires
  	- name - The name of the API Key
  	- sysId - The Sys ID of the API Key

  */
  getDecryptedActiveKeys: function() {
      return JSON.stringify(this.getAllActiveKeys());
  },

  /**
   *
   * Check is dev mode is on/off
   *
   **/
  isDevMode: function() {
      return '' + gs.getProperty('sn_agent.dev_mode', 'false');
  },

  /*
  	Returns the API Key based on its Sys ID
  */
  getApiKeyBySysId: function(sysId) {
      if (!sysId)
          return "<api-key>";

      var gr;

      // Get API Key from new table
      if (gs.tableExists('mid_webserver_api_key_credentials')) {
          gr = new GlideRecord('mid_webserver_api_key_credentials');
          if (!gr.get('sys_id', sysId))
              return "<api-key>";

          return this.decryptKey(gr.getValue('authentication_key'));
      }

      // Get API key from legacy table
      else if (gs.tableExists('ecc_agent_webserver_api_key')) {
          gr = new GlideRecord('ecc_agent_webserver_api_key');

          if (!gr.get('sys_id', sysId))
              return "<api-key>";

          return gr.getValue('api_key');
      }

      return "<api-key>";
  },

  // Returns the legacy API
  getLegacyApiKey: function() {
      var arrKeys = [];
      var keyObj = {};

      keyObj.name = "Singleton";
      keyObj.expires = "never";

      var agentExt = new GlideRecord("ecc_agent_webserver_api_key");
      agentExt.query();
      if (agentExt.next())
          keyObj.sysId = agentExt.getValue("sys_id");

      arrKeys.push(keyObj);

      return arrKeys;
  },

  /*
  	returns an array of all active API Keys
  */
  getAllActiveKeys: function() {
      // Legacy
      if (!gs.tableExists('mid_webserver_api_key_credentials'))
          return this.getLegacyApiKey();

      var arrKeys = [];
      var apiKeys = new GlideRecord("mid_webserver_api_key_credentials");
      apiKeys.addActiveQuery();
      // First order based on order, than if the key expires or not than, by expiration date
      apiKeys.orderBy('order');
      apiKeys.orderBy('expires');
      apiKeys.orderByDesc('expiration_time');
      apiKeys.query();

      while (apiKeys.next()) {
          var keyObj = {};

          if (apiKeys.getValue('expires') == 1) {
              // If set to expire, and is already expired - do not return this value
              var exTime = new GlideDateTime(apiKeys.getValue('expiration_time'));
              var now = new GlideDateTime();
              if (now.after(exTime))
                  continue;

              keyObj.expires = new GlideDateTime(apiKeys.getValue('expiration_time')).getDisplayValue();
          } else
              keyObj.expires = 'never';

          // If needs to have the API Key - this is how
          //keyObj.apiKey = this.decryptKey(apiKeys.getValue('authentication_key'));
          keyObj.name = apiKeys.getValue('name');
          keyObj.sysId = apiKeys.getValue('sys_id');

          arrKeys.push(keyObj);
      }

      return arrKeys;
  },

  decryptKey: function(encryptedKey) {
      var clearData = "";
      try {
          var op = new sn_kmf_ns.KMFCryptoOperation("global.com_snc_core_automation_connection_credential_glideencrypter", "symmetric_unwrapping").withAlgorithm("AES").withOutputFormat("KMFNone");
          clearData = op.doOperation(encryptedKey);
      } catch (e) {
          gs.warn("AgentSingleLineInstallerCommands: decrypting key had failed.");
      }

      if (!clearData)
          return "<api-key>";

      return clearData;
  },

  /**
   *
   * Build install_script url
   *
   **/
  getInstallScriptUrl: function() {
      var instanceUrl = gs.getProperty("glide.servlet.uri");

      if (gs.nil(instanceUrl))
          instanceUrl = "https://" + gs.getProperty('instance_name') + ".service-now.com/";

      if (instanceUrl.endsWith('/'))
          return instanceUrl + "api/sn_agent/agents/install_agent";

      return instanceUrl + "/api/sn_agent/agents/install_agent";
  },


  /**
   *
   * select midserver which has the lowest number of agents
   *
   **/
  getEndpointUrlList: function() {

      var DEFAULT_MAX_INSTALLER_ENDPOINTS = 3;
      var MAX_INSTALLER_ENDPOINTS = parseInt(gs.getProperty('sn_agent.installer_max_endpoints', DEFAULT_MAX_INSTALLER_ENDPOINTS));

      var eccAgent = new GlideRecord('sn_agent_mid_webserver_endpoint_url_view');
      eccAgent.addQuery("endpoint_status", "Started");
      eccAgent.orderBy('midserver_number_of_agents');
      eccAgent.setLimit(MAX_INSTALLER_ENDPOINTS);
      eccAgent.query();

      var endpointUrls = [];
      while (eccAgent.next()) {
          endpointUrls.push(eccAgent.getValue("endpoint_endpoint_url"));
      }

      if (endpointUrls.length <= 0)
          return "wss://<mid_ip>:<port>/ws/events";

      return endpointUrls.join();
  },

  /**
   *
   * Check that Cloud Services is active on Instance by checking for module existence
   *
   **/
  isCloudServicesActive: function() {
      return GlidePluginManager.isActive("com.sn_itom_cloud_services");
  },

  type: 'AgentSingleLineInstallerCommands'
});

Sys ID

c6ce67645ff5f01069d74db3de7313e0

Offical Documentation

Official Docs: