def __init__(self):
     self.cfg = params()
     self.resource_instance = resource_instance.ResourceInstance()
     self.vpc = vpc.Vpc()
     # resource_group_id and self.resource_plan_id for free dns instance
     self.resource_group_id = "aef66560191746fe804b9a66874f62b1"
     self.resource_plan_id = "dc1460a6-37bd-4e2b-8180-d0f86ff39baa"
def cos_client(**kwargs):
    """Create Cloud Object Storage client

    :param mode: Access mode
    :type mode: str
    :param location: Region where to host the bucket
    :type location: str
    :param service_instance: Resource instance name or ID
    :type service_instance: str
    :return: Cloud Object Storage client
    :rtype: dict
    """
    cfg = params()

    # Build dict of argument and assign default value when needed
    args = {
        'mode': kwargs.get('mode'),
        'location': kwargs.get('location'),
        'service_instance': kwargs.get('service_instance'),
        'account': kwargs.get('account',
                              decode_token()['account']['bss']),
    }
    ri = resource_instance.ResourceInstance()

    try:
        # Check if endpoint exists
        endpoint = _get_endpoint(mode=args["mode"], location=args["location"])
        if "errors" in endpoint:
            return endpoint

        ri_info = None
        if args['service_instance']:
            # Check if resource instance exists and retrieve information
            ri_info = ri.get_resource_instance(args["service_instance"])
            if "errors" in ri_info:
                return ri_info
        else:
            # Automatically detect if cloud-object-storage service exists.
            # If multiple resource instance exist then the last one to match
            # the regex will be used.
            service = "cloud-object-storage"
            regex = "crn:v1:bluemix:public:{}:global:a/{}".format(
                service, args['account'])
            data = ri.get_resource_instances()
            for instance in data['resources']:
                if re.search(regex, instance['id']):
                    ri_info = instance

        client = ibm_boto3.client('s3',
                                  ibm_api_key_id=cfg["key"],
                                  ibm_service_instance_id=ri_info['id'],
                                  config=Config(signature_version='oauth'),
                                  endpoint_url=endpoint)

        return client

    except Exception as error:
        print("Error creating Cloud Object Storage client. {}".format(error))
Exemple #3
0
 def __init__(self):
     self.cfg = params()
     self.vpc = vpc.Vpc()
     self.image = image.Image()
     self.subnet = subnet.Subnet()
     self.fip = floating_ip.Fip()
     self.volume = volume.Volume()
     self.keyring = keyring.Key()
     self.rg = resource_group.ResourceGroup()
 def __init__(self, **kwargs):
     self.cfg = params()
     self.client = client.cos_client(
         mode=kwargs.get('mode', 'regional'),
         location=kwargs.get('location', self.cfg['region']),
         service_instance=kwargs.get('service_instance')
     )
     self.bucket = bucket.Bucket(
         mode=kwargs.get('mode', 'regional'),
         location=kwargs.get('location', self.cfg['region']),
         service_instance=kwargs.get('service_instance')
         )
def client():
    """Create SoftLayer client

    :return: The SoftLayer client
    """
    cfg = params()
    endpoint_url = "https://{}/rest/v3.1/".format(constants.SL_URL)
    try:
        client = SoftLayer.create_client_from_env(
            username=cfg['cis_username'],
            api_key=cfg['cis_apikey'],
            endpoint_url=endpoint_url,
        )

        return client

    except SoftLayer.SoftLayerError as error:
        print("Error creating SoftLayer client. {}".format(error))
        raise
Exemple #6
0
 def __init__(self):
     self.cfg = params()
 def __init__(self):
     self.cfg = params()
     self.vpc = vpc.Vpc()
     self.gateway = gw.Gateway()
     self.acl = acl.Acl()
     self.rg = resource_group.ResourceGroup()
Exemple #8
0
 def __init__(self):
     self.cfg = params()
     self.vpc = vpc.Vpc()
     self.rg = resource_group.ResourceGroup()
     self.instance = instance.Instance()
 def __init__(self):
     self.cfg = params()
     self.ri = resource_instance.ResourceInstance()
Exemple #10
0
 def __init__(self):
     self.cfg = params()
     self.rg = resource_group.ResourceGroup()
Exemple #11
0
 def __init__(self):
     self.cfg = params()
     self.subnet = subnet.Subnet()
     self.rg = resource_group.ResourceGroup()
 def __init__(self):
     self.cfg = params()
     self.vpc = vpc.Vpc()
     self.fip = floating_ip.Fip()
     self.rg = resource_group.ResourceGroup()
Exemple #13
0
from ibmcloud_python_sdk.utils import constants
from ibmcloud_python_sdk.config import params
from ibmcloud_python_sdk.utils import common
from jwt import decode

cfg = params()
headers = {}


def decode_token():
    """Decode JWT token

    :return: JSON JWT information
    :rtype: dict
    """
    try:
        token = get_headers()["Authorization"]
        return decode(token.split(" ")[1], verify=False)

    except Exception as error:
        print("Error decoding token. {}".format(error))
        raise


def get_token(url, key):
    """Generate JWT IAM token

    :param url: IAM URL
    :type url: string
    :param key: API Key
    :type key: string
Exemple #14
0
 def __init__(self):
     self.cfg = params()
     self.rg = resource_group.ResourceGroup()
     self.volume = volume.Volume()
Exemple #15
0
 def __init__(self):
     self.cfg = params()
     self.client = SoftLayer.create_client_from_env(
         username=self.cfg['cis_username'], api_key=self.cfg['cis_apikey'])
     self.dns = SoftLayer.DNSManager(self.client)
 def __init__(self):
     self.cfg = params()
     self.instance = instance.Instance()
def query_wrapper(conn_type, method, path, headers=None, payload=None):
    """Execute HTTP query and return JSON response

    :param conn_type: Define which URL should be used for the connection
        such as "iaas", "auth", "cis", or "rg" (resource group)
    :type conn_type: str
    :param method: HTTP method that should be used such as
        GET, POST, PUT, DELETE, etc...
    :type method: str
    :param path: Path used by within the query
    :type path: str
    :param headers: Headers to send with the query is required such
        authentication token, content type, etc...
    :type headers: dict, optional
    :param payload: JSON payload send during the query
    :type payload: dict, optional
    :return: JSON response
    :rtype: dict
    """
    cfg = params()
    timeout = cfg["http_timeout"]

    if conn_type == "iaas":
        conn = http.client.HTTPSConnection(cfg["is_url"], timeout=timeout)
    elif conn_type == "rg":
        conn = http.client.HTTPSConnection(cfg["rg_url"], timeout=timeout)
    elif conn_type == "auth":
        conn = http.client.HTTPSConnection(cfg["auth_url"], timeout=timeout)
    elif conn_type == "dns":
        conn = http.client.HTTPSConnection(cfg["dns_url"], timeout=timeout)
    elif conn_type == "em":
        conn = http.client.HTTPSConnection(cfg["em_url"], timeout=timeout)
    elif conn_type == "sl":
        if headers and cfg["cis_username"] and cfg["cis_apikey"]:
            header = base64.encodebytes(
                ('%s:%s' % (cfg["cis_username"], cfg["cis_apikey"])
                 ).encode('utf8')).decode('utf8').replace('\n', '')
            headers["Authorization"] = "Basic {}".format(header)
        conn = http.client.HTTPSConnection(cfg["sl_url"], timeout=timeout)
    elif conn_type == "power":
        conn = http.client.HTTPSConnection(cfg["pi_url"], timeout=timeout)

    if cache.client():
        if method == "GET" and conn_type != "auth":
            obj = "{}{}".format(_account_id(headers), path)
            item = cache.get_item(obj)
            if item is not None:
                return {"data": json.loads(item.decode("utf-8"))}
            else:
                pass

    conn.request(method, path, payload, headers)

    # Get and read response data
    res = conn.getresponse()
    data = res.read()

    if not data:
        # Return empty data and HTTP response this is mostly
        # due to DELETE request which doesn't return any data
        return {"data": None, "response": res}
    else:
        if cache.client():
            obj = "{}{}".format(_account_id(headers), path)
            # Store item into caching system
            cache.set_item(obj, data)

        # Return data and HTTP response
        return {"data": json.loads(data), "response": res}