Better fix for moving stuff into an Executor.
[osm/N2VC.git] / juju / utils.py
1 import asyncio
2 import concurrent.futures
3 import os
4 from pathlib import Path
5
6
7 async def execute_process(*cmd, log=None):
8 '''
9 Wrapper around asyncio.create_subprocess_exec.
10
11 '''
12 p = await asyncio.create_subprocess_exec(
13 *cmd,
14 stdin=asyncio.subprocess.PIPE,
15 stdout=asyncio.subprocess.PIPE,
16 stderr=asyncio.subprocess.PIPE,
17 )
18 stdout, stderr = await p.communicate()
19 if log:
20 log.debug("Exec %s -> %d", cmd, p.returncode)
21 if stdout:
22 log.debug(stdout.decode('utf-8'))
23 if stderr:
24 log.debug(stderr.decode('utf-8'))
25 return p.returncode == 0
26
27
28 def _read_ssh_key():
29 '''
30 Inner function for read_ssh_key, suitable for passing to our
31 Executor.
32
33 '''
34 default_data_dir = Path(Path.home(), ".local", "share", "juju")
35 juju_data = os.environ.get("JUJU_DATA", default_data_dir)
36 ssh_key_path = Path(juju_data, 'ssh', 'juju_id_rsa.pub')
37 with ssh_key_path.open('r') as ssh_key_file:
38 ssh_key = ssh_key_file.readlines()[0].strip()
39 return ssh_key
40
41
42 async def read_ssh_key(loop):
43 '''
44 Attempt to read the local juju admin's public ssh key, so that it
45 can be passed on to a model.
46
47 '''
48 ssh_key = await loop.run_in_executor(
49 concurrent.futures.ThreadPoolExecutor(),
50 _read_ssh_key
51 )
52 return ssh_key