def _get_ironic_meters_info(self): """Returns additional info for each meter That will be used for augmenting the Ceilometer meter """ # TODO(lsmola) Unless the Ceilometer will provide the information # below, I need to define it as a static here. I will be joining this # to info that I am able to obtain from Ceilometer meters, hopefully # some day it will be supported all. return datastructures.SortedDict([ ('hardware.ipmi.current', { 'label': '', 'description': _("Current of hardwares"), }), ('hardware.ipmi.fan', { 'label': '', 'description': _("Fan speed of hardwares"), }), ('hardware.ipmi.temperature', { 'label': '', 'description': _("Temperature of sensors"), }), ('hardware.ipmi.voltage', { 'label': '', 'description': _("voltage of sensors"), }), ])
def generate_year(self, year_num): year = datastructures.SortedDict() for term_name in self.TERMS: year[term_name] = self.generate_term(year_num, term_name) return year
def __init__(self, request, data=None, needs_form_wrapper=None, **kwargs): self.request = request self.data = data self.kwargs = kwargs self._needs_form_wrapper = needs_form_wrapper self._no_data_message = self._meta.no_data_message self.breadcrumb = None self.current_item_id = None self.permissions = self._meta.permissions # Create a new set columns = [] for key, _column in self._columns.items(): column = copy.copy(_column) column.table = self columns.append((key, column)) self.columns = datastructures.SortedDict(columns) self._populate_data_cache() # Associate these actions with this table for action in self.base_actions.values(): action.table = self self.needs_summary_row = any( [col.summation for col in self.columns.values()])
def get_initial(self): profile = self._get_object() # Set project name tenant_dict = _get_tenant_list(self.request) try: bindings = api.neutron.profile_bindings_list( self.request, 'network') except Exception: msg = _('Failed to obtain network profile binding') redirect = self.success_url exceptions.handle(self.request, msg, redirect=redirect) bindings_dict = datastructures.SortedDict([(b.profile_id, b.tenant_id) for b in bindings]) project_id = bindings_dict.get(profile.id) project = tenant_dict.get(project_id) project_name = getattr(project, 'name', project_id) return { 'profile_id': profile['id'], 'name': profile['name'], 'segment_range': profile['segment_range'], 'segment_type': profile['segment_type'], 'physical_network': profile['physical_network'], 'sub_type': profile['sub_type'], 'multicast_ip_range': profile['multicast_ip_range'], 'project': project_name }
def load_cells(self, datum=None): # Compile all the cells on instantiation. table = self.table if datum: self.datum = datum else: datum = self.datum cells = [] for column in table.columns.values(): cell = table._meta.cell_class(datum, column, self) cells.append((column.name or column.auto, cell)) self.cells = datastructures.SortedDict(cells) if self.ajax: interval = conf.HORIZON_CONFIG['ajax_poll_interval'] self.attrs['data-update-interval'] = interval self.attrs['data-update-url'] = self.get_ajax_update_url() self.classes.append("ajax-update") # Add the row's status class and id to the attributes to be rendered. self.classes.append(self.status_class) id_vals = { "table": self.table.name, "sep": STRING_SEPARATOR, "id": table.get_object_id(datum) } self.id = "%(table)s%(sep)srow%(sep)s%(id)s" % id_vals self.attrs['id'] = self.id # Add the row's display name if available display_name = table.get_object_display(datum) if display_name: self.attrs['data-display'] = html.escape(display_name)
def generate_term(self, year_num, term_name): term = datastructures.SortedDict() for week_num in xrange(self.week_from, self.week_to + 1): term[week_num] = self.calculate_date(year_num, term_name, week_num) return term
def _get_ipmi_meters_info(self): """Returns additional info for each meter That will be used for augmenting the Ceilometer meter """ # TODO(lsmola) Unless the Ceilometer will provide the information # below, I need to define it as a static here. I will be joining this # to info that I am able to obtain from Ceilometer meters, hopefully # some day it will be supported all. return datastructures.SortedDict([ ('hardware.ipmi.node.power', { 'label': '', 'description': _("System Current Power"), }), ('hardware.ipmi.fan', { 'label': '', 'description': _("Fan RPM"), }), ('hardware.ipmi.temperature', { 'label': '', 'description': _("Sensor Temperature Reading"), }), ('hardware.ipmi.current', { 'label': '', 'description': _("Sensor Current Reading"), }), ('hardware.ipmi.voltage', { 'label': '', 'description': _("Sensor Voltage Reading"), }), ('hardware.ipmi.node.temperature', { 'label': '', 'description': _("System Temperature Reading"), }), ('hardware.ipmi.node.outlet_temperature', { 'label': '', 'description': _("System Outlet Temperature Reading"), }), ('hardware.ipmi.node.airflow', { 'label': '', 'description': _("System Airflow Reading"), }), ('hardware.ipmi.node.cups', { 'label': '', 'description': _("System CUPS Reading"), }), ('hardware.ipmi.node.cpu_util', { 'label': '', 'description': _("System CPU Utility Reading"), }), ('hardware.ipmi.node.mem_util', { 'label': '', 'description': _("System Memory Utility Reading"), }), ('hardware.ipmi.node.io_util', { 'label': '', 'description': _("System IO Utility Reading"), }), ])
def generate_years(self): years = datastructures.SortedDict() for year in xrange(self.year_from, self.year_to + 1): years[year] = self.generate_year(year) return years
def _get_tenant_list(request): tenants = [] try: tenants, has_more = api.keystone.tenant_list(request) except Exception: msg = _('Unable to retrieve project information.') exceptions.handle(request, msg) return datastructures.SortedDict([(t.id, t) for t in tenants])
def __init__(self, workflow): super(TableStep, self).__init__(workflow) if not self.table_classes: class_name = self.__class__.__name__ raise NotImplementedError("You must define a table_class " "attribute on %s" % class_name) # Instantiate our table classes but don't assign data yet table_instances = [(table._meta.name, table(workflow.request, needs_form_wrapper=False)) for table in self.table_classes] self._tables = datastructures.SortedDict(table_instances) self._table_data_loaded = False
def __init__(self, column, datum, form): self.form = form super(FormsetRow, self).__init__(column, datum) if self.cells == []: # We need to be able to handle empty rows, because there may # be extra empty forms in a formset. The original DataTable breaks # on this, because it sets self.cells to [], but later expects a # SortedDict. We just fill self.cells with empty Cells. cells = [] for column in self.table.columns.values(): cell = self.table._meta.cell_class(None, column, self) cells.append((column.name or column.auto, cell)) self.cells = datastructures.SortedDict(cells)
def __init__(self, semester, course_prefix=None): self.semester = semester self.course_prefix = course_prefix self.import_time = datetime.datetime.now() self.stats = datastructures.SortedDict([ ('initial', 0), # items initialy in db ('scraped', 0), # items we have scraped ('processed', 0), # items that made it through prepare_data() ('persisted', 0), # items that are in db ('created', 0), # items that have been created ('updated', 0), # items we have updated ('unaltered', 0), # items we found but did not alter ('deleted', 0), # items we plan to delete ('final', 0), # items left in db after scrape+delete ])
def _get_profiles(request, type_p): try: profiles = api.neutron.profile_list(request, type_p) except Exception: profiles = [] msg = _('Network Profiles could not be retrieved.') exceptions.handle(request, msg) if profiles: # Set project name tenant_dict = _get_tenant_list(request) bindings = api.neutron.profile_bindings_list(request, type_p) bindings_dict = datastructures.SortedDict([(b.profile_id, b.tenant_id) for b in bindings]) for p in profiles: project_id = bindings_dict.get(p.id) project = tenant_dict.get(project_id) p.project_name = getattr(project, 'name', None) return profiles
def _get_kwapi_meters_info(self): """Returns additional info for each meter That will be used for augmenting the Ceilometer meter """ # TODO(lsmola) Unless the Ceilometer will provide the information # below, I need to define it as a static here. I will be joining this # to info that I am able to obtain from Ceilometer meters, hopefully # some day it will be supported all. return datastructures.SortedDict([ ('energy', { 'label': '', 'description': _("Amount of energy"), }), ('power', { 'label': '', 'description': _("Power consumption"), }), ])
def _get_cinder_meters_info(self): """Returns additional info for each meter That will be used for augmenting the Ceilometer meter """ # TODO(lsmola) Unless the Ceilometer will provide the information # below, I need to define it as a static here. I will be joining this # to info that I am able to obtain from Ceilometer meters, hopefully # some day it will be supported all. return datastructures.SortedDict([ ('volume', { 'label': '', 'description': _("Duration of volume"), }), ('volume.size', { 'label': '', 'description': _("Size of volume"), }), ])
def _get_glance_meters_info(self): """Returns additional info for each meter That will be used for augmenting the Ceilometer meter """ # TODO(lsmola) Unless the Ceilometer will provide the information # below, I need to define it as a static here. I will be joining this # to info that I am able to obtain from Ceilometer meters, hopefully # some day it will be supported all. return datastructures.SortedDict([ ('image', { 'label': '', 'description': _("Image existence check"), }), ('image.size', { 'label': '', 'description': _("Uploaded image size"), }), ('image.update', { 'label': '', 'description': _("Number of update on the image"), }), ('image.upload', { 'label': '', 'description': _("Number of upload of the image"), }), ('image.delete', { 'label': '', 'description': _("Number of delete on the image"), }), ('image.download', { 'label': '', 'description': _("Image is downloaded"), }), ('image.serve', { 'label': '', 'description': _("Image is served out"), }), ])
def _get_swift_meters_info(self): """Returns additional info for each meter That will be used for augmenting the Ceilometer meter """ # TODO(lsmola) Unless the Ceilometer will provide the information # below, I need to define it as a static here. I will be joining this # to info that I am able to obtain from Ceilometer meters, hopefully # some day it will be supported all. return datastructures.SortedDict([ ('storage.objects', { 'label': '', 'description': _("Number of objects"), }), ('storage.objects.size', { 'label': '', 'description': _("Total size of stored objects"), }), ('storage.objects.containers', { 'label': '', 'description': _("Number of containers"), }), ('storage.objects.incoming.bytes', { 'label': '', 'description': _("Number of incoming bytes"), }), ('storage.objects.outgoing.bytes', { 'label': '', 'description': _("Number of outgoing bytes"), }), ('storage.api.request', { 'label': '', 'description': _("Number of API requests against swift"), }), ])
def __new__(mcs, name, bases, attrs): # Process options from Meta class_name = name attrs["_meta"] = opts = DataTableOptions(attrs.get("Meta", None)) # Gather columns; this prevents the column from being an attribute # on the DataTable class and avoids naming conflicts. columns = [] for attr_name, obj in attrs.items(): if issubclass(type(obj), (opts.column_class, Column)): column_instance = attrs.pop(attr_name) column_instance.name = attr_name column_instance.classes.append('normal_column') columns.append((attr_name, column_instance)) columns.sort(key=lambda x: x[1].creation_counter) # Iterate in reverse to preserve final order for base in bases[::-1]: if hasattr(base, 'base_columns'): columns = base.base_columns.items() + columns attrs['base_columns'] = datastructures.SortedDict(columns) # If the table is in a ResourceBrowser, the column number must meet # these limits because of the width of the browser. if opts.browser_table == "navigation" and len(columns) > 1: raise ValueError("You can only assign one column to %s." % class_name) if opts.browser_table == "content" and len(columns) > 2: raise ValueError("You can only assign two columns to %s." % class_name) if opts.columns: # Remove any columns that weren't declared if we're being explicit # NOTE: we're iterating a COPY of the list here! for column_data in columns[:]: if column_data[0] not in opts.columns: columns.pop(columns.index(column_data)) # Re-order based on declared columns columns.sort(key=lambda x: attrs['_meta'].columns.index(x[0])) # Add in our auto-generated columns if opts.multi_select and opts.browser_table != "navigation": multi_select = opts.column_class("multi_select", verbose_name="", auto="multi_select") multi_select.classes.append('multi_select_column') columns.insert(0, ("multi_select", multi_select)) if opts.actions_column: actions_column = opts.column_class("actions", verbose_name=_("Actions"), auto="actions") actions_column.classes.append('actions_column') columns.append(("actions", actions_column)) # Store this set of columns internally so we can copy them per-instance attrs['_columns'] = datastructures.SortedDict(columns) # Gather and register actions for later access since we only want # to instantiate them once. # (list() call gives deterministic sort order, which sets don't have.) actions = list(set(opts.row_actions) | set(opts.table_actions)) actions.sort(key=operator.attrgetter('name')) actions_dict = datastructures.SortedDict([(action.name, action()) for action in actions]) attrs['base_actions'] = actions_dict if opts._filter_action: # Replace our filter action with the instantiated version opts._filter_action = actions_dict[opts._filter_action.name] # Create our new class! return type.__new__(mcs, name, bases, attrs)
def load_cells(self, datum=None): """ Load the row's data (either provided at initialization or as an argument to this function), initiailize all the cells contained by this row, and set the appropriate row properties which require the row's data to be determined. This function is called automatically by :meth:`~horizon.tables.Row.__init__` if the ``datum`` argument is provided. However, by not providing the data during initialization this function allows for the possibility of a two-step loading pattern when you need a row instance but don't yet have the data available. """ # Compile all the cells on instantiation. table = self.table if datum: self.datum = datum else: datum = self.datum cells = [] for column in table.columns.values(): if column.auto == "multi_select": # FIXME: TableStep code modified # multi_select fields in the table must be checked after # a server action # TODO(remove this ugly code and create proper TableFormWidget) multi_select_values = [] if (getattr(table, 'request', False) and getattr(table.request, 'POST', False)): multi_select_values = table.request.POST.getlist( self.table._meta.multi_select_name) multi_select_values += getattr(table, 'active_multi_select_values', []) if unicode(table.get_object_id(datum)) in multi_select_values: multi_select_value = lambda value: True else: multi_select_value = lambda value: False widget = forms.CheckboxInput(check_test=multi_select_value) # Convert value to string to avoid accidental type conversion data = widget.render(self.table._meta.multi_select_name, unicode(table.get_object_id(datum))) # FIXME: end of added TableStep code table._data_cache[column][table.get_object_id(datum)] = data elif column.auto == "form_widget": # FIXME: Added for TableStep: widget = column.form_widget widget_name = "%s__%s__%s" % \ (self.table._meta.multi_select_name, column.name, unicode(table.get_object_id(datum))) data = widget.render(widget_name, column.get_data(datum), column.form_widget_attributes) table._data_cache[column][table.get_object_id(datum)] = data elif column.auto == "actions": data = table.render_row_actions(datum) table._data_cache[column][table.get_object_id(datum)] = data else: data = column.get_data(datum) cell = horizon_tables.Cell(datum, data, column, self) cells.append((column.name or column.auto, cell)) self.cells = datastructures.SortedDict(cells) if self.ajax: interval = conf.HORIZON_CONFIG['ajax_poll_interval'] self.attrs['data-update-interval'] = interval self.attrs['data-update-url'] = self.get_ajax_update_url() self.classes.append("ajax-update") # Add the row's status class and id to the attributes to be rendered. self.classes.append(self.status_class) id_vals = { "table": self.table.name, "sep": STRING_SEPARATOR, "id": table.get_object_id(datum) } self.id = "%(table)s%(sep)srow%(sep)s%(id)s" % id_vals self.attrs['id'] = self.id # Add the row's display name if available display_name = table.get_object_display(datum) if display_name: self.attrs['data-display'] = html.escape(display_name)
def _get_nova_meters_info(self): """Returns additional info for each meter That will be used for augmenting the Ceilometer meter. """ # TODO(lsmola) Unless the Ceilometer will provide the information # below, I need to define it as a static here. I will be joining this # to info that I am able to obtain from Ceilometer meters, hopefully # some day it will be supported all. meters_info = datastructures.SortedDict([ ("instance", { 'label': '', 'description': _("Duration of instance"), }), ("instance:<type>", { 'label': '', 'description': _("Duration of instance <type> " "(openstack types)"), }), ("memory", { 'label': '', 'description': _("Volume of RAM in MB"), }), ("cpu", { 'label': '', 'description': _("CPU time used"), }), ("cpu_util", { 'label': '', 'description': _("Average CPU utilization"), }), ("vcpus", { 'label': '', 'description': _("Number of VCPUs"), }), ("disk.read.requests", { 'label': '', 'description': _("Number of read requests"), }), ("disk.write.requests", { 'label': '', 'description': _("Number of write requests"), }), ("disk.read.bytes", { 'label': '', 'description': _("Volume of reads in B"), }), ("disk.write.bytes", { 'label': '', 'description': _("Volume of writes in B"), }), ("disk.root.size", { 'label': '', 'description': _("Size of root disk in GB"), }), ("disk.ephemeral.size", { 'label': '', 'description': _("Size of ephemeral disk " "in GB"), }), ("network.incoming.bytes", { 'label': '', 'description': _("Number of incoming bytes " "on the network for a VM interface"), }), ("network.outgoing.bytes", { 'label': '', 'description': _("Number of outgoing bytes " "on the network for a VM interface"), }), ("network.incoming.packets", { 'label': '', 'description': _("Number of incoming " "packets for a VM interface"), }), ("network.outgoing.packets", { 'label': '', 'description': _("Number of outgoing " "packets for a VM interface"), }) ]) # Adding flavor based meters into meters_info dict # TODO(lsmola) this kind of meter will be probably deprecated # https://bugs.launchpad.net/ceilometer/+bug/1208365 . Delete it then. for flavor in get_flavor_names(self._request): name = 'instance:%s' % flavor meters_info[name] = dict(meters_info["instance:<type>"]) meters_info[name]['description'] = ( _('Duration of instance type %s (openstack flavor)') % flavor) # TODO(lsmola) allow to set specific in local_settings. For all meters # because users can have their own agents and meters. return meters_info
def _get_neutron_meters_info(self): """Returns additional info for each meter That will be used for augmenting the Ceilometer meter """ # TODO(lsmola) Unless the Ceilometer will provide the information # below, I need to define it as a static here. I will be joining this # to info that I am able to obtain from Ceilometer meters, hopefully # some day it will be supported all. return datastructures.SortedDict([ ('network', { 'label': '', 'description': _("Duration of network"), }), ('network.create', { 'label': '', 'description': _("Creation requests for this network"), }), ('network.update', { 'label': '', 'description': _("Update requests for this network"), }), ('subnet', { 'label': '', 'description': _("Duration of subnet"), }), ('subnet.create', { 'label': '', 'description': _("Creation requests for this subnet"), }), ('subnet.update', { 'label': '', 'description': _("Update requests for this subnet"), }), ('port', { 'label': '', 'description': _("Duration of port"), }), ('port.create', { 'label': '', 'description': _("Creation requests for this port"), }), ('port.update', { 'label': '', 'description': _("Update requests for this port"), }), ('router', { 'label': '', 'description': _("Duration of router"), }), ('router.create', { 'label': '', 'description': _("Creation requests for this router"), }), ('router.update', { 'label': '', 'description': _("Update requests for this router"), }), ('ip.floating', { 'label': '', 'description': _("Duration of floating ip"), }), ('ip.floating.create', { 'label': '', 'description': _("Creation requests for this floating ip"), }), ('ip.floating.update', { 'label': '', 'description': _("Update requests for this floating ip"), }), ])
def Layout(self, request, response): """Manage content pane depending on passed in query parameter.""" self.reason = request.REQ.get("reason", "") if "/" in self.reason and not self.reason.startswith("http"): self.reason = "http://%s" % self.reason self.host_advanced_headings = [] self.host_headings = [] self.general_headings = datastructures.SortedDict([ ("General", ("Management", [], [])), ("Configuration", ("Configuration", [], [])) ]) # Introspect all the categories for cls in self.classes.values(): try: if not aff4.issubclass(cls, renderers.Renderer): continue cls.CheckAccess(request) except access_control.UnauthorizedAccess: continue for behaviour in self.general_headings: if behaviour in cls.behaviours: self.general_headings[behaviour][1].append( (cls, cls.__name__)) if behaviour + "Advanced" in cls.behaviours: self.general_headings[behaviour][2].append( (cls, cls.__name__)) if "Host" in cls.behaviours: self.host_headings.append((cls, cls.__name__)) if "HostAdvanced" in cls.behaviours: self.host_advanced_headings.append((cls, cls.__name__)) # Sort the output so they are in order. for heading in self.general_headings: # pylint: disable=g-long-lambda lkey = lambda x: (getattr(x[0], "order", 10), getattr(x[0], "description", "")) self.general_headings[heading][1].sort(key=lkey) self.host_headings.sort(key=lambda x: getattr(x[0], "order", 10)) self.hosts = [] self.unauthorized = False self.client_id = request.REQ.get("client_id") if self.client_id: client = aff4.FACTORY.Open(self.client_id, token=request.token) self.hosts.append( (self.client_id, client.Get(client.Schema.HOSTNAME))) try: # Also check for proper access. aff4.FACTORY.Open(client.urn.Add("acl_check"), token=request.token) except access_control.UnauthorizedAccess as e: self.unauthorized = True self.unauthorized_exception = e super(Navigator, self).Layout(request, response) if self.unauthorized: renderers.Renderer.GetPlugin("UnauthorizedRenderer")().Layout( request, response, exception=e) return self.CallJavascript(response, "Navigator.Layout", renderer=self.__class__.__name__, client_id=self.client_id, poll_time=self.poll_time)
### This is a non-standard method of checking the availability of different modules in django. ### TODO: Find/create a more centralized, simple, standard method of doing this. from exceptions import ImportError from django.conf import settings from django.utils import datastructures ### # Check if comments are available if hasattr(settings, 'INSTALLED_APPS' ) and 'django.contrib.comments' in settings.INSTALLED_APPS: comments = True else: comments = False markup_filters = datastructures.SortedDict() ### # Check if markup is available if hasattr(settings, 'INSTALLED_APPS' ) and 'django.contrib.markup' in settings.INSTALLED_APPS: markup = True else: markup = False # Check for supported markup methods try: import textile markup_filters['textile'] = True except ImportError: markup_filters['textile'] = False