def clusters(cls, session): """ Method will prompt user to select a cluster Args: session (obj): Auth session object Returns: cluster (str): Name of selected cluster """ clusters_choices = Query.create_container( session, session.content.rootFolder, [vim.ComputeResource], True ) clusters = Query.list_obj_attrs(clusters_choices, 'name') clusters.sort() for num, opt in enumerate(clusters, start=1): print('%s: %s' % (num, opt)) while True: val = int(raw_input('\nPlease select number: ').strip()) if int(val) <= len(clusters): # need to substract 1 since we start enumeration at 1. val = int(val) - 1 selected_cluster = clusters[val] break else: print('Invalid number.') continue cls.logger.info(selected_cluster) return selected_cluster
def folders(cls, session, datacenter): """ Method will prompt user to select a folder from a datacenter Args: session (obj): Auth session object datacenter (str): Name of datacenter Returns: folder (str): Name of selected folder """ datacenters = Query.create_container( session, session.content.rootFolder, [vim.Datacenter], True ) folders = Query.list_vm_folders( datacenters.view, datacenter ) folders.sort() for num, opt in enumerate(folders, start=1): print('%s: %s' % (num, opt)) while True: val = int(raw_input('\nPlease select number: ').strip()) if int(val) <= len(folders): # need to substract 1 since we start enumeration at 1. val = int(val) - 1 selected_folder = folders[val] break else: print('Invalid number.') continue cls.logger.info(selected_folder) return selected_folder
def clusters(cls, session): """ Method will prompt user to select a cluster Args: session (obj): Auth session object Returns: cluster (str): Name of selected cluster """ clusters_choices = Query.create_container(session, session.content.rootFolder, [vim.ComputeResource], True) clusters = Query.list_obj_attrs(clusters_choices, 'name') clusters.sort() for num, opt in enumerate(clusters, start=1): print('%s: %s' % (num, opt)) while True: val = int(raw_input('\nPlease select number: ').strip()) if int(val) <= len(clusters): # need to substract 1 since we start enumeration at 1. val = int(val) - 1 selected_cluster = clusters[val] break else: print('Invalid number.') continue cls.logger.info(selected_cluster) return selected_cluster
def folders(cls, session, datacenter): """ Method will prompt user to select a folder from a datacenter Args: session (obj): Auth session object datacenter (str): Name of datacenter Returns: folder (str): Name of selected folder """ datacenters = Query.create_container(session, session.content.rootFolder, [vim.Datacenter], True) folders = Query.list_vm_folders(datacenters.view, datacenter) folders.sort() for num, opt in enumerate(folders, start=1): print('%s: %s' % (num, opt)) while True: val = int(raw_input('\nPlease select number: ').strip()) if int(val) <= len(folders): # need to substract 1 since we start enumeration at 1. val = int(val) - 1 selected_folder = folders[val] break else: print('Invalid number.') continue cls.logger.info(selected_folder) return selected_folder
def __init__(self, auth, opts, dotrc): VMConfig.__init__(self) self.auth = auth self.opts = opts self.dotrc = dotrc self.datacenters = Query.create_container( self.auth.session, self.auth.session.content.rootFolder, [vim.Datacenter], True) self.clusters = Query.create_container( self.auth.session, self.auth.session.content.rootFolder, [vim.ComputeResource], True) self.folders = Query.create_container( self.auth.session, self.auth.session.content.rootFolder, [vim.Folder], True) self.virtual_machines = Query.create_container( self.auth.session, self.auth.session.content.rootFolder, [vim.VirtualMachine], True)
def __init__(self, auth, opts, dotrc): VMConfig.__init__(self) self.auth = auth self.opts = opts self.dotrc = dotrc self.datacenters = Query.create_container( self.auth.session, self.auth.session.content.rootFolder, [vim.Datacenter], True ) self.clusters = Query.create_container( self.auth.session, self.auth.session.content.rootFolder, [vim.ComputeResource], True ) self.folders = Query.create_container( self.auth.session, self.auth.session.content.rootFolder, [vim.Folder], True ) self.virtual_machines = Query.create_container( self.auth.session, self.auth.session.content.rootFolder, [vim.VirtualMachine], True )
def datastores(cls, session, cluster): """ Method will prompt user to select a datastore from a cluster Args: session (obj): Auth session object cluster (str): Name of cluster Returns: datastore (str): Name of selected datastore """ clusters = Query.create_container(session, session.content.rootFolder, [vim.ComputeResource], True) datastores = Query.return_datastores(clusters.view, cluster) print('\n') if (len(datastores) - 1) == 0: print('No Datastores Found.') sys.exit(1) else: print('%s Datastores Found.\n' % (len(datastores) - 1)) for num, opt in enumerate(datastores): # the first item is the header information, so we will # not allow it as an option. if num == 0: print('\t%s' % ('{0:30}\t{1:10}\t{2:10}\t{3:6}\t{4:10}\t{5:6}'.format( *opt))) else: print('%s: %s' % (num, '{0:30}\t{1:10}\t{2:10}\t{3:6}\t{4:10}\t{5:6}'.format( *opt))) while True: val = int(raw_input('\nPlease select number: ').strip()) if val > 0 and val <= (len(datastores) - 1): break else: print('Invalid number') continue datastore = datastores[val][0] cls.logger.info(datastore) return datastore
def datastores(cls, session, cluster): """ Method will prompt user to select a datastore from a cluster Args: session (obj): Auth session object cluster (str): Name of cluster Returns: datastore (str): Name of selected datastore """ clusters = Query.create_container( session, session.content.rootFolder, [vim.ComputeResource], True ) datastores = Query.return_datastores(clusters.view, cluster) print('\n') if (len(datastores) -1) == 0: print('No Datastores Found.') sys.exit(1) else: print('%s Datastores Found.\n' % (len(datastores) - 1)) for num, opt in enumerate(datastores): # the first item is the header information, so we will # not allow it as an option. if num == 0: print('\t%s' % ('{0:30}\t{1:10}\t{2:10}\t{3:6}\t{4:10}\t{5:6}'.format(*opt))) else: print('%s: %s' % (num, '{0:30}\t{1:10}\t{2:10}\t{3:6}\t{4:10}\t{5:6}'.format(*opt))) while True: val = int(raw_input('\nPlease select number: ').strip()) if val > 0 and val <= (len(datastores) - 1): break else: print('Invalid number') continue datastore = datastores[val][0] cls.logger.info(datastore) return datastore
def main(self): """ This is the main method, which parses all the argparse options and runs the necessary code blocks if True. """ try: call_count = 0 self.auth = Auth(self.opts.host) self.auth.login( self.opts.user, self.opts.passwd, self.opts.domain, self.opts.passwd_file ) self.opts.passwd = None self.logger.debug(self.opts) virtual_machines_container = Query.create_container( self.auth.session, self.auth.session.content.rootFolder, [vim.VirtualMachine], True ) self.vmcfg = VMConfigHelper(self.auth, self.opts, argparser.dotrc) self.clustercfg = ClusterConfig(self.auth, self.opts, argparser.dotrc) call_count = self.auth.session.content.sessionManager.currentSession.callCount if not self.opts.datacenter: self.opts.datacenter = Prompts.datacenters(self.auth.session) if self.opts.cmd == 'create': if self.opts.config: for cfg in self.opts.config: spec = self.vmcfg.dict_merge( argparser.dotrc, yaml.load(cfg, Loader=yaml.FullLoader) ) cfgcheck_update = CfgCheck.cfg_checker(spec, self.auth, self.opts) spec['vmconfig'].update( self.vmcfg.dict_merge(spec['vmconfig'], cfgcheck_update) ) spec = self.vmcfg.pre_create_hooks(**spec) spec = self.vmcfg.create_wrapper(**spec) self.vmcfg.post_create_hooks(**spec) filename = spec['vmconfig']['name'] + '.yaml' server_cfg = {} server_cfg['vmconfig'] = {} server_cfg['vmconfig'].update(spec['vmconfig']) if spec.get('mkbootiso', None): server_cfg['mkbootiso'] = {} server_cfg['mkbootiso'].update(spec['mkbootiso']) print( yaml.dump(server_cfg, default_flow_style=False), file=open(os.path.join(os.environ['OLDPWD'], filename), 'w') ) if self.opts.cmd == 'mount': self.vmcfg.mount_wrapper(self.opts.datastore, self.opts.path, *self.opts.name) if self.opts.cmd == 'power': self.vmcfg.power_wrapper(self.opts.power, *self.opts.name) if self.opts.cmd == 'umount': self.vmcfg.umount_wrapper(*self.opts.name) if self.opts.cmd == 'upload': self.vmcfg.upload_wrapper( self.opts.datastore, self.opts.dest, self.opts.verify_ssl, *self.opts.iso ) if self.opts.cmd == 'add': hostname = Query.get_obj(virtual_machines_container.view, self.opts.name) # nics if self.opts.device == 'nic': self.vmcfg.add_nic_recfg(hostname) if self.opts.cmd == 'reconfig': host = Query.get_obj(virtual_machines_container.view, self.opts.name) if self.opts.cfgs: self.logger.info( 'reconfig: %s cfgs: %s', host.name, ' '.join('%s=%s' % (k, v) for k, v in self.opts.cfgs.items()) ) self.vmcfg.reconfig(host, **self.opts.cfgs) if self.opts.folder: self.vmcfg.folder_recfg() if self.opts.device == 'disk': self.vmcfg.disk_recfg() if self.opts.device == 'nic': self.vmcfg.nic_recfg() if self.opts.cmd == 'drs': if not self.opts.cluster: self.opts.cluster = Prompts.clusters(self.auth.session) self.clustercfg.drs_rule() if self.opts.cmd == 'query': datacenters_container = Query.create_container( self.auth.session, self.auth.session.content.rootFolder, [vim.Datacenter], True ) clusters_container = Query.create_container( self.auth.session, self.auth.session.content.rootFolder, [vim.ClusterComputeResource], True ) if self.opts.anti_affinity_rules: if self.opts.cluster: anti_affinity_rules = Query.return_anti_affinity_rules( clusters_container.view, self.opts.cluster ) else: cluster = Prompts.clusters(self.auth.session) anti_affinity_rules = Query.return_anti_affinity_rules( clusters_container.view, cluster ) if not anti_affinity_rules: print('No antiaffinity rules defined.') else: print('Antiaffinity rules:') for key, val in sorted(anti_affinity_rules.items()): print('{0}: {1}'.format(key, ' '.join(sorted(val)))) if self.opts.datastores: if self.opts.cluster: datastores = Query.return_datastores( clusters_container.view, self.opts.cluster ) else: cluster = Prompts.clusters(self.auth.session) datastores = Query.return_datastores(clusters_container.view, cluster) for row in datastores: print('{0:30}\t{1:10}\t{2:10}\t{3:6}\t{4:10}\t{5:6}'.format(*row)) if self.opts.folders: if self.opts.datacenter: folders = Query.list_vm_folders( datacenters_container.view, self.opts.datacenter ) folders.sort() for folder in folders: print(folder) else: datacenter = Prompts.datacenters(self.auth.session) folders = Query.list_vm_folders(datacenters_container.view, datacenter) folders.sort() for folder in folders: print(folder) if self.opts.clusters: clusters = Query.list_obj_attrs(clusters_container, 'name') clusters.sort() for cluster in clusters: print(cluster) if self.opts.networks: if self.opts.cluster: cluster = Query.get_obj(clusters_container.view, self.opts.cluster) networks = Query.list_obj_attrs(cluster.network, 'name', view=False) networks.sort() for net in networks: print(net) else: cluster_name = Prompts.clusters(self.auth.session) cluster = Query.get_obj(clusters_container.view, cluster_name) networks = Query.list_obj_attrs(cluster.network, 'name', view=False) networks.sort() for net in networks: print(net) if self.opts.vms: vms = Query.list_vm_info(datacenters_container.view, self.opts.datacenter) for key, value in vms.items(): print(key, value) if self.opts.vmconfig: for name in self.opts.vmconfig: virtmachine = Query.get_obj(virtual_machines_container.view, name) self.logger.debug(virtmachine.config) if self.opts.createcfg: print( yaml.dump( Query.vm_config( virtual_machines_container.view, name, self.opts.createcfg ), default_flow_style=False ) ) else: print( yaml.dump( Query.vm_config(virtual_machines_container.view, name), default_flow_style=False ) ) if self.opts.vm_by_datastore: if self.opts.cluster and self.opts.datastore: vms = Query.vm_by_datastore( clusters_container.view, self.opts.cluster, self.opts.datastore ) for vm_name in vms: print(vm_name) else: if not self.opts.cluster: cluster = Prompts.clusters(self.auth.session) if not self.opts.datastore: datastore = Prompts.datastores(self.auth.session, cluster) print() vms = Query.vm_by_datastore(clusters_container.view, cluster, datastore) for vm_name in vms: print(vm_name) if self.opts.vm_guest_ids: for guest_id in Query.list_guestids(): print(guest_id) self.auth.logout() self.logger.debug('Call count: {0}'.format(call_count)) except ValueError as err: self.logger.error(err, exc_info=False) self.auth.logout() self.logger.debug('Call count: {0}'.format(call_count)) sys.exit(3) except vim.fault.InvalidLogin as loginerr: self.logger.error(loginerr.msg, exc_info=False) sys.exit(2) except ssl.CertificateError as err: self.logger.error(err, exc_info=False) sys.exit(2) except KeyboardInterrupt as err: self.logger.error(err, exc_info=False) self.auth.logout() self.logger.debug('Call count: {0}'.format(call_count)) sys.exit(1)
def main(self): """ This is the main method, which parses all the argparse options and runs the necessary code blocks if True. """ try: self.auth = Auth(self.opts.host) self.auth.login(self.opts.user, self.opts.passwd, self.opts.domain, self.opts.passwd_file) self.opts.passwd = None self.logger.debug(self.opts) virtual_machines_container = Query.create_container( self.auth.session, self.auth.session.content.rootFolder, [vim.VirtualMachine], True) self.vmcfg = VMConfigHelper(self.auth, self.opts, argparser.dotrc) self.clustercfg = ClusterConfig(self.auth, self.opts, argparser.dotrc) call_count = self.auth.session.content.sessionManager.currentSession.callCount if self.opts.cmd == 'create': if self.opts.config: for cfg in self.opts.config: spec = self.vmcfg.dict_merge(argparser.dotrc, yaml.load(cfg)) cfgcheck_update = CfgCheck.cfg_checker( spec, self.auth, self.opts) spec['vmconfig'].update( self.vmcfg.dict_merge(spec['vmconfig'], cfgcheck_update)) spec = self.vmcfg.pre_create_hooks(**spec) spec = self.vmcfg.create_wrapper(**spec) self.vmcfg.post_create_hooks(**spec) filename = spec['vmconfig']['name'] + '.yaml' server_cfg = {} server_cfg['vmconfig'] = {} server_cfg['vmconfig'].update(spec['vmconfig']) if spec.get('mkbootiso', None): server_cfg['mkbootiso'] = {} server_cfg['mkbootiso'].update(spec['mkbootiso']) print(yaml.dump(server_cfg, default_flow_style=False), file=open(filename, 'w')) if self.opts.cmd == 'mount': self.vmcfg.mount_wrapper(self.opts.datastore, self.opts.path, *self.opts.name) if self.opts.cmd == 'power': self.vmcfg.power_wrapper(self.opts.power, *self.opts.name) if self.opts.cmd == 'umount': self.vmcfg.umount_wrapper(*self.opts.name) if self.opts.cmd == 'upload': self.vmcfg.upload_wrapper(self.opts.datastore, self.opts.dest, self.opts.verify_ssl, *self.opts.iso) if self.opts.cmd == 'add': hostname = Query.get_obj(virtual_machines_container.view, self.opts.name) # nics if self.opts.device == 'nic': self.vmcfg.add_nic_recfg(hostname) if self.opts.cmd == 'reconfig': host = Query.get_obj(virtual_machines_container.view, self.opts.name) if self.opts.cfgs: self.logger.info( 'reconfig: %s cfgs: %s', host.name, ' '.join('%s=%s' % (k, v) for k, v in self.opts.cfgs.iteritems())) self.vmcfg.reconfig(host, **self.opts.cfgs) if self.opts.folder: self.vmcfg.folder_recfg() if self.opts.device == 'disk': self.vmcfg.disk_recfg() if self.opts.device == 'nic': self.vmcfg.nic_recfg() if self.opts.cmd == 'drs': if not self.opts.cluster: self.opts.cluster = Prompts.clusters(self.auth.session) self.clustercfg.drs_rule() if self.opts.cmd == 'query': datacenters_container = Query.create_container( self.auth.session, self.auth.session.content.rootFolder, [vim.Datacenter], True) clusters_container = Query.create_container( self.auth.session, self.auth.session.content.rootFolder, [vim.ClusterComputeResource], True) if self.opts.anti_affinity_rules: if self.opts.cluster: anti_affinity_rules = Query.return_anti_affinity_rules( clusters_container.view, self.opts.cluster) else: cluster = Prompts.clusters(self.auth.session) anti_affinity_rules = Query.return_anti_affinity_rules( clusters_container.view, cluster) if not anti_affinity_rules: print('No antiaffinity rules defined.') else: print('Antiaffinity rules:') for key, val in sorted( anti_affinity_rules.iteritems()): print('{0}: {1}'.format(key, ' '.join(sorted(val)))) if self.opts.datastores: if self.opts.cluster: datastores = Query.return_datastores( clusters_container.view, self.opts.cluster) else: cluster = Prompts.clusters(self.auth.session) datastores = Query.return_datastores( clusters_container.view, cluster) for row in datastores: print('{0:30}\t{1:10}\t{2:10}\t{3:6}\t{4:10}\t{5:6}'. format(*row)) if self.opts.folders: if self.opts.datacenter: folders = Query.list_vm_folders( datacenters_container.view, self.opts.datacenter) folders.sort() for folder in folders: print(folder) else: datacenter = Prompts.datacenters(self.auth.session) folders = Query.list_vm_folders( datacenters_container.view, datacenter) folders.sort() for folder in folders: print(folder) if self.opts.clusters: clusters = Query.list_obj_attrs(clusters_container, 'name') clusters.sort() for cluster in clusters: print(cluster) if self.opts.networks: if self.opts.cluster: cluster = Query.get_obj(clusters_container.view, self.opts.cluster) networks = Query.list_obj_attrs(cluster.network, 'name', view=False) networks.sort() for net in networks: print(net) else: cluster_name = Prompts.clusters(self.auth.session) cluster = Query.get_obj(clusters_container.view, cluster_name) networks = Query.list_obj_attrs(cluster.network, 'name', view=False) networks.sort() for net in networks: print(net) if self.opts.vms: vms = Query.list_vm_info(datacenters_container.view, self.opts.datacenter) for key, value in vms.iteritems(): print(key, value) if self.opts.vmconfig: for name in self.opts.vmconfig: virtmachine = Query.get_obj( virtual_machines_container.view, name) self.logger.debug(virtmachine.config) if self.opts.createcfg: print( yaml.dump(Query.vm_config( virtual_machines_container.view, name, self.opts.createcfg), default_flow_style=False)) else: print( yaml.dump(Query.vm_config( virtual_machines_container.view, name), default_flow_style=False)) if self.opts.vm_by_datastore: if self.opts.cluster and self.opts.datastore: vms = Query.vm_by_datastore(clusters_container.view, self.opts.cluster, self.opts.datastore) for vm_name in vms: print(vm_name) else: if not self.opts.cluster: cluster = Prompts.clusters(self.auth.session) if not self.opts.datastore: datastore = Prompts.datastores( self.auth.session, cluster) print() vms = Query.vm_by_datastore(clusters_container.view, cluster, datastore) for vm_name in vms: print(vm_name) if self.opts.vm_guest_ids: for guest_id in Query.list_guestids(): print(guest_id) self.auth.logout() self.logger.debug('Call count: {0}'.format(call_count)) except ValueError as err: self.logger.error(err, exc_info=False) self.auth.logout() self.logger.debug('Call count: {0}'.format(call_count)) sys.exit(3) except vim.fault.InvalidLogin as loginerr: self.logger.error(loginerr.msg, exc_info=False) sys.exit(2) except KeyboardInterrupt as err: self.logger.error(err, exc_info=False) self.auth.logout() self.logger.debug('Call count: {0}'.format(call_count)) sys.exit(1)
def cfg_checker(cfg, auth, opts): """ Checks config for a valid configuration, and prompts user if information is missing Args: cfg (obj): Yaml object """ clusters = Query.create_container( auth.session, auth.session.content.rootFolder, [vim.ComputeResource], True ) # name if 'vmconfig' in cfg: # name if 'name' in cfg['vmconfig']: name = cfg['vmconfig']['name'] else: name = Prompts.name() # guestid if 'guestId' in cfg['vmconfig']: guestid = cfg['vmconfig']['guestId'] else: guestid = Prompts.guestids() print('\n%s guestid selected.' % (guestid)) # cluster if 'cluster' in cfg['vmconfig']: cluster = cfg['vmconfig']['cluster'] cluster_obj = Query.get_obj(clusters.view, cluster) else: cluster = Prompts.clusters(auth.session) cluster_obj = Query.get_obj(clusters.view, cluster) print('\n%s cluster selected.' % (cluster)) # datastore if 'datastore' in cfg['vmconfig']: datastore = cfg['vmconfig']['datastore'] else: datastore = Prompts.datastores(auth.session, cluster) print('\n%s datastore selected.' % (datastore)) # datacenter if not opts.datacenter: datacenter = Prompts.datacenters(auth.session) print('\n%s datacenter selected.' % (datacenter)) else: datacenter = opts.datacenter # nics if 'nics' in cfg['vmconfig']: nics = cfg['vmconfig']['nics'] print('nics: %s' % (nics)) else: nics = Prompts.networks(cluster_obj) print('\n%s networks selected.' % (','.join(nics))) # folder if 'folder' in cfg['vmconfig']: folder = cfg['vmconfig']['folder'] else: folder = Prompts.folders(auth.session, datacenter) print('\n%s folder selected.' % (folder)) else: name = Prompts.name() guestid = Prompts.guestids() print('\n%s selected.' % (guestid)) cluster = Prompts.clusters(auth.session) print('\n%s selected.' % (cluster)) datastore = Prompts.datastores(auth.session, cluster) print('\n%s selected.' % (datastore)) datacenter = Prompts.datacenters(auth.session) print('\n%s selected.' % (datacenter)) nics = Prompts.networks(cluster_obj) print('\n%s selected.' % (','.join(nics))) folder = Prompts.folders(auth.session, datacenter) print('\n%s selected.' % (folder)) output = { 'name': name, 'guestId': guestid, 'cluster': cluster, 'datastore': datastore, 'datacenter': datacenter, 'nics': nics, 'folder': folder } return output
def drs_rule(self): """ Method messes with DRS rules. Currently only Anti Affinity rules, and only add or delete. For safety, it has a concept of a vctools prefix. The prefix lives in the rc file, or can be declared by a flag. This is so you "can't" delete a rule that was not created by vctools. Args: cluster (str): cluster to modify type (str): currently only anti-affinity oper (add|delete): operation mode name (str): name of the rule vms (list): list of vms (to add, not used for delete) Returns true if successful. """ cluster = self.opts.cluster drs_type = self.opts.drs_type name = self.opts.name vms = self.opts.vms function = self.opts.function self.logger.debug(cluster, drs_type, name, vms, function) # containers we need clusters = Query.create_container( self.auth.session, self.auth.session.content.rootFolder, [vim.ComputeResource], True ) virtual_machines = Query.create_container( self.auth.session, self.auth.session.content.rootFolder, [vim.VirtualMachine], True ) # our cluster object cluster_obj = Query.get_obj(clusters.view, cluster) if drs_type == 'anti-affinity': if function == 'add': vm_obj_list = [] for vm_obj in vms: vm_obj_list.append(Query.get_obj(virtual_machines.view, vm_obj)) # check to see if this rule name is in use if Query.is_anti_affinity_rule(cluster_obj, name): raise ValueError('Error: rule name "%s" is already in use' % name) # check to see vms are in the right cluster for vm_obj in vm_obj_list: if not Query.is_vm_in_cluster(cluster_obj, vm_obj): raise ValueError( 'Error: the vm "%s" is not in the stated cluster' % vm_obj.name ) # check to see if the vms already have DRS rules for vm_obj in vm_obj_list: match = 0 for rule in cluster_obj.configuration.rule: if hasattr(rule, 'vm'): for rulevm in rule.vm: if vm_obj == rulevm: match = 1 if match != 0: raise ValueError( 'Error: the vm "%s" is already in a DRS rule' % vm_obj.name ) new_rule = vim.ClusterAntiAffinityRuleSpec() new_rule.name = name new_rule.userCreated = True new_rule.enabled = True for vm_obj in vm_obj_list: new_rule.vm.append(vm_obj) rule_spec = vim.cluster.RuleSpec(info=new_rule, operation='add') config_spec = vim.cluster.ConfigSpecEx(rulesSpec=[rule_spec]) Tasks.task_monitor(cluster_obj.ReconfigureComputeResource_Task( config_spec, modify=True), False) self.logger.info('new AA DRS rule on %s: %s', cluster, name) if function == 'delete': #Delete an AntiAffinity Rule # check to see if this rule name is in use, and delete if found found = False for existing_rule in cluster_obj.configuration.rule: if existing_rule.name == name: found = True # doublecheck this is an AA rule if isinstance(existing_rule, vim.cluster.AntiAffinityRuleSpec): rule_spec = vim.cluster.RuleSpec( removeKey=existing_rule.key, operation='remove') config_spec = vim.cluster.ConfigSpecEx(rulesSpec=[rule_spec]) Tasks.task_monitor(cluster_obj.ReconfigureComputeResource_Task( config_spec, modify=True), False) self.logger.info('Deleted AA DRS rule on %s: %s', cluster, name) else: raise ValueError( 'Error: rule name "%s" not an AntiAffinity rule' % name ) if not found: raise ValueError('Error: rule name "%s" not found' % name)
def cfg_checker(cfg, auth, opts): """ Checks config for a valid configuration, and prompts user if information is missing Args: cfg (obj): Yaml object """ clusters = Query.create_container(auth.session, auth.session.content.rootFolder, [vim.ComputeResource], True) # name if 'vmconfig' in cfg: # name if 'name' in cfg['vmconfig']: name = cfg['vmconfig']['name'] else: name = Prompts.name() # guestid if 'guestId' in cfg['vmconfig']: guestid = cfg['vmconfig']['guestId'] else: guestid = Prompts.guestids() print('\n%s selected.' % (guestid)) # cluster if 'cluster' in cfg['vmconfig']: cluster = cfg['vmconfig']['cluster'] cluster_obj = Query.get_obj(clusters.view, cluster) else: cluster = Prompts.clusters(auth.session) cluster_obj = Query.get_obj(clusters.view, cluster) print('\n%s selected.' % (cluster)) # datastore if 'datastore' in cfg['vmconfig']: datastore = cfg['vmconfig']['datastore'] else: datastore = Prompts.datastores(auth.session, cluster) print('\n%s selected.' % (datastore)) # datacenter if not opts.datacenter: datacenter = Prompts.datacenters(auth.session) print('\n%s selected.' % (datacenter)) else: datacenter = opts.datacenter # nics if 'nics' in cfg['vmconfig']: nics = cfg['vmconfig']['nics'] print('nics: %s' % (nics)) else: nics = Prompts.networks(cluster_obj) print('\n%s selected.' % (','.join(nics))) # folder if 'folder' in cfg['vmconfig']: folder = cfg['vmconfig']['folder'] else: folder = Prompts.folders(auth.session, datacenter) print('\n%s selected.' % (folder)) else: name = Prompts.name() guestid = Prompts.guestids() print('\n%s selected.' % (guestid)) cluster = Prompts.clusters(auth.session) print('\n%s selected.' % (cluster)) datastore = Prompts.datastores(auth.session, cluster) print('\n%s selected.' % (datastore)) datacenter = Prompts.datacenters(auth.session) print('\n%s selected.' % (datacenter)) nics = Prompts.networks(cluster_obj) print('\n%s selected.' % (','.join(nics))) folder = Prompts.folders(auth.session, datacenter) print('\n%s selected.' % (folder)) output = { 'name': name, 'guestId': guestid, 'cluster': cluster, 'datastore': datastore, 'nics': nics, 'folder': folder } return output
def drs_rule(self): """ Method messes with DRS rules. Currently only Anti Affinity rules, and only add or delete. For safety, it has a concept of a vctools prefix. The prefix lives in the rc file, or can be declared by a flag. This is so you "can't" delete a rule that was not created by vctools. Args: cluster (str): cluster to modify type (str): currently only anti-affinity oper (add|delete): operation mode name (str): name of the rule vms (list): list of vms (to add, not used for delete) Returns true if successful. """ cluster = self.opts.cluster drs_type = self.opts.drs_type name = self.opts.name vms = self.opts.vms function = self.opts.function self.logger.debug(cluster, drs_type, name, vms, function) # containers we need clusters = Query.create_container(self.auth.session, self.auth.session.content.rootFolder, [vim.ComputeResource], True) virtual_machines = Query.create_container( self.auth.session, self.auth.session.content.rootFolder, [vim.VirtualMachine], True) # our cluster object cluster_obj = Query.get_obj(clusters.view, cluster) if drs_type == 'anti-affinity': if function == 'add': vm_obj_list = [] for vm_obj in vms: vm_obj_list.append( Query.get_obj(virtual_machines.view, vm_obj)) # check to see if this rule name is in use if Query.is_anti_affinity_rule(cluster_obj, name): raise ValueError( 'Error: rule name "%s" is already in use' % name) # check to see vms are in the right cluster for vm_obj in vm_obj_list: if not Query.is_vm_in_cluster(cluster_obj, vm_obj): raise ValueError( 'Error: the vm "%s" is not in the stated cluster' % vm_obj.name) # check to see if the vms already have DRS rules for vm_obj in vm_obj_list: match = 0 for rule in cluster_obj.configuration.rule: if hasattr(rule, 'vm'): for rulevm in rule.vm: if vm_obj == rulevm: match = 1 if match != 0: raise ValueError( 'Error: the vm "%s" is already in a DRS rule' % vm_obj.name) new_rule = vim.ClusterAntiAffinityRuleSpec() new_rule.name = name new_rule.userCreated = True new_rule.enabled = True for vm_obj in vm_obj_list: new_rule.vm.append(vm_obj) rule_spec = vim.cluster.RuleSpec(info=new_rule, operation='add') config_spec = vim.cluster.ConfigSpecEx(rulesSpec=[rule_spec]) Tasks.task_monitor( cluster_obj.ReconfigureComputeResource_Task(config_spec, modify=True), False) self.logger.info('new AA DRS rule on %s: %s', cluster, name) if function == 'delete': #Delete an AntiAffinity Rule # check to see if this rule name is in use, and delete if found found = False for existing_rule in cluster_obj.configuration.rule: if existing_rule.name == name: found = True # doublecheck this is an AA rule if isinstance(existing_rule, vim.cluster.AntiAffinityRuleSpec): rule_spec = vim.cluster.RuleSpec( removeKey=existing_rule.key, operation='remove') config_spec = vim.cluster.ConfigSpecEx( rulesSpec=[rule_spec]) Tasks.task_monitor( cluster_obj.ReconfigureComputeResource_Task( config_spec, modify=True), False) self.logger.info('Deleted AA DRS rule on %s: %s', cluster, name) else: raise ValueError( 'Error: rule name "%s" not an AntiAffinity rule' % name) if not found: raise ValueError('Error: rule name "%s" not found' % name)