Completed
Push — master ( f2bf85...6cd35a )
by Marc-Alexandre
56s
created

smartdispatch.detect_cluster()   B

Complexity

Conditions 5

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 5
dl 0
loc 20
rs 8.5454
1
import re
2
import fcntl
3
import logging
4
import hashlib
5
import unicodedata
6
import json
7
8
from distutils.util import strtobool
9
from subprocess import Popen, PIPE
10
from contextlib import contextmanager
11
12
13
def print_boxed(string):
14
    splitted_string = string.split('\n')
15
    max_len = max(map(len, splitted_string))
16
    box_line = u"\u2500" * (max_len + 2)
17
18
    out = u"\u250c" + box_line + u"\u2510\n"
19
    out += '\n'.join([u"\u2502 {} \u2502".format(line.ljust(max_len)) for line in splitted_string])
20
    out += u"\n\u2514" + box_line + u"\u2518"
21
    print out
22
23
24
def yes_no_prompt(query, default=None):
25
    available_prompts = {None: " [y/n] ", 'y': " [Y/n] ", 'n': " [y/N] "}
26
27
    if default not in available_prompts:
28
        raise ValueError("Invalid default: '{}'".format(default))
29
30
    while True:
31
        try:
32
            answer = raw_input("{0}{1}".format(query, available_prompts[default]))
33
            return strtobool(answer)
34
        except ValueError:
35
            if answer == '' and default is not None:
36
                return strtobool(default)
37
38
39
def chunks(sequence, n):
40
    """ Yield successive n-sized chunks from sequence. """
41
    for i in xrange(0, len(sequence), n):
42
        yield sequence[i:i + n]
43
44
45
def generate_uid_from_string(value):
46
    """ Create unique identifier from a string. """
47
    return hashlib.sha256(value).hexdigest()
48
49
50
def slugify(value):
51
    """
52
    Converts to lowercase, removes non-word characters (alphanumerics and
53
    underscores) and converts spaces to underscores. Also strips leading and
54
    trailing whitespace.
55
56
    Reference
57
    ---------
58
    https://github.com/django/django/blob/1.7c3/django/utils/text.py#L436
59
    """
60
    value = unicodedata.normalize('NFKD', unicode(value, "UTF-8")).encode('ascii', 'ignore').decode('ascii')
61
    value = re.sub('[^\w\s-]', '', value).strip().lower()
62
    return str(re.sub('[-\s]+', '_', value))
63
64
65
def encode_escaped_characters(text, escaping_character="\\"):
66
    """ Escape the escaped character using its hex representation """
67
    def hexify(match):
68
        return "\\x{0}".format(match.group()[-1].encode("hex"))
69
70
    return re.sub(r"\\.", hexify, text)
71
72
73
def decode_escaped_characters(text):
74
    """ Convert hex representation to the character it represents """
75
    if len(text) == 0:
76
        return ''
77
78
    def unhexify(match):
79
        return match.group()[2:].decode("hex")
80
81
    return re.sub(r"\\x..", unhexify, text)
82
83
84
@contextmanager
85
def open_with_lock(*args, **kwargs):
86
    """ Context manager for opening file with an exclusive lock. """
87
    f = open(*args, **kwargs)
88
    try:
89
        fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
90
    except IOError:
91
        logging.info("Can't immediately write-lock the file ({0}), blocking ...".format(f.name))
92
        fcntl.lockf(f, fcntl.LOCK_EX)
93
    yield f
94
    fcntl.lockf(f, fcntl.LOCK_UN)
95
    f.close()
96
97
98
def save_dict_to_json_file(path, dictionary):
99
    with open(path, "w") as json_file:
100
        json_file.write(json.dumps(dictionary, indent=4, separators=(',', ': ')))
101
102
103
def load_dict_from_json_file(path):
104
    with open(path, "r") as json_file:
105
        return json.loads(json_file.read())
106
107
108
def detect_cluster():
109
    # Get server status
110
    try:
111
        output = Popen(["qstat", "-B"], stdout=PIPE).communicate()[0]
112
    except OSError:
113
        # If qstat is not available we assume that the cluster is unknown.
114
        return None
115
    # Get server name from status
116
    server_name = output.split('\n')[2].split(' ')[0]
117
    # Cleanup the name and return it
118
    cluster_name = None
119
    if server_name.split('.')[-1] == 'm':
120
        cluster_name = "mammouth"
121
    elif server_name.split('.')[-1] == 'guil':
122
        cluster_name = "guillimin"
123
    elif server_name.split('.')[-1] == 'helios':
124
        cluster_name = "helios"
125
    elif server_name.split('.')[-1] == 'hades':
126
        cluster_name = "hades"
127
    return cluster_name
128
129
130
def get_launcher(cluster_name):
131
    if cluster_name == "helios":
132
        return "msub"
133
    else:
134
        return "qsub"
135