2 # Module that parses constraints
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.
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.
14 # Once https://bugs.launchpad.net/juju/+bug/1645402 is addressed, this
15 # module should be deprecated.
20 # Matches on a string specifying memory size
21 MEM
= re
.compile('^[1-9][0-9]*[MGTP]$')
23 # Multiplication factors to get Megabytes
28 "P": 1024 * 1024 * 1024
31 def parse(constraints
):
33 Constraints must be expressed as a string containing only spaces
34 and key value pairs joined by an '='.
37 if constraints
is None:
40 if type(constraints
) is dict:
41 # Fowards compatibilty: already parsed
45 normalize_key(k
): normalize_value(v
) for k
, v
in [
46 s
.split("=") for s
in constraints
.split(" ")]}
51 def normalize_key(key
):
54 key
= key
.replace("-", "_") # Our _client lib wants "_" in place of "-"
58 def normalize_value(value
):
62 # Translate aliases to Megabytes. e.g. 1G = 10240
63 return int(value
[:-1]) * FACTORS
[value
[-1:]]
67 values
= value
.split(",")
68 values
= [normalize_value(v
) for v
in values
]