Ejemplo n.º 1
0
    def run_sarg_command(self, cmdSARG, cmdArgs={}):
        """
    Wrapper function to convert CLI commands to the rest API.

    Args:

      :cmdSARG: Command to use (eg. reportsnaps, reportapps... etc.)
      :cmdArgs: Dictionary with arguments to the command

    Return:

      return a dictionary of the SARG command, mapping to the same JSON response from the API.

    Example:

      reportapps -a 1234 -x

      self.run_sarg_command("reportapps", { 'a': 1234, 'x': None })

    """

        _URI = self._sargURI

        # append the command to URI
        _URI += cmdSARG + '?'

        # append the argument
        for key in cmdArgs:
            if type(cmdArgs[key]) == dict:
                # Actifio API expects this to be urlencoded
                _URI += key + '=' + urlencode_str('&'.join([
                    filter_key + '=' + cmdArgs[key][filter_key]
                    for filter_key in cmdArgs[key]
                ])) + '&'
            elif cmdArgs[key] == None:
                _URI += urlencode_str(key) + '&'
            else:
                _URI += urlencode_str(key) + '=' + urlencode_str(
                    str(cmdArgs[key])) + '&'

        _URI += 'sessionid=' + Actifio._sessionid[self.appliance][
            self.username]["sessionid"]
        try:
            sargout = self._httppool.request('GET', _URI)
            if self._verbose:
                print(_URI)
        except urllib3.exceptions.NewConnectionError:
            raise ActConnectError("Unable to make connection to the appliance")
        else:
            response = json.loads(sargout.data)
            if sargout.status != 200:
                self._lastout = ''
                raise ActAPIError(response['errormessage'],
                                  response['errorcode'])
            else:
                self._lastout = response
                return self._lastout
Ejemplo n.º 2
0
  def __init__(self, appliance, username='', password='', token='', cert_validation=False, verbose=True):
    """
    Actifio instance:

    :appliance: IP or FQDN of the appliance
    :username: Username to login to the appliance
    :password: Password

    """
    # vendor key is fixed
    vendorkey = "195B-4370-2506-0A60-1F41-5829-067B-603C-6737-1244-0A11-6742-0745-4023-1A"
    # functools need a __name__ for the wraps
    self.__name__ = "Actifio"
    # compose the URI for the API
    self._apiBase = "/actifio/api"
    if token == '' and username == '':
      raise ActUserError ("Either 'username' or 'token' required for authentication.")
    
    if token != '':
      try:
        token_json = json.loads (base64.decodebytes(token))
      except:
        raise ActUserError ("Incorrect token format. Use 'act_gentoken' command to generate a authentication token")
    
      self.username = token_json["username"]
      self.password = token_json["password"]
    else:
      self.username = username
      self.password = password

    self.appliance = appliance
    self.version = 'not_known'

    #sessionid is unique per user in an appliance, and this is global 
    if Actifio._sessionid.get(appliance) == None:
      Actifio._sessionid.update({appliance: {}})
    if Actifio._sessionid[appliance].get(self.username) == None:
      Actifio._sessionid[appliance].update({ self.username: {}})
      Actifio._sessionid[appliance][self.username].update({ "sessionid": "" })
      # Actifio._sessionid[appliance][self.username].update({ "password": self.password})
    
    # compose the login params
    self._loginParams = "/login?name=" + urlencode_str(self.username)
    self._loginParams += "&password="******"&vendorkey=" + vendorkey

    self._loginURI = self._apiBase + self._loginParams
    self._infoURI = self._apiBase + "/info/"
    self._taskURI = self._apiBase + "/task/"
    self._sargURI = self._apiBase + "/report/"

    # create the https poolmanager
    cert_str = 'CERT_REQUIRED' if cert_validation else 'CERT_NONE'

    timeout = urllib3.util.timeout.Timeout(connect=5.0)
    self._httppool = urllib3.HTTPSConnectionPool(host=appliance, port=443, cert_reqs=cert_str, timeout=timeout)
    self._verbose = verbose
Ejemplo n.º 3
0
  def __init__(self, appliance, username, password, cert_validation=False, verbose=True):
    """
    Actifio instance:

    :appliance: IP or FQDN of the appliance
    :username: Username to login to the appliance
    :password: Password

    """
    # vendor key is fixed
    vendorkey = "195B-4370-2506-0A60-1F41-5829-067B-603C-6737-1244-0A11-6742-0745-4023-1A"
    # functools need a __name__ for the wraps
    self.__name__ = "Actifio"
    # compose the URI for the API
    self._apiBase = "/actifio/api"
    self.appliance = appliance
    self.username = username
    self.version = 'not_known'
    #sessionid is unique per user in an appliance
    Actifio._sessionid.update({appliance: {}})
    Actifio._sessionid[appliance].update({ username: ''})
    # compose the login params
    self._loginParams = "/login?name=" + urlencode_str(username)
    self._loginParams += "&password="******"&vendorkey=" + vendorkey

    self._loginURI = self._apiBase + self._loginParams
    self._infoURI = self._apiBase + "/info/"
    self._taskURI = self._apiBase + "/task/"
    self._sargURI = self._apiBase + "/report/"

    # create the https poolmanager
    cert_str = 'CERT_REQUIRED' if cert_validation else 'CERT_NONE'

    timeout = urllib3.util.timeout.Timeout(connect=5.0)
    self._httppool = urllib3.HTTPSConnectionPool(host=appliance, port=443, cert_reqs=cert_str, timeout=timeout)
    self._verbose = verbose
Ejemplo n.º 4
0
    def run_uds_command(self, cmdType, cmdUDS, cmdArgs={}):
        """
    Wrapper function to convert CLI commands to the rest API.

    Args:

      :cmdType: info / task
      :cmdUDS: Command to use (eg. lsuser, lshost, mkapplication... etc.)
      :cmdArgs: Dictionary with arguments to the command

    Returns:

      Returns a dictionary of API response.

    Example:

      vmdiscovery -discovercluster -host 1234

      { 'discovercluster': None, 'host': 1234 }

      lsapplication -filtervalues "appname=mydb&hostname=myhost"

      { 'filtervalues': { 'appname': 'mydb', 'hostname': 'myhost' } }

      lshost 123

      { 'argument': 123 }


    .. note:: RESTfulAPI_*.pdf would be good referecne point for the __SIMILARITY__ and __PATTERN__ of the cmdArgs.

    """

        _URI = self._infoURI if cmdType == "info" else self._taskURI

        # append the command to URI
        _URI += cmdUDS + '?'

        # provision for the non-equal opprations
        def __regex_args(key, value):
            import re
            not_equal = re.compile(r'^not\s+(.*)')
            greater_than = re.compile(r'^\>\s*(.*)')
            smaler_than = re.compile(r'^\<\s*(.*)')

            ne_match = not_equal.search(value)
            gt_match = greater_than.search(value)
            st_match = smaler_than.search(value)

            if ne_match is not None:
                return key + "!=" + ne_match.group(1)
            if st_match is not None:
                if key != "provisioningoptions":
                    return key + "<" + st_match.group(1)
            if gt_match is not None:
                return key + ">" + gt_match.group(1)
            else:
                return key + "=" + value

        # append the argument
        for key in cmdArgs:
            if type(cmdArgs[key]) == dict:
                # Actifio API expects this to be urlencoded
                _URI += key + '=' + urlencode_str('&'.join([
                    __regex_args(filter_key, cmdArgs[key][filter_key])
                    for filter_key in cmdArgs[key]
                ])) + '&'
            elif cmdArgs[key] == None:
                _URI += urlencode_str(key) + '&'
            else:
                _URI += urlencode_str(key) + '=' + urlencode_str(
                    str(cmdArgs[key])) + '&'

        _URI += 'sessionid=' + Actifio._sessionid[self.appliance][
            self.username]["sessionid"]
        try:
            udsout = self._httppool.request(
                'GET' if cmdType == 'info' else 'POST', _URI)
            if self._verbose:
                print(_URI)
        except Exception as e:
            # print (e)
            raise ActConnectError("Failed to connect the appliance")
        else:
            response = json.loads(udsout.data)
            if udsout.status != 200:
                self._lastout = ''
                raise ActAPIError(response['errormessage'],
                                  response['errorcode'])
            else:
                self._lastout = response
                return self._lastout