Ejemplo n.º 1
0
    def __init__(self, json_config=None):

        if json_config:
            self.config = from_file(profile_name=json_config.get("profile"))
        else:
            self.config = from_file()

        self._identity_client = IdentityClient(self.config)
        self._compute_client = ComputeClient(self.config)
        self._network_client = VirtualNetworkClient(self.config)
Ejemplo n.º 2
0
	def __init__(self,tenancy_name):
		config = Config(tenancy_name)
		self.config = config.config
		self.compartment_id = self.config['tenancy']
		self.fingerprint = self.config['fingerprint']
		self.key_file = self.config["key_file"]
		self.admin_user_id = self.config["user"]
		self.identity = IdentityClient(self.config)
		self.users = list()
		self.list_users()
		self.compartments = list()
		self.availability_domains = list()
		self.store_compartments()
		self.list_availability_domains()
Ejemplo n.º 3
0
	def __init__(self):
		config = {}
		try:
			signer = Config.signer
			self.identity = IdentityClient(config=config, signer=signer)
			self.compartment_id = Config.tenancy_id
		except Exception:
			config = Config.config
			self.identity = IdentityClient(config)
			self.compartment_id = config["tenancy"]
		
		self.compartments = list()
		self.availability_domain_list = list()
		self.update_ads()
Ejemplo n.º 4
0
    def authenticate(self, profile=None, **kwargs):

        try:

            config = from_file(profile_name=profile)
            compartment_id = config["tenancy"]

            # Get the current user
            identity = IdentityClient(config)
            identity.get_user(config["user"]).data

            return OracleCredentials(config, compartment_id)

        except Exception as e:
            raise AuthenticationException(e)
Ejemplo n.º 5
0
    def authenticate(self, profile=None, **kwargs):

        try:

            # Set logging level to error for libraries as otherwise generates a lot of warnings
            logging.getLogger('oci').setLevel(logging.ERROR)

            config = from_file(profile_name=profile)

            # Get the current user
            identity = IdentityClient(config)
            identity.get_user(config["user"]).data

            return OracleCredentials(config)

        except Exception as e:
            raise AuthenticationException(e)
 def set_connect(self, secret_data):
     self.identity_client = IdentityClient(secret_data)
     self.database_client = DatabaseClient(secret_data)
     self.disk_client = BlockstorageClient(secret_data)
     self.compute_client = ComputeClient(secret_data)
     self.compute_management_client = ComputeManagementClient(secret_data)
     self.virtual_network_client = VirtualNetworkClient(secret_data)
     self.load_balancer_client = LoadBalancerClient(secret_data)
     self.network_load_balancer_client = NetworkLoadBalancerClient(secret_data)
Ejemplo n.º 7
0
def oracle_connect_service(service, credentials, region_name=None):
    try:
        if service == 'identity':
            return IdentityClient(credentials.config)
        else:
            print_exception('Service %s not supported' % service)
            return None

    except Exception as e:
        print_exception(e)
        return None
Ejemplo n.º 8
0
 def handle(self, *args, **options):
     from oci.identity import IdentityClient
     config = oci.config.from_file()
     identity = IdentityClient(config)
     from oci.identity.models import CreateGroupDetails
     request = CreateGroupDetails()
     compartment_id = config["tenancy"]
     request.compartment_id = compartment_id
     request.name = "my-test-group"
     request.description = "Created with the Python SDK"
     group = identity.create_group(request)
     from oci.identity.models import CreateUserDetails
     request = CreateUserDetails()
     request.compartment_id = compartment_id
     request.name = "my-test-user"
     request.description = "Created with the Python SDK"
     user = identity.create_user(request)
     from oci.identity.models import AddUserToGroupDetails
     request = AddUserToGroupDetails()
     request.group_id = group.data.id
     request.user_id = user.data.id
     response = identity.add_user_to_group(request)
     print(response.status)
Ejemplo n.º 9
0
class Compartment:
    def __init__(self):
        config = {}
        try:
            signer = Config.signer
            self.identity = IdentityClient(config=config, signer=signer)
            self.compartment_id = Config.tenancy_id
        except Exception:
            config = Config.config
            self.identity = IdentityClient(config)
            self.compartment_id = config["tenancy"]

        self.compartments = list()
        self.availability_domain_list = list()
        self.update_ads()

# send requests to list all compartments and its child

    def list_compartments(self):
        return oci.pagination.list_call_get_all_results(
            self.identity.list_compartments,
            self.compartment_id,
            compartment_id_in_subtree=True).data

    # Return compartment data and store in a list
    def store_compartments(self):
        for compartment in self.list_compartments():
            self.compartments.append(compartment)

    def list_availability_domain(self):
        return self.identity.list_availability_domains(
            self.compartment_id).data

    def update_ads(self):
        for i in self.list_availability_domain():
            self.availability_domain_list.append(i)

    def get_compartment_name(self, ids):
        return [i.name for i in self.compartments if i.id == ids][0]

    def get_compartment_id_list(self):
        return self.compartments
Ejemplo n.º 10
0
class IdentityFacade:
    def __init__(self, credentials: OracleCredentials):
        self._credentials = credentials
        self._client = IdentityClient(self._credentials.config)

    async def get_users(self):
        response = await run_concurrently(lambda: list_call_get_all_results(
            self._client.list_users, self._credentials.compartment_id))
        return response.data

    async def get_user_api_keys(self, user_id):
        response = await run_concurrently(lambda: list_call_get_all_results(
            self._client.list_api_keys, user_id))
        return response.data

    async def get_groups(self):
        response = await run_concurrently(lambda: list_call_get_all_results(
            self._client.list_groups, self._credentials.compartment_id))
        return response.data

    async def get_group_users(self, group_id):
        response = await run_concurrently(lambda: list_call_get_all_results(
            self._client.list_user_group_memberships,
            self._credentials.compartment_id,
            group_id=group_id))
        return response.data

    async def get_policies(self):
        response = await run_concurrently(lambda: list_call_get_all_results(
            self._client.list_policies, self._credentials.compartment_id))
        return response.data

    async def get_authentication_policy(self):
        response = await run_concurrently(
            lambda: self._client.get_authentication_policy(self._credentials.
                                                           compartment_id))
        return response.data
Ejemplo n.º 11
0
import oci
from oci.identity import IdentityClient
from oci.core import VirtualNetworkClient, ComputeClient
from app.oci_config import get_configuration, get_compartment_scope, get_vcn_scope

config = get_configuration()
identity_client = IdentityClient(config)
compute_client = ComputeClient(config)
network_client = VirtualNetworkClient(config)


def get_oci_user():
    user = identity_client.get_user(config["user"]).data
    return user


def get_compute_instances_details():

    try:
        response = compute_client.list_instances(
            compartment_id=get_compartment_scope())
        return response.data
    except Exception as e:
        return {"problem encountered": e.__repr__()}


def get_compute_instances_status():

    try:
        response = {}
        instance_responses = compute_client.list_instances(
Ejemplo n.º 12
0
 def __init__(self, credentials: OracleCredentials):
     self._credentials = credentials
     self._client = IdentityClient(self._credentials.config)
Ejemplo n.º 13
0
class IdentityFacade:
    def __init__(self, credentials: OracleCredentials):
        self._credentials = credentials
        self._client = IdentityClient(self._credentials.config)

    async def get_users(self):
        try:
            response = await run_concurrently(
                lambda: list_call_get_all_results(
                    self._client.list_users, self._credentials.get_scope()))
            return response.data
        except Exception as e:
            print_exception(f'Failed to retrieve users: {e}')
            return []

    async def get_user_api_keys(self, user_id):
        try:
            response = await run_concurrently(
                lambda: list_call_get_all_results(self._client.list_api_keys,
                                                  user_id))
            return response.data
        except Exception as e:
            print_exception(f'Failed to retrieve user api keys: {e}')
            return []

    async def get_groups(self):
        try:
            response = await run_concurrently(
                lambda: list_call_get_all_results(
                    self._client.list_groups, self._credentials.get_scope()))
            return response.data
        except Exception as e:
            print_exception(f'Failed to retrieve groups: {e}')
            return []

    async def get_group_users(self, group_id):
        try:
            response = await run_concurrently(
                lambda: list_call_get_all_results(
                    self._client.list_user_group_memberships,
                    self._credentials.get_scope(),
                    group_id=group_id))
            return response.data
        except Exception as e:
            print_exception(f'Failed to retrieve group users: {e}')
            return []

    async def get_policies(self):
        try:
            response = await run_concurrently(
                lambda: list_call_get_all_results(
                    self._client.list_policies, self._credentials.get_scope()))
            return response.data
        except Exception as e:
            print_exception(f'Failed to retrieve policies: {e}')
            return None

    async def get_authentication_policy(self):
        try:
            response = await run_concurrently(
                lambda: self._client.get_authentication_policy(
                    self._credentials.config['tenancy']))
            return response.data
        except Exception as e:
            print_exception(f'Failed to retrieve authentication policy: {e}')
            return []
Ejemplo n.º 14
0
    else:
        print("Running with: ")
        print("Username: {}".format(sys.argv[1]))
        print("")


#
# Main
#
print("")

controlla_params()

validate_config(config)

print("Validate config OK")

username = sys.argv[1]

client = IdentityClient(config)

# set user details
details = CreateUserDetails(compartment_id=config.get("tenancy"),
                            description="ocipy_created",
                            name=username)

client.create_user(details)

print("User created !")
print("")
Ejemplo n.º 15
0
 def identity(self, region=None):    
     try:
         return IdentityClient(self.config)
     except oci.exceptions.ClientError as err:
         print(err, file=sys.stderr)
         sys.exit(1)
Ejemplo n.º 16
0
class OciWrapper:
    def __init__(self, json_config=None):

        if json_config:
            self.config = from_file(profile_name=json_config.get("profile"))
        else:
            self.config = from_file()

        self._identity_client = IdentityClient(self.config)
        self._compute_client = ComputeClient(self.config)
        self._network_client = VirtualNetworkClient(self.config)

    def get_compartment_list(self):
        """
            :return list of all compartments in a tenancy
        """
        return self._identity_client.list_compartments(
            self.config.get('tenancy')).data

    def list_compartments(self):
        """
            Provide a list of compartments
            :return JSON with compartment list
        """
        d = self._identity_client.list_compartments(
            self.config.get('tenancy')).data
        return json.loads(str(d))

    def get_compartment_id_from_name(self, compartment_name):
        return next((item for item in self.get_compartment_list()
                     if item.name == compartment_name)).id

    def get_instance_id_from_name(self, compartment_id, instance_name):
        instance_ids = []
        for item in self._compute_client.list_instances(compartment_id).data:
            if item.display_name == instance_name and item.lifecycle_state == "RUNNING" or item.lifecycle_state == "STOPPED":
                instance_ids.append(item.id)
        return instance_ids

    def get_instance_details(self, compartment_id, instance_id):
        # get running instance details
        # this assumes that only one istance with the given display name is running
        return next((item for item in self._compute_client.list_instances(
            compartment_id).data if item.id == instance_id))

    def get_bv_id(self, compartment_id, instance_id):

        i_details = self.get_instance_details(compartment_id, instance_id)

        # get boot volume details
        _tmp = next(
            (item
             for item in self._compute_client.list_boot_volume_attachments(
                 i_details.availability_domain, compartment_id).data
             if item.instance_id == instance_id))
        boot_vol_attachment_id = _tmp.id
        logging.debug("Boot volume attachment OCID: %s",
                      boot_vol_attachment_id)
        boot_vol_id = _tmp.boot_volume_id
        logging.debug("Boot volume OCID: %s", boot_vol_id)
        return boot_vol_id, boot_vol_attachment_id

    def detach_bv(self, bv_id):
        """
            detach block volume
        """

        logging.info("Detaching boot volume...")
        response = self._compute_client.detach_boot_volume(bv_id)
        get_instance_response = oci.wait_until(
            self._compute_client,
            self._compute_client.get_boot_volume_attachment(bv_id),
            'lifecycle_state', 'DETACHED')
        logging.info("Boot volume detached")

    def launch_instance(self, instance_details):
        """
            launch instance
            :return istance OCID
        """

        try:
            logging.info("Starting new instance...")
            response = self._compute_client.launch_instance(instance_details)
            oci.wait_until(self._compute_client,
                           self._compute_client.get_instance(response.data.id),
                           'lifecycle_state', 'RUNNING')
            logging.info("Instance started [%s]", response.data.id)
            return response.data.id
        except ServiceError as err:
            logging.error(
                'unable to launch a new instance code %s - message %s' %
                (err.code, err.message))

    def stop_instance(self, instance_id, detach_bv=False):
        """
            stop instance
        """

        logging.info("Stopping instance...")
        response = self._compute_client.instance_action(instance_id, "stop")
        get_instance_response = oci.wait_until(
            self._compute_client,
            self._compute_client.get_instance(instance_id), 'lifecycle_state',
            'STOPPED')
        logging.info("Instance stopped")

    def terminate_instance(self,
                           compartment_id,
                           instance_id,
                           preserve_bv=False):
        """
        terminate the smaller instance
        :param compartment_id: compartment OCID
        :param instance_id: instance OCID
        :param preserve_bv: if True preserve the boot volume
        :return:
        """
        logging.info("Terminating instance...")
        self._compute_client.terminate_instance(
            instance_id, preserve_boot_volume=preserve_bv)
        oci.wait_until(self._compute_client,
                       self._compute_client.get_instance(instance_id),
                       'lifecycle_state', 'TERMINATED')
        logging.info("Instance terminated")

    def scale(self,
              new_shape,
              compartment_name=None,
              compartment_ocid=None,
              instance_name=None,
              instance_ocid=None):
        """
        Scale-up function
        """

        if not compartment_ocid:
            compartment_ocid = self.get_compartment_id_from_name(
                compartment_name)
            if not compartment_ocid:
                raise ValueError('unable to locate any compartment named: %s' %
                                 instance_name)

        if not instance_ocid:
            temp_instance_ids = self.get_instance_id_from_name(
                compartment_ocid, instance_name)
            if not temp_instance_ids or len(temp_instance_ids) < 1:
                raise ValueError('unable to locate any instance named: %s' %
                                 instance_name)
            elif len(temp_instance_ids) > 1:
                raise ValueError('name (%s) is used by multiple instances' %
                                 instance_name)
            else:
                instance_ocid = temp_instance_ids[0]

        logging.info("Scaling up instance: %s [%s]", instance_name,
                     instance_ocid)
        old_instance_details = self.get_instance_details(
            compartment_ocid, instance_ocid)

        #get vnic details
        # TODO: Manage multiple vnics. This assumes that instance has a single vnic.
        vnic_id = next((item
                        for item in self._compute_client.list_vnic_attachments(
                            compartment_ocid).data
                        if item.instance_id == instance_ocid)).vnic_id
        vnic_attachment_details = self._network_client.get_vnic(vnic_id).data
        logging.debug("vnic attachment details: %s", vnic_attachment_details)

        # TODO: manage Public floating IP
        # TODO: manage block volumes

        #stopping instance
        self.stop_instance(instance_ocid)

        #detach boot volume
        bv_ocid, bv_attachment_ocid = self.get_bv_id(compartment_ocid,
                                                     instance_ocid)
        self.detach_bv(bv_attachment_ocid)

        #terminating the old instance
        self.terminate_instance(compartment_ocid, instance_ocid, True)

        instance_details = models.LaunchInstanceDetails(
            availability_domain=old_instance_details.availability_domain,
            compartment_id=old_instance_details.compartment_id,
            create_vnic_details=models.CreateVnicDetails(
                assign_public_ip=bool(vnic_attachment_details.public_ip),
                display_name=vnic_attachment_details.display_name,
                hostname_label=vnic_attachment_details.hostname_label,
                private_ip=vnic_attachment_details.private_ip,
                skip_source_dest_check=vnic_attachment_details.
                skip_source_dest_check,
                subnet_id=vnic_attachment_details.subnet_id,
            ),
            display_name=old_instance_details.display_name,
            extended_metadata=old_instance_details.extended_metadata,
            ipxe_script=old_instance_details.ipxe_script,
            metadata=old_instance_details.metadata,
            shape=new_shape,
            source_details=models.InstanceSourceViaBootVolumeDetails(
                source_type="bootVolume", boot_volume_id=bv_ocid))

        new_instance_ocid = self.launch_instance(instance_details)
        return new_instance_ocid

    def _test(self, c_ocid, i_ocid):
        idet = self.get_instance_details(c_ocid, i_ocid)
        return idet
    exit(1)

if not os.path.exists('.oci/oci_api_key.pem'):
    logging.error("File .oci/oci_api_key.pem missing!")
    exit(1)

if not os.path.exists('.oci/oci_api_key_public.pem'):
    logging.error("File .oci/oci_api_key_public.pem missing!")
    exit(1)

logging.info("Loading configuration from .oci")
config = from_file(file_location=".oci/config")
logging.info("Validating configuration from .oci")
validate_config(config)

identity = IdentityClient(config)
tenant_compartment_id = config["tenancy"]

logging.info("Retrieving all compartments")
compartments = getCompartmentRecurse(identity, tenant_compartment_id)
logging.debug(compartments)

if compartments.get(newCompartmentName) is not None:
    logging.error("Compartment already exists!")
    sendMail(newCompartmentOwner, "Subscription already exists",
             "Subscription %s already exists!" % newCompartmentName)
    exit(2)

newCompartmentNameParts = newCompartmentName.split('-')
newCompartmentParent = compartments[newCompartmentNameParts[1].lower()]
Ejemplo n.º 18
0
class Identity:
	def __init__(self,tenancy_name):
		config = Config(tenancy_name)
		self.config = config.config
		self.compartment_id = self.config['tenancy']
		self.fingerprint = self.config['fingerprint']
		self.key_file = self.config["key_file"]
		self.admin_user_id = self.config["user"]
		self.identity = IdentityClient(self.config)
		self.users = list()
		self.list_users()
		self.compartments = list()
		self.availability_domains = list()
		self.store_compartments()
		self.list_availability_domains()

	def list_availability_domains(self):
		for i in self.identity.list_availability_domains(self.compartment_id, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY).data:
			self.availability_domains.append(i)


	def store_compartments(self):
		for compartment in self.list_compartments():
			self.compartments.append(compartment)



	def get_compartment_path_name(self, compartment_id):
		temp = ""
		id = compartment_id
		while id != self.compartment_id:
			compartment = self.get_compartment_details(id)
			temp = compartment.name + "/" + temp
			id = compartment.compartment_id
		return temp

	def get_compartment_details(self, compartment_id):
		return [compartment for compartment in self.compartments if compartment.id == compartment_id][0]


	#List all compartments
	def list_compartments(self):
		return oci.pagination.list_call_get_all_results(self.identity.list_compartments,self.compartment_id,compartment_id_in_subtree=True, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY).data


#	List all users with pagination
	def list_users(self):
		users = self.identity.list_users(self.compartment_id)
		for user in users.data:
			self.users.append(user)
		while users.has_next_page:
			users = self.identity.list_users(self.compartment_id,page = users.next_page)
			for user in users.data:
				self.users.append(user)

		return self.users

#	Get local Users with User class logic
	def get_local_users(self):
		local_users = list()
		for user in self.users:
			user_obj = User(user)
			if user_obj.is_user_local():
				local_users.append(user)

		return local_users

#	Invalid users are the ones who is not local and not service users.
#	Fetch it from the User class logic
	def get_invalid_users(self):
		invalid_users = list()
		for user in self.users:
			user_obj = User(user)
			if not user_obj.is_user_valid():
				invalid_users.append(user)

		return invalid_users

#	Get service users from User class
	def get_service_users(self):
		service_users = list()
		for user in self.users:
			user_obj = User(user)
			if user_obj.is_user_service():
				service_users.append(user)

		return service_users