Added deprecation notice, and a bit of forwards compatibilty.
[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 # Once https://bugs.launchpad.net/juju/+bug/1645402 is addressed, this
15 # module should be deprecated.
16 #
17
18 import re
19
20 # Matches on a string specifying memory size
21 MEM = re.compile('^[1-9][0-9]*[MGTP]$')
22
23 # Multiplication factors to get Megabytes
24 FACTORS = {
25 "M": 1,
26 "G": 1024,
27 "T": 1024 * 1024,
28 "P": 1024 * 1024 * 1024
29 }
30
31 def parse(constraints):
32 """
33 Constraints must be expressed as a string containing only spaces
34 and key value pairs joined by an '='.
35
36 """
37 if constraints is None:
38 return None
39
40 if type(constraints) is dict:
41 # Fowards compatibilty: already parsed
42 return constraints
43
44 constraints = {
45 normalize_key(k): normalize_value(v) for k, v in [
46 s.split("=") for s in constraints.split(" ")]}
47
48 return constraints
49
50
51 def normalize_key(key):
52 key = key.strip()
53
54 key = key.replace("-", "_") # Our _client lib wants "_" in place of "-"
55 return key
56
57
58 def normalize_value(value):
59 value = value.strip()
60
61 if MEM.match(value):
62 # Translate aliases to Megabytes. e.g. 1G = 10240
63 return int(value[:-1]) * FACTORS[value[-1:]]
64
65 if "," in value:
66 # Handle csv strings.
67 values = value.split(",")
68 values = [normalize_value(v) for v in values]
69 return values
70
71 return value