b17ac459120e952ac2852dfccd87495c26123241
13 from http
.client
import HTTPSConnection
18 from juju
.errors
import JujuAPIError
, JujuConnectionError
20 log
= logging
.getLogger("websocket")
27 # Connect to an arbitrary api server
28 client = await Connection.connect(
29 api_endpoint, model_uuid, username, password, cacert)
31 # Connect using a controller/model name
32 client = await Connection.connect_model('local.local:default')
34 # Connect to the currently active model
35 client = await Connection.connect_current()
39 self
, endpoint
, uuid
, username
, password
, cacert
=None,
41 self
.endpoint
= endpoint
43 self
.username
= username
44 self
.password
= password
45 self
.macaroons
= macaroons
48 self
.__request
_id
__ = 0
59 def _get_ssl(self
, cert
=None):
60 return ssl
.create_default_context(
61 purpose
=ssl
.Purpose
.CLIENT_AUTH
, cadata
=cert
)
65 url
= "wss://{}/model/{}/api".format(self
.endpoint
, self
.uuid
)
67 url
= "wss://{}/api".format(self
.endpoint
)
70 kw
['ssl'] = self
._get
_ssl
(self
.cacert
)
72 self
.ws
= await websockets
.connect(url
, **kw
)
73 log
.info("Driver connected to juju %s", url
)
76 async def close(self
):
80 result
= await self
.ws
.recv()
81 if result
is not None:
82 result
= json
.loads(result
)
85 async def rpc(self
, msg
, encoder
=None):
86 self
.__request
_id
__ += 1
87 msg
['request-id'] = self
.__request
_id
__
88 if'params' not in msg
:
90 if "version" not in msg
:
91 msg
['version'] = self
.facades
[msg
['type']]
92 outgoing
= json
.dumps(msg
, indent
=2, cls
=encoder
)
93 await self
.ws
.send(outgoing
)
94 result
= await self
.recv()
95 if result
and 'error' in result
:
96 raise JujuAPIError(result
)
99 def http_headers(self
):
100 """Return dictionary of http headers necessary for making an http
101 connection to the endpoint of this Connection.
103 :return: Dictionary of headers
106 if not self
.username
:
109 creds
= u
'{}:{}'.format(
110 tag
.user(self
.username
),
113 token
= base64
.b64encode(creds
.encode())
115 'Authorization': 'Basic {}'.format(token
.decode())
118 def https_connection(self
):
119 """Return an https connection to this Connection's endpoint.
121 Returns a 3-tuple containing::
123 1. The :class:`HTTPSConnection` instance
124 2. Dictionary of auth headers to be used with the connection
125 3. The root url path (str) to be used for requests.
128 endpoint
= self
.endpoint
129 host
, remainder
= endpoint
.split(':', 1)
132 port
, _
= remainder
.split('/', 1)
134 conn
= HTTPSConnection(
136 context
=self
._get
_ssl
(self
.cacert
),
140 "/model/{}".format(self
.uuid
)
143 return conn
, self
.http_headers(), path
145 async def clone(self
):
146 """Return a new Connection, connected to the same websocket endpoint
150 return await Connection
.connect(
159 async def controller(self
):
160 """Return a Connection to the controller at self.endpoint
163 return await Connection
.connect(
174 cls
, endpoint
, uuid
, username
, password
, cacert
=None,
176 """Connect to the websocket.
178 If uuid is None, the connection will be to the controller. Otherwise it
179 will be to the model.
182 client
= cls(endpoint
, uuid
, username
, password
, cacert
, macaroons
)
185 redirect_info
= await client
.redirect_info()
186 if not redirect_info
:
187 await client
.login(username
, password
, macaroons
)
192 s
for servers
in redirect_info
['servers']
193 for s
in servers
if s
["scope"] == 'public'
195 for server
in servers
:
197 "{value}:{port}".format(**server
), uuid
, username
,
198 password
, redirect_info
['ca-cert'], macaroons
)
201 result
= await client
.login(username
, password
, macaroons
)
202 if 'discharge-required-error' in result
:
205 except Exception as e
:
210 "Couldn't authenticate to %s", endpoint
)
213 async def connect_current(cls
):
214 """Connect to the currently active model.
217 jujudata
= JujuData()
218 controller_name
= jujudata
.current_controller()
219 models
= jujudata
.models()[controller_name
]
220 model_name
= models
['current-model']
222 return await cls
.connect_model(
223 '{}:{}'.format(controller_name
, model_name
))
226 async def connect_current_controller(cls
):
227 """Connect to the currently active controller.
230 jujudata
= JujuData()
231 controller_name
= jujudata
.current_controller()
232 if not controller_name
:
233 raise JujuConnectionError('No current controller')
235 return await cls
.connect_controller(controller_name
)
238 async def connect_controller(cls
, controller_name
):
239 """Connect to a controller by name.
242 jujudata
= JujuData()
243 controller
= jujudata
.controllers()[controller_name
]
244 endpoint
= controller
['api-endpoints'][0]
245 cacert
= controller
.get('ca-cert')
246 accounts
= jujudata
.accounts()[controller_name
]
247 username
= accounts
['user']
248 password
= accounts
.get('password')
249 macaroons
= get_macaroons() if not password
else None
251 return await cls
.connect(
252 endpoint
, None, username
, password
, cacert
, macaroons
)
255 async def connect_model(cls
, model
):
256 """Connect to a model by name.
258 :param str model: <controller>:<model>
261 controller_name
, model_name
= model
.split(':')
263 jujudata
= JujuData()
264 controller
= jujudata
.controllers()[controller_name
]
265 endpoint
= controller
['api-endpoints'][0]
266 cacert
= controller
.get('ca-cert')
267 accounts
= jujudata
.accounts()[controller_name
]
268 username
= accounts
['user']
269 password
= accounts
.get('password')
270 models
= jujudata
.models()[controller_name
]
271 model_uuid
= models
['models'][model_name
]['uuid']
272 macaroons
= get_macaroons() if not password
else None
274 return await cls
.connect(
275 endpoint
, model_uuid
, username
, password
, cacert
, macaroons
)
277 def build_facades(self
, info
):
280 self
.facades
[facade
['name']] = facade
['versions'][-1]
282 async def login(self
, username
, password
, macaroons
=None):
287 if username
and not username
.startswith('user-'):
288 username
= 'user-{}'.format(username
)
290 result
= await self
.rpc({
295 "auth-tag": username
,
296 "credentials": password
,
297 "nonce": "".join(random
.sample(string
.printable
, 12)),
298 "macaroons": macaroons
or []
300 response
= result
['response']
301 self
.build_facades(response
.get('facades', {}))
302 self
.info
= response
.copy()
305 async def redirect_info(self
):
307 result
= await self
.rpc({
309 "request": "RedirectInfo",
312 except JujuAPIError
as e
:
313 if e
.message
== 'not redirected':
316 return result
['response']
321 self
.path
= os
.environ
.get('JUJU_DATA') or '~/.local/share/juju'
322 self
.path
= os
.path
.abspath(os
.path
.expanduser(self
.path
))
324 def current_controller(self
):
325 cmd
= shlex
.split('juju list-controllers --format yaml')
326 output
= subprocess
.check_output(cmd
)
327 output
= yaml
.safe_load(output
)
328 return output
.get('current-controller', '')
330 def controllers(self
):
331 return self
._load
_yaml
('controllers.yaml', 'controllers')
334 return self
._load
_yaml
('models.yaml', 'controllers')
337 return self
._load
_yaml
('accounts.yaml', 'controllers')
339 def _load_yaml(self
, filename
, key
):
340 filepath
= os
.path
.join(self
.path
, filename
)
341 with io
.open(filepath
, 'rt') as f
:
342 return yaml
.safe_load(f
)[key
]
346 """Decode and return macaroons from default ~/.go-cookies
350 cookie_file
= os
.path
.expanduser('~/.go-cookies')
351 with
open(cookie_file
, 'r') as f
:
352 cookies
= json
.load(f
)
353 except (OSError, ValueError) as e
:
354 log
.warn("Couldn't load macaroons from %s", cookie_file
)
358 c
['Value'] for c
in cookies
359 if c
['Name'].startswith('macaroon-') and c
['Value']
363 json
.loads(base64
.b64decode(value
).decode('utf-8'))
364 for value
in base64_macaroons