class CloudStackInventory(object): def __init__(self): parser = argparse.ArgumentParser() parser.add_argument('--host') parser.add_argument('--list', action='store_true') parser.add_argument('--project') options = parser.parse_args() try: self.cs = CloudStack(**read_config()) except CloudStackException as e: print("Error: Could not connect to CloudStack API", file=sys.stderr) project_id = '' if options.project: project_id = self.get_project_id(options.project) if options.host: data = self.get_host(options.host) print(json.dumps(data, indent=2)) elif options.list: data = self.get_list() print(json.dumps(data, indent=2)) else: print("usage: --list | --host <hostname> [--project <project>]", file=sys.stderr) sys.exit(1) def get_project_id(self, project): projects = self.cs.listProjects() if projects: for p in projects['project']: if p['name'] == project or p['id'] == project: return p['id'] print("Error: Project %s not found." % project, file=sys.stderr) sys.exit(1) def get_host(self, name, project_id=''): hosts = self.cs.listVirtualMachines(projectid=project_id) data = {} if not hosts: return data for host in hosts['virtualmachine']: host_name = host['displayname'] if name == host_name: data['zone'] = host['zonename'] if 'group' in host: data['group'] = host['group'] data['state'] = host['state'] data['service_offering'] = host['serviceofferingname'] data['affinity_group'] = host['affinitygroup'] data['security_group'] = host['securitygroup'] data['cpu_number'] = host['cpunumber'] data['cpu_speed'] = host['cpuspeed'] if 'cpuused' in host: data['cpu_used'] = host['cpuused'] data['memory'] = host['memory'] data['tags'] = host['tags'] data['hypervisor'] = host['hypervisor'] data['created'] = host['created'] data['nic'] = [] for nic in host['nic']: data['nic'].append({ 'ip': nic['ipaddress'], 'mac': nic['macaddress'], 'netmask': nic['netmask'], 'gateway': nic['gateway'], 'type': nic['type'], }) if nic['isdefault']: data['default_ip'] = nic['ipaddress'] break; return data def get_list(self, project_id=''): data = { 'all': { 'hosts': [], }, '_meta': { 'hostvars': {}, }, } groups = self.cs.listInstanceGroups(projectid=project_id) if groups: for group in groups['instancegroup']: group_name = group['name'] if group_name and not group_name in data: data[group_name] = { 'hosts': [] } hosts = self.cs.listVirtualMachines(projectid=project_id) if not hosts: return data for host in hosts['virtualmachine']: host_name = host['displayname'] data['all']['hosts'].append(host_name) data['_meta']['hostvars'][host_name] = {} data['_meta']['hostvars'][host_name]['zone'] = host['zonename'] if 'group' in host: data['_meta']['hostvars'][host_name]['group'] = host['group'] data['_meta']['hostvars'][host_name]['state'] = host['state'] data['_meta']['hostvars'][host_name]['service_offering'] = host['serviceofferingname'] data['_meta']['hostvars'][host_name]['affinity_group'] = host['affinitygroup'] data['_meta']['hostvars'][host_name]['security_group'] = host['securitygroup'] data['_meta']['hostvars'][host_name]['cpu_number'] = host['cpunumber'] data['_meta']['hostvars'][host_name]['cpu_speed'] = host['cpuspeed'] if 'cpuused' in host: data['_meta']['hostvars'][host_name]['cpu_used'] = host['cpuused'] data['_meta']['hostvars'][host_name]['created'] = host['created'] data['_meta']['hostvars'][host_name]['memory'] = host['memory'] data['_meta']['hostvars'][host_name]['tags'] = host['tags'] data['_meta']['hostvars'][host_name]['hypervisor'] = host['hypervisor'] data['_meta']['hostvars'][host_name]['created'] = host['created'] data['_meta']['hostvars'][host_name]['nic'] = [] for nic in host['nic']: data['_meta']['hostvars'][host_name]['nic'].append({ 'ip': nic['ipaddress'], 'mac': nic['macaddress'], 'netmask': nic['netmask'], 'gateway': nic['gateway'], 'type': nic['type'], }) if nic['isdefault']: data['_meta']['hostvars'][host_name]['default_ip'] = nic['ipaddress'] group_name = '' if 'group' in host: group_name = host['group'] if group_name and group_name in data: data[group_name]['hosts'].append(host_name) return data
class CloudStackInventory(object): def __init__(self): parser = argparse.ArgumentParser() parser.add_argument('--host') parser.add_argument('--list', action='store_true') parser.add_argument('--tag', help="Filter machines by a tag. Should be in the form key=value.") parser.add_argument('--project') parser.add_argument('--domain') options = parser.parse_args() try: self.cs = CloudStack(**read_config()) except CloudStackException: print("Error: Could not connect to CloudStack API", file=sys.stderr) domain_id = None if options.domain: domain_id = self.get_domain_id(options.domain) project_id = None if options.project: project_id = self.get_project_id(options.project, domain_id) if options.host: data = self.get_host(options.host, project_id, domain_id) print(json.dumps(data, indent=2)) elif options.list: tags = dict() if options.tag: tags['tags[0].key'], tags['tags[0].value'] = options.tag.split('=') data = self.get_list(project_id, domain_id, **tags) print(json.dumps(data, indent=2)) else: print("usage: --list [--tag <tag>] | --host <hostname> [--project <project>] [--domain <domain_path>]", file=sys.stderr) sys.exit(1) def get_domain_id(self, domain): domains = self.cs.listDomains(listall=True) if domains: for d in domains['domain']: if d['path'].lower() == domain.lower(): return d['id'] print("Error: Domain %s not found." % domain, file=sys.stderr) sys.exit(1) def get_project_id(self, project, domain_id=None): projects = self.cs.listProjects(domainid=domain_id) if projects: for p in projects['project']: if p['name'] == project or p['id'] == project: return p['id'] print("Error: Project %s not found." % project, file=sys.stderr) sys.exit(1) def get_host(self, name, project_id=None, domain_id=None, **kwargs): hosts = self.cs.listVirtualMachines(projectid=project_id, domainid=domain_id, fetch_list=True, **kwargs) data = {} if not hosts: return data for host in hosts: host_name = host['displayname'] if name == host_name: data['zone'] = host['zonename'] if 'group' in host: data['group'] = host['group'] data['state'] = host['state'] data['service_offering'] = host['serviceofferingname'] data['affinity_group'] = host['affinitygroup'] data['security_group'] = host['securitygroup'] data['cpu_number'] = host['cpunumber'] data['cpu_speed'] = host['cpuspeed'] if 'cpuused' in host: data['cpu_used'] = host['cpuused'] data['memory'] = host['memory'] data['tags'] = host['tags'] data['hypervisor'] = host['hypervisor'] data['created'] = host['created'] data['nic'] = [] for nic in host['nic']: data['nic'].append({ 'ip': nic['ipaddress'], 'mac': nic['macaddress'], 'netmask': nic['netmask'], 'gateway': nic['gateway'], 'type': nic['type'], }) if nic['isdefault']: data['default_ip'] = nic['ipaddress'] break return data def get_list(self, project_id=None, domain_id=None, **kwargs): data = { 'all': { 'hosts': [], }, '_meta': { 'hostvars': {}, }, } groups = self.cs.listInstanceGroups(projectid=project_id, domainid=domain_id) if groups: for group in groups['instancegroup']: group_name = group['name'] if group_name and group_name not in data: data[group_name] = { 'hosts': [] } hosts = self.cs.listVirtualMachines(projectid=project_id, domainid=domain_id, fetch_list=True, **kwargs) if not hosts: return data for host in hosts: host_name = host['displayname'] data['all']['hosts'].append(host_name) data['_meta']['hostvars'][host_name] = {} # Make a group per zone data['_meta']['hostvars'][host_name]['zone'] = host['zonename'] group_name = host['zonename'] if group_name not in data: data[group_name] = { 'hosts': [] } data[group_name]['hosts'].append(host_name) if 'group' in host: data['_meta']['hostvars'][host_name]['group'] = host['group'] data['_meta']['hostvars'][host_name]['state'] = host['state'] data['_meta']['hostvars'][host_name]['service_offering'] = host['serviceofferingname'] data['_meta']['hostvars'][host_name]['affinity_group'] = host['affinitygroup'] data['_meta']['hostvars'][host_name]['security_group'] = host['securitygroup'] data['_meta']['hostvars'][host_name]['cpu_number'] = host['cpunumber'] data['_meta']['hostvars'][host_name]['cpu_speed'] = host['cpuspeed'] if 'cpuused' in host: data['_meta']['hostvars'][host_name]['cpu_used'] = host['cpuused'] data['_meta']['hostvars'][host_name]['created'] = host['created'] data['_meta']['hostvars'][host_name]['memory'] = host['memory'] data['_meta']['hostvars'][host_name]['tags'] = host['tags'] data['_meta']['hostvars'][host_name]['hypervisor'] = host['hypervisor'] data['_meta']['hostvars'][host_name]['created'] = host['created'] data['_meta']['hostvars'][host_name]['nic'] = [] for nic in host['nic']: data['_meta']['hostvars'][host_name]['nic'].append({ 'ip': nic['ipaddress'], 'mac': nic['macaddress'], 'netmask': nic['netmask'], 'gateway': nic['gateway'], 'type': nic['type'], }) if nic['isdefault']: data['_meta']['hostvars'][host_name]['default_ip'] = nic['ipaddress'] group_name = '' if 'group' in host: group_name = host['group'] if group_name and group_name in data: data[group_name]['hosts'].append(host_name) return data
class CloudStackInventory(object): def __init__(self): parser = argparse.ArgumentParser() parser.add_argument('--host') parser.add_argument('--list', action='store_true') parser.add_argument( '--tag', help="Filter machines by a tag. Should be in the form key=value.") parser.add_argument('--project') parser.add_argument('--domain') options = parser.parse_args() try: self.cs = CloudStack(**read_config()) except CloudStackException: print("Error: Could not connect to CloudStack API", file=sys.stderr) domain_id = None if options.domain: domain_id = self.get_domain_id(options.domain) project_id = None if options.project: project_id = self.get_project_id(options.project, domain_id) if options.host: data = self.get_host(options.host, project_id, domain_id) print(json.dumps(data, indent=2)) elif options.list: tags = dict() if options.tag: tags['tags[0].key'], tags['tags[0].value'] = options.tag.split( '=') data = self.get_list(project_id, domain_id, **tags) print(json.dumps(data, indent=2)) else: print( "usage: --list [--tag <tag>] | --host <hostname> [--project <project>] [--domain <domain_path>]", file=sys.stderr) sys.exit(1) def get_domain_id(self, domain): domains = self.cs.listDomains(listall=True) if domains: for d in domains['domain']: if d['path'].lower() == domain.lower(): return d['id'] print("Error: Domain %s not found." % domain, file=sys.stderr) sys.exit(1) def get_project_id(self, project, domain_id=None): projects = self.cs.listProjects(domainid=domain_id) if projects: for p in projects['project']: if p['name'] == project or p['id'] == project: return p['id'] print("Error: Project %s not found." % project, file=sys.stderr) sys.exit(1) def get_host(self, name, project_id=None, domain_id=None, **kwargs): hosts = self.cs.listVirtualMachines(projectid=project_id, domainid=domain_id, fetch_list=True, **kwargs) data = {} if not hosts: return data for host in hosts: host_name = host['displayname'] if name == host_name: data['zone'] = host['zonename'] if 'group' in host: data['group'] = host['group'] data['state'] = host['state'] data['service_offering'] = host['serviceofferingname'] data['affinity_group'] = host['affinitygroup'] data['security_group'] = host['securitygroup'] data['cpu_number'] = host['cpunumber'] data['cpu_speed'] = host['cpuspeed'] if 'cpuused' in host: data['cpu_used'] = host['cpuused'] data['memory'] = host['memory'] data['tags'] = host['tags'] data['hypervisor'] = host['hypervisor'] data['created'] = host['created'] data['nic'] = [] for nic in host['nic']: data['nic'].append({ 'ip': nic['ipaddress'], 'mac': nic['macaddress'], 'netmask': nic['netmask'], 'gateway': nic['gateway'], 'type': nic['type'], }) if nic['isdefault']: data['default_ip'] = nic['ipaddress'] break return data def get_list(self, project_id=None, domain_id=None, **kwargs): data = { 'all': { 'hosts': [], }, '_meta': { 'hostvars': {}, }, } groups = self.cs.listInstanceGroups(projectid=project_id, domainid=domain_id) if groups: for group in groups['instancegroup']: group_name = group['name'] if group_name and group_name not in data: data[group_name] = {'hosts': []} hosts = self.cs.listVirtualMachines(projectid=project_id, domainid=domain_id, fetch_list=True, **kwargs) if not hosts: return data for host in hosts: host_name = host['displayname'] data['all']['hosts'].append(host_name) data['_meta']['hostvars'][host_name] = {} # Make a group per zone data['_meta']['hostvars'][host_name]['zone'] = host['zonename'] group_name = host['zonename'] if group_name not in data: data[group_name] = {'hosts': []} data[group_name]['hosts'].append(host_name) if 'group' in host: data['_meta']['hostvars'][host_name]['group'] = host['group'] data['_meta']['hostvars'][host_name]['state'] = host['state'] data['_meta']['hostvars'][host_name]['service_offering'] = host[ 'serviceofferingname'] data['_meta']['hostvars'][host_name]['affinity_group'] = host[ 'affinitygroup'] data['_meta']['hostvars'][host_name]['security_group'] = host[ 'securitygroup'] data['_meta']['hostvars'][host_name]['cpu_number'] = host[ 'cpunumber'] data['_meta']['hostvars'][host_name]['cpu_speed'] = host[ 'cpuspeed'] if 'cpuused' in host: data['_meta']['hostvars'][host_name]['cpu_used'] = host[ 'cpuused'] data['_meta']['hostvars'][host_name]['created'] = host['created'] data['_meta']['hostvars'][host_name]['memory'] = host['memory'] data['_meta']['hostvars'][host_name]['tags'] = host['tags'] data['_meta']['hostvars'][host_name]['hypervisor'] = host[ 'hypervisor'] data['_meta']['hostvars'][host_name]['created'] = host['created'] data['_meta']['hostvars'][host_name]['nic'] = [] for nic in host['nic']: data['_meta']['hostvars'][host_name]['nic'].append({ 'ip': nic['ipaddress'], 'mac': nic['macaddress'], 'netmask': nic['netmask'], 'gateway': nic['gateway'], 'type': nic['type'], }) if nic['isdefault']: data['_meta']['hostvars'][host_name]['default_ip'] = nic[ 'ipaddress'] group_name = '' if 'group' in host: group_name = host['group'] if group_name and group_name in data: data[group_name]['hosts'].append(host_name) return data
class CloudStackChaosMonkey(object): def __init__(self, group, chaos_action, max_not_running=0, min_wait=10, max_wait=300): self.actions = [ 'reboot', 'stop', 'stop-wait-start', 'no-action', ] self.cs = CloudStack(**read_config()) self.max_not_running = max_not_running self.group = group self.chaos_action = chaos_action self.min_wait = min_wait self.max_wait = max_wait def get_instances(self): group = self.get_instance_groups() if group: instances = self.cs.listVirtualMachines( instancegroupid=group['id']) else: instances = self.cs.listVirtualMachines() if not instances: sys.stderr.write("No VMs found") sys.exit(1) instances_not_running = 0 for instance in instances.get('virtualmachine') or []: if instance['state'].lower() != "running": instances_not_running += 1 if instances_not_running > self.max_not_running: print( "max-not-running reached: %s > %s. Avoiding too much chaos." % (instances_not_running, self.max_not_running)) sys.exit(0) return instances.get('virtualmachine') or [] def get_instance_groups(self): if not self.group: return None groups = self.cs.listInstanceGroups(name=self.group) if not groups: sys.stderr.write("No group %s found" % self.group) sys.exit(1) return groups['instancegroup'][0] def make_chaos(self): instances = self.get_instances() random_number = random.randint(0, len(instances) - 1) instance = instances[random_number] if instance['state'].lower() != "running": return action = self.find_action() print("action: %s" % action) if action == "stop": print("stop %s" % instance['displayname']) res = self.cs.stopVirtualMachine(id=instance['id']) instance = self.poll_job(res, 'virtualmachine') elif action == "reboot": print("reboot %s" % instance['displayname']) res = self.cs.rebootVirtualMachine(id=instance['id']) instance = self.poll_job(res, 'virtualmachine') elif action == "stop-wait-start": print("stop-wait-start %s" % instance['displayname']) res = self.cs.stopVirtualMachine(id=instance['id']) instance = self.poll_job(res, 'virtualmachine') random_number = random.randint(self.min_wait, self.max_wait) print("Wating %s" % random_number) time.sleep(random_number) res = self.cs.startVirtualMachine(id=instance['id']) instance = self.poll_job(res, 'virtualmachine') def find_action(self): if self.chaos_action not in self.actions: random_number = random.randint(0, len(self.actions) - 1) return self.actions[random_number] else: return self.chaos_action def poll_job(self, job=None, key=None): if 'jobid' in job: while True: res = self.cs.queryAsyncJobResult(jobid=job['jobid']) if res['jobstatus'] != 0 and 'jobresult' in res: if 'errortext' in res['jobresult']: self.module.fail_json(msg="Failed: '%s'" % res['jobresult']['errortext']) if key and key in res['jobresult']: job = res['jobresult'][key] sys.stdout.write("\n") break sys.stdout.write(".") sys.stdout.flush() time.sleep(2) return job