def _net_delete(self): self.add_header('---------[Neutron net delete]---------') count = len(self.multiSelect) if not count: try: self.multiSelect.append(self.netIdVar.get()) count = 1 except Exception as e: self.print_line(strutils.safe_encode(six.text_type(e))) if not len(self.multiSelect[0]): self.print_line("No Network selected") return if not askyesno('Confirm', 'Delete ' + str(count) + ' networks?'): self.print_line('Delete cancelled.') return for net in self.multiSelect: if not len(net): continue self.print_line('Deleting network [%s]' % net) try: delete_network(net) self.print_line('instance id [%s] delete scheduled' % net) except Exception as e: self.print_line(strutils.safe_encode(six.text_type(e))) self.netIdVar.set('') del self.multiSelect[:] self.print_line('-------- Deletion(s) complete --------')
def _nova_delete(self): self.add_header('---------[Nova delete]---------') count = len(self.multiSelect) if not count: try: count = 1 self.multiSelect.append(self.novaLV.get()) except Exception as e: self.print_line(strutils.safe_encode(six.text_type(e))) if not len(self.multiSelect[0]): self.print_line("No Instance selected") return self.print_line('[%s] instance(s) in list' % count) if not askyesno('Confirm', 'Delete ' + str(count) + ' instance(s)?'): self.print_line('Delete cancelled.') return for i in self.multiSelect: self.print_line('Deleting instance id [%s]' % i) try: nova_delete(i) self.print_line('instance id [%s] delete scheduled' % i) except Exception as e: self.print_line(strutils.safe_encode(six.text_type(e))) self.novaLV.set('') del self.multiSelect[:] self.print_line('-------- Deletion(s) complete --------') return
def _run_hot(self): rh = RainbowHeat() f = askopenfilename(defaultextension='.yaml', title='Select Heat Template') if not f: self.print_line('Stack Create canncelled.') return name = '' sn = StackName(self.top) name = sn.get_name() if name: self._clear() # offset del self.multiSelect[:] self.toplist = [] self.activeVar = self.novaLV self.activeVar.set('') try: with Capture() as output: rh.stack_create(f, name) for l in output: try: id = l.split('|')[1] except: id = "NULL" self.toplist.append(id) self.print_line(l) # for v in self.toplist: # print v except Exception as e: print(strutils.safe_encode(six.text_type(e))) self.print_line(strutils.safe_encode(six.text_type(e))) else: self.print_line('Stack Create canncelled.')
def _net_create(self): mess = [ 'Note: Create will fail in sites where more than', 'the defaults are required to create a network.', 'Manually confirm failure.' ] self._clear() self.add_header('---------[Neutron net create]---------') newnets = [] try: name = 'RainbowNet-' + str(int(ut())) nn = NetName(self.top, title='Net Name', netname=name) self.nname = nn.get_name() if len(self.nname) == 0: self.print_line('---------[Net Create Cancelled]---------') return self.print_line('Creating network..') nid = create_named_net(self.nname) self.netIdVar.set(nid) newnets.append(self.nname) except Exception as e: self.print_line(strutils.safe_encode(six.text_type(e))) self.netIdVar.set('') return 0 # num = int(num)-1 nl = neutron_net_list() for i in nl['networks']: if i['name'] in newnets: self.print_line('|%s|%s|%s' % (i['id'], i['status'].ljust(8), i['name'])) if len(self.netIdVar.get()): return 1 else: self._print_mess(mess) return 0
def main(): try: HeatShell().main(sys.argv[1:]) except Exception as e: print(strutils.safe_encode(six.text_type(e)), file=sys.stderr) sys.exit(1)
def list(self, stack_id, resource_name=None, **kwargs): """Get a list of events. :param stack_id: ID of stack the events belong to :param resource_name: Optional name of resources to filter events by :rtype: list of :class:`Event` """ params = {} if 'filters' in kwargs: filters = kwargs.pop('filters') params.update(filters) for key, value in six.iteritems(kwargs): if value: params[key] = value if resource_name is None: url = '/stacks/%s/events' % stack_id else: stack_id = self._resolve_stack_id(stack_id) url = '/stacks/%s/resources/%s/events' % (parse.quote( stack_id, ''), parse.quote(strutils.safe_encode(resource_name), '')) if params: url += '?%s' % parse.urlencode(params, True) return self._list(url, 'events')
def print_list(objs, fields, formatters=None, sortby_index=0, mixed_case_fields=None): """Print a list or objects as a table, one row per object. :param objs: iterable of :class:`Resource` :param fields: attributes that correspond to columns, in order :param formatters: `dict` of callables for field formatting :param sortby_index: index of the field for sorting table rows :param mixed_case_fields: fields corresponding to object attributes that have mixed case names (e.g., 'serverId') """ formatters = formatters or {} mixed_case_fields = mixed_case_fields or [] if sortby_index is None: kwargs = {} else: kwargs = {"sortby": fields[sortby_index]} pt = prettytable.PrettyTable(fields, caching=False) pt.align = "l" for o in objs: row = [] for field in fields: if field in formatters: row.append(formatters[field](o)) else: if field in mixed_case_fields: field_name = field.replace(" ", "_") else: field_name = field.lower().replace(" ", "_") data = getattr(o, field_name, "") row.append(data) pt.add_row(row) print(strutils.safe_encode(pt.get_string(**kwargs)))
def list(self, stack_id, resource_name=None, **kwargs): """Get a list of events. :param stack_id: ID of stack the events belong to :param resource_name: Optional name of resources to filter events by :rtype: list of :class:`Event` """ params = {} if 'filters' in kwargs: filters = kwargs.pop('filters') params.update(filters) for key, value in six.iteritems(kwargs): if value: params[key] = value if resource_name is None: url = '/stacks/%s/events' % stack_id else: stack_id = self._resolve_stack_id(stack_id) url = '/stacks/%s/resources/%s/events' % ( parse.quote(stack_id, ''), parse.quote(strutils.safe_encode(resource_name), '')) if params: url += '?%s' % parse.urlencode(params, True) return self._list(url, 'events')
def print_dict(dct, dict_property="Property", wrap=0): """Print a `dict` as a table of two columns. :param dct: `dict` to print :param dict_property: name of the first column :param wrap: wrapping for the second column """ pt = prettytable.PrettyTable([dict_property, 'Value'], caching=False) pt.align = 'l' for k, v in six.iteritems(dct): # convert dict to str to check length if isinstance(v, dict): v = six.text_type(v) if wrap > 0: v = textwrap.fill(six.text_type(v), wrap) # if value has a newline, add in multiple rows # e.g. fault with stacktrace if v and isinstance(v, six.string_types) and r'\n' in v: lines = v.strip().split(r'\n') col1 = k for line in lines: pt.add_row([col1, line]) col1 = '' else: pt.add_row([k, v]) print(strutils.safe_encode(pt.get_string()))
def print_dict(dct, dict_property="Property", wrap=0): """Print a `dict` as a table of two columns. :param dct: `dict` to print :param dict_property: name of the first column :param wrap: wrapping for the second column """ pt = prettytable.PrettyTable([dict_property, "Value"], caching=False) pt.align = "l" for k, v in six.iteritems(dct): # convert dict to str to check length if isinstance(v, dict): v = six.text_type(v) if wrap > 0: v = textwrap.fill(six.text_type(v), wrap) # if value has a newline, add in multiple rows # e.g. fault with stacktrace if v and isinstance(v, six.string_types) and r"\n" in v: lines = v.strip().split(r"\n") col1 = k for line in lines: pt.add_row([col1, line]) col1 = "" else: pt.add_row([k, v]) print(strutils.safe_encode(pt.get_string()))
def test_resource_show(self): self._script_keystone_client() resp_dict = {"resource": {"description": "", "links": [{"href": "http://heat.example.com:8004/foo", "rel": "self"}, {"href": "http://heat.example.com:8004/foo2", "rel": "resource"}], "logical_resource_id": "aResource", "physical_resource_id": "43b68bae-ed5d-4aed-a99f-0b3d39c2418a", "required_by": [], "resource_name": "aResource", "resource_status": "CREATE_COMPLETE", "resource_status_reason": "state changed", "resource_type": "OS::Nova::Server", "updated_time": "2014-01-06T16:14:26Z"}} resp = fakes.FakeHTTPResponse( 200, 'OK', {'content-type': 'application/json'}, jsonutils.dumps(resp_dict)) stack_id = 'teststack/1' resource_name = 'aResource' http.HTTPClient.json_request( 'GET', '/stacks/%s/resources/%s' % ( urlutils.quote(stack_id, ''), urlutils.quote(strutils.safe_encode( resource_name), '') )).AndReturn((resp, resp_dict)) self.m.ReplayAll() resource_show_text = self.shell('resource-show {0} {1}'.format( stack_id, resource_name)) required = [ 'description', 'links', 'http://heat.example.com:8004/foo[0-9]', 'logical_resource_id', 'aResource', 'physical_resource_id', '43b68bae-ed5d-4aed-a99f-0b3d39c2418a', 'required_by', 'resource_name', 'aResource', 'resource_status', 'CREATE_COMPLETE', 'resource_status_reason', 'state changed', 'resource_type', 'OS::Nova::Server', 'updated_time', '2014-01-06T16:14:26Z', ] for r in required: self.assertRegexpMatches(resource_show_text, r)
def generate_template(self, resource_name): """DEPRECATED! Use `generate_template` of `ResourceTypeManager` instead. """ url_str = '/resource_types/%s/template' % ( parse.quote(strutils.safe_encode(resource_name), '')) resp, body = self.client.json_request('GET', url_str) return body
def get(self, resource_type): """Get the details for a specific resource_type. :param resource_type: name of the resource type to get the details for """ url_str = '/resource_types/%s' % (parse.quote( strutils.safe_encode(resource_type), '')) resp, body = self.client.json_request('GET', url_str) return body
def find_resource(manager, name_or_id, **find_args): """Look for resource in a given manager. Used as a helper for the _find_* methods. Example: def _find_hypervisor(cs, hypervisor): #Get a hypervisor by name or ID. return cliutils.find_resource(cs.hypervisors, hypervisor) """ # first try to get entity as integer id try: return manager.get(int(name_or_id)) except (TypeError, ValueError, exceptions.NotFound): pass # now try to get entity as uuid try: tmp_id = strutils.safe_encode(name_or_id) if uuidutils.is_uuid_like(tmp_id): return manager.get(tmp_id) except (TypeError, ValueError, exceptions.NotFound): pass # for str id which is not uuid if getattr(manager, "is_alphanum_id_allowed", False): try: return manager.get(name_or_id) except exceptions.NotFound: pass try: try: return manager.find(human_id=name_or_id, **find_args) except exceptions.NotFound: pass # finally try to find entity by name try: resource = getattr(manager, "resource_class", None) name_attr = resource.NAME_ATTR if resource else "name" kwargs = {name_attr: name_or_id} kwargs.update(find_args) return manager.find(**kwargs) except exceptions.NotFound: msg = _("No %(name)s with a name or " "ID of '%(name_or_id)s' exists.") % { "name": manager.resource_class.__name__.lower(), "name_or_id": name_or_id, } raise exceptions.CommandError(msg) except exceptions.NoUniqueMatch: msg = _("Multiple %(name)s matches found for " "'%(name_or_id)s', use an ID to be more specific.") % { "name": manager.resource_class.__name__.lower(), "name_or_id": name_or_id, } raise exceptions.CommandError(msg)
def get(self, resource_type): """Get the details for a specific resource_type. :param resource_type: name of the resource type to get the details for """ url_str = '/resource_types/%s' % ( parse.quote(strutils.safe_encode(resource_type), '')) resp, body = self.client.json_request('GET', url_str) return body
def main(args=None): try: if args is None: args = sys.argv[1:] HeatShell().main(args) except Exception as e: if '--debug' in args or '-d' in args: raise else: print(strutils.safe_encode(six.text_type(e)), file=sys.stderr) sys.exit(1)
def signal(self, stack_id, resource_name, data=None): """Signal a specific resource. :param stack_id: ID of stack containing the resource :param resource_name: ID of resource to send signal to """ stack_id = self._resolve_stack_id(stack_id) url_str = '/stacks/%s/resources/%s/signal' % (parse.quote( stack_id, ''), parse.quote(strutils.safe_encode(resource_name), '')) resp, body = self.client.json_request('POST', url_str, data=data) return body
def metadata(self, stack_id, resource_name): """Get the metadata for a specific resource. :param stack_id: ID of stack containing the resource :param resource_name: ID of resource to get metadata for """ stack_id = self._resolve_stack_id(stack_id) url_str = '/stacks/%s/resources/%s/metadata' % (parse.quote( stack_id, ''), parse.quote(strutils.safe_encode(resource_name), '')) resp, body = self.client.json_request('GET', url_str) return body['metadata']
def metadata(self, stack_id, resource_name): """Get the metadata for a specific resource. :param stack_id: ID of stack containing the resource :param resource_name: ID of resource to get metadata for """ stack_id = self._resolve_stack_id(stack_id) url_str = '/stacks/%s/resources/%s/metadata' % ( parse.quote(stack_id, ''), parse.quote(strutils.safe_encode(resource_name), '')) resp, body = self.client.json_request('GET', url_str) return body['metadata']
def signal(self, stack_id, resource_name, data=None): """Signal a specific resource. :param stack_id: ID of stack containing the resource :param resource_name: ID of resource to send signal to """ stack_id = self._resolve_stack_id(stack_id) url_str = '/stacks/%s/resources/%s/signal' % ( parse.quote(stack_id, ''), parse.quote(strutils.safe_encode(resource_name), '')) resp, body = self.client.json_request('POST', url_str, data=data) return body
def get(self, stack_id, resource_name, event_id): """Get the details for a specific event. :param stack_id: ID of stack containing the event :param resource_name: ID of resource the event belongs to :param event_id: ID of event to get the details for """ stack_id = self._resolve_stack_id(stack_id) url_str = '/stacks/%s/resources/%s/events/%s' % (parse.quote( stack_id, ''), parse.quote(strutils.safe_encode(resource_name), ''), parse.quote(event_id, '')) resp, body = self.client.json_request('GET', url_str) return Event(self, body['event'])
def metadata(self, stack_id, resource_name): """Get the metadata for a specific resource. :param stack_id: ID of stack containing the resource :param resource_name: ID of resource to get metadata for """ stack_id = self._resolve_stack_id(stack_id) # Use urlutils for python2/python3 compatibility url_str = '/stacks/%s/resources/%s/metadata' % ( urlutils.quote(stack_id, ''), urlutils.quote(strutils.safe_encode(resource_name), '')) resp, body = self.api.json_request('GET', url_str) return body['metadata']
def get(self, stack_id, resource_name, event_id): """Get the details for a specific event. :param stack_id: ID of stack containing the event :param resource_name: ID of resource the event belongs to :param event_id: ID of event to get the details for """ stack_id = self._resolve_stack_id(stack_id) url_str = '/stacks/%s/resources/%s/events/%s' % ( parse.quote(stack_id, ''), parse.quote(strutils.safe_encode(resource_name), ''), parse.quote(event_id, '')) resp, body = self.client.json_request('GET', url_str) return Event(self, body['event'])
def list(self, stack_id, resource_name=None): """Get a list of events. :param stack_id: ID of stack the events belong to :param resource_name: Optional name of resources to filter events by :rtype: list of :class:`Event` """ if resource_name is None: url = '/stacks/%s/events' % stack_id else: stack_id = self._resolve_stack_id(stack_id) url = '/stacks/%s/resources/%s/events' % ( parse.quote(stack_id, ''), parse.quote(strutils.safe_encode(resource_name), '')) return self._list(url, "events")
def main(args=None): try: if args is None: args = sys.argv[1:] HeatShell().main(args) except KeyboardInterrupt: print("... terminating heat client", file=sys.stderr) sys.exit(130) except Exception as e: if '--debug' in args or '-d' in args: raise else: print(strutils.safe_encode(six.text_type(e)), file=sys.stderr) sys.exit(1)
def _auth_check(self): self.print_line("Initializing auth check...") if (not os.environ.get('OS_TENANT_ID')) and ( not os.environ.get('OS_TENANT_NAME')): self._key_error('OS_TENANT_ID or OS_TENANT_NAME') return for key in ['OS_USERNAME', 'OS_PASSWORD', 'OS_AUTH_URL']: if key not in os.environ.keys(): self._key_error(key) break if not len(os.environ[key]): self._get_creds() break try: self.ksclient = get_keystone_client() self.print_line("Auth check: PASS") except Exception as e: self.print_line('Auth check: FAIL [%s]' % strutils.safe_encode(six.text_type(e)))
def print_list(objs, fields, formatters=None, sortby_index=0, mixed_case_fields=None): """Print a list or objects as a table, one row per object. :param objs: iterable of :class:`Resource` :param fields: attributes that correspond to columns, in order :param formatters: `dict` of callables for field formatting :param sortby_index: index of the field for sorting table rows :param mixed_case_fields: fields corresponding to object attributes that have mixed case names (e.g., 'serverId') """ formatters = formatters or {} mixed_case_fields = mixed_case_fields or [] if sortby_index is None: kwargs = {} else: kwargs = {'sortby': fields[sortby_index]} pt = prettytable.PrettyTable(fields, caching=False) pt.align = 'l' for o in objs: row = [] for field in fields: if field in formatters: row.append(formatters[field](o)) else: if field in mixed_case_fields: field_name = field.replace(' ', '_') else: field_name = field.lower().replace(' ', '_') data = getattr(o, field_name, '') row.append(data) pt.add_row(row) print(strutils.safe_encode(pt.get_string(**kwargs)))
def generate_template(self, resource_name): url_str = '/resource_types/%s/template' % (parse.quote( strutils.safe_encode(resource_name), '')) resp, body = self.client.json_request('GET', url_str) return body
def find_resource(manager, name_or_id, **find_args): """Look for resource in a given manager. Used as a helper for the _find_* methods. Example: def _find_hypervisor(cs, hypervisor): #Get a hypervisor by name or ID. return cliutils.find_resource(cs.hypervisors, hypervisor) """ # first try to get entity as integer id try: return manager.get(int(name_or_id)) except (TypeError, ValueError, exceptions.NotFound): pass # now try to get entity as uuid try: tmp_id = strutils.safe_encode(name_or_id) if uuidutils.is_uuid_like(tmp_id): return manager.get(tmp_id) except (TypeError, ValueError, exceptions.NotFound): pass # for str id which is not uuid if getattr(manager, 'is_alphanum_id_allowed', False): try: return manager.get(name_or_id) except exceptions.NotFound: pass try: try: return manager.find(human_id=name_or_id, **find_args) except exceptions.NotFound: pass # finally try to find entity by name try: resource = getattr(manager, 'resource_class', None) name_attr = resource.NAME_ATTR if resource else 'name' kwargs = {name_attr: name_or_id} kwargs.update(find_args) return manager.find(**kwargs) except exceptions.NotFound: msg = _("No %(name)s with a name or " "ID of '%(name_or_id)s' exists.") % \ { "name": manager.resource_class.__name__.lower(), "name_or_id": name_or_id } raise exceptions.CommandError(msg) except exceptions.NoUniqueMatch: msg = _("Multiple %(name)s matches found for " "'%(name_or_id)s', use an ID to be more specific.") % \ { "name": manager.resource_class.__name__.lower(), "name_or_id": name_or_id } raise exceptions.CommandError(msg)
def test_event_list(self): self._script_keystone_client() resp_dict = {"events": [ {"event_time": "2013-12-05T14:14:30Z", "id": self.event_id_one, "links": [{"href": "http://heat.example.com:8004/foo", "rel": "self"}, {"href": "http://heat.example.com:8004/foo2", "rel": "resource"}, {"href": "http://heat.example.com:8004/foo3", "rel": "stack"}], "logical_resource_id": "aResource", "physical_resource_id": None, "resource_name": "aResource", "resource_status": "CREATE_IN_PROGRESS", "resource_status_reason": "state changed"}, {"event_time": "2013-12-05T14:14:30Z", "id": self.event_id_two, "links": [{"href": "http://heat.example.com:8004/foo", "rel": "self"}, {"href": "http://heat.example.com:8004/foo2", "rel": "resource"}, {"href": "http://heat.example.com:8004/foo3", "rel": "stack"}], "logical_resource_id": "aResource", "physical_resource_id": "bce15ec4-8919-4a02-8a90-680960fb3731", "resource_name": "aResource", "resource_status": "CREATE_COMPLETE", "resource_status_reason": "state changed"}]} resp = fakes.FakeHTTPResponse( 200, 'OK', {'content-type': 'application/json'}, jsonutils.dumps(resp_dict)) stack_id = 'teststack/1' resource_name = 'testresource/1' http.HTTPClient.json_request( 'GET', '/stacks/%s/resources/%s/events' % ( urlutils.quote(stack_id, ''), urlutils.quote(strutils.safe_encode( resource_name), ''))).AndReturn((resp, resp_dict)) self.m.ReplayAll() event_list_text = self.shell('event-list {0} --resource {1}'.format( stack_id, resource_name)) required = [ 'resource_name', 'id', 'resource_status_reason', 'resource_status', 'event_time', 'aResource', self.event_id_one, self.event_id_two, 'state changed', 'CREATE_IN_PROGRESS', 'CREATE_COMPLETE', '2013-12-05T14:14:30Z', '2013-12-05T14:14:30Z', ] for r in required: self.assertRegexpMatches(event_list_text, r)
def test_event_show(self): self._script_keystone_client() resp_dict = {"event": {"event_time": "2013-12-05T14:14:30Z", "id": self.event_id_one, "links": [{"href": "http://heat.example.com:8004/foo", "rel": "self"}, {"href": "http://heat.example.com:8004/foo2", "rel": "resource"}, {"href": "http://heat.example.com:8004/foo3", "rel": "stack"}], "logical_resource_id": "aResource", "physical_resource_id": None, "resource_name": "aResource", "resource_properties": {"admin_user": "******", "availability_zone": "nova"}, "resource_status": "CREATE_IN_PROGRESS", "resource_status_reason": "state changed", "resource_type": "OS::Nova::Server" }} resp = fakes.FakeHTTPResponse( 200, 'OK', {'content-type': 'application/json'}, jsonutils.dumps(resp_dict)) stack_id = 'teststack/1' resource_name = 'testresource/1' http.HTTPClient.json_request( 'GET', '/stacks/%s/resources/%s/events/%s' % ( urlutils.quote(stack_id, ''), urlutils.quote(strutils.safe_encode( resource_name), ''), urlutils.quote(self.event_id_one, '') )).AndReturn((resp, resp_dict)) self.m.ReplayAll() event_list_text = self.shell('event-show {0} {1} {2}'.format( stack_id, resource_name, self.event_id_one)) required = [ 'Property', 'Value', 'event_time', '2013-12-05T14:14:30Z', 'id', self.event_id_one, 'links', 'http://heat.example.com:8004/foo[0-9]', 'logical_resource_id', 'physical_resource_id', 'resource_name', 'aResource', 'resource_properties', 'admin_user', 'availability_zone', 'resource_status', 'CREATE_IN_PROGRESS', 'resource_status_reason', 'state changed', 'resource_type', 'OS::Nova::Server', ] for r in required: self.assertRegexpMatches(event_list_text, r)
def generate_template(self, resource_type): url_str = '/resource_types/%s/template' % ( parse.quote(strutils.safe_encode(resource_type), '')) resp, body = self.client.json_request('GET', url_str) return body
def generate_template(self, resource_name): # Use urlutils for python2/python3 compatibility url_str = '/resource_types/%s/template' % ( urlutils.quote(strutils.safe_encode(resource_name), '')) resp, body = self.api.json_request('GET', url_str) return body