Example #1
0
def request_process(aurl, req):
    """Perform HTTP(s) request based on Provided Params.

    :param aurl:
    :param req:
    :param https:
    :return read_resp:
    """

    conn = http.open_connection(url=aurl)

    # Make the request for authentication
    try:
        _method, _url, _body, _headers = req
        conn.request(method=_method, url=_url, body=_body, headers=_headers)
        resp = conn.getresponse()
    except Exception as exc:
        LOG.error('Not able to perform Request ERROR: %s', exc)
        raise AttributeError("Failure to perform Authentication %s ERROR:\n%s"
                             % (exc, traceback.format_exc()))
    else:
        resp_read = resp.read()
        status_code = resp.status
        if status_code >= 300:
            LOG.error('HTTP connection exception: '
                      'Response %s - Response Code %s\n%s',
                      resp_read, status_code, traceback.format_exc())
            raise httplib.HTTPException('Failed to authenticate %s'
                                        % status_code)

        LOG.debug('Connection successful MSG: %s - STATUS: %s', resp.reason,
                  resp.status)
        return resp_read
    finally:
        conn.close()
Example #2
0
def parse_reqtype():
    """Setup our Authentication POST.

    username and setup are only used in APIKEY/PASSWORD Authentication
    """

    setup = {'username': ARGS.get('os_user')}
    if ARGS.get('os_token') is not None:
        auth_body = {'auth': {'token': {'id': ARGS.get('os_token')}}}
    elif ARGS.get('os_password') is not None:
        prefix = 'passwordCredentials'
        setup['password'] = ARGS.get('os_password')
        auth_body = {'auth': {prefix: setup}}
    elif ARGS.get('os_apikey') is not None:
        prefix = 'RAX-KSKEY:apiKeyCredentials'
        setup['apiKey'] = ARGS.get('os_apikey')
        auth_body = {'auth': {prefix: setup}}
    else:
        LOG.error(traceback.format_exc())
        raise AttributeError('No Password, APIKey, or Token Specified')

    if ARGS.get('os_tenant'):
        auth_body['auth']['tenantName'] = ARGS.get('os_tenant')

    LOG.debug('AUTH Request Type > %s', auth_body)
    return auth_body
Example #3
0
def authenticate():
    """Authentication For Openstack API.

    Pulls the full Openstack Service Catalog Credentials are the Users API
    Username and Key/Password "osauth" has a Built in Rackspace Method for
    Authentication

    Set a DC Endpoint and Authentication URL for the OpenStack environment
    """

    # Setup the request variables
    url = auth.parse_region()
    a_url = http.parse_url(url=url, auth=True)
    auth_json = auth.parse_reqtype()

    # remove the prefix for the Authentication URL if Found
    LOG.debug("POST == REQUEST DICT > JSON DUMP %s", auth_json)
    auth_json_req = json.dumps(auth_json)
    headers = {"Content-Type": "application/json"}

    # Send Request
    request = ("POST", a_url.path, auth_json_req, headers)
    resp_read = auth.request_process(aurl=a_url, req=request)
    LOG.debug("POST Authentication Response %s", resp_read)
    try:
        auth_resp = json.loads(resp_read)
    except ValueError as exp:
        LOG.error("Authentication Failure %s\n%s", exp, traceback.format_exc())
        raise turbo.SystemProblem("JSON Decode Failure. ERROR: %s - RESP %s" % (exp, resp_read))
    else:
        auth_info = auth.parse_auth_response(auth_resp)
        token, tenant, user, inet, enet, cnet, acfep = auth_info
        report.reporter(msg=("API Access Granted. TenantID: %s Username: %s" % (tenant, user)), prt=False, log=True)
        return token, tenant, user, inet, enet, cnet, a_url, acfep
Example #4
0
def parse_reqtype():
    """Setup our Authentication POST.

    username and setup are only used in APIKEY/PASSWORD Authentication
    """

    setup = {'username': ARGS.get('os_user')}
    if ARGS.get('os_token') is not None:
        auth_body = {'auth': {'token': {'id': ARGS.get('os_token')}}}
    elif ARGS.get('os_password') is not None:
        prefix = 'passwordCredentials'
        setup['password'] = ARGS.get('os_password')
        auth_body = {'auth': {prefix: setup}}
    elif ARGS.get('os_apikey') is not None:
        prefix = 'RAX-KSKEY:apiKeyCredentials'
        setup['apiKey'] = ARGS.get('os_apikey')
        auth_body = {'auth': {prefix: setup}}
    else:
        LOG.error(traceback.format_exc())
        raise AttributeError('No Password, APIKey, or Token Specified')

    if ARGS.get('os_tenant'):
        auth_body['auth']['tenantName'] = ARGS.get('os_tenant')

    LOG.debug('AUTH Request Type > %s', auth_body)
    return auth_body
Example #5
0
    def start(self):
        """This is the upload method.

        Uses file_upload is to simply upload all files and folders to a
        specified container.
        """

        # Index Local Files for Upload
        with multi.spinner():
            f_indexed = methods.get_local_files()

        if ARGS.get('pattern_match'):
            f_indexed = basic.match_filter(
                idx_list=f_indexed, pattern=ARGS['pattern_match']
            )

        num_files = len(f_indexed)

        # Get The rate of concurrency
        concurrency = multi.set_concurrency(args=ARGS, file_count=num_files)

        # Package up the Payload
        payload = multi.manager_dict(
            http.prep_payload(
                auth=self.auth,
                container=ARGS.get('container', basic.rand_string()),
                source=basic.get_local_source(),
                args=ARGS
            )
        )

        LOG.info('MESSAGE\t: "%s" Files have been found.', num_files)
        LOG.debug('PAYLOAD\t: "%s"', payload)

        # Set the actions class up
        self.go = actions.CloudActions(payload=payload)

        kwargs = {'url': payload['url'],
                  'container': payload['c_name']}
        # get that the container exists if not create it.
        self.go.container_create(**kwargs)
        kwargs['source'] = payload['source']
        kwargs['cf_job'] = getattr(self.go, 'object_putter')

        multi.job_processer(
            num_jobs=num_files,
            objects=f_indexed,
            job_action=multi.doerator,
            concur=concurrency,
            kwargs=kwargs
        )

        if ARGS.get('delete_remote') is True:
            self.remote_delete(payload=payload,
                               f_indexed=f_indexed)
Example #6
0
    def start(self):
        """This is the upload method.

        Uses file_upload is to simply upload all files and folders to a
        specified container.
        """

        # Index Local Files for Upload
        f_indexed = methods.get_local_files()

        if ARGS.get('pattern_match'):
            f_indexed = basic.match_filter(
                idx_list=f_indexed, pattern=ARGS['pattern_match']
            )

        num_files = len(f_indexed)

        # Get The rate of concurrency
        concurrency = multi.set_concurrency(args=ARGS, file_count=num_files)

        # Package up the Payload
        payload = multi.manager_dict(
            http.prep_payload(
                auth=self.auth,
                container=ARGS.get('container', basic.rand_string()),
                source=basic.get_local_source(),
                args=ARGS
            )
        )

        LOG.info('MESSAGE\t: "%s" Files have been found.', num_files)
        LOG.debug('PAYLOAD\t: "%s"', payload)

        # Set the actions class up
        self.go = actions.CloudActions(payload=payload)

        kwargs = {'url': payload['url'],
                  'container': payload['c_name']}
        # get that the container exists if not create it.
        self.go.container_create(**kwargs)
        kwargs['source'] = payload['source']
        kwargs['cf_job'] = getattr(self.go, 'object_putter')

        multi.job_processer(
            num_jobs=num_files,
            objects=f_indexed,
            job_action=multi.doerator,
            concur=concurrency,
            kwargs=kwargs
        )

        if ARGS.get('delete_remote') is True:
            self.remote_delete(payload=payload,
                               f_indexed=f_indexed)
Example #7
0
def authenticate():
    """Authentication For Openstack API.

    Pulls the full Openstack Service Catalog Credentials are the Users API
    Username and Key/Password "osauth" has a Built in Rackspace Method for
    Authentication

    Set a DC Endpoint and Authentication URL for the OpenStack environment
    """

    # Setup the request variables
    a_url = "https://zebra.zerovm.org/auth/v1.0"
    #a_url = http.parse_url(url=url, auth=True)
    auth_json = auth.parse_reqtype()
    print auth_json
    # remove the prefix for the Authentication URL if Found
#    LOG.debug('POST == REQUEST DICT > JSON DUMP %s', auth_json)
#    auth_json_req = json.dumps(auth_json)
    headers = {
        'Content-Type': 'application/json',
        "X-Auth-User": auth_json['auth']['passwordCredentials']['username'],
        "X-Auth-Key": auth_json['auth']['passwordCredentials']['password']}

    # Send Request
    try:
        auth_resp = requests.get(
            url=a_url, headers=headers
        )
        if auth_resp.status_code >= 300:
            raise SystemExit(
                'Authentication Failure, %s %s' % (auth_resp.status_code,
                                                   auth_resp.reason)
            )
    except ValueError as exp:
        LOG.error('Authentication Failure %s\n%s', exp, traceback.format_exc())
        raise turbo.SystemProblem('JSON Decode Failure. ERROR: %s' % exp)
    else:
        LOG.debug('POST Authentication Response %s', auth_resp.json())
        #auth_info = auth.parse_auth_response(auth_resp.json())
        #token, tenant, user, inet, enet, cnet, acfep = auth_info
        token = auth_resp.headers['x-auth-token']
        tenant, user = auth_json['auth']['passwordCredentials']['username'].split(":")
        inet = urlparse.urlparse(auth_resp.headers['x-storage-url'])
        enet = inet
        cnet = None
        acfep = inet
        report.reporter(
            msg=('API Access Granted. TenantID: %s Username: %s'
                 % (tenant, user)),
            prt=False,
            log=True
        )
        return token, tenant, user, inet, enet, cnet, urlparse.urlparse(a_url), acfep
Example #8
0
def authenticate():
    """Authentication For Openstack API.

    Pulls the full Openstack Service Catalog Credentials are the Users API
    Username and Key/Password "osauth" has a Built in Rackspace Method for
    Authentication

    Set a DC Endpoint and Authentication URL for the OpenStack environment
    """

    # Setup the request variables
    a_url = "https://zebra.zerovm.org/auth/v1.0"
    #a_url = http.parse_url(url=url, auth=True)
    auth_json = auth.parse_reqtype()
    print auth_json
    # remove the prefix for the Authentication URL if Found
    #    LOG.debug('POST == REQUEST DICT > JSON DUMP %s', auth_json)
    #    auth_json_req = json.dumps(auth_json)
    headers = {
        'Content-Type': 'application/json',
        "X-Auth-User": auth_json['auth']['passwordCredentials']['username'],
        "X-Auth-Key": auth_json['auth']['passwordCredentials']['password']
    }

    # Send Request
    try:
        auth_resp = requests.get(url=a_url, headers=headers)
        if auth_resp.status_code >= 300:
            raise SystemExit('Authentication Failure, %s %s' %
                             (auth_resp.status_code, auth_resp.reason))
    except ValueError as exp:
        LOG.error('Authentication Failure %s\n%s', exp, traceback.format_exc())
        raise turbo.SystemProblem('JSON Decode Failure. ERROR: %s' % exp)
    else:
        LOG.debug('POST Authentication Response %s', auth_resp.json())
        #auth_info = auth.parse_auth_response(auth_resp.json())
        #token, tenant, user, inet, enet, cnet, acfep = auth_info
        token = auth_resp.headers['x-auth-token']
        tenant, user = auth_json['auth']['passwordCredentials'][
            'username'].split(":")
        inet = urlparse.urlparse(auth_resp.headers['x-storage-url'])
        enet = inet
        cnet = None
        acfep = inet
        report.reporter(msg=('API Access Granted. TenantID: %s Username: %s' %
                             (tenant, user)),
                        prt=False,
                        log=True)
        return token, tenant, user, inet, enet, cnet, urlparse.urlparse(
            a_url), acfep
Example #9
0
def authenticate():
    """Authentication For Openstack API.

    Pulls the full Openstack Service Catalog Credentials are the Users API
    Username and Key/Password "osauth" has a Built in Rackspace Method for
    Authentication

    Set a DC Endpoint and Authentication URL for the OpenStack environment
    """

    # Setup the request variables
    url = auth.parse_region()
    a_url = http.parse_url(url=url, auth=True)
    auth_json = auth.parse_reqtype()

    # remove the prefix for the Authentication URL if Found
    LOG.debug('POST == REQUEST DICT > JSON DUMP %s', auth_json)
    auth_json_req = json.dumps(auth_json)
    headers = {'Content-Type': 'application/json'}

    # Send Request
    try:
        auth_resp = http.post_request(
            url=a_url, headers=headers, body=auth_json_req
        )
        if auth_resp.status_code >= 300:
            raise SystemExit(
                'Authentication Failure, %s %s' % (auth_resp.status_code,
                                                   auth_resp.reason)
            )
    except ValueError as exp:
        LOG.error('Authentication Failure %s\n%s', exp, traceback.format_exc())
        raise turbo.SystemProblem('JSON Decode Failure. ERROR: %s' % exp)
    else:
        LOG.debug('POST Authentication Response %s', auth_resp.json())
        auth_info = auth.parse_auth_response(auth_resp.json())
        token, tenant, user, inet, enet, cnet, acfep = auth_info
        report.reporter(
            msg=('API Access Granted. TenantID: %s Username: %s'
                 % (tenant, user)),
            prt=False,
            log=True
        )
        return token, tenant, user, inet, enet, cnet, a_url, acfep
Example #10
0
def authenticate():
    """Authentication For Openstack API.

    Pulls the full Openstack Service Catalog Credentials are the Users API
    Username and Key/Password "osauth" has a Built in Rackspace Method for
    Authentication

    Set a DC Endpoint and Authentication URL for the OpenStack environment
    """

    # Setup the request variables
    url = auth.parse_region()
    a_url = http.parse_url(url=url, auth=True)
    auth_json = auth.parse_reqtype()

    # remove the prefix for the Authentication URL if Found
    LOG.debug('POST == REQUEST DICT > JSON DUMP %s', auth_json)
    auth_json_req = json.dumps(auth_json)
    headers = {'Content-Type': 'application/json'}

    # Send Request
    try:
        auth_resp = http.post_request(url=a_url,
                                      headers=headers,
                                      body=auth_json_req)
        if auth_resp.status_code >= 300:
            raise SystemExit('Authentication Failure, %s %s' %
                             (auth_resp.status_code, auth_resp.reason))
    except ValueError as exp:
        LOG.error('Authentication Failure %s\n%s', exp, traceback.format_exc())
        raise turbo.SystemProblem('JSON Decode Failure. ERROR: %s' % exp)
    else:
        LOG.debug('POST Authentication Response %s', auth_resp.json())
        auth_info = auth.parse_auth_response(auth_resp.json())
        token, tenant, user, inet, enet, cnet, acfep = auth_info
        report.reporter(msg=('API Access Granted. TenantID: %s Username: %s' %
                             (tenant, user)),
                        prt=False,
                        log=True)
        return token, tenant, user, inet, enet, cnet, a_url, acfep
def authenticate():
    """Authentication For Openstack API.

    Pulls the full Openstack Service Catalog Credentials are the Users API
    Username and Key/Password "osauth" has a Built in Rackspace Method for
    Authentication

    Set a DC Endpoint and Authentication URL for the OpenStack environment

    :param auth_dict: required parameters are auth_url
    """

    # Setup the request variables
    url, rax = auth.parse_region()
    a_url = http.parse_url(url=url, auth=True)
    auth_json = auth.parse_reqtype()

    # remove the prefix for the Authentication URL if Found
    LOG.debug('POST == REQUEST DICT > JSON DUMP %s', auth_json)
    auth_json_req = json.dumps(auth_json)
    headers = {'Content-Type': 'application/json'}

    # Send Request
    request = ('POST', a_url.path, auth_json_req, headers)
    resp_read = auth.request_process(aurl=a_url, req=request)
    LOG.debug('POST Authentication Response %s', resp_read)
    try:
        auth_resp = json.loads(resp_read)
    except ValueError as exp:
        LOG.error('Authentication Failure %s\n%s', exp, traceback.format_exc())
        raise turbo.SystemProblem('JSON Decode Failure. ERROR: %s - RESP %s' %
                                  (exp, resp_read))
    else:
        auth_info = auth.parse_auth_response(auth_resp)
        token, tenant, user, inet, enet, cnet, acfep = auth_info
        report.reporter(msg=('API Access Granted. TenantID: %s Username: %s' %
                             (tenant, user)),
                        prt=False,
                        log=True)
        return token, tenant, user, inet, enet, cnet, a_url, acfep
Example #12
0
def request_process(aurl, req):
    """Perform HTTP(s) request based on Provided Params.

    :param aurl:
    :param req:
    :param https:
    :return read_resp:
    """

    conn = http.open_connection(url=aurl)

    # Make the request for authentication
    try:
        _method, _url, _body, _headers = req
        conn.request(method=_method, url=_url, body=_body, headers=_headers)
        resp = conn.getresponse()
    except Exception as exc:
        LOG.error('Not able to perform Request ERROR: %s', exc)
        raise AttributeError(
            "Failure to perform Authentication %s ERROR:\n%s" %
            (exc, traceback.format_exc()))
    else:
        resp_read = resp.read()
        status_code = resp.status
        if status_code >= 300:
            LOG.error(
                'HTTP connection exception: '
                'Response %s - Response Code %s\n%s', resp_read, status_code,
                traceback.format_exc())
            raise httplib.HTTPException('Failed to authenticate %s' %
                                        status_code)

        LOG.debug('Connection successful MSG: %s - STATUS: %s', resp.reason,
                  resp.status)
        return resp_read
    finally:
        conn.close()