12 from http
.client
import HTTPSConnection
18 from juju
.errors
import JujuError
, JujuAPIError
, JujuConnectionError
19 from juju
.utils
import IdQueue
21 log
= logging
.getLogger("websocket")
28 # Connect to an arbitrary api server
29 client = await Connection.connect(
30 api_endpoint, model_uuid, username, password, cacert)
32 # Connect using a controller/model name
33 client = await Connection.connect_model('local.local:default')
35 # Connect to the currently active model
36 client = await Connection.connect_current()
38 Note: Any connection method or constructor can accept an optional `loop`
39 argument to override the default event loop from `asyncio.get_event_loop`.
42 self
, endpoint
, uuid
, username
, password
, cacert
=None,
43 macaroons
=None, loop
=None):
44 self
.endpoint
= endpoint
46 self
.username
= username
47 self
.password
= password
48 self
.macaroons
= macaroons
50 self
.loop
= loop
or asyncio
.get_event_loop()
52 self
.__request
_id
__ = 0
56 self
.messages
= IdQueue(loop
=self
.loop
)
64 def _get_ssl(self
, cert
=None):
65 return ssl
.create_default_context(
66 purpose
=ssl
.Purpose
.CLIENT_AUTH
, cadata
=cert
)
70 url
= "wss://{}/model/{}/api".format(self
.endpoint
, self
.uuid
)
72 url
= "wss://{}/api".format(self
.endpoint
)
75 kw
['ssl'] = self
._get
_ssl
(self
.cacert
)
76 kw
['loop'] = self
.loop
78 self
.ws
= await websockets
.connect(url
, **kw
)
79 self
.loop
.create_task(self
.receiver())
80 log
.info("Driver connected to juju %s", url
)
83 async def close(self
):
86 async def recv(self
, request_id
):
87 return await self
.messages
.get(request_id
)
89 async def receiver(self
):
91 result
= await self
.ws
.recv()
92 if result
is not None:
93 result
= json
.loads(result
)
94 await self
.messages
.put(result
['request-id'], result
)
96 async def rpc(self
, msg
, encoder
=None):
97 self
.__request
_id
__ += 1
98 msg
['request-id'] = self
.__request
_id
__
99 if'params' not in msg
:
101 if "version" not in msg
:
102 msg
['version'] = self
.facades
[msg
['type']]
103 outgoing
= json
.dumps(msg
, indent
=2, cls
=encoder
)
104 await self
.ws
.send(outgoing
)
105 result
= await self
.recv(msg
['request-id'])
110 if 'error' in result
:
112 raise JujuAPIError(result
)
114 if not 'response' in result
:
115 # This may never happen
118 if 'results' in result
['response']:
119 # Check for errors in a result list.
121 for res
in result
['response']['results']:
122 if res
.get('error', {}).get('message'):
123 errors
.append(res
['error']['message'])
125 raise JujuError(errors
)
127 elif result
['response'].get('error', {}).get('message'):
128 raise JujuError(result
['response']['error']['message'])
132 def http_headers(self
):
133 """Return dictionary of http headers necessary for making an http
134 connection to the endpoint of this Connection.
136 :return: Dictionary of headers
139 if not self
.username
:
142 creds
= u
'{}:{}'.format(
143 tag
.user(self
.username
),
146 token
= base64
.b64encode(creds
.encode())
148 'Authorization': 'Basic {}'.format(token
.decode())
151 def https_connection(self
):
152 """Return an https connection to this Connection's endpoint.
154 Returns a 3-tuple containing::
156 1. The :class:`HTTPSConnection` instance
157 2. Dictionary of auth headers to be used with the connection
158 3. The root url path (str) to be used for requests.
161 endpoint
= self
.endpoint
162 host
, remainder
= endpoint
.split(':', 1)
165 port
, _
= remainder
.split('/', 1)
167 conn
= HTTPSConnection(
169 context
=self
._get
_ssl
(self
.cacert
),
173 "/model/{}".format(self
.uuid
)
176 return conn
, self
.http_headers(), path
178 async def clone(self
):
179 """Return a new Connection, connected to the same websocket endpoint
183 return await Connection
.connect(
193 async def controller(self
):
194 """Return a Connection to the controller at self.endpoint
197 return await Connection
.connect(
209 cls
, endpoint
, uuid
, username
, password
, cacert
=None,
210 macaroons
=None, loop
=None):
211 """Connect to the websocket.
213 If uuid is None, the connection will be to the controller. Otherwise it
214 will be to the model.
217 client
= cls(endpoint
, uuid
, username
, password
, cacert
, macaroons
,
221 redirect_info
= await client
.redirect_info()
222 if not redirect_info
:
223 await client
.login(username
, password
, macaroons
)
228 s
for servers
in redirect_info
['servers']
229 for s
in servers
if s
["scope"] == 'public'
231 for server
in servers
:
233 "{value}:{port}".format(**server
), uuid
, username
,
234 password
, redirect_info
['ca-cert'], macaroons
)
237 result
= await client
.login(username
, password
, macaroons
)
238 if 'discharge-required-error' in result
:
241 except Exception as e
:
246 "Couldn't authenticate to %s", endpoint
)
249 async def connect_current(cls
, loop
=None):
250 """Connect to the currently active model.
253 jujudata
= JujuData()
254 controller_name
= jujudata
.current_controller()
255 model_name
= jujudata
.current_model()
257 return await cls
.connect_model(
258 '{}:{}'.format(controller_name
, model_name
), loop
)
261 async def connect_current_controller(cls
, loop
=None):
262 """Connect to the currently active controller.
265 jujudata
= JujuData()
266 controller_name
= jujudata
.current_controller()
267 if not controller_name
:
268 raise JujuConnectionError('No current controller')
270 return await cls
.connect_controller(controller_name
, loop
)
273 async def connect_controller(cls
, controller_name
, loop
=None):
274 """Connect to a controller by name.
277 jujudata
= JujuData()
278 controller
= jujudata
.controllers()[controller_name
]
279 endpoint
= controller
['api-endpoints'][0]
280 cacert
= controller
.get('ca-cert')
281 accounts
= jujudata
.accounts()[controller_name
]
282 username
= accounts
['user']
283 password
= accounts
.get('password')
284 macaroons
= get_macaroons() if not password
else None
286 return await cls
.connect(
287 endpoint
, None, username
, password
, cacert
, macaroons
, loop
)
290 async def connect_model(cls
, model
, loop
=None):
291 """Connect to a model by name.
293 :param str model: [<controller>:]<model>
296 jujudata
= JujuData()
299 # explicit controller given
300 controller_name
, model_name
= model
.split(':')
302 # use the current controller if one isn't explicitly given
303 controller_name
= jujudata
.current_controller()
306 accounts
= jujudata
.accounts()[controller_name
]
307 username
= accounts
['user']
308 # model name must include a user prefix, so add it if it doesn't
309 if '/' not in model_name
:
310 model_name
= '{}/{}'.format(username
, model_name
)
312 controller
= jujudata
.controllers()[controller_name
]
313 endpoint
= controller
['api-endpoints'][0]
314 cacert
= controller
.get('ca-cert')
315 password
= accounts
.get('password')
316 models
= jujudata
.models()[controller_name
]
317 model_uuid
= models
['models'][model_name
]['uuid']
318 macaroons
= get_macaroons() if not password
else None
320 return await cls
.connect(
321 endpoint
, model_uuid
, username
, password
, cacert
, macaroons
, loop
)
323 def build_facades(self
, info
):
326 self
.facades
[facade
['name']] = facade
['versions'][-1]
328 async def login(self
, username
, password
, macaroons
=None):
333 if username
and not username
.startswith('user-'):
334 username
= 'user-{}'.format(username
)
336 result
= await self
.rpc({
341 "auth-tag": username
,
342 "credentials": password
,
343 "nonce": "".join(random
.sample(string
.printable
, 12)),
344 "macaroons": macaroons
or []
346 response
= result
['response']
347 self
.build_facades(response
.get('facades', {}))
348 self
.info
= response
.copy()
351 async def redirect_info(self
):
353 result
= await self
.rpc({
355 "request": "RedirectInfo",
358 except JujuAPIError
as e
:
359 if e
.message
== 'not redirected':
362 return result
['response']
367 self
.path
= os
.environ
.get('JUJU_DATA') or '~/.local/share/juju'
368 self
.path
= os
.path
.abspath(os
.path
.expanduser(self
.path
))
370 def current_controller(self
):
371 cmd
= shlex
.split('juju list-controllers --format yaml')
372 output
= subprocess
.check_output(cmd
)
373 output
= yaml
.safe_load(output
)
374 return output
.get('current-controller', '')
376 def current_model(self
, controller_name
=None):
377 if not controller_name
:
378 controller_name
= self
.current_controller()
379 models
= self
.models()[controller_name
]
380 if 'current-model' not in models
:
381 raise JujuError('No current model')
382 return models
['current-model']
384 def controllers(self
):
385 return self
._load
_yaml
('controllers.yaml', 'controllers')
388 return self
._load
_yaml
('models.yaml', 'controllers')
391 return self
._load
_yaml
('accounts.yaml', 'controllers')
393 def _load_yaml(self
, filename
, key
):
394 filepath
= os
.path
.join(self
.path
, filename
)
395 with io
.open(filepath
, 'rt') as f
:
396 return yaml
.safe_load(f
)[key
]
400 """Decode and return macaroons from default ~/.go-cookies
404 cookie_file
= os
.path
.expanduser('~/.go-cookies')
405 with
open(cookie_file
, 'r') as f
:
406 cookies
= json
.load(f
)
407 except (OSError, ValueError):
408 log
.warn("Couldn't load macaroons from %s", cookie_file
)
412 c
['Value'] for c
in cookies
413 if c
['Name'].startswith('macaroon-') and c
['Value']
417 json
.loads(base64
.b64decode(value
).decode('utf-8'))
418 for value
in base64_macaroons