def run_job(job_name): """ Method to run the Job specified on demand. :param job_name(str): Protection Job name. :return: None. """ status, job_id = _name_to_job_id(job_name) if not status: print("Protection Job with name: %s doesn't exist" % job_name) exit(0) req_body = ProtectionJobRequestBody() req_body.run_type = RunTypeEnum.KREGULAR cohesity_client.protection_jobs.create_run_protection_job(id=job_id, body=req_body) # Get the status of this Job run. jresp = cohesity_client.protection_runs.get_protection_runs(job_id=job_id, num_runs=1) if jresp == []: time.sleep(20) jresp = cohesity_client.protection_runs.get_protection_runs( job_id=job_id, num_runs=1)[0] else: jresp = jresp[0] if jresp.backup_run.status == StatusSourceBackupStatusEnum.KSUCCESS or \ jresp.backup_run.status == StatusSourceBackupStatusEnum.KACCEPTED: print("Protection Job %s started successfully" % job_name) elif jresp.backup_run.status == StatusSourceBackupStatusEnum.KERROR: print("Protection Job %s failed." % job_name)
def create_vmware_protection_job( job_name, vcenter_name, sources, policy="Gold", domain="DefaultStorageDomain", pause_job=True, timezone="Europe/Berlin", description="", ): """ Create Protection Job for VMware Source. CLI Examples: .. code-block:: bash salt "*" cohesity.create_vmware_protection_job job_name=job_name vcenter_name=vcenter_name sources=virtual_machine salt "*" cohesity.create_vmware_protection_job job_name=job_name vcenter_name=vcenter_name sources=virtual_machine1,virtualmachine2 salt "*" cohesity.create_vmware_protection_job job_name=job_name vcenter_name=vcenter_name sources=virtual_machine1,virtualmachine2 policy=Gold domain=DefaultStorageDomain pause_job=True timezone=Europe/Berlin description='Salt Job' salt "*" cohesity.create_vmware_protection_job job_name=job_name vcenter_name=vcenter_name sources=virtual_machine1,virtualmachine2 policy=Gold domain=DefaultStorageDomain pause_job=True timezone=Europe/Berlin """ try: cohesity_client = _get_client() # Check if the job already exists. resp = cohesity_client.protection_jobs.get_protection_jobs( names=job_name, is_deleted=False) if resp and resp[0].name == job_name: return "Job with name {} already exists.".format(job_name) body = ProtectionJobRequestBody() body.name = job_name body.description = description body.policy_id = _get_policy_id(policy) body.timezone = timezone body.view_box_id = _get_sd_id(domain) body.environment = env_enum.K_VMWARE body.pause = True body.parent_source_id, body.source_ids = _get_vmware_source_ids( vcenter_name, sources.split(",")) if body.parent_source_id == -1: return "Unable to fetch Vcenter with name {}".format(vcenter_name) elif len(body.source_ids) == 0: return ("Minimum of one VM is required to created protection job." " Unable to find atleast provided VMs {} in the Vcenter {}" .format(",".join(sources), vcenter_name)) else: resp = cohesity_client.protection_jobs.create_protection_job(body) if pause_job: # Pause the job. jobstate_body = ChangeProtectionJobStateParam() jobstate_body.pause = pause_job cohesity_client.protection_jobs.change_protection_job_state( resp.id, jobstate_body) return "Successfully created ProtectionGroup: {}".format(body.name) except APIException as err: return "Error creating job {} {}".format(job_name, err)
def create_nas_protection_job(nas_source, object_id): try: body = ProtectionJobRequestBody() body.environment = EnvironmentEnum.KGENERICNAS body.name = parser.get('cohesity', 'job_name_prefix') + \ nas_source.split(':/')[1] body.policy_id = get_policy_id(parser.get('cohesity', 'policy')) body.view_box_id = get_storage_domain_id(parser.get('cohesity','storage_domain')) body.source_ids=[object_id] body.parent_source_id = \ cohesity_client.protection_sources.list_protection_sources_root_nodes( environments=EnvironmentEnum.KGENERICNAS)[0].protection_source.id body.timezone = cohesity_client.cluster.get_cluster().timezone pro_resp = cohesity_client.protection_jobs.create_protection_job(body=body) return pro_resp.id except APIException as ex: print("Unable to create Protection Job for %s due to: %s" %( nas_source, ex.message))
def create_protection_job(vm_ids, vcenter_id): """ Method to create :param vm_ids [int]: List of VM id :param vcenter_id int: Vcenter ID in cohesity cluster. :return: """ try: body = ProtectionJobRequestBody() body.name = JOB['name'] body.policy_id = _get_protection_policy_id(JOB['policy_name']) body.view_box_id = _get_storage_domain_id() body.parent_source_id = vcenter_id body.source_ids = vm_ids body.timezone = "America/Los_Angeles" # TODO use pytz cohesity_client.protection_jobs.create_protection_job(body) except APIException as ex: print("Unable to create Protection Job due to: %s" % ex.context.response.raw_body) print("Successfully added VMs added to protection job.")
def main(): # => Load the default arguments including those specific to the Cohesity Protection Jobs. argument_spec = cohesity_common_argument_spec() argument_spec.update( dict( state=dict(choices=['present', 'absent', 'started', 'stopped'], default='present'), name=dict(type='str', required=True, aliases=['job_name']), description=dict(type='str', default=''), environment=dict(default='kOracle'), protection_policy=dict(type='str', aliases=['policy'], default='Bronze'), storage_domain=dict(type='str', default='DefaultStorageDomain'), time_zone=dict(type='str', default=''), start_time=dict(type='str', default=''), delete_backups=dict(type='bool', default=False), ondemand_run_type=dict( choices=['Regular', 'Full', 'Log', 'System'], default='Regular'), cancel_active=dict(type='bool', default=False), validate_certs=dict(type='bool', default=False), endpoint=dict(type=str, default=''), databases=dict(type=list, default=[]), )) # => Create a new module object module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) if not module.params.get("time_zone"): module.params["time_zone"] = get_timezone() global cohesity_client cohesity_client = get_cohesity_client(module) results = dict(changed=False, msg='Attempting to manage Protection Source', state=module.params.get('state')) job_exists, job_meta_data = check__protection_job__exists(module) if module.check_mode: check_mode_results = dict( changed=False, msg= 'Check Mode: Cohesity Protection Job is not currently registered', id='') if module.params.get('state') == 'present': if job_exists: check_mode_results[ 'msg'] = 'Check Mode: Cohesity Protection Job is currently registered. No changes' else: check_mode_results[ 'msg'] = 'Check Mode: Cohesity Protection Job is not currently registered. This action would register the Cohesity Protection Job.' check_mode_results['id'] = job_exists else: if job_exists: check_mode_results[ 'msg'] = 'Check Mode: Cohesity Protection Job is currently registered. This action would unregister the Cohesity Protection Job.' check_mode_results['id'] = job_exists else: check_mode_results[ 'msg'] = 'Check Mode: Cohesity Protection Job is not currently registered. No changes.' module.exit_json(**check_mode_results) elif module.params.get('state') == 'present': parent_id, source_id = get_source_id_by_endpoint(module) if not (parent_id and source_id): module.fail_json( msg= "Source '%s' is not registered to cluster, Please register the source and try again." % module.params.get('endpoint')) check__mandatory__params(module) body = ProtectionJobRequestBody() body.name = module.params.get('name') body.parent_source_id = source_id body.source_ids = [source_id] body.view_box_id = get__storage_domain_id__by_name(module) body.environment = module.params.get('environment') body.policy_id = get__prot_policy_id__by_name(module) body.timezone = module.params.get('time_zone').strip() body.description = module.params.get('description') databases = module.params.get('databases') if databases: entity_ids = list() application_nodes = [] body.source_special_parameters = list() resp = cohesity_client.protection_sources.list_protection_sources( environment='kOracle', id=parent_id) if not resp: module.fail_json( msg="Oracle source is not available to protect") for node in resp[0].nodes: application_nodes.extend(node.get("applicationNodes", [])) # Make copy of database list and remove once entity id fetched. This check # is to ensure availability of databases in server. copy_database = copy.deepcopy(databases) for database in databases: for node in application_nodes: if node["protectionSource"]["name"] == database.strip(): entity_ids.append(node["protectionSource"]["id"]) copy_database.remove(database) if len(databases) == len(entity_ids): break if copy_database: module.fail_json( "Following list of databases are not available in the " "Oracle Server: %s" % ", ".join(copy_database)) spl_params = SourceSpecialParameter() spl_params.source_id = source_id spl_params.oracle_special_parameters = OracleSpecialParameters() spl_params.oracle_special_parameters.application_entity_ids = entity_ids body.source_special_parameters.append(spl_params) if module.params.get('start_time'): start_time = list(module.params.get('start_time').replace(':', '')) if not len(start_time) == 4: # => There are only so many options here but if we get more characters # => than four then we need to escape quickly. module.fail_json( msg='Invalid start_time selected (' + module.params.get('start_time') + '). Please review and submit the correct Protection Job Starting time.' ) body.start_time = dict(hour=int(start_time[0] + start_time[1]), minute=int(start_time[2] + start_time[3])) try: if job_exists: response = cohesity_client.protection_jobs.update_protection_job( body, job_exists) msg = 'Updation of Cohesity Protection Job Complete' else: response = cohesity_client.protection_jobs.create_protection_job( body) msg = 'Creation of Cohesity Protection Job Complete' response = dict(id=response.id, name=response.name, environment=response.environment) results = dict(changed=True, msg=msg, **response) except APIException as err: module.fail_json(msg=err.message) elif module.params.get('state') == 'absent': if job_exists: job_id = job_meta_data.uid.id status, _, _ = get_protection_run__status__by_id(module, job_id) if status: stop_job(module, job_id) while True: status, _, _ = get_protection_run__status__by_id( module, job_id) if not status: time.sleep(10) break response = unregister_job(module, job_exists) results = dict( changed=True, msg='Unregistration of Cohesity Protection Job Complete', id=job_exists, name=module.params.get('name')) else: results = dict( changed=False, msg= 'The Protection Job for this host is currently not registered', name=module.params.get('name')) elif module.params.get('state') == 'started': if job_exists: response = start_job(module) results = dict( changed=True, msg='The Protection Job for this host has been started', id=job_exists, name=module.params.get('name')) else: results = dict( changed=False, msg= 'The Protection Job for this host is currently not registered', name=module.params.get('name')) elif module.params.get('state') == 'stopped': if job_exists: job_id = job_meta_data.uid.id response = stop_job(module, job_id) results = dict( changed=True, msg='The Protection Job for this host has been stopped', id=job_id, name=module.params.get('name')) else: results = dict( changed=False, msg= 'The Protection Job for this host is currently not registered', name=module.params.get('name')) else: # => This error should never happen based on the set assigned to the parameter. # => However, in case, we should raise an appropriate error. module.fail_json(msg='Invalid State selected: {0}'.format( module.params.get('state')), changed=False) module.exit_json(**results)
def main(): # => Load the default arguments including those specific to the Cohesity Protection Jobs. argument_spec = cohesity_common_argument_spec() argument_spec.update( dict( state=dict(choices=['present', 'absent', 'started', 'stopped'], default='present'), name=dict(type='str', required=True, aliases=['job_name']), description=dict(type='str', default=''), environment=dict(default='kOracle'), protection_policy=dict(type='str', aliases=['policy'], default='Bronze'), storage_domain=dict(type='str', default='DefaultStorageDomain'), time_zone=dict(type='str', default='America/Los_Angeles'), start_time=dict(type='str', default=''), delete_backups=dict(type='bool', default=False), ondemand_run_type=dict( choices=['Regular', 'Full', 'Log', 'System'], default='Regular'), cancel_active=dict(type='bool', default=False), validate_certs=dict(type='bool', default=False), endpoint=dict(type=str, default=''), )) # => Create a new module object module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) global cohesity_client cohesity_client = get_cohesity_client(module) results = dict(changed=False, msg='Attempting to manage Protection Source', state=module.params.get('state')) job_exists, job_meta_data = check__protection_job__exists(module) if module.check_mode: check_mode_results = dict( changed=False, msg= 'Check Mode: Cohesity Protection Job is not currently registered', id='') if module.params.get('state') == 'present': if job_exists: check_mode_results[ 'msg'] = 'Check Mode: Cohesity Protection Job is currently registered. No changes' else: check_mode_results[ 'msg'] = 'Check Mode: Cohesity Protection Job is not currently registered. This action would register the Cohesity Protection Job.' check_mode_results['id'] = job_exists else: if job_exists: check_mode_results[ 'msg'] = 'Check Mode: Cohesity Protection Job is currently registered. This action would unregister the Cohesity Protection Job.' check_mode_results['id'] = job_exists else: check_mode_results[ 'msg'] = 'Check Mode: Cohesity Protection Job is not currently registered. No changes.' module.exit_json(**check_mode_results) elif module.params.get('state') == 'present': parent_id, source_id = get_source_id_by_endpoint(module) check__mandatory__params(module) body = ProtectionJobRequestBody() body.name = module.params.get('name') body.parent_source_id = parent_id body.source_ids = [source_id] body.view_box_id = get__storage_domain_id__by_name(module) body.environment = module.params.get('environment') body.policy_id = get__prot_policy_id__by_name(module) body.timezone = module.params.get('time_zone').strip() body.description = module.params.get('description') if module.params.get('start_time'): start_time = list(module.params.get('start_time').replace(':', '')) if not len(start_time) == 4: # => There are only so many options here but if we get more characters # => than four then we need to escape quickly. module.fail_json( msg='Invalid start_time selected (' + module.params.get('start_time') + '). Please review and submit the correct Protection Job Starting time.' ) body.start_time = dict(hour=int(start_time[0] + start_time[1]), minute=int(start_time[2] + start_time[3])) if job_exists: response = cohesity_client.protection_jobs.update_protection_job( body, job_exists) msg = 'Updation of Cohesity Protection Job Complete' else: response = cohesity_client.protection_jobs.create_protection_job( body) msg = 'Creation of Cohesity Protection Job Complete' response = dict(id=response.id, name=response.name, environment=response.environment) results = dict(changed=True, msg=msg, **response) elif module.params.get('state') == 'absent': if job_exists: job_id = job_meta_data.uid.id status, _, _ = get_protection_run__status__by_id(module, job_id) if status: stop_job(module, job_id) while True: status, _, _ = get_protection_run__status__by_id( module, job_id) if not status: time.sleep(10) break response = unregister_job(module, job_exists) results = dict( changed=True, msg='Unregistration of Cohesity Protection Job Complete', id=job_exists, name=module.params.get('name')) else: results = dict( changed=False, msg= 'The Protection Job for this host is currently not registered', name=module.params.get('name')) elif module.params.get('state') == 'started': if job_exists: response = start_job(module) results = dict( changed=True, msg='The Protection Job for this host has been started', id=job_exists, name=module.params.get('name')) else: results = dict( changed=False, msg= 'The Protection Job for this host is currently not registered', name=module.params.get('name')) elif module.params.get('state') == 'stopped': if job_exists: job_id = job_meta_data.uid.id response = stop_job(module, job_id) results = dict( changed=True, msg='The Protection Job for this host has been stopped', id=job_id, name=module.params.get('name')) else: results = dict( changed=False, msg= 'The Protection Job for this host is currently not registered', name=module.params.get('name')) else: # => This error should never happen based on the set assigned to the parameter. # => However, in case, we should raise an appropriate error. module.fail_json(msg='Invalid State selected: {0}'.format( module.params.get('state')), changed=False) module.exit_json(**results)