예제 #1
0
 def validateVersion(self):
     version = self.get(uri['version'])
     if 'minimumVersion' in version:
         if self._apiVersion < version['minimumVersion']:
             raise HPEOneViewException('Unsupported API Version')
     if 'currentVersion' in version:
         if self._apiVersion > version['currentVersion']:
             raise HPEOneViewException('Unsupported API Version')
     self._validateVersion = True
예제 #2
0
    def login(self, cred, verbose=False):
        try:
            if self._validateVersion is False:
                self.validateVersion()
        except Exception:
            raise(HPEOneViewException('Failure during login attempt.\n %s' % traceback.format_exc()))

        cred['loginMsgAck'] = True  # This will handle the login acknowledgement message
        self._cred = cred
        try:
            if self._cred.get("sessionID"):
                self.set_session_id(self._cred["sessionID"])
                task, body = self.put(uri['loginSessions'], None)
            else:
                self._cred.pop("sessionID", None)
                task, body = self.post(uri['loginSessions'], self._cred)
        except HPEOneViewException:
            logger.exception('Login failed')
            raise
        auth = body['sessionID']
        # Add the auth ID to the headers dictionary
        self._headers['auth'] = auth
        self._session = True
        if verbose is True:
            print(('Session Key: ' + auth))
        logger.info('Logged in successfully')
예제 #3
0
    def patch(self, uri, timeout=-1):
        """
        Sets the state of task to cancelling only if IsCancellable is set to true for the task and its children or
        children are in terminal state.

        Args:
            uri: URI of task resource.
            timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
                in OneView; it just stops waiting for its completion.

        Returns:
            dict: Updated resource.
        """
        resp, body = self._connection.do_http('PATCH', path=uri, body=None)

        if resp.status >= 400:
            raise HPEOneViewException(body)
        elif resp.status == 304:
            if body and not isinstance(body, dict):
                try:
                    body = json.loads(body)
                except Exception:
                    pass
        elif resp.status == 202:
            task = self._connection.__get_task_from_response(resp, body)
            return self._task_monitor.wait_for_task(task, timeout)

        return body
    def test_exception_constructor_with_unicode(self):
        exception = HPEOneViewException(u"A message string")

        self.assertEqual(exception.msg, "A message string")
        self.assertEqual(exception.oneview_response, None)
        self.assertEqual(exception.args[0], "A message string")
        self.assertEqual(len(exception.args), 1)
    def test_exception_constructor_with_invalid_dict(self):
        exception = HPEOneViewException({'msg': "A message string"})

        self.assertEqual(exception.msg, None)
        self.assertEqual(exception.oneview_response,
                         {'msg': "A message string"})
        self.assertEqual(exception.args[0], None)
        self.assertEqual(exception.args[1], {'msg': "A message string"})
    def test_should_log_message(self, mock_logging_error, mock_traceback):
        message = "test message"
        exception = HPEOneViewException(message)
        traceback_ex = None
        handle_exceptions(exception.__class__, exception, traceback_ex,
                          mock_logging_error)

        log_message = "Uncaught Exception: HPEOneViewException with message: test message"
        mock_logging_error.error.assert_called_once_with(log_message)
    def test_should_print_exception(self, mock_logging_error, mock_traceback):
        message = "test message"
        exception = HPEOneViewException(message)
        traceback_ex = None
        handle_exceptions(exception.__class__, exception, traceback_ex,
                          mock_logging_error)

        mock_traceback.assert_called_once_with(exception.__class__, exception,
                                               traceback_ex)
    def test_exception_constructor_with_invalid_type(self):
        exception = HPEOneViewException(
            ['List, item 1', "List, item 2: A message string"])

        self.assertEqual(exception.msg, None)
        self.assertEqual(exception.oneview_response,
                         ['List, item 1', "List, item 2: A message string"])
        self.assertEqual(exception.args[0], None)
        self.assertEqual(exception.args[1],
                         ['List, item 1', "List, item 2: A message string"])
    def test_should_log_oneview_reponse(self, mock_logging_error,
                                        mock_traceback):
        message = {"msg": "test message"}
        exception = HPEOneViewException(message)
        traceback_ex = None
        handle_exceptions(exception.__class__, exception, traceback_ex,
                          mock_logging_error)

        log_message = "Uncaught Exception: HPEOneViewException with message: \n{'msg': 'test message'}"
        mock_logging_error.error.assert_called_once_with(log_message)
예제 #10
0
    def test_pickle_HPEOneViewException_message(self):
        message = "test message"
        exception = HPEOneViewException(message)
        tempf = tempfile.NamedTemporaryFile(delete=False)
        with tempf as f:
            pickle.dump(exception, f)

        with open(tempf.name, 'rb') as f:
            exception = pickle.load(f)

        os.remove(tempf.name)
        self.assertEqual('HPEOneViewException', exception.__class__.__name__)
예제 #11
0
    def test_should_create_new_user(self):
        self.resource.get_by.side_effect = HPEOneViewException('FAKE_MSG_ERROR')
        self.resource.create.return_value = DEFAULT_PARAMS

        self.mock_ansible_module.params = PARAMS_FOR_PRESENT

        UserModule().run()

        self.mock_ansible_module.exit_json.assert_called_once_with(
            changed=True,
            msg=UserModule.MSG_CREATED,
            ansible_facts=dict(user=DEFAULT_PARAMS)
        )
예제 #12
0
    def download_to_stream(self,
                           stream_writer,
                           url,
                           body='',
                           method='GET',
                           custom_headers=None):
        http_headers = self._headers.copy()
        if custom_headers:
            http_headers.update(custom_headers)

        chunk_size = 4096
        conn = None

        successful_connected = False
        while not successful_connected:
            try:
                conn = self.get_connection()
                conn.request(method, url, body, http_headers)
                resp = conn.getresponse()

                if resp.status >= 400:
                    self.__handle_download_error(resp, conn)

                if resp.status == 302:
                    return self.download_to_stream(
                        stream_writer=stream_writer,
                        url=resp.getheader('Location'),
                        body=body,
                        method=method,
                        custom_headers=http_headers)

                tempbytes = True
                while tempbytes:
                    tempbytes = resp.read(chunk_size)
                    if tempbytes:  # filter out keep-alive new chunks
                        stream_writer.write(tempbytes)

                conn.close()
                successful_connected = True
            except http.client.BadStatusLine:
                logger.warning('Bad Status Line. Trying again...')
                if conn:
                    conn.close()
                time.sleep(1)
                continue
            except http.client.HTTPException:
                raise HPEOneViewException(
                    'Failure during login attempt.\n %s' %
                    traceback.format_exc())

        return successful_connected
예제 #13
0
 def get(self, uri, custom_headers=None):
     resp, body = self.do_http('GET', uri, '', custom_headers=custom_headers)
     if resp.status >= 400:
         raise HPEOneViewException(body)
     if resp.status == 302:
         body = self.get(resp.getheader('Location'))
     if type(body) is dict:
         if 'nextPageUri' in body:
             self._nextPage = body['nextPageUri']
         if 'prevPageUri' in body:
             self._prevPage = body['prevPageUri']
         if 'total' in body:
             self._numTotalRecords = body['total']
         if 'count' in body:
             self._numDisplayedRecords = body['count']
     return body
예제 #14
0
    def __handle_download_error(self, resp, conn):
        try:
            tempbytes = resp.read()
            tempbody = tempbytes.decode('utf-8')
            try:
                body = json.loads(tempbody)
            except ValueError:
                body = tempbody
        except UnicodeDecodeError:  # Might be binary data
            body = tempbytes
            conn.close()
        if not body:
            body = "Error " + str(resp.status)

        conn.close()
        raise HPEOneViewException(body)
예제 #15
0
    def post_multipart(self, uri, fields, files, baseName, verbose=False):
        content_type = self.encode_multipart_formdata(fields, files, baseName,
                                                      verbose)
        inputfile = self._open(files + '.b64', 'rb')
        mappedfile = mmap.mmap(inputfile.fileno(), 0, access=mmap.ACCESS_READ)
        if verbose is True:
            print(('Uploading ' + files + '...'))
        conn = self.get_connection()
        # conn.set_debuglevel(1)
        conn.connect()
        conn.putrequest('POST', uri)
        conn.putheader('uploadfilename', baseName)
        conn.putheader('auth', self._headers['auth'])
        conn.putheader('Content-Type', content_type)
        totalSize = os.path.getsize(files + '.b64')
        conn.putheader('Content-Length', totalSize)
        conn.putheader('X-API-Version', self._apiVersion)
        conn.endheaders()

        while mappedfile.tell() < mappedfile.size():
            # Send 1MB at a time
            # NOTE: Be careful raising this value as the read chunk
            # is stored in RAM
            readSize = 1048576
            conn.send(mappedfile.read(readSize))
            if verbose is True:
                print('%d bytes sent... \r' % mappedfile.tell())
        mappedfile.close()
        inputfile.close()
        os.remove(files + '.b64')
        response = conn.getresponse()
        body = response.read().decode('utf-8')

        if body:
            try:
                body = json.loads(body)
            except ValueError:
                body = response.read().decode('utf-8')

        conn.close()

        if response.status >= 400:
            raise HPEOneViewException(body)

        return response, body
예제 #16
0
    def do_http(self, method, path, body, custom_headers=None):
        http_headers = self._headers.copy()
        if custom_headers:
            http_headers.update(custom_headers)

        bConnected = False
        conn = None
        while bConnected is False:
            try:
                conn = self.get_connection()
                conn.request(method, path, body, http_headers)
                resp = conn.getresponse()
                tempbytes = ''
                try:
                    tempbytes = resp.read()
                    tempbody = tempbytes.decode('utf-8')
                except UnicodeDecodeError:  # Might be binary data
                    tempbody = tempbytes
                    conn.close()
                    bConnected = True
                    return resp, tempbody
                if tempbody:
                    try:
                        body = json.loads(tempbody)
                    except ValueError:
                        body = tempbody
                conn.close()
                bConnected = True
            except http.client.BadStatusLine:
                logger.warning('Bad Status Line. Trying again...')
                if conn:
                    conn.close()
                time.sleep(1)
                continue
            except http.client.HTTPException:
                raise HPEOneViewException(
                    'Failure during login attempt.\n %s' %
                    traceback.format_exc())

        return resp, body
예제 #17
0
    def __do_rest_call(self, http_method, uri, body, custom_headers):
        resp, body = self.do_http(method=http_method,
                                  path=uri,
                                  body=json.dumps(body),
                                  custom_headers=custom_headers)
        if resp.status >= 400:
            raise HPEOneViewException(body)

        if resp.status == 304:
            if body and not isinstance(body, dict):
                try:
                    body = json.loads(body)
                except Exception:
                    pass
        elif resp.status == 202:
            task = self.__get_task_from_response(resp, body)
            return task, body

        if self.__body_content_is_task(body):
            return body, body

        return None, body
예제 #18
0
    def get_by(self, field, value):
        """
        Gets all Users that match the filter.

        The search is case-insensitive.

        Args:
            field: Field name to filter. Accepted values: 'name', 'userName', 'role'
            value: Value to filter.

        Returns:
            list: A list of Users.
        """
        if field == 'userName' or field == 'name':
            return self._client.get(self.URI + '/' + value)
        elif field == 'role':
            value = value.replace(" ", "%20")
            return self._client.get(self.URI + '/roles/users/' +
                                    value)['members']
        else:
            raise HPEOneViewException(
                'Only userName, name and role can be queried for this resource.'
            )
if all_firmwares:
    firmware_driver = firmware_drivers.get_by_name(all_firmwares[0]['name'])

if firmware_driver:
    print("Found a firmware by name: '{}'.\n  uri = '{}'".format(
        firmware_driver.data['name'], firmware_driver.data['uri']))
else:
    # Getting a SPP and a hotfix from within the Appliance to use in the custom SPP creation.
    try:
        spp = firmware_drivers.get_by('bundleType', "SPP")[0]
        options['baselineUri'] = spp['uri']
        print(
            "\nSPP named '{}' found within appliance. Saving for custom SPP.".
            format(spp['name']))
    except IndexError:
        raise HPEOneViewException(
            'No available SPPs found within appliance. Stopping run.')

    try:
        hotfix = firmware_drivers.get_by('bundleType', "Hotfix")[0]
        options['hotfixUris'] = [hotfix['uri']]
        print(
            "\nHotfix named '{}' found within appliance. Saving for custom SPP."
            .format(hotfix['name']))
    except IndexError:
        raise HPEOneViewException(
            'No available hotfixes found within appliance. Stopping run.')

    # Create the custom SPP
    print("\nCreate the custom SPP '{}'".format(options['customBaselineName']))
    firmware_driver = firmware_drivers.create(options)
    print("  Custom SPP '%s' created successfully" %
 def test_get_by_aliasName_when_not_found(self, mock_get_by):
     mock_get_by.side_effect = HPEOneViewException("not found")
     self.assertEqual(self._certificate_server.get_by_alias_name("test1"),
                      None)
예제 #21
0
 def test_login_with_exception_in_put_username_password_sessionID(self, mock_put, mock_get):
     mock_get.side_effect = [{'minimumVersion': 800, 'currentVersion': 400}]
     mock_put.side_effect = HPEOneViewException("Failed")
     self.assertRaises(HPEOneViewException, self.connection.login, {"userName": "******",
                                                                    "password": "", "sessionID": "123"})
예제 #22
0
    def test_login_with_exception_in_put(self, mock_put, mock_get):
        mock_get.side_effect = [{'minimumVersion': 800, 'currentVersion': 400}]
        mock_put.side_effect = HPEOneViewException("Failed")

        self.assertRaises(HPEOneViewException, self.connection.login, {"sessionID": "123"})
예제 #23
0
 def test_get_by_called_with_userName_with_exception(self, mock_get):
     mock_get.side_effect = HPEOneViewException("username is not found")
     result = self._users.get_by_userName('testUser')
     self.assertIsNone(result)