452754e3f960f0ce32f7151cc9423bd99ef32e76
15 from juju
.errors
import JujuAPIError
17 log
= logging
.getLogger("websocket")
24 # Connect to an arbitrary api server
25 client = await Connection.connect(
26 api_endpoint, model_uuid, username, password, cacert)
28 # Connect using a controller/model name
29 client = await Connection.connect_model('local.local:default')
31 # Connect to the currently active model
32 client = await Connection.connect_current()
36 self
, endpoint
, uuid
, username
, password
, cacert
=None,
38 self
.endpoint
= endpoint
40 self
.username
= username
41 self
.password
= password
42 self
.macaroons
= macaroons
45 self
.__request
_id
__ = 0
56 def _get_ssl(self
, cert
=None):
57 return ssl
.create_default_context(
58 purpose
=ssl
.Purpose
.CLIENT_AUTH
, cadata
=cert
)
62 url
= "wss://{}/model/{}/api".format(self
.endpoint
, self
.uuid
)
64 url
= "wss://{}/api".format(self
.endpoint
)
67 kw
['ssl'] = self
._get
_ssl
(self
.cacert
)
69 self
.ws
= await websockets
.connect(url
, **kw
)
70 log
.info("Driver connected to juju %s", url
)
73 async def close(self
):
77 result
= await self
.ws
.recv()
78 if result
is not None:
79 result
= json
.loads(result
)
82 async def rpc(self
, msg
, encoder
=None):
83 self
.__request
_id
__ += 1
84 msg
['request-id'] = self
.__request
_id
__
85 if'params' not in msg
:
87 if "version" not in msg
:
88 msg
['version'] = self
.facades
[msg
['type']]
89 outgoing
= json
.dumps(msg
, indent
=2, cls
=encoder
)
90 await self
.ws
.send(outgoing
)
91 result
= await self
.recv()
92 if result
and 'error' in result
:
93 raise JujuAPIError(result
)
96 async def clone(self
):
97 """Return a new Connection, connected to the same websocket endpoint
101 return await Connection
.connect(
110 async def controller(self
):
111 """Return a Connection to the controller at self.endpoint
114 return await Connection
.connect(
125 cls
, endpoint
, uuid
, username
, password
, cacert
=None,
127 """Connect to the websocket.
129 If uuid is None, the connection will be to the controller. Otherwise it
130 will be to the model.
133 client
= cls(endpoint
, uuid
, username
, password
, cacert
, macaroons
)
136 redirect_info
= await client
.redirect_info()
137 if not redirect_info
:
138 await client
.login(username
, password
, macaroons
)
143 s
for servers
in redirect_info
['servers']
144 for s
in servers
if s
["scope"] == 'public'
146 for server
in servers
:
148 "{value}:{port}".format(**server
), uuid
, username
,
149 password
, redirect_info
['ca-cert'], macaroons
)
152 result
= await client
.login(username
, password
, macaroons
)
153 if 'discharge-required-error' in result
:
156 except Exception as e
:
161 "Couldn't authenticate to %s", endpoint
)
164 async def connect_current(cls
):
165 """Connect to the currently active model.
168 jujudata
= JujuData()
169 controller_name
= jujudata
.current_controller()
170 models
= jujudata
.models()[controller_name
]
171 model_name
= models
['current-model']
173 return await cls
.connect_model(
174 '{}:{}'.format(controller_name
, model_name
))
177 async def connect_current_controller(cls
):
178 """Connect to the currently active controller.
181 jujudata
= JujuData()
182 controller_name
= jujudata
.current_controller()
184 return await cls
.connect_controller(controller_name
)
187 async def connect_controller(cls
, controller_name
):
188 """Connect to a controller by name.
191 jujudata
= JujuData()
192 controller
= jujudata
.controllers()[controller_name
]
193 endpoint
= controller
['api-endpoints'][0]
194 cacert
= controller
.get('ca-cert')
195 accounts
= jujudata
.accounts()[controller_name
]
196 username
= accounts
['user']
197 password
= accounts
.get('password')
198 macaroons
= get_macaroons() if not password
else None
200 return await cls
.connect(
201 endpoint
, None, username
, password
, cacert
, macaroons
)
204 async def connect_model(cls
, model
):
205 """Connect to a model by name.
207 :param str model: <controller>:<model>
210 controller_name
, model_name
= model
.split(':')
212 jujudata
= JujuData()
213 controller
= jujudata
.controllers()[controller_name
]
214 endpoint
= controller
['api-endpoints'][0]
215 cacert
= controller
.get('ca-cert')
216 accounts
= jujudata
.accounts()[controller_name
]
217 username
= accounts
['user']
218 password
= accounts
.get('password')
219 models
= jujudata
.models()[controller_name
]
220 model_uuid
= models
['models'][model_name
]['uuid']
221 macaroons
= get_macaroons() if not password
else None
223 return await cls
.connect(
224 endpoint
, model_uuid
, username
, password
, cacert
, macaroons
)
226 def build_facades(self
, info
):
229 self
.facades
[facade
['name']] = facade
['versions'][-1]
231 async def login(self
, username
, password
, macaroons
=None):
236 if username
and not username
.startswith('user-'):
237 username
= 'user-{}'.format(username
)
239 result
= await self
.rpc({
244 "auth-tag": username
,
245 "credentials": password
,
246 "nonce": "".join(random
.sample(string
.printable
, 12)),
247 "macaroons": macaroons
or []
249 response
= result
['response']
250 self
.build_facades(response
.get('facades', {}))
251 self
.info
= response
.copy()
254 async def redirect_info(self
):
256 result
= await self
.rpc({
258 "request": "RedirectInfo",
261 except JujuAPIError
as e
:
262 if e
.message
== 'not redirected':
265 return result
['response']
270 self
.path
= os
.environ
.get('JUJU_DATA') or '~/.local/share/juju'
271 self
.path
= os
.path
.abspath(os
.path
.expanduser(self
.path
))
273 def current_controller(self
):
274 cmd
= shlex
.split('juju show-controller --format yaml')
275 output
= subprocess
.check_output(cmd
)
276 output
= yaml
.safe_load(output
)
277 return list(output
.keys())[0]
279 def controllers(self
):
280 return self
._load
_yaml
('controllers.yaml', 'controllers')
283 return self
._load
_yaml
('models.yaml', 'controllers')
286 return self
._load
_yaml
('accounts.yaml', 'controllers')
288 def _load_yaml(self
, filename
, key
):
289 filepath
= os
.path
.join(self
.path
, filename
)
290 with io
.open(filepath
, 'rt') as f
:
291 return yaml
.safe_load(f
)[key
]
295 """Decode and return macaroons from default ~/.go-cookies
299 cookie_file
= os
.path
.expanduser('~/.go-cookies')
300 with
open(cookie_file
, 'r') as f
:
301 cookies
= json
.load(f
)
302 except (OSError, ValueError) as e
:
303 log
.warn("Couldn't load macaroons from %s", cookie_file
)
307 c
['Value'] for c
in cookies
308 if c
['Name'].startswith('macaroon-') and c
['Value']
312 json
.loads(base64
.b64decode(value
).decode('utf-8'))
313 for value
in base64_macaroons