Module: check_mk
Branch: master
Commit: 4d98b96e3ac0b9b6810d94e8568b184014785a29
URL: http://git.mathias-kettner.de/git/?p=check_mk.git;a=commit;h=4d98b96e3ac0b9…
Author: Lars Michelsen <lm(a)mathias-kettner.de>
Date: Mon Feb 19 09:08:09 2018 +0100
Moved gen_id() from lib to utils
Change-Id: I4cf33f39738cf13161eceaae2cd570fb3e7666e1
---
web/htdocs/lib.py | 11 -----------
web/htdocs/notify.py | 5 +++--
web/htdocs/userdb.py | 4 ++--
web/htdocs/utils.py | 13 +++++++++++++
web/htdocs/watolib.py | 4 ++--
web/htdocs/weblib.py | 6 +++---
6 files changed, 23 insertions(+), 20 deletions(-)
diff --git a/web/htdocs/lib.py b/web/htdocs/lib.py
index 1c0a2ff..13d4975 100644
--- a/web/htdocs/lib.py
+++ b/web/htdocs/lib.py
@@ -30,17 +30,6 @@ from cmk.regex import regex
import cmk.store as store
import cmk.paths
-# Generates a unique id
-def gen_id():
- try:
- return file('/proc/sys/kernel/random/uuid').read().strip()
- except IOError:
- # On platforms where the above file does not exist we try to
- # use the python uuid module which seems to be a good fallback
- # for those systems. Well, if got python < 2.5 you are lost for now.
- import uuid
- return str(uuid.uuid4())
-
# Load all files below share/check_mk/web/plugins/WHAT into a
# specified context (global variables). Also honors the
# local-hierarchy for OMD
diff --git a/web/htdocs/notify.py b/web/htdocs/notify.py
index 61f6199..73d95ea 100644
--- a/web/htdocs/notify.py
+++ b/web/htdocs/notify.py
@@ -24,7 +24,8 @@
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
-import config, forms, time, lib, userdb
+import utils
+import config, forms, time, userdb
import subprocess
from valuespec import *
import cmk.store as store
@@ -202,7 +203,7 @@ def _validate_msg(msg, varprefix):
raise MKUserError('dest', _('A user with the id "%s" does not exist.') % user_id)
def _process_notify_message(msg):
- msg['id'] = lib.gen_id()
+ msg['id'] = utils.gen_id()
msg['time'] = time.time()
# construct the list of recipients
diff --git a/web/htdocs/userdb.py b/web/htdocs/userdb.py
index 51175bb..699c3a4 100644
--- a/web/htdocs/userdb.py
+++ b/web/htdocs/userdb.py
@@ -444,7 +444,7 @@ def initialize_session(username):
# Creates a random session id for the user and returns it.
def create_session_id():
- return gen_id()
+ return utils.gen_id()
# Updates the current session of the user and returns the session_id or only
@@ -880,7 +880,7 @@ def rewrite_users():
def create_cmk_automation_user():
- secret = gen_id()
+ secret = utils.gen_id()
users = load_users(lock=True)
users["automation"] = {
diff --git a/web/htdocs/utils.py b/web/htdocs/utils.py
index 4eda962..c9efe6e 100644
--- a/web/htdocs/utils.py
+++ b/web/htdocs/utils.py
@@ -102,6 +102,7 @@ def saveint(x):
# Furthermore we filter out non-printable characters. The byte
# 0x00 for example does not make it through HTTP and the URL.
def get_random_string(size, from_ascii=48, to_ascii=90):
+ """Generate a random string (no cryptographic safety)"""
secret = ""
urandom = file("/dev/urandom")
while len(secret) < size:
@@ -109,3 +110,15 @@ def get_random_string(size, from_ascii=48, to_ascii=90):
if ord(c) >= from_ascii and ord(c) <= to_ascii:
secret += c
return secret
+
+
+def gen_id():
+ """Generates a unique id"""
+ try:
+ return file('/proc/sys/kernel/random/uuid').read().strip()
+ except IOError:
+ # On platforms where the above file does not exist we try to
+ # use the python uuid module which seems to be a good fallback
+ # for those systems. Well, if got python < 2.5 you are lost for now.
+ import uuid
+ return str(uuid.uuid4())
diff --git a/web/htdocs/watolib.py b/web/htdocs/watolib.py
index 3ea27e9..3b8c7a8 100644
--- a/web/htdocs/watolib.py
+++ b/web/htdocs/watolib.py
@@ -4839,7 +4839,7 @@ class ActivateChangesWriter(ActivateChanges):
def _new_change_id(self):
- return gen_id()
+ return utils.gen_id()
def _add_change_to_site(self, site_id, change_id, action_name, text, obj,
@@ -4994,7 +4994,7 @@ class ActivateChangesManager(ActivateChanges):
def _new_activation_id(self):
- return gen_id()
+ return utils.gen_id()
def _get_sites(self, sites):
diff --git a/web/htdocs/weblib.py b/web/htdocs/weblib.py
index 0491c24..53b9f9c 100644
--- a/web/htdocs/weblib.py
+++ b/web/htdocs/weblib.py
@@ -25,7 +25,7 @@
# Boston, MA 02110-1301 USA.
import config
-import lib
+import utils
import re
from gui_exceptions import MKUserError
@@ -79,14 +79,14 @@ def cleanup_old_selections():
# Generates a selection id or uses the given one
def selection_id():
if not html.has_var('selection'):
- sel_id = lib.gen_id()
+ sel_id = utils.gen_id()
html.set_var('selection', sel_id)
return sel_id
else:
sel_id = html.var('selection')
# Avoid illegal file access by introducing .. or /
if not re.match("^[-0-9a-zA-Z]+$", sel_id):
- new_id = lib.gen_id()
+ new_id = utils.gen_id()
html.set_var('selection', new_id)
return new_id
else:
Module: check_mk
Branch: master
Commit: 56e47ea3187954187a8fd59250a4ef1a10a91411
URL: http://git.mathias-kettner.de/git/?p=check_mk.git;a=commit;h=56e47ea3187954…
Author: Lars Michelsen <lm(a)mathias-kettner.de>
Date: Mon Feb 19 08:02:22 2018 +0100
Moved num_split() from lib to utils
Change-Id: I3dd5cdcdced4f73f9e7e6c7f6bfb869e25bbf9b3
---
web/htdocs/availability.py | 7 +++--
web/htdocs/lib.py | 15 ---------
web/htdocs/table.py | 6 ++--
web/htdocs/utils.py | 78 ++++++++++++++++++++++++++++++++++++++++++++++
web/htdocs/views.py | 5 ++-
web/htdocs/wato.py | 3 +-
6 files changed, 89 insertions(+), 25 deletions(-)
diff --git a/web/htdocs/availability.py b/web/htdocs/availability.py
index 057a9a1..9bce3d9 100644
--- a/web/htdocs/availability.py
+++ b/web/htdocs/availability.py
@@ -24,6 +24,7 @@
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
+import utils
import bi, views, visuals
import sites
# TODO: Get rid of import of views
@@ -1985,10 +1986,10 @@ def get_av_groups(availability_table, avoptions):
# Sort according to host and service. First after site, then
# host (natural sort), then service
def cmp_av_entry(a, b):
- return cmp(a["site"], b["site"]) or \
- cmp(num_split(a["host"]) + (a["host"],), num_split(b["host"]) + (b["host"],)) or \
+ return utils.cmp_num_split(a["site"], b["site"]) or \
+ utils.cmp_num_split(a["host"], b["host"]) or \
cmp(views.cmp_service_name_equiv(a["service"]), views.cmp_service_name_equiv(b["service"])) or \
- cmp(a["service"], b["service"])
+ utils.cmp_num_split(a["service"], b["service"])
def history_url_of(av_object, time_range):
diff --git a/web/htdocs/lib.py b/web/htdocs/lib.py
index 3c37a73..cb5c7d4 100644
--- a/web/htdocs/lib.py
+++ b/web/htdocs/lib.py
@@ -141,18 +141,3 @@ def tryint(x):
return int(x)
except:
return x
-
-
-# Splits a word into sequences of numbers and non-numbers.
-# Creates a tuple from these where the number are converted
-# into int datatype. That way a naturual sort can be
-# implemented.
-def num_split(s):
- parts = []
- for part in re.split('(\d+)', s):
- try:
- parts.append(int(part))
- except ValueError:
- parts.append(part)
-
- return tuple(parts)
diff --git a/web/htdocs/table.py b/web/htdocs/table.py
index 0d9e75a..a6abf10 100644
--- a/web/htdocs/table.py
+++ b/web/htdocs/table.py
@@ -27,8 +27,8 @@
import re
from contextlib import contextmanager
+import utils
import config
-from lib import num_split
tables = []
@@ -521,8 +521,8 @@ def _sort_rows(rows, sort_col, sort_reverse):
# sorting. This gives the user the chance to change the sorting and
# see the table in the first place.
try:
- rows.sort(cmp=lambda a, b: cmp(num_split(a[0][sort_col][0]),
- num_split(b[0][sort_col][0])),
+ rows.sort(cmp=lambda a, b: utils.cmp_num_split(a[0][sort_col][0],
+ b[0][sort_col][0]),
reverse=sort_reverse==1)
except IndexError:
pass
diff --git a/web/htdocs/utils.py b/web/htdocs/utils.py
new file mode 100644
index 0000000..55adb65
--- /dev/null
+++ b/web/htdocs/utils.py
@@ -0,0 +1,78 @@
+#!/usr/bin/python
+# -*- encoding: utf-8; py-indent-offset: 4 -*-
+# +------------------------------------------------------------------+
+# | ____ _ _ __ __ _ __ |
+# | / ___| |__ ___ ___| | __ | \/ | |/ / |
+# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
+# | | |___| | | | __/ (__| < | | | | . \ |
+# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
+# | |
+# | Copyright Mathias Kettner 2014 mk(a)mathias-kettner.de |
+# +------------------------------------------------------------------+
+#
+# This file is part of Check_MK.
+# The official homepage is at http://mathias-kettner.de/check_mk.
+#
+# check_mk is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation in version 2. check_mk is distributed
+# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
+# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
+# PARTICULAR PURPOSE. See the GNU General Public License for more de-
+# tails. You should have received a copy of the GNU General Public
+# License along with GNU Make; see the file COPYING. If not, write
+# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
+# Boston, MA 02110-1301 USA.
+
+"""This is an unsorted collection of small unrelated helper functions which are
+usable in all components of the Web GUI of Check_MK
+
+Please try to find a better place for the things you want to put here."""
+
+import re
+
+
+def drop_dotzero(v, digits=2):
+ """Renders a number as a floating point number and drops useless
+ zeroes at the end of the fraction
+
+ 45.1 -> "45.1"
+ 45.0 -> "45"
+ """
+ t = "%%.%df" % digits % v
+ if "." in t:
+ return t.rstrip("0").rstrip(".")
+ else:
+ return t
+
+
+def num_split(s):
+ """Splits a word into sequences of numbers and non-numbers.
+
+ Creates a tuple from these where the number are converted into int datatype.
+ That way a naturual sort can be implemented.
+ """
+ parts = []
+ for part in re.split('(\d+)', s):
+ try:
+ parts.append(int(part))
+ except ValueError:
+ parts.append(part)
+
+ return tuple(parts)
+
+
+def cmp_num_split(a, b):
+ """Compare two strings, separate numbers and non-numbers from before."""
+ return cmp(num_split(a), num_split(b))
+
+
+def cmp_version(a, b):
+ """Compare two version numbers with each other
+ Allow numeric version numbers, but also characters.
+ """
+ if a == None or b == None:
+ return cmp(a, b)
+ aa = map(num_split, a.split("."))
+ bb = map(num_split, b.split("."))
+ return cmp(aa, bb)
diff --git a/web/htdocs/views.py b/web/htdocs/views.py
index 415f496..259ff52 100644
--- a/web/htdocs/views.py
+++ b/web/htdocs/views.py
@@ -24,6 +24,7 @@
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
+import utils
import config, time, os, re, pprint
import weblib, traceback, forms, valuespec, inventory, visuals, metrics
import sites
@@ -3038,9 +3039,7 @@ def cmp_simple_string(column, r1, r2):
return cmp_insensitive_string(v1, v2)
def cmp_num_split(column, r1, r2):
- c1 = num_split(r1[column].lower())
- c2 = num_split(r2[column].lower())
- return cmp(c1, c2)
+ return utils.cmp_num_split(r1[column].lower(), r2[column].lower())
def cmp_string_list(column, r1, r2):
v1 = ''.join(r1.get(column, []))
diff --git a/web/htdocs/wato.py b/web/htdocs/wato.py
index f07c51e..405d986 100644
--- a/web/htdocs/wato.py
+++ b/web/htdocs/wato.py
@@ -101,6 +101,7 @@ import time
import traceback
from hashlib import sha256
+import utils
import i18n
import config
import table
@@ -811,7 +812,7 @@ class ModeFolder(WatoMode):
show_checkboxes = html.var('show_checkboxes', '0') == '1'
hostnames = self._folder.hosts().keys()
- hostnames.sort(cmp = lambda a, b: cmp(num_split(a), num_split(b)))
+ hostnames.sort(cmp=utils.cmp_num_split)
search_text = html.var("search")
# Helper function for showing bulk actions. This is needed at the bottom
Module: check_mk
Branch: master
Commit: da4e27637bc58c3934eec08268b71dbcda2a5aa0
URL: http://git.mathias-kettner.de/git/?p=check_mk.git;a=commit;h=da4e27637bc58c…
Author: Lars Michelsen <lm(a)mathias-kettner.de>
Date: Mon Feb 19 09:05:45 2018 +0100
Moved get_random_string() from lib to utils
Change-Id: I6955b8432c42c65f1fceb20221764bdb63dd3fbc
---
web/htdocs/lib.py | 14 --------------
web/htdocs/login.py | 3 ++-
web/htdocs/utils.py | 15 +++++++++++++++
web/htdocs/watolib.py | 3 ++-
4 files changed, 19 insertions(+), 16 deletions(-)
diff --git a/web/htdocs/lib.py b/web/htdocs/lib.py
index c264eee..1c0a2ff 100644
--- a/web/htdocs/lib.py
+++ b/web/htdocs/lib.py
@@ -30,20 +30,6 @@ from cmk.regex import regex
import cmk.store as store
import cmk.paths
-# We should use /dev/random here for cryptographic safety. But
-# that involves the great problem that the system might hang
-# because of loss of entropy. So we hope /dev/urandom is enough.
-# Furthermore we filter out non-printable characters. The byte
-# 0x00 for example does not make it through HTTP and the URL.
-def get_random_string(size, from_ascii=48, to_ascii=90):
- secret = ""
- urandom = file("/dev/urandom")
- while len(secret) < size:
- c = urandom.read(1)
- if ord(c) >= from_ascii and ord(c) <= to_ascii:
- secret += c
- return secret
-
# Generates a unique id
def gen_id():
try:
diff --git a/web/htdocs/login.py b/web/htdocs/login.py
index 7c4c323..383002e 100644
--- a/web/htdocs/login.py
+++ b/web/htdocs/login.py
@@ -26,6 +26,7 @@
import config
import userdb
+import utils
from lib import *
from log import logger
from html_mod_python import FinalizeRequest
@@ -105,7 +106,7 @@ def load_secret():
return secret
def generate_secret():
- return get_random_string(256)
+ return utils.get_random_string(256)
# Load the password serial of the user. This serial identifies the current config
# state of the user account. If either the password is changed or the account gets
diff --git a/web/htdocs/utils.py b/web/htdocs/utils.py
index 40c3119..4eda962 100644
--- a/web/htdocs/utils.py
+++ b/web/htdocs/utils.py
@@ -94,3 +94,18 @@ def saveint(x):
return int(x)
except:
return 0
+
+
+# We should use /dev/random here for cryptographic safety. But
+# that involves the great problem that the system might hang
+# because of loss of entropy. So we hope /dev/urandom is enough.
+# Furthermore we filter out non-printable characters. The byte
+# 0x00 for example does not make it through HTTP and the URL.
+def get_random_string(size, from_ascii=48, to_ascii=90):
+ secret = ""
+ urandom = file("/dev/urandom")
+ while len(secret) < size:
+ c = urandom.read(1)
+ if ord(c) >= from_ascii and ord(c) <= to_ascii:
+ secret += c
+ return secret
diff --git a/web/htdocs/watolib.py b/web/htdocs/watolib.py
index 528fed8..3ea27e9 100644
--- a/web/htdocs/watolib.py
+++ b/web/htdocs/watolib.py
@@ -42,6 +42,7 @@
# | Doing this that must be done when the module WATO is loaded. |
# '----------------------------------------------------------------------'
+import utils
import os, shutil, subprocess, base64, pickle, pwd
import glob
import traceback
@@ -4068,7 +4069,7 @@ def get_login_secret(create_on_demand = False):
if not create_on_demand:
return None
- secret = get_random_string(32)
+ secret = utils.get_random_string(32)
store.save_data_to_file(path, secret)
return secret