Completed
Pull Request — master (#106)
by Marc-Alexandre
58s
created

smartdispatch.detect_cluster()   C

Complexity

Conditions 7

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 7
dl 0
loc 22
rs 5.7894
1
from __future__ import print_function
2
3
import re
4
import binascii
5
import hashlib
6
import unicodedata
7
import json
8
9
from distutils.util import strtobool
10
from subprocess import Popen, PIPE
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 range(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.encode()).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
    # Convert `value` to Unicode so we can slugify it using the unicodedata module.
61
    try:
62
        value = unicode(value, "UTF-8")
63
    except NameError:
64
        pass  # In Python 3, all strings are already stored as Unicode.
65
66
    # Replace all compatibility characters with their equivalents.
67
    value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
68
    value = re.sub('[^\w\s-]', '', value).strip().lower()
69
    return str(re.sub('[-\s]+', '_', value))
70
71
72
def encode_escaped_characters(text, escaping_character="\\"):
73
    """ Escape the escaped character using its hex representation """
74
    def hexify(match):
75
        # Reference: http://stackoverflow.com/questions/18298251/python-hex-values-to-convert-to-a-string-integer
76
        return "\\x" + binascii.hexlify(match.group()[-1].encode()).decode()
77
78
    return re.sub(r"\\.", hexify, text)
79
80
81
def decode_escaped_characters(text):
82
    """ Convert hex representation to the character it represents """
83
    if len(text) == 0:
84
        return ''
85
86
    def unhexify(match):
87
        return binascii.unhexlify(match.group()[2:]).decode()
88
89
    return re.sub(r"\\x..", unhexify, text)
90
91
92
def save_dict_to_json_file(path, dictionary):
93
    with open(path, "w") as json_file:
94
        json_file.write(json.dumps(dictionary, indent=4, separators=(',', ': ')))
95
96
97
def load_dict_from_json_file(path):
98
    with open(path, "r") as json_file:
99
        return json.loads(json_file.read())
100
101
102
def detect_cluster():
103
    # Get server status
104
    try:
105
        output = Popen(["qstat", "-B"], stdout=PIPE).communicate()[0]
106
        if isinstance(output, bytes):
107
            output = output.decode("utf-8")
108
    except OSError:
109
        # If qstat is not available we assume that the cluster is unknown.
110
        return None
111
    # Get server name from status
112
    server_name = output.split('\n')[2].split(' ')[0]
113
    # Cleanup the name and return it
114
    cluster_name = None
115
    if server_name.split('.')[-1] == 'm':
116
        cluster_name = "mammouth"
117
    elif server_name.split('.')[-1] == 'guil':
118
        cluster_name = "guillimin"
119
    elif server_name.split('.')[-1] == 'helios':
120
        cluster_name = "helios"
121
    elif server_name.split('.')[-1] == 'hades':
122
        cluster_name = "hades"
123
    return cluster_name
124
125
126
def get_launcher(cluster_name):
127
    if cluster_name == "helios":
128
        return "msub"
129
    else:
130
        return "qsub"
131