43a80a358e16e662b1ee16f042b70cb18c06cf4d
[osm/N2VC.git] / juju / constraints.py
1 #
2 # Module that parses constraints
3 #
4 # The current version of juju core expects the client to take
5 # constraints given in the form "mem=10G foo=bar" and parse them into
6 # json that looks like {"mem": 10240, "foo": "bar"}. This module helps us
7 # accomplish that task.
8 #
9 # We do not attempt to duplicate the checking done in
10 # client/_client.py:Value here. That class will verify that the
11 # constraints keys are valid, and that we can successfully dump the
12 # constraints dict to json.
13 #
14
15 import re
16
17 # Matches on a string specifying memory size
18 MEM = re.compile('^[1-9][0-9]*[MGTP]$')
19
20 # Multiplication factors to get Megabytes
21 FACTORS = {
22 "M": 1,
23 "G": 1024,
24 "T": 1024 * 1024,
25 "P": 1024 * 1024 * 1024
26 }
27
28 def parse(constraints):
29 """
30 Constraints must be expressed as a string containing only spaces
31 and key value pairs joined by an '='.
32
33 """
34 if constraints is None:
35 return None
36
37 constraints = {
38 normalize_key(k): normalize_value(v) for k, v in [
39 s.split("=") for s in constraints.split(" ")]}
40
41 return constraints
42
43
44 def normalize_key(key):
45 key = key.strip()
46
47 key = key.replace("-", "_") # Our _client lib wants "_" in place of "-"
48 return key
49
50
51 def normalize_value(value):
52 value = value.strip()
53
54 if MEM.match(value):
55 # Translate aliases to Megabytes. e.g. 1G = 10240
56 return int(value[:-1]) * FACTORS[value[-1:]]
57
58 if "," in value:
59 # Handle csv strings.
60 values = value.split(",")
61 values = [normalize_value(v) for v in values]
62 return values
63
64 return value