Ejemplo n.º 1
0
class ComputeClientRoutes(TestCase):
    def setUp(self):
        self.server = ServerThread(app)
        self.server.start()
        self.oci_config = get_oci_config()
        self.compute_cli = ComputeClient(
            config=self.oci_config["config"],
            service_endpoint="http://localhost:12000")
        self.compute_cli_composite_op = ComputeClientCompositeOperations(
            self.compute_cli)

        self.test_instance = create_instance(
            self.oci_config["compartment_id"],
            self.compute_cli_composite_op,
            "dummy-instance",
        )

    def test_terminate_instance(self):
        response: Response = self.compute_cli.terminate_instance(
            self.test_instance.id)
        self.assertEqual(response.status, 204)

        sleep(5)

        with self.assertRaises(ServiceError) as e:
            self.compute_cli.get_instance(self.test_instance.id)
            self.assertEqual(e.exception.status, 404)

    def test_terminate_non_existent_instance(self):
        with self.assertRaises(ServiceError) as e:
            self.compute_cli.get_instance("non_existent_instance")
            self.assertEqual(e.exception.status, 404)

    def tearDown(self):
        self.server.shutdown()
Ejemplo n.º 2
0
 def __init__(self):
     config = {}
     try:
         signer = Config.signer
         self.compute_client = ComputeClient(config=config, signer=signer)
     except Exception:
         config = Config.config
         self.compute_client = ComputeClient(config)
Ejemplo n.º 3
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.º 4
0
def get_instances(client: ComputeClient = None,
                  compartment_id: str = None) -> List[OCIInstance]:
    """Return a complete, unfiltered list of instances in the compartment."""
    instances = []

    instances_raw = client.list_instances(compartment_id=compartment_id)
    instances.extend(instances_raw.data)
    while instances_raw.has_next_page:
        instances_raw = client.list_instances(compartment_id=compartment_id,
                                              page=instances_raw.next_page)
        instances.extend(instances_raw.data)

    return instances
Ejemplo n.º 5
0
class Instance:
    def __init__(self):
        config = {}
        try:
            signer = Config.signer
            self.compute_client = ComputeClient(config=config, signer=signer)
        except Exception:
            config = Config.config
            self.compute_client = ComputeClient(config)

    # Request to list all volume attachments
    def list_volume_attachments(self, compartment_id):
        try:
            return list_call_get_all_results(
                self.compute_client.list_volume_attachments,
                compartment_id).data
        except ServiceError as identifier:
            print(identifier)
            # logger.error(identifier.message)
            exit()

    def list_boot_volume_attachments(self, ad, compartment_id):
        return list_call_get_all_results(
            self.compute_client.list_boot_volume_attachments, ad,
            compartment_id).data

    def get_instance_details(self, instance_id):
        try:
            instance_data = self.compute_client.get_instance(instance_id).data
        except Exception as e:
            if (e.status == 404):
                print(f"Instance Id {instance_id} is incorrect; Status: 404")
                # logger.error(f"Instance Id {instance_id} is incorrect; Status: 404")
            else:
                print(
                    f"Not authorized for {instance_id}; Status: {str(e.status)}"
                )
                # logger.error(f"Not authorized for {instance_id}; Status: {str(e.status)}")

            raise
        return instance_data

    # gets the instance tag and caches the instance tags to reduce number of request

    def get_instance_tags(self, instance_id):
        instance_details = self.compute_client.get_instance(instance_id).data
        tags = dict()
        tags["defined_tags"] = instance_details.defined_tags
        tags["freeform_tags"] = instance_details.freeform_tags
        return tags
Ejemplo n.º 6
0
def performChangeCompartment():
    global compute_client
    global work_request_client
    global availability_domain
    try:
        # read oci config
        config = oci.config.from_file()

        # create ComputeClient() with configuration
        compute_client = ComputeClient(config)

        # create WorkRequestClient() with configuration
        work_request_client = WorkRequestClient(config)

        response = getInstanceResponse()
        availability_domain = response.data.availability_domain
        source_compartment_id = response.data.compartment_id
        if source_compartment_id == target_compartment_id:
            errorExit(" Source and target compartment ids are same !")

        # List instance info before move
        info(' ')
        info(' Instance info before compartment move : ')
        info('   ETag : ' + response.headers['etag'])
        printInstanceInfo(source_compartment_id)

        # create ChangeInstanceCompartmentDetails() with compartment_id
        compartment_details = ChangeInstanceCompartmentDetails()
        compartment_details.compartment_id = target_compartment_id

        info(' ')
        info(' Moving Instance to target compartment ...')
        # call change_instance_compartment() on ComputeClient
        response = compute_client.change_instance_compartment(
            instance_id,
            compartment_details,
            if_match=if_match,
            opc_retry_token=opc_retry_token)

        # List instance info after move
        waitForMoveCompletion(response)
        info(' ')
        info(' Instance info after compartment move : ')
        if 'etag' in response.headers.keys():
            info('   ETag : ' + response.headers['etag'])
        printInstanceInfo(target_compartment_id)
        successExit()
    except Exception:
        info(' Unexpected error ')
        raise
class ComputeClientRoutes(TestCase):
    def setUp(self):
        self.server = ServerThread(app)
        self.server.start()
        self.oci_config = get_oci_config()
        self.compute_cli = ComputeClient(
            config=self.oci_config["config"],
            service_endpoint="http://localhost:12000")
        self.compute_cli_composite_op = ComputeClientCompositeOperations(
            self.compute_cli)

        self.test_instance = create_instance(
            self.oci_config["compartment_id"],
            self.compute_cli_composite_op,
            "dummy-instance",
        )

    def test_list_instances_without_params(self):
        response: Response = self.compute_cli.list_instances(
            self.oci_config["compartment_id"])

        self.assertEqual(response.status, 200)
        self.assertIsInstance(response.data, list)
        self.assertEqual(len(response.data), 1)

    def test_list_instances_with_params(self):
        response: Response = self.compute_cli.list_instances(
            self.oci_config["compartment_id"], display_name="dummy-instance")

        self.assertEqual(response.status, 200)
        self.assertIsInstance(response.data, list)
        self.assertEqual(len(response.data), 1)

        instances: List[Instance] = response.data
        test_instance = instances[0]

        self.assertEqual(test_instance.display_name,
                         self.test_instance.display_name)

        response: Response = self.compute_cli.list_instances(
            self.oci_config["compartment_id"], display_name="oopsss")

        self.assertEqual(response.status, 200)
        self.assertIsInstance(response.data, list)
        self.assertEqual(len(response.data), 0)

    def tearDown(self):
        terminate_instance(self.test_instance.id, self.compute_cli)
        self.server.shutdown()
Ejemplo n.º 8
0
    def setUp(self):
        self.server = ServerThread(app)
        self.server.start()
        self.oci_config = get_oci_config()
        self.compute_cli = ComputeClient(
            config=self.oci_config["config"],
            service_endpoint="http://localhost:12000")
        self.compute_cli_composite_op = ComputeClientCompositeOperations(
            self.compute_cli)

        self.test_instance = create_instance(
            self.oci_config["compartment_id"],
            self.compute_cli_composite_op,
            "dummy-instance",
        )
Ejemplo n.º 9
0
 def compute(self):    
     
     try:
         return ComputeClient(self.config)
     except oci.exceptions.ClientError as err:
         print(err, file=sys.stderr)
         sys.exit(1)
Ejemplo n.º 10
0
    def run_job(self):
        self.status = SUCCESS
        self.log_callback.info('Creating image.')

        self.request_credentials([self.account])
        credentials = self.credentials[self.account]

        config = {
            'user': self.oci_user_id,
            'key_content': credentials['signing_key'],
            'fingerprint': credentials['fingerprint'],
            'tenancy': self.tenancy,
            'region': self.region
        }
        compute_client = ComputeClient(config)
        compute_composite_client = ComputeClientCompositeOperations(
            compute_client)

        object_name = self.status_msg['object_name']
        namespace = self.status_msg['namespace']
        self.cloud_image_name = self.status_msg['cloud_image_name']

        image_source_details = ImageSourceViaObjectStorageTupleDetails(
            bucket_name=self.bucket,
            namespace_name=namespace,
            object_name=object_name,
            source_image_type=self.image_type,
            operating_system=self.operating_system,
            operating_system_version=self.operating_system_version)

        image_details = CreateImageDetails(
            compartment_id=self.compartment_id,
            display_name=self.cloud_image_name,
            image_source_details=image_source_details,
            launch_mode=self.launch_mode)

        retry_strategy = RetryStrategyBuilder(
            max_attempts=self.max_oci_attempts,
            service_error_retry_config={
                'service_error_retry_config': {
                    400: ['LimitExceeded']
                }
            }).get_retry_strategy()
        response = compute_composite_client.create_image_and_wait_for_state(
            create_image_details=image_details,
            wait_for_states=[Image.LIFECYCLE_STATE_AVAILABLE],
            operation_kwargs={'retry_strategy': retry_strategy},
            waiter_kwargs={'max_wait_seconds': self.max_oci_wait_seconds})

        self.status_msg['image_id'] = response.data.id
        self.log_callback.info(
            'Created image has ID: {0}.'.format(object_name))
Ejemplo n.º 11
0
    def cleanup_image(self, credentials, image_id):
        self.log_callback.info(
            'Cleaning up image: {0} in region: {1}.'.format(
                self.cloud_image_name,
                self.region
            )
        )

        config = {
            'user': self.oci_user_id,
            'key_content': credentials['signing_key'],
            'fingerprint': credentials['fingerprint'],
            'tenancy': self.tenancy,
            'region': self.region
        }
        compute_client = ComputeClient(config)
        compute_composite_client = ComputeClientCompositeOperations(
            compute_client
        )
        retry_strategy = RetryStrategyBuilder(
            max_attempts=self.max_oci_attempts,
            service_error_retry_config={
                'service_error_retry_config': {400: ['LimitExceeded']}
            }
        ).get_retry_strategy()

        try:
            compute_composite_client.delete_image_and_wait_for_state(
                image_id=image_id,
                wait_for_states=[
                    Image.LIFECYCLE_STATE_DELETED
                ],
                operation_kwargs={'retry_strategy': retry_strategy},
                waiter_kwargs={'max_wait_seconds': self.max_oci_wait_seconds}
            )
        except Exception as error:
            msg = 'Failed to cleanup image: {0}'.format(error)
            self.add_error_msg(msg)
            self.log_callback.warning(msg)
class ComputeClientRoutes(TestCase):
    def setUp(self):
        self.server = ServerThread(app)
        self.server.start()
        self.oci_config = get_oci_config()
        self.compute_cli = ComputeClient(
            config=self.oci_config["config"],
            service_endpoint="http://localhost:12000")
        self.compute_cli_composite_op = ComputeClientCompositeOperations(
            self.compute_cli)

        self.test_instance = create_instance(
            self.oci_config["compartment_id"],
            self.compute_cli_composite_op,
            "dummy-instance",
        )

    def test_perform_action(self):
        response: Response = self.compute_cli.list_instances(
            self.oci_config["compartment_id"], display_name="dummy-instance")
        instances: List[Instance] = response.data
        test_instance = instances[0]

        for action in list(InstanceAction.__members__.keys()):
            response: Response = self.compute_cli.instance_action(
                test_instance.id, action=action)

            assert response.status == 200
            assert response.data
            assert response.data.id == test_instance.id

    def test_perform_action_on_nonexistent_instance(self):
        with self.assertRaises(ServiceError) as e:
            self.compute_cli.instance_action("non_existent_instance",
                                             action="RESET")
            self.assertEqual(e.exception.status, 404)

    def test_perform_invalid_action(self):
        with self.assertRaises(ServiceError) as e:
            self.compute_cli.instance_action("dummy-instance",
                                             action="CRAZY_DUDE")
            self.assertEqual(e.exception.status, 404)

    def tearDown(self):
        terminate_instance(self.test_instance.id, self.compute_cli)
        self.server.shutdown()
Ejemplo n.º 13
0
class Instance:
    def __init__(self):
        config = {}
        try:
            signer = Config.signer
            self.compute_client = ComputeClient(config=config, signer=signer)
        except Exception:
            config = Config.config
            self.compute_client = ComputeClient(config)

    # Request to list all volume attachments
    def list_volume_attachments(self, compartment_id):
        try:
            return list_call_get_all_results(
                self.compute_client.list_volume_attachments,
                compartment_id,
                retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY,
            ).data
        except ServiceError as identifier:
            logging.error(traceback.format_exc())
            logging.error(identifier + " " + compartment_id)
            exit()

    def get_instance_details(self, instance_id):
        try:
            instance_data = self.compute_client.get_instance(
                instance_id, retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY
            ).data
        except Exception as e:
            if e.status == 404:
                logging.error(f"Instance Id {instance_id} is incorrect; Status: 404")
            else:
                logging.error(
                    f"Not authorized for {instance_id}; Status: {str(e.status)}"
                )

            raise
        return instance_data
Ejemplo n.º 14
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.º 15
0
        print("Usage: stop_instance.py ocid")

        sys.exit(-1)
    else:
        print("Running with: ")
        print("Instance OCID: {}".format(sys.argv[1]))
        print("")

#
# Main
#
print("")

controlla_params()

validate_config(config)

print("Validate config OK")

ocid = sys.argv[1]

client = ComputeClient(config)

print('Stopping instance...')

client.instance_action(ocid, 'STOP')

print("Instance to be stopped !")
print("")

Ejemplo n.º 16
0
def terminate_instance(instance_id: str, compute_client: ComputeClient) -> None:
    compute_client.terminate_instance(instance_id)
Ejemplo n.º 17
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
        'the AD where the pool will be spun up (the pool in this example only spans a single AD)',
        required=True)

    parser.add_argument('--subnet-id', help='the ', required=True)

    parser.add_argument('--image-id',
                        help='the image ID to use for instances',
                        required=True)

    args = parser.parse_args()

    # create the compute management client
    compute_management_client = ComputeManagementClient(config)

    # create the compute client
    compute_client = ComputeClient(config)

    launch_details = InstanceConfigurationLaunchInstanceDetails(
        compartment_id=args.compartment_id,
        display_name="some instance name",
        shape="VM.Standard2.1",
        source_details=InstanceConfigurationInstanceSourceViaImageDetails(
            image_id=args.image_id),
        create_vnic_details=InstanceConfigurationCreateVnicDetails())

    instance_details = ComputeInstanceDetails(launch_details=launch_details,
                                              block_volumes=[
                                                  _create_block_volume_details(
                                                      args.compartment_id,
                                                      args.availability_domain)
                                              ])
Ejemplo n.º 19
0
	exit()

if len(sys.argv) != 3:
	printUsage()


action = sys.argv[1].upper()
instancePrefix = sys.argv[2]

print action
if action != "-START" and action != "-STOP"  and action !="-LIST":
	printUsage
	
config = from_file()

compute  =  ComputeClient(config)
instances =[]
state = "RUNNING"
checkpoint_compartment="ocid1.compartment.oc1..aaaaaaaaowoexmvnos6b7e6csjshxkim4nu2fhte3cyttyp6cg5alwmf4csq"
frontline_compartment = "ocid1.tenancy.oc1..aaaaaaaago6llvabe46trovlahpyfeakbovwbogudjprbts3gxwstplxtyxq"
# response = compute.list_instances(compartment_id=frontline_compartment)
response = compute.list_instances(compartment_id=checkpoint_compartment)
for instance in response.data:
	if fnmatch(instance.display_name, instancePrefix):
		if action == "-LIST" :
			print instance.display_name.ljust(32) + "	" + instance.lifecycle_state
			print instance
		if action == "-STOP" and instance.lifecycle_state == "RUNNING":
			print "stopping  instance" ,instance.display_name
			state = "STOPPED"
			instances.append(instance)