diff --git a/.travis.yml b/.travis.yml index 5409d6dd3..922d0bda4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,7 @@ language: python python: - '2.7' +- '3.7' env: matrix: - DJANGO_VERSION="Django<1.9" @@ -110,14 +111,14 @@ install: - sudo tar -xzvf pnp4nagios-0.6.24.tar.gz - cd pnp4nagios-0.6.24 - sudo ./configure - --prefix=${NAGIOS_HOME} - --with-nagios-user=${NAGIOS_USER} - --with-nagios-group=${NAGIOS_GROUP} + --prefix=${NAGIOS_HOME} + --with-nagios-user=${NAGIOS_USER} + --with-nagios-group=${NAGIOS_GROUP} --sysconfdir=${NAGIOS_HOME}/etc/pnp --exec-prefix=${NAGIOS_HOME} - --datarootdir=${NAGIOS_HOME}/share/pnp + --datarootdir=${NAGIOS_HOME}/share/pnp --with-rrdtool=/usr/bin/rrdtool - --sysconfdir=${NAGIOS_HOME}/etc/pnp + --sysconfdir=${NAGIOS_HOME}/etc/pnp --with-perfdata-dir=${NAGIOS_HOME}/share/perfdata --with-perfdata-logfile=${NAGIOS_HOME}/var/perfdata.log --with-perfdata-spool-dir=${NAGIOS_HOME}/var/spool/perfdata @@ -171,6 +172,7 @@ install: - export APACHE_LOG_DIR=/var/log/apache2 - sudo usermod -G www-data nagios +- pip install future - pip install $DJANGO_VERSION - pip install mock - pip install simplejson @@ -226,7 +228,7 @@ install: - cp -r /usr/share/okconfig/templates/* ${NAGIOS_HOME}/etc/okconfig/templates/ - cp -r /usr/share/okconfig/examples/* ${NAGIOS_HOME}/etc/okconfig/examples/ - pynag config --append cfg_dir=${NAGIOS_HOME}/etc/okconfig -- ls -l ${NAGIOS_HOME}/etc/okconfig +- ls -l ${NAGIOS_HOME}/etc/okconfig # Configure Adagios - pynag config --append "broker_module=/usr/local/nagios/lib/mk-livestatus/livestatus.o /usr/local/nagios/var/rw/live" diff --git a/adagios/__init__.py b/adagios/__init__.py index 657f77d51..8cf36a45d 100644 --- a/adagios/__init__.py +++ b/adagios/__init__.py @@ -63,7 +63,7 @@ def add_plugin(name="myplugin", modulepath=None): # will successfully start up if any of the plugins have errors try: from adagios import settings - for k,v in settings.plugins.items(): + for k,v in list(settings.plugins.items()): try: add_plugin(k,v) except Exception: diff --git a/adagios/auth.py b/adagios/auth.py index 0e13d4407..7eb50c318 100644 --- a/adagios/auth.py +++ b/adagios/auth.py @@ -19,6 +19,8 @@ """ +from builtins import str +from builtins import object import adagios.status.utils import adagios.views @@ -186,5 +188,5 @@ def process_view(self, request, view_func, view_args, view_kwargs): try: path = module_name + '.' + function_name check_access_to_path(request, path) - except adagios.exceptions.AccessDenied, e: + except adagios.exceptions.AccessDenied as e: return adagios.views.http_403(request, exception=e) diff --git a/adagios/bi/__init__.py b/adagios/bi/__init__.py index 93268f9c4..28feffd8f 100644 --- a/adagios/bi/__init__.py +++ b/adagios/bi/__init__.py @@ -1,3 +1,4 @@ +from __future__ import division # Adagios is a web based Nagios configuration interface # # Copyright (C) 2014, Pall Sigurdsson @@ -15,6 +16,9 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . +from builtins import str +from builtins import object +from past.utils import old_div from pynag.Utils import PynagError, defaultdict __author__ = 'palli' @@ -122,7 +126,7 @@ def get_status(self): self.errors.append( _("We have not implemented how to use status method %s") % str(self.status_method)) return 3 - except Exception, e: + except Exception as e: self.errors.append(e) return 3 @@ -137,14 +141,14 @@ def get_state_summary(self): def get_all_states(self): """ Returns a list of all subprocess states """ - return map(lambda x: x.get_status(), self.get_processes()) + return [x.get_status() for x in self.get_processes()] def get_worst_state(self): """ Returns the worst state of any sub items """ try: return int(max(self.get_all_states())) - except Exception, e: + except Exception as e: self.errors.append(e) return 3 @@ -153,7 +157,7 @@ def get_best_state(self): """ try: return int(min(self.get_all_states())) - except Exception, e: + except Exception as e: self.errors.append(e) return 3 @@ -191,7 +195,7 @@ def run_business_rules(self): states = tags[tag] # Filter out states ok - states = filter(lambda x: x > 0, states) + states = [x for x in states if x > 0] if not states: # Nothing more to do continue if len(states) >= num_problems: @@ -255,7 +259,7 @@ def resolve_macrostring(self, string): all_macros = self.resolve_all_macros() try: return string.format(**all_macros) - except KeyError, e: + except KeyError as e: raise PynagError(_("Invalid macro in string. %s") % str(e)) def resolve_macro(self, macroname, default='raise exception'): @@ -288,23 +292,23 @@ def resolve_macro(self, macroname, default='raise exception'): elif macroname == 'percent_state_0': if len(self.get_all_states()) == 0: return 0 - return 100.0 * state_summary[0] / sum(state_summary) + return old_div(100.0 * state_summary[0], sum(state_summary)) elif macroname == 'percent_state_1': if len(self.get_all_states()) == 0: return 0 - return 100.0 * state_summary[1] / sum(state_summary) + return old_div(100.0 * state_summary[1], sum(state_summary)) elif macroname == 'percent_state_2': if len(self.get_all_states()) == 0: return 0 - return 100.0 * state_summary[2] / sum(state_summary) + return old_div(100.0 * state_summary[2], sum(state_summary)) elif macroname == 'percent_state_3': if len(self.get_all_states()) == 0: return 0 - return 100.0 * state_summary[3] / sum(state_summary) + return old_div(100.0 * state_summary[3], sum(state_summary)) elif macroname == 'percent_problems': if len(self.get_all_states()) == 0: return 0 - return 100.0 * sum(state_summary[1:]) / sum(state_summary) + return old_div(100.0 * sum(state_summary[1:]), sum(state_summary)) elif macroname == 'current_state': return self.get_status() elif macroname == 'friendly_state': @@ -372,8 +376,7 @@ def remove_pnp_graph(self, host_name, service_description, metric_name): data['metric_name'] = metric_name if not self.graphs: return - self.graphs = filter( - lambda x: frozenset(x) != frozenset(data), self.graphs) + self.graphs = [x for x in self.graphs if frozenset(x) != frozenset(data)] def get_pnp_last_value(self, host_name, service_description, metric_name): """ Looks up current nagios perfdata via mk-livestatus and returns the last value for a specific metric (str) @@ -572,7 +575,7 @@ def get_status(self): if service_status == 3: return 2 return service_status - except Exception, e: + except Exception as e: self.errors.append(e) return 3 @@ -583,11 +586,8 @@ def get_processes(self): else: services = self._livestatus.get_services( 'Filter: host_groups >= %s' % self.name) - livestatus_objects = map( - lambda x: [x.get('host_name') + '/' + x.get( - 'description'), x.get('state')], - services - ) + livestatus_objects = [[x.get('host_name') + '/' + x.get( + 'description'), x.get('state')] for x in services] for i in livestatus_objects: process = BusinessProcess(i[0]) process.get_status = lambda: i[1] @@ -667,7 +667,7 @@ def get_status(self): try: self.load() return self._service.get('state', 3) - except Exception, e: + except Exception as e: self.errors.append(e) return 3 @@ -687,7 +687,7 @@ def load(self): def get_status(self): try: self.load() - except Exception, e: + except Exception as e: self.errors.append(e) return 3 method = self.status_method @@ -753,7 +753,7 @@ def create_host(self): self.host_not_found = True self.errors.append(_("Host not found: ") % self.name) all_hosts = pynag.Model.Host.objects.all - all_hosts = map(lambda x: x.host_name, all_hosts) + all_hosts = [x.host_name for x in all_hosts] if self.name not in all_hosts: host = pynag.Model.Host(use="generic-domain", host_name=self.name, address=self.name) host.action_url = "http://%s" % self.name @@ -819,7 +819,7 @@ def get_all_json(filename=None): raw_data = None try: raw_data = open(filename, 'r').read() - except IOError, e: + except IOError as e: if e.errno == 2: # File does not exist return [] if not raw_data: @@ -834,7 +834,7 @@ def get_all_processes(filename=None): result = [] try: json_data = get_all_json(filename=filename) - except IOError, e: + except IOError as e: if e.errno == 2: json_data = [] else: @@ -848,7 +848,7 @@ def get_all_processes(filename=None): def get_all_process_names(filename=None): """ Return a list of all process names out there """ - return map(lambda x: x.name, get_all_processes(filename=filename)) + return [x.name for x in get_all_processes(filename=filename)] def get_business_process(process_name, process_type=None, **kwargs): @@ -862,13 +862,13 @@ def get_business_process(process_name, process_type=None, **kwargs): my_business_process = BPClass(process_name) try: my_business_process.load() - except Exception, e: + except Exception as e: my_business_process.errors.append(e) my_business_process.data.update(kwargs) return my_business_process -class PNP4NagiosGraph: +class PNP4NagiosGraph(object): """ Represents one single PNP 4 nagios graph """ @@ -885,5 +885,5 @@ def get_image_urls(self): 'json', host=self.host_name, srv=self.service_description) graphs = json.loads(json_str) # only use graphs with same label - graphs = filter(lambda x: x['ds_name'] == self.label, graphs) + graphs = [x for x in graphs if x['ds_name'] == self.label] return graphs diff --git a/adagios/bi/forms.py b/adagios/bi/forms.py index 4239aae8f..88445ec79 100644 --- a/adagios/bi/forms.py +++ b/adagios/bi/forms.py @@ -41,8 +41,7 @@ def save(self): self.bp.remove_process(process_name, process_type) self.bp.save() -status_method_choices = map( - lambda x: (x, x), adagios.bi.BusinessProcess.status_calculation_methods) +status_method_choices = [(x, x) for x in adagios.bi.BusinessProcess.status_calculation_methods] class BusinessProcessForm(forms.Form): @@ -121,7 +120,7 @@ def add_process(self): self.bp.save() choices = 'businessprocess', 'hostgroup', 'servicegroup', 'service', 'host' -process_type_choices = map(lambda x: (x, x), choices) +process_type_choices = [(x, x) for x in choices] class AddSubProcess(forms.Form): diff --git a/adagios/bi/tests.py b/adagios/bi/tests.py index 944a62a19..f00928414 100644 --- a/adagios/bi/tests.py +++ b/adagios/bi/tests.py @@ -157,7 +157,7 @@ def loadPage(self, url): c = Client() response = c.get(url) self.assertEqual(response.status_code, 200, _("Expected status code 200 for page %s") % url) - except Exception, e: + except Exception as e: self.assertEqual(True, "Unhandled exception while loading %s: %s" % (url, e)) def test_delete(self): diff --git a/adagios/context_processors.py b/adagios/context_processors.py index 176417cc7..7e08ee50c 100644 --- a/adagios/context_processors.py +++ b/adagios/context_processors.py @@ -15,6 +15,7 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . +from builtins import str import pynag.Model import os import getpass @@ -41,49 +42,49 @@ def on_page_load(request): results = {} update_global_variables() - for k, v in reload_configfile(request).items(): + for k, v in list(reload_configfile(request).items()): results[k] = v - for k, v in get_httpuser(request).items(): + for k, v in list(get_httpuser(request).items()): results[k] = v - for k, v in get_tagged_comments(request).items(): + for k, v in list(get_tagged_comments(request).items()): results[k] = v - for k, v in check_nagios_running(request).items(): + for k, v in list(check_nagios_running(request).items()): results[k] = v - for k, v in get_notifications(request).items(): + for k, v in list(get_notifications(request).items()): results[k] = v - for k, v in get_unhandled_problems(request).items(): + for k, v in list(get_unhandled_problems(request).items()): results[k] = v - for k, v in resolve_urlname(request).items(): + for k, v in list(resolve_urlname(request).items()): results[k] = v - for k, v in check_selinux(request).items(): + for k, v in list(check_selinux(request).items()): results[k] = v - for k, v in activate_plugins(request).items(): + for k, v in list(activate_plugins(request).items()): results[k] = v - for k, v in check_destination_directory(request).items(): + for k, v in list(check_destination_directory(request).items()): results[k] = v - for k, v in check_nagios_cfg(request).items(): + for k, v in list(check_nagios_cfg(request).items()): results[k] = v - for k, v in get_current_time(request).items(): + for k, v in list(get_current_time(request).items()): results[k] = v - for k, v in get_okconfig(request).items(): + for k, v in list(get_okconfig(request).items()): results[k] = v - for k, v in get_nagios_url(request).items(): + for k, v in list(get_nagios_url(request).items()): results[k] = v - for k, v in get_local_user(request).items(): + for k, v in list(get_local_user(request).items()): results[k] = v - for k, v in get_current_settings(request).items(): + for k, v in list(get_current_settings(request).items()): results[k] = v - for k, v in get_plugins(request).items(): + for k, v in list(get_plugins(request).items()): results[k] = v - for k, v in get_current_version(request).items(): + for k, v in list(get_current_version(request).items()): results[k] = v - for k, v in get_serverside_includes(request).items(): + for k, v in list(get_serverside_includes(request).items()): results[k] = v - for k, v in get_user_preferences(request).items(): + for k, v in list(get_user_preferences(request).items()): results[k] = v - for k, v in get_all_backends(request).items(): + for k, v in list(get_all_backends(request).items()): results[k] = v - for k, v in get_all_nonworking_backends(request).items(): + for k, v in list(get_all_nonworking_backends(request).items()): results[k] = v return results @@ -138,7 +139,7 @@ def get_serverside_includes(request): def activate_plugins(request): """ Activates any plugins specified in settings.plugins """ - for k, v in settings.plugins.items(): + for k, v in list(settings.plugins.items()): add_plugin(name=k, modulepath=v) return {'misc_menubar_items': adagios.misc_menubar_items, 'menubar_items': adagios.menubar_items} @@ -344,7 +345,7 @@ def reload_configfile(request): try: clear_notification("configfile") settings.reload_configfile() - except Exception, e: + except Exception as e: add_notification( level="warning", message=str(e), notification_id="configfile") return {} diff --git a/adagios/forms.py b/adagios/forms.py index e0e5f4da1..86804084e 100644 --- a/adagios/forms.py +++ b/adagios/forms.py @@ -26,10 +26,10 @@ class AdagiosForm(forms.Form): def clean(self): cleaned_data = {} tmp = super(AdagiosForm, self).clean() - for k,v in tmp.items(): - if isinstance(k, (unicode)): + for k,v in list(tmp.items()): + if isinstance(k, (str)): k = smart_str(k) - if isinstance(v, (unicode)): + if isinstance(v, (str)): v = smart_str(v) cleaned_data[k] = v return cleaned_data diff --git a/adagios/misc/forms.py b/adagios/misc/forms.py index 31ec9439e..0e8e6f9d8 100644 --- a/adagios/misc/forms.py +++ b/adagios/misc/forms.py @@ -17,6 +17,7 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . +from builtins import str from django import forms from django.core.mail import send_mail @@ -184,7 +185,7 @@ def save(self): if not os.path.isfile(settings.adagios_configfile): open(settings.adagios_configfile, 'w').write( _("# Autocreated by adagios")) - for k, v in self.cleaned_data.items(): + for k, v in list(self.cleaned_data.items()): Model.config._edit_static_file( attribute=k, new_value=v, filename=settings.adagios_configfile) self.adagios_configfile = settings.adagios_configfile @@ -229,7 +230,7 @@ def check_file_exists(self, filename): def clean(self): cleaned_data = super(self.__class__, self).clean() - for k, v in cleaned_data.items(): + for k, v in list(cleaned_data.items()): # Convert all unicode to quoted strings if type(v) == type(u''): cleaned_data[k] = str('''"%s"''' % v) @@ -433,7 +434,7 @@ def __init__(self, initial=None, *args, **kwargs): elif k == "event_broker_options": my_initial[k] = v # If view specified any initial values, they overwrite ours - for k, v in initial.items(): + for k, v in list(initial.items()): my_initial[k] = v if 'broker_module' not in my_initial: my_initial['broker_module'] = self.get_suggested_npcdmod_path() @@ -689,7 +690,7 @@ def parse(self): c.pre_object_list = items c._post_parse() all_objects = [] - for object_type, objects in c.data.items(): + for object_type, objects in list(c.data.items()): model = pynag.Model.string_to_class.get( object_type, pynag.Model.ObjectDefinition) for i in objects: diff --git a/adagios/misc/helpers.py b/adagios/misc/helpers.py index 915c40788..0fbf4c6a3 100644 --- a/adagios/misc/helpers.py +++ b/adagios/misc/helpers.py @@ -24,6 +24,7 @@ """ +from builtins import str import platform import re from pynag import Model @@ -66,7 +67,7 @@ def get_objects(object_type=None, with_fields="id,shortname,object_type", **kwar object_type=object_type, **kwargs) with_fields = with_fields.split(',') # return map(lambda x: _get_dict(x), tmp) - return map(lambda x: object_to_dict(x, attributes=with_fields), tmp) + return [object_to_dict(x, attributes=with_fields) for x in tmp] def servicestatus(with_fields="host_name,service_description,current_state,plugin_output"): @@ -77,7 +78,7 @@ def servicestatus(with_fields="host_name,service_description,current_state,plugi result_list = [] for serv in s.data['servicestatus']: current_object = {} - for k, v in serv.items(): + for k, v in list(serv.items()): if fields == ['*'] or k in fields: current_object[k] = v result_list.append(current_object) @@ -167,7 +168,7 @@ def change_service_attribute(identifier, new_value): try: service = Model.Service.objects.get_by_shortname( "%s/%s" % (host_name, service_description)) - except KeyError, e: + except KeyError as e: raise KeyError(_("Could not find service %s") % e) service[attribute_name] = new_value service.save() @@ -260,7 +261,7 @@ def dnslookup(host_name): try: (name, aliaslist, addresslist) = gethostbyname_ex(host_name) return {'host': name, 'aliaslist': aliaslist, 'addresslist': addresslist} - except Exception, e: + except Exception as e: return {'error': str(e)} @@ -276,7 +277,7 @@ def contactgroup_hierarchy(**kwargs): arr = [display, i.contactgroup_members or '', str(i)] result.append(arr) return result - except Exception, e: + except Exception as e: return {'error': str(e)} @@ -297,7 +298,7 @@ def add_object(object_type, filename=None, **kwargs): my_object = Model.string_to_class.get(object_type)() if filename is not None: my_object.set_filename(filename) - for k, v in kwargs.items(): + for k, v in list(kwargs.items()): my_object[k] = v my_object.save() return {"filename": my_object.get_filename(), "raw_definition": str(my_object)} @@ -390,7 +391,7 @@ def get_object_statistics(): """ object_types = [] Model.ObjectDefinition.objects.reload_cache() - for k, v in Model.ObjectFetcher._cached_object_type.items(): + for k, v in list(Model.ObjectFetcher._cached_object_type.items()): total = len(v) object_types.append({"object_type": k, "total": total}) return object_types @@ -407,8 +408,8 @@ def autocomplete(q): services = Model.Service.objects.filter(service_description__contains=q) hostgroups = Model.Hostgroup.objects.filter(hostgroup_name__contains=q) - result['hosts'] = sorted(set(map(lambda x: x.host_name, hosts))) - result['hostgroups'] = sorted(set(map(lambda x: x.hostgroup_name, hostgroups))) - result['services'] = sorted(set(map(lambda x: x.service_description, services))) + result['hosts'] = sorted(set([x.host_name for x in hosts])) + result['hostgroups'] = sorted(set([x.hostgroup_name for x in hostgroups])) + result['services'] = sorted(set([x.service_description for x in services])) return result diff --git a/adagios/misc/rest.py b/adagios/misc/rest.py index 08babbc2e..9b98aa109 100644 --- a/adagios/misc/rest.py +++ b/adagios/misc/rest.py @@ -23,6 +23,7 @@ """ +from builtins import str from adagios import __version__, notifications, tasks from adagios.settings import plugins from adagios import userdata @@ -68,7 +69,7 @@ def clear_notification(notification_id): def get_notifications(request): """ Shows all current notifications """ result = [] - for k in notifications.keys(): + for k in list(notifications.keys()): i = notifications[k] if i.get('user') and i.get('user') != request.META.get('remote_user'): continue # Skipt this message if it is meant for someone else @@ -125,7 +126,7 @@ def set_user_preference(request, **kwargs): except Exception as e: raise e - for (k, v) in kwargs.iteritems(): + for (k, v) in kwargs.items(): if not k.startswith('_'): user.set_pref(k, v) user.save() diff --git a/adagios/misc/tests.py b/adagios/misc/tests.py index e6bdbe6b3..133282134 100644 --- a/adagios/misc/tests.py +++ b/adagios/misc/tests.py @@ -90,7 +90,7 @@ def loadPage(self, url): c = Client() response = c.get(url) self.assertEqual(response.status_code, 200, _("Expected status code 200 for page %s") % url) - except Exception, e: + except Exception as e: self.assertEqual(True, _("Unhandled exception while loading %(url)s: %(e)s") % {'url': url, 'e': e}) def test_user_preferences(self): diff --git a/adagios/misc/views.py b/adagios/misc/views.py index 8be46c253..c12aa6333 100644 --- a/adagios/misc/views.py +++ b/adagios/misc/views.py @@ -76,7 +76,7 @@ def settings(request): try: form.save() m.append(_("%s successfully saved.") % form.adagios_configfile) - except IOError, exc: + except IOError as exc: e.append(exc) else: raise Exception(_("We only support methods GET or POST")) @@ -134,12 +134,12 @@ def gitlog(request): raise Exception(_("No files selected.")) git.commit(message=commit_message, filelist=filelist) m.append(_("%s files successfully commited.") % len(filelist)) - except Exception, e: + except Exception as e: c['errors'].append(e) # Check if nagiosdir has a git repo or not try: c['uncommited_files'] = git.get_uncommited_files() - except pynag.Model.EventHandlers.EventHandlerError, e: + except pynag.Model.EventHandlers.EventHandlerError as e: if e.errorcode == 128: c['no_git_repo_found'] = True @@ -171,7 +171,7 @@ def gitlog(request): difflines.append({'tag': tag, 'line': i}) c['difflines'] = difflines c['commit_id'] = commit - except Exception, e: + except Exception as e: c['errors'].append(e) return render_to_response('gitlog.html', c, context_instance=RequestContext(request)) @@ -225,7 +225,7 @@ def pnp4nagios(request): try: c['npcd_config'] = forms.PNPConfigForm(initial=request.GET) - except Exception, e: + except Exception as e: c['errors'].append(e) #c['interesting_objects'] = form.interesting_objects if request.method == 'POST' and 'save_broker_module' in request.POST: @@ -271,7 +271,7 @@ def edit_file(request, filename): filename=filename, data=request.POST) if c['form'].is_valid(): c['form'].save() - except Exception, e: + except Exception as e: c['errors'].append(e) return render_to_response('editfile.html', c, context_instance=RequestContext(request)) @@ -311,10 +311,10 @@ def icons(request, image_name=None): for filename in files: filenames.append(os.path.join(root, filename)) # Cut image_path out of every filename - filenames = map(lambda x: x[len(image_path):], filenames) + filenames = [x[len(image_path):] for x in filenames] # Filter out those silly .gd2 files that don't display inside a browser - filenames = filter(lambda x: not x.lower().endswith('.gd2'), filenames) + filenames = [x for x in filenames if not x.lower().endswith('.gd2')] filenames.sort() if not image_name: @@ -380,9 +380,9 @@ def mail(request): for x in service: c['form'].status_objects.append(x) c['form'].services.append(x) - except AttributeError, e: + except AttributeError as e: c['errors'].append(_("AttributeError for '%(i)s': %(e)s") % {'i': i, 'e': e}) - except KeyError, e: + except KeyError as e: c['errors'].append(_("Error adding service '%(i)s': %(e)s") % {'i': i, 'e': e}) c['services'] = c['form'].services @@ -444,7 +444,7 @@ def preferences(request): if request.method == 'POST': c['form'] = forms.UserdataForm(data=request.POST) if c['form'].is_valid(): - for k, v in c['form'].cleaned_data.iteritems(): + for k, v in c['form'].cleaned_data.items(): user.set_pref(k, v) user.save() # will save in json and trigger the hooks c['messages'].append(_('Preferences have been saved.')) diff --git a/adagios/objectbrowser/__init__.py b/adagios/objectbrowser/__init__.py index 6dec3af2a..0cc695423 100644 --- a/adagios/objectbrowser/__init__.py +++ b/adagios/objectbrowser/__init__.py @@ -48,5 +48,5 @@ def startup(): try: import pynag.Model startup() -except Exception, e: +except Exception as e: pass diff --git a/adagios/objectbrowser/forms.py b/adagios/objectbrowser/forms.py index 19bc6d49f..a50222b7a 100644 --- a/adagios/objectbrowser/forms.py +++ b/adagios/objectbrowser/forms.py @@ -17,6 +17,9 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . +#from __future__ import unicode_literals +from builtins import str +from past.builtins import basestring from django import forms from django.utils.safestring import mark_safe from django.utils.encoding import smart_str @@ -53,7 +56,7 @@ ) # All objects definition types in our config, in a form that is good for pynag forms -ALL_OBJECT_TYPES = sorted(map(lambda x: (x, x), Model.string_to_class.keys())) +ALL_OBJECT_TYPES = sorted([(x, x) for x in list(Model.string_to_class.keys())]) # When boolean fields are set in configuration, generally 1=True and 0=False BOOLEAN_CHOICES = (('', 'not set'), ('1', '1'), ('0', '0')) @@ -100,20 +103,20 @@ def __init__(self, object_type, inline_help_text=None, complete="shortname", *ar def get_all_shortnames(self, object_type): """ Returns a list of all shortnames, given a specific object type.""" objects = self.get_all_objects(object_type) - shortnames = map(lambda x: x.get_shortname(), objects) + shortnames = [x.get_shortname() for x in objects] # Remove objects with no shortname - shortnames = filter(lambda x: x, shortnames) + shortnames = [x for x in shortnames if x] return shortnames def get_all_object_names(self, object_type): """ Returns a list of all object names (name attribute) for a given object type. """ objects = self.get_all_objects(object_type) - names = map(lambda x: x.name, objects) + names = [x.name for x in objects] # Remove objects with no name - names = filter(lambda x: x, names) + names = [x for x in names if x] return names def get_all_objects(self, object_type): @@ -166,7 +169,7 @@ def prepare_value(self, value): """ if value is None: return [] - if isinstance(value, str): + if isinstance(value, basestring): self.attributelist = AttributeList(value) self.__prefix = self.attributelist.operator return self.attributelist.fields @@ -208,7 +211,7 @@ class PynagForm(AdagiosForm): def clean(self): cleaned_data = super(PynagForm, self).clean() - for k, v in cleaned_data.items(): + for k, v in list(cleaned_data.items()): # change from unicode to str v = cleaned_data[k] = smart_str(v) @@ -228,11 +231,11 @@ def changed_data(self): # This can happen for example because some views decide not to print all # Fields to the browser changed_data = super(PynagForm, self).changed_data - changed_data = filter(lambda x: x in self.data, changed_data) + changed_data = [x for x in changed_data if x in self.data] return changed_data def save(self): - changed_keys = map(lambda x: smart_str(x), self.changed_data) + changed_keys = [smart_str(x) for x in self.changed_data] for k in changed_keys: # Ignore fields that did not appear in the POST at all EXCEPT @@ -288,7 +291,7 @@ def __init__(self, pynag_object, *args, **kwargs): # Special hack for macros # If this is a post and any post data looks like a nagios macro # We will generate a field for it on the fly - macros = filter(lambda x: x.startswith('$') and x.endswith('$'), self.data.keys()) + macros = [x for x in list(self.data.keys()) if x.startswith('$') and x.endswith('$')] for field_name in macros: # if field_name.startswith('$ARG'): # self.fields[field_name] = self.get_pynagField(field_name, css_tag='defined') @@ -318,7 +321,7 @@ def __init__(self, pynag_object, *args, **kwargs): self.initial = pynag_object._defined_attributes self.initial.update(pynag_object._changes) - for name, field in self.fields.items(): + for name, field in list(self.fields.items()): if name in self.initial: field.initial = self.initial[name] elif name in self.pynag_object: @@ -360,14 +363,12 @@ def get_pynagField(self, field_name, css_tag="", required=None): elif field_name.endswith('_period'): all_objects = Model.Timeperiod.objects.filter( timeperiod_name__contains='') - choices = [('', '')] + map( - lambda x: (x.timeperiod_name, x.timeperiod_name), all_objects) + choices = [('', '')] + [(x.timeperiod_name, x.timeperiod_name) for x in all_objects] field = forms.ChoiceField(choices=sorted(choices)) elif field_name.endswith('notification_commands'): all_objects = Model.Command.objects.filter( command_name__contains='') - choices = [('', '')] + map( - lambda x: (x.command_name, x.command_name), all_objects) + choices = [('', '')] + [(x.command_name, x.command_name) for x in all_objects] field = PynagChoiceField(choices=sorted(choices)) # elif field_name == 'check_command': # all_objects = Model.Command.objects.all @@ -474,7 +475,7 @@ def save(self): def clean(self): cleaned_data = super(AdvancedEditForm, self).clean() - for k, v in cleaned_data.items(): + for k, v in list(cleaned_data.items()): # change from unicode to str cleaned_data[k] = smart_str(v) return cleaned_data @@ -487,7 +488,7 @@ def __init__(self, pynag_object, *args, **kwargs): # Lets find out what attributes to create object_type = pynag_object['object_type'] all_attributes = sorted(object_definitions.get(object_type).keys()) - for field_name in self.pynag_object.keys() + all_attributes: + for field_name in list(self.pynag_object.keys()) + all_attributes: if field_name == 'meta': continue help_text = "" @@ -650,7 +651,7 @@ def __init__(self, objects=None, *args, **kwargs): if not objects: objects = [] forms.Form.__init__(self, *args, **kwargs) - for k, v in self.data.items(): + for k, v in list(self.data.items()): if k.startswith('hidden_'): obj = Model.ObjectDefinition.objects.get_by_id(v) if obj not in self.all_objects: @@ -665,7 +666,7 @@ def __init__(self, objects=None, *args, **kwargs): def clean(self): #self.cleaned_data = {} - for k, v in self.data.items(): + for k, v in list(self.data.items()): if k.startswith('hidden_'): self.cleaned_data[k] = v obj = Model.ObjectDefinition.objects.get_by_id(v) @@ -677,7 +678,7 @@ def clean(self): obj = Model.ObjectDefinition.objects.get_by_id(object_id) if obj not in self.changed_objects: self.changed_objects.append(obj) - for k, v in self.cleaned_data.items(): + for k, v in list(self.cleaned_data.items()): self.cleaned_data[k] = smart_str(self.cleaned_data[k]) return self.cleaned_data @@ -799,7 +800,7 @@ def __init__(self, object_type, initial=None, *args, **kwargs): # For some reason calling super()__init__() with initial as a parameter # will not work on PynagChoiceFields. This forces initial value to be set: initial = initial or {} - for field_name, field in self.fields.items(): + for field_name, field in list(self.fields.items()): initial_value = initial.get(field_name, None) if initial_value: field.initial = str(initial_value) @@ -835,7 +836,7 @@ def changed_data(self): See https://github.com/opinkerfi/adagios/issues/527 """ - return self.fields.keys() + return list(self.fields.keys()) def clean(self): cleaned_data = super(AddObjectForm, self).clean() diff --git a/adagios/objectbrowser/tests.py b/adagios/objectbrowser/tests.py index dddf4bca8..37b5e298f 100644 --- a/adagios/objectbrowser/tests.py +++ b/adagios/objectbrowser/tests.py @@ -94,7 +94,7 @@ def loadPage(self, url, expected_code=200): c = Client() response = c.get(url) self.assertEqual(response.status_code, expected_code, _("Expected status code 200 for page %(url)s") % {'url': url}) - except Exception, e: + except Exception as e: self.assertEqual(True, _("Unhandled exception while loading %(url)s: %(error)s") % {'url': url, 'error': e}) @@ -225,7 +225,7 @@ def _change_object_via_form(self, my_object=None, **kwargs): my_object = self._create_new_host() data = {} - for key, value in kwargs.iteritems(): + for key, value in kwargs.items(): data[key] = value # Create new form for saving the data form = adagios.objectbrowser.forms.PynagForm(my_object, data=data) @@ -249,7 +249,7 @@ def test_changed_data(self): data['service_description'] = "new_description" form = adagios.objectbrowser.forms.PynagForm(my_object, data=data) self.assertTrue(form.is_valid()) - self.assertEqual(data.keys(), form.changed_data) + self.assertEqual(list(data.keys()), form.changed_data) data['hostgroup_name'] = 'bla' form = adagios.objectbrowser.forms.PynagForm(my_object, data=data) @@ -328,7 +328,7 @@ def test_issue_389_via_view(self): # Iterate through every field in our original service, make sure # They are all same as expected - for key, old_value in my_object._defined_attributes.items(): + for key, old_value in list(my_object._defined_attributes.items()): new_value = new_service[key] # TODO: Find out what is broken in check_command if key in ('check_command'): @@ -376,7 +376,7 @@ def test_init_are_fields_initilized(self): self.assertEqual(dataset, form.initial) self.assertEqual({}, form.data) - for field_name, field in form.fields.items(): + for field_name, field in list(form.fields.items()): expected_data = dataset.get(field_name, None) message = "Testing initial value for field %s" % field_name self.assertEqual(expected_data, field.initial, message) diff --git a/adagios/objectbrowser/views.py b/adagios/objectbrowser/views.py index b7363edd3..f70dcd7bd 100644 --- a/adagios/objectbrowser/views.py +++ b/adagios/objectbrowser/views.py @@ -17,6 +17,7 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . +from builtins import str from django.shortcuts import render_to_response, redirect, HttpResponse, Http404 from django.http import HttpResponseRedirect from django.template import RequestContext @@ -61,12 +62,12 @@ def geek_edit(request, object_id): # Get our object try: o = ObjectDefinition.objects.get_by_id(id=object_id) - except Exception, e: + except Exception as e: # This is an ugly hack. If unknown object ID was specified and it so happens to # Be the same as a brand new empty object definition we will assume that we are # to create a new object definition instead of throwing error because ours was # not found. - for i in Model.string_to_class.values(): + for i in list(Model.string_to_class.values()): if i().get_id() == object_id: o = i() break @@ -82,7 +83,7 @@ def geek_edit(request, object_id): try: form.save() m.append("Object Saved manually to '%s'" % o['filename']) - except Exception, e: + except Exception as e: c['errors'].append(e) return render_to_response('edit_object.html', c, context_instance=RequestContext(request)) else: @@ -108,12 +109,12 @@ def advanced_edit(request, object_id): try: o = ObjectDefinition.objects.get_by_id(id=object_id) c['my_object'] = o - except Exception, e: + except Exception as e: # This is an ugly hack. If unknown object ID was specified and it so happens to # Be the same as a brand new empty object definition we will assume that we are # to create a new object definition instead of throwing error because ours was # not found. - for i in Model.string_to_class.values(): + for i in list(Model.string_to_class.values()): if i().get_id() == object_id: o = i() break @@ -130,7 +131,7 @@ def advanced_edit(request, object_id): try: c['advanced_form'].save() m.append(_("Object Saved to %(filename)s") % o) - except Exception, e: + except Exception as e: c['errors'].append(e) return render_to_response('edit_object.html', c, context_instance=RequestContext(request)) else: @@ -183,7 +184,7 @@ def edit_object(request, object_id=None): c['form'].save() c['messages'].append(_("Object Saved to %(filename)s") % my_object) return HttpResponseRedirect(reverse('edit_object', kwargs={'object_id': my_object.get_id()})) - except Exception, e: + except Exception as e: c['errors'].append(e) else: c['errors'].append(_("Could not validate form input")) @@ -197,14 +198,14 @@ def edit_object(request, object_id=None): try: c['effective_hosts'] = my_object.get_effective_hosts() - except KeyError, e: + except KeyError as e: c['errors'].append(_("Could not find host: %(error)s") % {'error': str(e)}) except AttributeError: pass try: c['effective_parents'] = my_object.get_effective_parents(cache_only=True) - except KeyError, e: + except KeyError as e: c['errors'].append(_("Could not find parent: %(error)s") % {'error': str(e)}) # Every object type has some special treatment, so lets resort @@ -241,7 +242,7 @@ def _edit_contact(request, c): try: c['effective_contactgroups'] = c[ 'my_object'].get_effective_contactgroups() - except KeyError, e: + except KeyError as e: c['errors'].append(_("Could not find contact: %(error)s") % {'error': str(e)}) return render_to_response('edit_contact.html', c, context_instance=RequestContext(request)) @@ -283,27 +284,27 @@ def _edit_service(request, c): try: c['effective_servicegroups'] = service.get_effective_servicegroups() - except KeyError, e: + except KeyError as e: c['errors'].append(_("Could not find servicegroup: %(error)s") % {'error': str(e)}) try: c['effective_contacts'] = service.get_effective_contacts() - except KeyError, e: + except KeyError as e: c['errors'].append(_("Could not find contact: %(error)s") % {'error': str(e)}) try: c['effective_contactgroups'] = service.get_effective_contact_groups() - except KeyError, e: + except KeyError as e: c['errors'].append(_("Could not find contact_group: %(error)s") % {'error': str(e)}) try: c['effective_hostgroups'] = service.get_effective_hostgroups() - except KeyError, e: + except KeyError as e: c['errors'].append(_("Could not find hostgroup: %(error)s") % {'error': str(e)}) try: c['effective_command'] = service.get_effective_check_command() - except KeyError, e: + except KeyError as e: if service.check_command is not None: c['errors'].append(_("Could not find check_command: %(error)s") % {'error': str(e)}) elif service.register != '0': @@ -312,8 +313,7 @@ def _edit_service(request, c): # For the check_command editor, we inject current check_command and a list # of all check_commands c['check_command'] = (service.check_command or '').split("!")[0] - c['command_names'] = map( - lambda x: x.get("command_name", ''), Model.Command.objects.all) + c['command_names'] = [x.get("command_name", '') for x in Model.Command.objects.all] if c['check_command'] in (None, '', 'None'): c['check_command'] = '' @@ -331,18 +331,18 @@ def _edit_contactgroup(request, c): try: c['effective_contactgroups'] = c[ 'my_object'].get_effective_contactgroups() - except KeyError, e: + except KeyError as e: c['errors'].append(_("Could not find contact_group: %(error)s") % {'error': str(e)}) try: c['effective_contacts'] = c['my_object'].get_effective_contacts() - except KeyError, e: + except KeyError as e: c['errors'].append("Could not find contact: %s" % str(e)) try: c['effective_memberof'] = Model.Contactgroup.objects.filter( contactgroup_members__has_field=c['my_object'].contactgroup_name) - except Exception, e: + except Exception as e: c['errors'].append(e) return render_to_response('edit_contactgroup.html', c, context_instance=RequestContext(request)) @@ -354,12 +354,12 @@ def _edit_hostgroup(request, c): try: c['effective_services'] = sorted( hostgroup.get_effective_services(), key=lambda x: x.get_description()) - except KeyError, e: + except KeyError as e: c['errors'].append(_("Could not find service: %(error)s") % {'error': str(e)}) try: c['effective_memberof'] = Model.Hostgroup.objects.filter( hostgroup_members__has_field=c['my_object'].hostgroup_name) - except Exception, e: + except Exception as e: c['errors'].append(e) return render_to_response('edit_hostgroup.html', c, context_instance=RequestContext(request)) @@ -370,7 +370,7 @@ def _edit_servicegroup(request, c): try: c['effective_memberof'] = Model.Servicegroup.objects.filter( servicegroup_members__has_field=c['my_object'].servicegroup_name) - except Exception, e: + except Exception as e: c['errors'].append(e) return render_to_response('edit_servicegroup.html', c, context_instance=RequestContext(request)) @@ -418,27 +418,27 @@ def _edit_host(request, c): try: c['effective_services'] = sorted( host.get_effective_services(), key=lambda x: x.get_description()) - except KeyError, e: + except KeyError as e: c['errors'].append(_("Could not find service: %(error)s") % {'error': str(e)}) try: c['effective_hostgroups'] = host.get_effective_hostgroups() - except KeyError, e: + except KeyError as e: c['errors'].append(_("Could not find hostgroup: %(error)s") % {'error': str(e)}) try: c['effective_contacts'] = host.get_effective_contacts() - except KeyError, e: + except KeyError as e: c['errors'].append(_("Could not find contact: %(error)s") % {'error': str(e)}) try: c['effective_contactgroups'] = host.get_effective_contact_groups() - except KeyError, e: + except KeyError as e: c['errors'].append(_("Could not find contact_group: %(error)s") % {'error': str(e)}) try: c['effective_command'] = host.get_effective_check_command() - except KeyError, e: + except KeyError as e: if host.check_command is not None: c['errors'].append(_("Could not find check_command: %(error)s") % {'error': str(e)}) elif host.register != '0': @@ -562,7 +562,7 @@ def bulk_edit(request): 'description': i.get_description(), }) c['success'] = "success" - except IOError, e: + except IOError as e: c['errors'].append(e) return render_to_response('bulk_edit.html', c, context_instance=RequestContext(request)) @@ -595,7 +595,7 @@ def bulk_delete(request): if request.method == "POST": # Post items starting with "hidden_" will be displayed on the resulting web page # Post items starting with "change_" will be modified - for i in request.POST.keys(): + for i in list(request.POST.keys()): if i.startswith('change_'): my_id = i[len('change_'):] my_obj = ObjectDefinition.objects.get_by_id(my_id) @@ -610,7 +610,7 @@ def bulk_delete(request): for i in c['form'].changed_objects: c['messages'].append( "Deleted %s %s" % (i.object_type, i.get_description())) - except IOError, e: + except IOError as e: c['errors'].append(e) return render_to_response('bulk_delete.html', c, context_instance=RequestContext(request)) @@ -642,7 +642,7 @@ def bulk_copy(request): elif request.method == "POST": # Post items starting with "hidden_" will be displayed on the resulting web page # Post items starting with "change_" will be modified - for i in request.POST.keys(): + for i in list(request.POST.keys()): if i.startswith('change_'): my_id = i[len('change_'):] my_obj = ObjectDefinition.objects.get_by_id(my_id) @@ -658,7 +658,7 @@ def bulk_copy(request): c['messages'].append( _("Successfully copied %(object_type)s %(description)s") % {'object_type': i.object_type, 'description': i.get_description()}) - except IOError, e: + except IOError as e: c['errors'].append(e) return render_to_response('bulk_copy.html', c, context_instance=RequestContext(request)) @@ -687,7 +687,7 @@ def delete_object(request, object_id): if f.is_valid(): f.delete() return HttpResponseRedirect(reverse('objectbrowser') + "#" + my_obj.object_type) - except Exception, e: + except Exception as e: c['errors'].append(e) return render_to_response('delete_object.html', c, context_instance=RequestContext(request)) @@ -710,7 +710,7 @@ def copy_object(request, object_id): f.save() c['copied_objects'] = f.copied_objects c['success'] = 'success' - except IndexError, e: + except IndexError as e: c['errors'].append(e) return render_to_response('copy_object.html', c, context_instance=RequestContext(request)) @@ -757,7 +757,7 @@ def _querystring_to_objects(dictionary): """ result = [] Object = namedtuple('Object', 'object_type description') - for object_type in string_to_class.keys(): + for object_type in list(string_to_class.keys()): objects = dictionary.getlist(object_type) for i in objects: obj = (Object(object_type, i)) @@ -787,18 +787,18 @@ def _querydict_to_objects(request, raise_on_not_found=False): try: my_object = ObjectDefinition.objects.get_by_id(object_id) result.append(my_object) - except Exception, e: + except Exception as e: if raise_on_not_found is True: raise e # Find everything in querystring in the form of object_type=[shortnames] - for object_type,Class in string_to_class.items(): + for object_type,Class in list(string_to_class.items()): objects = mydict.getlist(object_type) for shortname in objects: try: my_object = Class.objects.get_by_shortname(shortname) result.append(my_object) - except Exception, e: + except Exception as e: # If a service was not found, check if it was registered in # some unusual way if object_type == 'service' and '/' in shortname: @@ -846,7 +846,7 @@ def add_to_group(request, group_type=None, group_name=''): elif group_type == 'servicegroup': obj.add_to_servicegroup(group_name) return HttpResponse("Success") - except Exception, e: + except Exception as e: errortype = e.__dict__.get('__name__') or str(type(e)) error = str(e) return HttpResponse(_("Failed to add object: %(errortype)s %(error)s ") % {'errortype': errortype, @@ -866,7 +866,7 @@ def edit_all(request, object_type, attribute_name): messages = [] errors = [] objects = Model.string_to_class.get(object_type).objects.all - objects = map(lambda x: (x.get_shortname, x.get(attribute_name)), objects) + objects = [(x.get_shortname, x.get(attribute_name)) for x in objects] return render_to_response('edit_all.html', locals(), context_instance=RequestContext(request)) @@ -913,7 +913,7 @@ def copy_and_edit_object(request, object_id): If object_id is provided, that object will be copied into this one. """ kwargs = {} - for k, v in request.GET.items(): + for k, v in list(request.GET.items()): if v in ('', None, 'None'): v = None kwargs[k] = v diff --git a/adagios/okconfig_/forms.py b/adagios/okconfig_/forms.py index 923a6e251..1cef601cf 100644 --- a/adagios/okconfig_/forms.py +++ b/adagios/okconfig_/forms.py @@ -27,24 +27,23 @@ def get_all_hosts(): - return [('', _('Select a host'))] + map(lambda x: (x, x), helpers.get_host_names()) + return [('', _('Select a host'))] + [(x, x) for x in helpers.get_host_names()] def get_all_templates(): all_templates = okconfig.get_templates() - service_templates = filter(lambda x: 'host' not in x, all_templates) - return map(lambda x: (x, _("Standard %(service_template)s checks") % {"service_template": x}), service_templates) + service_templates = [x for x in all_templates if 'host' not in x] + return [(x, _("Standard %(service_template)s checks") % {"service_template": x}) for x in service_templates] def get_all_groups(): - return map(lambda x: (x, x), okconfig.get_groups()) + return [(x, x) for x in okconfig.get_groups()] def get_inactive_services(): """ List of all unregistered services (templates) """ inactive_services = [('', _('Select a service'))] - inactive_services += map(lambda x: (x.name, x.name), - Model.Service.objects.filter(service_description__contains="", name__contains="", register="0")) + inactive_services += [(x.name, x.name) for x in Model.Service.objects.filter(service_description__contains="", name__contains="", register="0")] inactive_services.sort() return inactive_services @@ -113,7 +112,7 @@ def clean(self): host_name = self.cleaned_data.get('host_name') templates = self.cleaned_data.get('templates') for i in templates: - if i not in okconfig.get_templates().keys(): + if i not in list(okconfig.get_templates().keys()): self._errors['templates'] = self.error_class( [_('template %s was not found') % i]) if not force and host_name in okconfig.get_hosts(): @@ -141,7 +140,7 @@ def clean(self): host_name = self.cleaned_data.get('host_name') templates = self.cleaned_data.get('templates') for i in templates: - if i not in okconfig.get_templates().keys(): + if i not in list(okconfig.get_templates().keys()): self._errors['templates'] = self.error_class( [_('template %s was not found') % i]) if not force and host_name not in okconfig.get_hosts(): @@ -211,7 +210,7 @@ def __init__(self, service=Model.Service(), *args, **kwargs): self.command_line = None try: self.command_line = service.get_effective_command_line() - for macro, value in service.get_all_macros().items(): + for macro, value in list(service.get_all_macros().items()): if macro.startswith('$_SERVICE') or macro.startswith('S$ARG'): macros.append(macro) for k in sorted(macros): diff --git a/adagios/okconfig_/tests.py b/adagios/okconfig_/tests.py index 43064a595..123c09ba1 100644 --- a/adagios/okconfig_/tests.py +++ b/adagios/okconfig_/tests.py @@ -31,7 +31,7 @@ class TestOkconfig(TestCase): def testOkconfigVerifies(self): result = okconfig.verify() - for k, v in result.items(): + for k, v in list(result.items()): self.assertTrue(v, msg=_("Failed on test: %s") % k) def testIndexPage(self): @@ -57,5 +57,5 @@ def loadPage(self, url): c = Client() response = c.get(url) self.assertEqual(response.status_code, 200, _("Expected status code 200 for page %s") % url) - except Exception, e: + except Exception as e: self.assertEqual(True, _("Unhandled exception while loading %(url)s: %(e)s") % {'url': url, 'e': e}) diff --git a/adagios/okconfig_/views.py b/adagios/okconfig_/views.py index 9ec8ea892..bbb480b36 100644 --- a/adagios/okconfig_/views.py +++ b/adagios/okconfig_/views.py @@ -68,7 +68,7 @@ def addgroup(request): group_name=group_name, alias=alias, force=force) c['group_name'] = group_name return addcomplete(request, c) - except Exception, e: + except Exception as e: c['errors'].append(_("error adding group: %s") % e) else: c['errors'].append(_('Could not validate input')) @@ -105,7 +105,7 @@ def addhost(request): force=force, templates=templates) c['host_name'] = host_name return addcomplete(request, c) - except Exception, e: + except Exception as e: c['errors'].append(_("error adding host: %s") % e) else: c['errors'].append(_('Could not validate input')) @@ -138,7 +138,7 @@ def addtemplate(request, host_name=None): c['messages'].append( _("Template was successfully added to host.")) return HttpResponseRedirect(reverse('adagios.okconfig_.views.edit', args=[host_name])) - except Exception, e: + except Exception as e: c['errors'].append(e) else: c['errors'].append(_("Could not validate form")) @@ -169,13 +169,13 @@ def addservice(request): c['my_object'] = new_service # Add custom macros if any were specified - for k, v in form.data.items(): + for k, v in list(form.data.items()): if k.startswith("_") or k.startswith('service_description'): new_service[k] = v try: new_service.save() return HttpResponseRedirect(reverse('edit_object', kwargs={'object_id': new_service.get_id()})) - except IOError, e: + except IOError as e: c['errors'].append(e) else: c['errors'].append(_("Could not validate form")) @@ -188,7 +188,7 @@ def verify_okconfig(request): c = {} c['errors'] = [] c['okconfig_checks'] = okconfig.verify() - for i in c['okconfig_checks'].values(): + for i in list(c['okconfig_checks'].values()): if i == False: c['errors'].append( _('There seems to be a problem with your okconfig installation')) @@ -237,7 +237,7 @@ def install_agent(request): c['hint'] = _("No nsclient copy found ") c['stdout'].append(i) c['stdout'] = '\n'.join(c['stdout']) - except Exception, e: + except Exception as e: c['errors'].append(e) else: c['errors'].append(_('invalid input')) @@ -259,7 +259,7 @@ def edit(request, host_name): try: c['myhost'] = Model.Host.objects.get_by_shortname(host_name) - except KeyError, e: + except KeyError as e: c['errors'].append(_("Host %s not found") % e) return render_to_response('edittemplate.html', c, context_instance=RequestContext(request)) # Get all services of that host that contain a service_description @@ -280,7 +280,7 @@ def edit(request, host_name): form.save() c['messages'].append( _("'%s' successfully saved.") % service.get_description()) - except Exception, e: + except Exception as e: c['errors'].append( _("Failed to save service %(service)s: %(exc)s") % {'service': service.get_description(), 'exc': e}) else: @@ -314,7 +314,7 @@ def scan_network(request): if not okconfig.is_valid(): return verify_okconfig(request) if request.method == 'GET': - if request.GET.has_key('network_address'): + if 'network_address' in request.GET: initial = request.GET else: my_ip = okconfig.network_scan.get_my_ip_address() @@ -332,6 +332,6 @@ def scan_network(request): network) for i in c['scan_results']: i.check() - except Exception, e: + except Exception as e: c['errors'].append(_("Error running scan")) return render_to_response('scan_network.html', c, context_instance=RequestContext(request)) diff --git a/adagios/pnp/functions.py b/adagios/pnp/functions.py index 8f3d4af8a..9c057be55 100644 --- a/adagios/pnp/functions.py +++ b/adagios/pnp/functions.py @@ -15,6 +15,7 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . +from builtins import str import os import pynag.Utils @@ -42,17 +43,17 @@ def run_pnp(pnp_command, **kwargs): """ try: pnp_path = settings.pnp_path - except Exception, e1: + except Exception as e1: pnp_path = find_pnp_path() # Cleanup kwargs pnp_arguments = {} - for k, v in kwargs.items(): + for k, v in list(kwargs.items()): k = str(k) if isinstance(v, list): v = v[0] v = str(v) pnp_arguments[k] = v - querystring = '&'.join(map(lambda x: "%s=%s" % x, pnp_arguments.items())) + querystring = '&'.join(["%s=%s" % x for x in list(pnp_arguments.items())]) pnp_parameters = pnp_command + "?" + querystring command = ['php', pnp_path, pnp_parameters] proc = subprocess.Popen(command, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE,) diff --git a/adagios/profiling.py b/adagios/profiling.py index e5d87b7e7..5b834cd21 100644 --- a/adagios/profiling.py +++ b/adagios/profiling.py @@ -20,14 +20,16 @@ # Code from https://code.djangoproject.com/wiki/ProfilingDjango -# Documentation at +# Documentation at # https://github.com/opinkerfi/adagios/wiki/Profiling-Decorators-within-Adagios -import hotshot +from __future__ import absolute_import +from builtins import str +import cProfile import os import time -import settings +from . import settings import tempfile import random @@ -45,10 +47,10 @@ def profile(log_file): for later processing and examination. It takes one argument, the profile log name. If it's a relative path, it - places it under the PROFILE_LOG_BASE. It also inserts a time stamp into the - file name, such that 'my_view.prof' become 'my_view-20100211T170321.prof', - where the time stamp is in UTC. This makes it easy to run and compare - multiple trials. + places it under the PROFILE_LOG_BASE. It also inserts a time stamp into the + file name, such that 'my_view.prof' become 'my_view-20100211T170321.prof', + where the time stamp is in UTC. This makes it easy to run and compare + multiple trials. """ if not os.path.isabs(log_file): @@ -62,7 +64,7 @@ def _inner(*args, **kwargs): base = base + "-" + time.strftime("%Y%m%dT%H%M%S", time.gmtime()) + str(random.randint(1,9999)) final_log_file = base + ext - prof = hotshot.Profile(final_log_file) + prof = cProfile.Profile(final_log_file) try: ret = prof.runcall(f, *args, **kwargs) finally: diff --git a/adagios/rest/tests.py b/adagios/rest/tests.py index 29672c61d..09efa88d9 100644 --- a/adagios/rest/tests.py +++ b/adagios/rest/tests.py @@ -21,7 +21,8 @@ Replace these with more appropriate tests for your application. """ - +#from __future__ import unicode_literals +from builtins import str from django.test import TestCase from django.test.client import Client from django.utils.translation import ugettext as _ @@ -58,7 +59,7 @@ def testDnsLookup(self): json_data = json.loads(response.content) self.assertEqual(response.status_code, 200, _("Expected status code 200 for page %s") % path) self.assertEqual(True, 'addresslist' in json_data, _("Expected 'addresslist' to appear in response")) - except KeyError, e: + except KeyError as e: self.assertEqual(True, _("Unhandled exception while loading %(path)s: %(exc)s") % {'path': path, 'exc': e}) def testGetAllHostsViaJSON(self): @@ -70,7 +71,7 @@ def testGetAllHostsViaJSON(self): json_data = json.loads(response.content) self.assertEqual(response.status_code, 200, _("Expected status code 200 for page %s") % path) self.assertEqual(['ok_host'], [x['name'] for x in json_data]) - self.assertEqual(['name', 'backend'], json_data[0].keys()) + self.assertEqual(['name', 'backend'], list(json_data[0].keys())) def loadPage(self, url): """ Load one specific page, and assert if return code is not 200 """ @@ -78,5 +79,5 @@ def loadPage(self, url): c = Client() response = c.get(url) self.assertEqual(response.status_code, 200, _("Expected status code 200 for page %s") % url) - except Exception, e: + except Exception as e: self.assertEqual(True, _("Unhandled exception while loading %(url)s: %(exc)s") % {'url': url, 'exc': e}) diff --git a/adagios/rest/urls.py b/adagios/rest/urls.py index 721a9f132..d91fa5362 100644 --- a/adagios/rest/urls.py +++ b/adagios/rest/urls.py @@ -40,7 +40,7 @@ #url(r'^/status.js$', 'rest.views.javascript', { 'module_name': 'adagios.rest.status' }, ), #(r'^/status/(?P.+?)/(?P.+?)/?$', 'rest.views.handle_request', { 'module_name': 'adagios.rest.status' }), -for module_name, module_path in rest_modules.items(): +for module_name, module_path in list(rest_modules.items()): base_pattern = r'^/%s' % module_name args = {'module_name': module_name, 'module_path': module_path} urlpatterns += patterns('adagios', diff --git a/adagios/rest/views.py b/adagios/rest/views.py index 259ac054d..efe76bd5a 100644 --- a/adagios/rest/views.py +++ b/adagios/rest/views.py @@ -16,6 +16,7 @@ # along with this program. If not, see . # Create your views here. +from builtins import str from django.shortcuts import render_to_response, redirect, render from django.core import serializers from django.http import HttpResponse, HttpResponseServerError @@ -61,11 +62,11 @@ def handle_request(request, module_name, module_path, attribute, format): c['form'] = CallFunctionForm(function=item, initial=request.GET) c['docstring'] = docstring c['module_name'] = module_name - if not request.GET.items(): + if not list(request.GET.items()): return render_to_response('function_form.html', c, context_instance=RequestContext(request)) # Handle get parameters arguments = {} - for k, v in request.GET.items(): + for k, v in list(request.GET.items()): # TODO: Is it safe to turn all digits to int ? #if str(v).isdigit(): v = int(float(v)) arguments[k.encode('utf-8')] = v.encode('utf-8') @@ -81,7 +82,7 @@ def handle_request(request, module_name, module_path, attribute, format): result = item else: arguments = {} # request.POST.items() - for k, v in request.POST.items(): + for k, v in list(request.POST.items()): arguments[k.encode('utf-8')] = v.encode('utf-8') # Here is a special hack, if the method we are calling has an argument # called "request" we will not let the remote user ship it in. @@ -213,8 +214,8 @@ def __init__(self, function, *args, **kwargs): function_paramaters = {} # If any paramaters were past via querystring, lets generate fields for # them - if kwargs.has_key('initial'): - for k, v in kwargs['initial'].items(): + if 'initial' in kwargs: + for k, v in list(kwargs['initial'].items()): function_paramaters[k] = v # Generate fields which resemble our functions default arguments argspec = inspect.getargspec(function) @@ -230,7 +231,7 @@ def __init__(self, function, *args, **kwargs): defaults = list(defaults) for i in args: self.fields[i] = forms.CharField(label=i) - for k, v in function_paramaters.items(): + for k, v in list(function_paramaters.items()): self.fields[k] = forms.CharField(label=k, initial=v) while len(defaults) > 0: value = defaults.pop() diff --git a/adagios/seleniumtests.py b/adagios/seleniumtests.py index b674f0162..579262975 100644 --- a/adagios/seleniumtests.py +++ b/adagios/seleniumtests.py @@ -1,3 +1,4 @@ +from __future__ import print_function from django.test import LiveServerTestCase from django.test import TestCase import adagios.settings diff --git a/adagios/settings.py b/adagios/settings.py index d3e1fbc4b..08451e60a 100644 --- a/adagios/settings.py +++ b/adagios/settings.py @@ -17,6 +17,7 @@ # Django settings for adagios project. +from past.builtins import execfile DEBUG = True TEMPLATE_DEBUG = DEBUG USE_TZ = True @@ -302,7 +303,7 @@ def reload_configfile(adagios_configfile=None): configfiles = glob(include) for configfile in configfiles: execfile(configfile, globals()) - except IOError, e: + except IOError as e: warn('Unable to open %s: %s' % (adagios_configfile, e.strerror)) reload_configfile() @@ -324,7 +325,7 @@ def get_random_string(length, stringset=string.ascii_letters + string.digits + s data = "\n# Automaticly generated secret_key\ndjango_secret_key = '%s'\n" % SECRET_KEY with open(adagios_configfile, "a") as config_fh: config_fh.write(data) - except Exception, e: + except Exception as e: warn("ERROR: Got %s while trying to save django secret_key in %s" % (type(e), adagios_configfile)) else: @@ -337,7 +338,7 @@ def get_random_string(length, stringset=string.ascii_letters + string.digits + s if enable_bi: plugins['bi'] = 'adagios.bi' -for k, v in plugins.items(): +for k, v in list(plugins.items()): INSTALLED_APPS.append(v) # default preferences, for new users or when they are not available diff --git a/adagios/status/forms.py b/adagios/status/forms.py index 1d60fe437..ec0c18f58 100644 --- a/adagios/status/forms.py +++ b/adagios/status/forms.py @@ -49,8 +49,7 @@ def save(self): self.bp.remove_process(process_name, process_type) self.bp.save() -status_method_choices = map( - lambda x: (x, x), adagios.businessprocess.BusinessProcess.status_calculation_methods) +status_method_choices = [(x, x) for x in adagios.businessprocess.BusinessProcess.status_calculation_methods] class BusinessProcessForm(forms.Form): @@ -129,7 +128,7 @@ def add_process(self): self.bp.save() choices = 'businessprocess', 'hostgroup', 'servicegroup', 'service', 'host' -process_type_choices = map(lambda x: (x, x), choices) +process_type_choices = [(x, x) for x in choices] class AddSubProcess(forms.Form): diff --git a/adagios/status/rest.py b/adagios/status/rest.py index cf8db07b7..6f8fddf07 100644 --- a/adagios/status/rest.py +++ b/adagios/status/rest.py @@ -21,7 +21,13 @@ with status of Nagios. """ +from __future__ import division +from __future__ import print_function +#from __future__ import unicode_literals +from past.builtins import cmp +from builtins import str, int +from past.utils import old_div import time import pynag.Control.Command import pynag.Model @@ -60,7 +66,7 @@ def services_dt(request, fields=None, **kwargs): 'aaData': [] } for service in services: - result['aaData'].append(service.values()) + result['aaData'].append(list(service.values())) return result @@ -75,7 +81,7 @@ def emails(request, *args, **kwargs): """ Returns a list of all emails of all contacts """ l = adagios.status.utils.livestatus(request) - return map(lambda x: x['email'], l.get_contacts('Filter: email !=')) + return [x['email'] for x in l.get_contacts('Filter: email !=')] def acknowledge_many(hostlist, servicelist, sticky=1, notify=1, persistent=0, author="adagios", comment="acknowledged by Adagios"): @@ -441,9 +447,9 @@ def autocomplete(request, q): services = adagios.status.utils.get_services(request, service_description__contains=q) hostgroups = adagios.status.utils.get_hostgroups(request, hostgroup_name__contains=q) - result['hosts'] = sorted(set(map(lambda x: x['name'], hosts))) - result['hostgroups'] = sorted(set(map(lambda x: x['name'], hostgroups))) - result['services'] = sorted(set(map(lambda x: x['description'], services))) + result['hosts'] = sorted(set([x['name'] for x in hosts])) + result['hostgroups'] = sorted(set([x['name'] for x in hostgroups])) + result['services'] = sorted(set([x['description'] for x in services])) return result @@ -478,7 +484,7 @@ def top_alert_producers(request, limit=5, start_time=None, end_time=None): for i in log: if 'host_name' in i and 'state' in i and i['state'] > 0: top_alert_producers[i['host_name']] += 1 - top_alert_producers = top_alert_producers.items() + top_alert_producers = list(top_alert_producers.items()) top_alert_producers.sort(cmp=lambda a, b: cmp(a[1], b[1]), reverse=True) if limit > len(top_alert_producers): top_alert_producers = top_alert_producers[:int(limit)] @@ -524,8 +530,8 @@ def state_history( elif object_type == 'hostgroup': hg = pynag.Model.Hostgroup.objects.get_by_shortname(hostgroup_name) hosts = hg.get_effective_hosts() - hostnames = map(lambda x: x.host_name, hosts) - log_entries = filter(lambda x: x['host_name'] in hostnames, log_entries) + hostnames = [x.host_name for x in hosts] + log_entries = [x for x in log_entries if x['host_name'] in hostnames] else: raise Exception(_("Unsupported object type: %s") % object_type) @@ -546,7 +552,7 @@ def state_history( css_hint[2] = 'danger' css_hint[3] = 'info' for i in log: - i['duration_percent'] = 100 * i['duration'] / total_duration + i['duration_percent'] = old_div(100 * i['duration'], total_duration) i['bootstrap_status'] = css_hint[i['state']] return log_entries @@ -565,7 +571,7 @@ def _get_service_model(host_name, service_description=None): """ try: return pynag.Model.Service.objects.get_by_shortname("%s/%s" % (host_name, service_description)) - except KeyError, e: + except KeyError as e: host = pynag.Model.Host.objects.get_by_shortname(host_name) for i in host.get_effective_services(): if i.service_description == service_description: @@ -602,7 +608,7 @@ def update_check_command(host_name, service_description=None, **kwargs): """ Saves all custom variables of a given service """ try: - for k, v in kwargs.items(): + for k, v in list(kwargs.items()): if service_description is None or service_description == '': obj = pynag.Model.Host.objects.get_by_shortname(host_name) else: @@ -620,7 +626,7 @@ def get_business_process_names(): """ Returns all configured business processes """ import adagios.businessprocess - return map(lambda x: x.name, adagios.businessprocess.get_all_processes()) + return [x.name for x in adagios.businessprocess.get_all_processes()] def get(request, object_type, *args, **kwargs): @@ -629,8 +635,7 @@ def get(request, object_type, *args, **kwargs): object_type += 's' if 'name__contains' in kwargs and object_type == 'services': name = str(kwargs['name__contains']) - livestatus_arguments = filter( - lambda x: x.startswith('name'), livestatus_arguments) + livestatus_arguments = [x for x in livestatus_arguments if x.startswith('name')] livestatus_arguments.append('Filter: host_name ~ %s' % name) livestatus_arguments.append('Filter: description ~ %s' % name) livestatus_arguments.append('Or: 2') @@ -752,7 +757,7 @@ def metrics(request, **kwargs): services = adagios.status.utils.get_services(request, fields=fields, **kwargs) for service in services: metrics = pynag.Utils.PerfData(service['perf_data']).metrics - metrics = filter(lambda x: x.is_valid(), metrics) + metrics = [x for x in metrics if x.is_valid()] for metric in metrics: metric_dict = { 'host_name': service['host_name'], @@ -777,7 +782,7 @@ def metric_names(request, **kwargs): services = adagios.status.utils.get_services(request, fields=fields, **kwargs) for service in services: metrics = pynag.Utils.PerfData(service['perf_data']).metrics - metrics = filter(lambda x: x.is_valid(), metrics) + metrics = [x for x in metrics if x.is_valid()] for metric in metrics: metric_names.add(metric.label) @@ -789,13 +794,13 @@ def metric_names(request, **kwargs): return result def wait(table, WaitObject, WaitCondition=None, WaitTrigger='check', **kwargs): - print _("Lets wait for"), locals() + print(_("Lets wait for"), locals()) if not WaitCondition: WaitCondition = "last_check > %s" % int(time.time()-1) livestatus = adagios.status.utils.livestatus(None) - print _("livestatus ok") + print(_("livestatus ok")) result = livestatus.get(table, 'Stats: state != 999', WaitObject=WaitObject, WaitCondition=WaitCondition, WaitTrigger=WaitTrigger, **kwargs) - print _("ok no more waiting for "), WaitObject + print(_("ok no more waiting for "), WaitObject) return result @@ -808,13 +813,13 @@ def wait_many(hostlist, servicelist, WaitCondition=None, WaitTrigger='check', ** continue WaitObject = host livestatus.get('hosts', WaitObject=WaitObject, WaitCondition=WaitCondition, WaitTrigger=WaitTrigger, **kwargs) - print WaitObject + print(WaitObject) for service in servicelist.split(';'): if not service: continue WaitObject = service.replace(',', ';') livestatus.get('services', WaitObject=WaitObject, WaitCondition=WaitCondition, WaitTrigger=WaitTrigger, **kwargs) - print WaitObject + print(WaitObject) def toggle_backend_visibility(request, backend_name): diff --git a/adagios/status/tests.py b/adagios/status/tests.py index 1994c9d33..7fbcf78c2 100644 --- a/adagios/status/tests.py +++ b/adagios/status/tests.py @@ -17,6 +17,7 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . +from builtins import str from django.test import TestCase from django.test.client import Client from django.utils.translation import ugettext as _ diff --git a/adagios/status/utils.py b/adagios/status/utils.py index 04996c81a..35d7048b6 100644 --- a/adagios/status/utils.py +++ b/adagios/status/utils.py @@ -20,6 +20,12 @@ # Utility functions for the status app. These are mostly used by # adagios.status.views +from __future__ import division +#from __future__ import unicode_literals +from past.builtins import cmp +from past.builtins import basestring +from builtins import str +from past.utils import old_div import pynag.Utils import pynag.Parsers import adagios.settings @@ -89,7 +95,7 @@ def get_all_backends(): # TODO: Properly support multiple instances, using split here is not a good idea backends = adagios.settings.livestatus_path or '' backends = backends.split(',') - backends = map(lambda x: x.strip(), backends) + backends = [x.strip() for x in backends] return backends @@ -110,7 +116,7 @@ def livestatus(request): try: user = userdata.User(request) if user.disabled_backends is not None: - backends = filter(lambda x: x not in user.disabled_backends, backends) + backends = [x for x in backends if x not in user.disabled_backends] clear_notification("userdata problem") except Exception as e: message = "%s: %s" % (type(e), str(e)) @@ -169,11 +175,11 @@ def add_statistics_to_hosts(result): try: total = float(total) host['health'] = float(ok) / total * 100.0 - host['percent_ok'] = ok / total * 100 - host['percent_warn'] = warn / total * 100 - host['percent_crit'] = crit / total * 100 - host['percent_unknown'] = unknown / total * 100 - host['percent_pending'] = pending / total * 100 + host['percent_ok'] = old_div(ok, total) * 100 + host['percent_warn'] = old_div(warn, total) * 100 + host['percent_crit'] = old_div(crit, total) * 100 + host['percent_unknown'] = old_div(unknown, total) * 100 + host['percent_pending'] = old_div(pending, total) * 100 except ZeroDivisionError: host['health'] = 'n/a' except Exception: @@ -288,7 +294,10 @@ def get_hosts(request, fields=None, *args, **kwargs): fields = _DEFAULT_HOST_COLUMNS # fields should be a list, lets create a Column: query for livestatus - if isinstance(fields, (str, unicode)): +# if isinstance(fields, str): +# fields = fields.split(',') + + if isinstance(fields, basestring): fields = fields.split(',') query.set_columns(*fields) @@ -478,11 +487,11 @@ def get_statistics(request, *args, **kwargs): # Calculate percentage of hosts/services that are "ok" try: - c['service_totals_percent'] = map(lambda x: float(100.0 * x / c['total_services']), c['service_totals']) + c['service_totals_percent'] = [float(old_div(100.0 * x, c['total_services'])) for x in c['service_totals']] except ZeroDivisionError: c['service_totals_percent'] = [0, 0, 0, 0] try: - c['host_totals_percent'] = map(lambda x: float(100.0 * x / c['total_hosts']), c['host_totals']) + c['host_totals_percent'] = [float(old_div(100.0 * x, c['total_hosts'])) for x in c['host_totals']] except ZeroDivisionError: c['host_totals_percent'] = [0, 0, 0, 0] diff --git a/adagios/status/views.py b/adagios/status/views.py index 17643cb06..0533e940b 100644 --- a/adagios/status/views.py +++ b/adagios/status/views.py @@ -17,6 +17,11 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . +from __future__ import division +from past.builtins import cmp +from builtins import str +from builtins import map +from past.utils import old_div from django.http import HttpResponse import time @@ -94,7 +99,7 @@ def network_parents(request): c['messages'] = [] hosts = utils.get_hosts(request, **request.GET) host_dict = {} - map(lambda x: host_dict.__setitem__(x['name'], x), hosts) + list(map(lambda x: host_dict.__setitem__(x['name'], x), hosts)) c['hosts'] = [] for i in hosts: @@ -112,8 +117,8 @@ def network_parents(request): crit += 1 total = float(len(i['childs'])) i['health'] = float(ok) / total * 100.0 - i['percent_ok'] = ok / total * 100 - i['percent_crit'] = crit / total * 100 + i['percent_ok'] = old_div(ok, total) * 100 + i['percent_crit'] = old_div(crit, total) * 100 return render_to_response('status_parents.html', c, context_instance=RequestContext(request)) @@ -201,8 +206,8 @@ def snippets_log(request): object_type = "hostgroup" hg = pynag.Model.Hostgroup.objects.get_by_shortname(hostgroup_name) hosts = hg.get_effective_hosts() - hostnames = map(lambda x: x.host_name, hosts) - log = filter(lambda x: x['host_name'] in hostnames, log) + hostnames = [x.host_name for x in hosts] + log = [x for x in log if x['host_name'] in hostnames] elif host_name: object_type = "host" else: @@ -227,7 +232,7 @@ def snippets_log(request): css_hint[2] = 'danger' css_hint[3] = 'unknown' for i in log: - i['duration_percent'] = 100 * i['duration'] / total_duration + i['duration_percent'] = old_div(100 * i['duration'], total_duration) i['bootstrap_status'] = css_hint[i['state']] return render_to_response('snippets/status_statehistory_snippet.html', locals(), context_instance=RequestContext(request)) @@ -313,7 +318,7 @@ def service_detail(request, host_name, service_description): # Get a complete list of network parents try: c['network_parents'] = reversed(_get_network_parents(request, host_name)) - except Exception, e: + except Exception as e: c['errors'].append(e) # Lets get some graphs @@ -321,7 +326,7 @@ def service_detail(request, host_name, service_description): try: tmp = run_pnp("json", host=host_name) tmp = json.loads(tmp) - except Exception, e: + except Exception as e: tmp = [] c['pnp4nagios_error'] = e c['graph_urls'] = tmp @@ -339,7 +344,7 @@ def service_detail(request, host_name, service_description): for graph in c['graphite']: if graph['css_id'] == adagios.settings.GRAPHITE_DEFAULT_TAB: default = {} - for k,v in graph['metrics'].items(): + for k,v in list(graph['metrics'].items()): default[k] = v c['graphite_default'] = default @@ -364,24 +369,24 @@ def _get_network_parents(request, host_name): result = [] backend = request.GET.get('backend', None) livestatus = adagios.status.utils.livestatus(request) - if isinstance(host_name, unicode): + if isinstance(u'host_name', str): host_name = smart_str(host_name) - if isinstance(host_name, str): + if isinstance(u'host_name', str): host = livestatus.get_host(host_name, backend) - elif isinstance(host_name, dict): + elif isinstance(u'host_name', dict): host = host_name else: raise KeyError( 'host_name must be str or dict (got %s)' % type(host_name)) parent_names = host['parents'] while len(parent_names) > 0: - parents = map(lambda x: livestatus.get_host(x, backend), parent_names) + parents = [livestatus.get_host(x, backend) for x in parent_names] # generate a list of grandparent names: grand_parents = set() for i in parents: - map(lambda x: grand_parents.add(x), i.get('parents')) + list(map(lambda x: grand_parents.add(x), i.get('parents'))) result.append(parents) parent_names = list(grand_parents) return result @@ -408,7 +413,7 @@ def hostgroup_detail(request, hostgroup_name): subgroups = subgroups.split(',') if subgroups == ['']: subgroups = [] - c['hostgroups'] = map(lambda x: livestatus.get_hostgroups('Filter: name = %s' % x)[0], subgroups) + c['hostgroups'] = [livestatus.get_hostgroups('Filter: name = %s' % x)[0] for x in subgroups] _add_statistics_to_hostgroups(c['hostgroups']) return render_to_response('status_hostgroup.html', c, context_instance=RequestContext(request)) @@ -424,8 +429,8 @@ def _add_statistics_to_hostgroups(hostgroups): hostgroup_parentgroups = defaultdict(set) hostgroup_childgroups = pynag.Model.ObjectRelations.hostgroup_hostgroups - for hostgroup, subgroups in hostgroup_childgroups.items(): - map(lambda x: hostgroup_parentgroups[x].add(hostgroup), subgroups) + for hostgroup, subgroups in list(hostgroup_childgroups.items()): + list(map(lambda x: hostgroup_parentgroups[x].add(hostgroup), subgroups)) for i in hostgroups: i['child_hostgroups'] = hostgroup_childgroups[i['name']] @@ -445,11 +450,11 @@ def _add_statistics_to_hostgroups(hostgroups): total = float(total) hg['health'] = float(ok) / total * 100.0 hg['health'] = float(ok) / total * 100.0 - hg['percent_ok'] = ok / total * 100 - hg['percent_warn'] = warn / total * 100 - hg['percent_crit'] = crit / total * 100 - hg['percent_unknown'] = unknown / total * 100 - hg['percent_pending'] = pending / total * 100 + hg['percent_ok'] = old_div(ok, total) * 100 + hg['percent_warn'] = old_div(warn, total) * 100 + hg['percent_crit'] = old_div(crit, total) * 100 + hg['percent_unknown'] = old_div(unknown, total) * 100 + hg['percent_pending'] = old_div(pending, total) * 100 except ZeroDivisionError: pass @@ -486,8 +491,8 @@ def status_hostgroups(request): hostgroup_parentgroups = defaultdict(set) hostgroup_childgroups = pynag.Model.ObjectRelations.hostgroup_hostgroups - for hostgroup, subgroups in hostgroup_childgroups.items(): - map(lambda x: hostgroup_parentgroups[x].add(hostgroup), subgroups) + for hostgroup, subgroups in list(hostgroup_childgroups.items()): + list(map(lambda x: hostgroup_parentgroups[x].add(hostgroup), subgroups)) for i in hostgroups: i['child_hostgroups'] = hostgroup_childgroups[i['name']] @@ -530,11 +535,11 @@ def status_hostgroups(request): try: total = float(total) host['health'] = float(ok) / total * 100.0 - host['percent_ok'] = ok / total * 100 - host['percent_warn'] = warn / total * 100 - host['percent_crit'] = crit / total * 100 - host['percent_unknown'] = unknown / total * 100 - host['percent_pending'] = pending / total * 100 + host['percent_ok'] = old_div(ok, total) * 100 + host['percent_warn'] = old_div(warn, total) * 100 + host['percent_crit'] = old_div(crit, total) * 100 + host['percent_unknown'] = old_div(unknown, total) * 100 + host['percent_pending'] = old_div(pending, total) * 100 except ZeroDivisionError: host['health'] = 'n/a' # Extra statistics for our hostgroups @@ -551,11 +556,11 @@ def status_hostgroups(request): total = float(total) hg['health'] = float(ok) / total * 100.0 hg['health'] = float(ok) / total * 100.0 - hg['percent_ok'] = ok / total * 100 - hg['percent_warn'] = warn / total * 100 - hg['percent_crit'] = crit / total * 100 - hg['percent_unknown'] = unknown / total * 100 - hg['percent_pending'] = pending / total * 100 + hg['percent_ok'] = old_div(ok, total) * 100 + hg['percent_warn'] = old_div(warn, total) * 100 + hg['percent_crit'] = old_div(crit, total) * 100 + hg['percent_unknown'] = old_div(unknown, total) * 100 + hg['percent_pending'] = old_div(pending, total) * 100 except ZeroDivisionError: pass return render_to_response('status_hostgroups.html', c, context_instance=RequestContext(request)) @@ -631,11 +636,11 @@ def _add_statistics_to_hosts(hosts): try: total = float(total) host['health'] = float(ok) / total * 100.0 - host['percent_ok'] = ok / total * 100 - host['percent_warn'] = warn / total * 100 - host['percent_crit'] = crit / total * 100 - host['percent_unknown'] = unknown / total * 100 - host['percent_pending'] = pending / total * 100 + host['percent_ok'] = old_div(ok, total) * 100 + host['percent_warn'] = old_div(warn, total) * 100 + host['percent_crit'] = old_div(crit, total) * 100 + host['percent_unknown'] = old_div(unknown, total) * 100 + host['percent_pending'] = old_div(pending, total) * 100 except ZeroDivisionError: host['health'] = 'n/a' host['percent_ok'] = 0 @@ -667,7 +672,7 @@ def test_livestatus(request): columns = "" limit = request.GET.get('limit') run_query = False - for k, v in request.GET.items(): + for k, v in list(request.GET.items()): if k == "submit": run_query = True if k.startswith('check_'): @@ -681,7 +686,7 @@ def test_livestatus(request): if run_query is True: c['results'] = livestatus.query(*query) c['query'] = livestatus.last_query - c['header'] = c['results'][0].keys() + c['header'] = list(c['results'][0].keys()) return render_to_response('test_livestatus.html', c, context_instance=RequestContext(request)) @@ -743,12 +748,11 @@ def _status_combined(request, optimized=False): if service_totals == 0: c['service_status'] = 0 else: - c['service_status'] = map( - lambda x: 100 * x / service_totals, service_status) + c['service_status'] = [old_div(100 * x, service_totals) for x in service_status] if host_totals == 0: c['host_status'] = 0 else: - c['host_status'] = map(lambda x: 100 * x / host_totals, host_status) + c['host_status'] = [old_div(100 * x, host_totals) for x in host_status] return c @@ -832,7 +836,7 @@ def state_history(request): services[short_name]['log'].append(i) services[short_name]['worst_logfile_state'] = max( services[short_name]['worst_logfile_state'], i['state']) - for service in services.values(): + for service in list(services.values()): last_item = None service['sla'] = float(0) service['num_problems'] = 0 @@ -858,7 +862,7 @@ def state_history(request): last_item['end_time'] = end_time last_item['duration'] = duration = last_item[ 'end_time'] - last_item['time'] - last_item['duration_percent'] = 100 * duration / total_duration + last_item['duration_percent'] = old_div(100 * duration, total_duration) service['duration'] += last_item['duration_percent'] if last_item['state'] == 0: service['sla'] += last_item['duration_percent'] @@ -914,7 +918,7 @@ def _status_log(request): # Any querystring parameters we will treat as a search string to get_log_entries, but we need to massage them # a little bit first kwargs = {} - for k, v in request.GET.items(): + for k, v in list(request.GET.items()): if k == 'search': k = 'search' elif k in ( @@ -931,7 +935,7 @@ def _status_log(request): c['log'].reverse() c['logs'] = {'all': []} for line in c['log']: - if line['class_name'] not in c['logs'].keys(): + if line['class_name'] not in list(c['logs'].keys()): c['logs'][line['class_name']] = [] c['logs'][line['class_name']].append(line) c['logs']['all'].append(line) @@ -994,7 +998,7 @@ def perfdata(request): perfdata = utils.get_services(request, fields=fields, **request.GET) for i in perfdata: metrics = pynag.Utils.PerfData(i['perf_data']).metrics - metrics = filter(lambda x: x.is_valid(), metrics) + metrics = [x for x in metrics if x.is_valid()] i['metrics'] = metrics c['perfdata'] = perfdata @@ -1161,7 +1165,7 @@ def perfdata2(request): metric_set = set() for i in services: perfdata = pynag.Utils.PerfData(i.get('perf_data', '')) - map(lambda x: metric_set.add(x.label), perfdata.metrics) + list(map(lambda x: metric_set.add(x.label), perfdata.metrics)) interesting_metrics = sorted(list(metric_set)) else: interesting_metrics = interesting_metrics.split(',') @@ -1170,8 +1174,8 @@ def perfdata2(request): for service in services: perfdata = pynag.Utils.PerfData(service['perf_data']) null_metric = pynag.Utils.PerfDataMetric() - metrics = map(lambda x: perfdata.get_perfdatametric( - x) or null_metric, interesting_metrics) + metrics = [perfdata.get_perfdatametric( + x) or null_metric for x in interesting_metrics] #metrics = filter(lambda x: x.is_valid(), metrics) service['metrics'] = metrics @@ -1213,6 +1217,6 @@ def backends(request): """ Display a list of available backends and their connection status """ livestatus = adagios.status.utils.livestatus(request) backends = livestatus.get_backends() - for i, v in backends.items(): + for i, v in list(backends.items()): v.test(raise_error=False) return render_to_response('status_backends.html', locals(), context_instance=RequestContext(request)) diff --git a/adagios/userdata.py b/adagios/userdata.py index 85859bd45..d786a8374 100644 --- a/adagios/userdata.py +++ b/adagios/userdata.py @@ -17,11 +17,13 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . +from __future__ import absolute_import +from builtins import object import os import json import collections -import settings +from . import settings class User(object): @@ -46,7 +48,7 @@ def __init__(self, request, autosave=False): self._conffile = self._get_prefs_location() self._check_path(self._conffile) # sets the preferences as attributes: - for k, v in self._get_conf().iteritems(): + for k, v in self._get_conf().items(): self.__dict__[k] = v def _check_path(self, path): @@ -91,7 +93,7 @@ def _get_conf(self): def __getattr__(self, name): """ Provides None as a default value. """ - if name not in self.__dict__.keys(): + if name not in list(self.__dict__.keys()): return None return self.__dict__[name] @@ -107,7 +109,7 @@ def set_pref(self, name, value): def to_dict(self): d = {} - for k in filter(lambda x: not(x.startswith('_')), self.__dict__.keys()): + for k in [x for x in list(self.__dict__.keys()) if not(x.startswith('_'))]: d[k] = self.__dict__[k] return d diff --git a/adagios/utils.py b/adagios/utils.py index 296e42cc7..8de2f6844 100755 --- a/adagios/utils.py +++ b/adagios/utils.py @@ -17,6 +17,8 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . +from __future__ import print_function +from builtins import object import adagios.status.utils import adagios import pynag.Model @@ -32,7 +34,7 @@ def wait(object_type, WaitObject, WaitCondition, WaitTrigger, **kwargs): livestatus = adagios.status.utils.livestatus(None) livestatus.get(object_type, WaitObject=WaitObject, WaitCondition=WaitCondition, WaitTrigger=WaitTrigger, **kwargs) - print WaitObject + print(WaitObject) def wait_for_objects(object_type, object_list, condition=None, trigger='check'): if not condition: @@ -60,7 +62,7 @@ def __init__(self, num_processes=5): self._pool = ThreadPool(processes=num_processes) def add(self, function, *args, **kwargs): - print "Adding Task:", locals() + print("Adding Task:", locals()) result = self._pool.apply_async(function, args, kwargs) self._tasks.append(result) #print result.get() @@ -68,8 +70,8 @@ def add(self, function, *args, **kwargs): def status(self): all_tasks = self._tasks for i in all_tasks: - print i.ready() - completed_tasks = filter(lambda x: x.ready(), all_tasks) + print(i.ready()) + completed_tasks = [x for x in all_tasks if x.ready()] return "{done}/{total} done.".format(done=len(completed_tasks), total=len(all_tasks)) def get_id(self): @@ -77,7 +79,7 @@ def get_id(self): def ready(self): """ Returns True if all the Tasks in this class have finished running. """ - return max(map(lambda x: x.ready(), self._tasks)) + return max([x.ready() for x in self._tasks]) def update_eventhandlers(request): diff --git a/adagios/views.py b/adagios/views.py index a84dc3672..1e7a2f0ac 100644 --- a/adagios/views.py +++ b/adagios/views.py @@ -15,6 +15,7 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . +from builtins import str from django.http import HttpResponse import traceback from django.shortcuts import render_to_response, redirect @@ -45,7 +46,7 @@ def wrapper(request, *args, **kwargs): time_now = time.ctime() duration = end_time - start_time return result - except Exception, e: + except Exception as e: c = {} c['exception'] = str(e) c['exception_type'] = str(type(e).__name__) diff --git a/scripts/static_businessprocess.py b/scripts/static_businessprocess.py index 19ca94452..3aee43fd9 100644 --- a/scripts/static_businessprocess.py +++ b/scripts/static_businessprocess.py @@ -21,6 +21,7 @@ """ static_businessprocesses .. This script loads a business process and staticly writes html view for it """ +from __future__ import print_function #source_template = "/usr/lib/python2.6/site-packages/adagios/status/templates/business_process_view.html" source_template = "/etc/adagios/pages.d/bi_process.html" @@ -57,7 +58,7 @@ def verbose(message): if options.verbose: - print message + print(message) def businessprocess_to_html(process_name, process_type='businessprocess'): @@ -132,5 +133,5 @@ def bi_graphs_to_json(process_name, process_type='businessprocess'): parser.error("Either provide business process name or specify --all") for i in processlist: - print "doing ", i + print("doing ", i) businessprocess_to_html(i) diff --git a/setup.py b/setup.py index 7f59f0a05..0e19a4c65 100644 --- a/setup.py +++ b/setup.py @@ -17,8 +17,9 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . +from __future__ import absolute_import +from __future__ import print_function import os - from distutils.core import setup from distutils.command.build import build from distutils.sysconfig import get_python_lib @@ -43,11 +44,11 @@ def get_filelist(path): elif os.path.isdir(relative_path): directories_to_check.append(relative_path) else: - print "what am i?", i + print("what am i?", i) return files template_files = get_filelist('adagios') -data_files = map(lambda x: x.replace('adagios/', '', 1), template_files) +data_files = [x.replace('adagios/', '', 1) for x in template_files] class adagios_build(build): @@ -85,12 +86,12 @@ def run(self): setup(name=app_name, version=version, description='Web Based Nagios Configuration', - author='Pall Sigurdsson, Tomas Edwardsson', - author_email='palli@opensource.is', + author='Pall Sigurdsson, Tomas Edwardsson, Gardar Thorsteinsson', + author_email='support@opinkerfi.is', url='https://adagios.opensource.is/', packages=['adagios'], package_data={'adagios': data_files}, - install_requires=['django<1.9', 'pynag>0.9.1'], + install_requires=['django<1.9', 'pynag>0.9.1', 'future'], cmdclass=dict(build=adagios_build), )