1+ import asyncio
12import logging
23import socket
3- import subprocess
44from datetime import datetime , timedelta
55from typing import Optional
66
@@ -14,10 +14,10 @@ def __init__(self, host: str, port: int) -> None:
1414 self .occupant : Optional [str ] = None
1515 self .user_id = socket .gethostname ()
1616
17- def is_free (self ) -> bool :
17+ async def is_free (self ) -> bool :
1818 try :
1919 command = f'[ -f { self .DEFAULT_FILEPATH } ] && cat { self .DEFAULT_FILEPATH } || echo'
20- output = self ._run_ssh_command (command ).strip ()
20+ output = ( await self ._run_ssh_command (command ) ).strip ()
2121 if not output :
2222 return True
2323 words = output .splitlines ()[0 ].strip ().split ()
@@ -30,20 +30,27 @@ def is_free(self) -> bool:
3030 logging .exception ('Could not access target system' )
3131 return False
3232
33- def set (self , info : str ) -> bool :
34- if not self .is_free ():
33+ async def set (self , info : str ) -> bool :
34+ if not await self .is_free ():
3535 return False
3636 try :
37- self ._run_ssh_command (f'echo "{ self .tag } \n { info } " > { self .DEFAULT_FILEPATH } ' )
37+ await self ._run_ssh_command (f'echo "{ self .tag } \n { info } " > { self .DEFAULT_FILEPATH } ' )
3838 return True
39- except subprocess . CalledProcessError :
39+ except RuntimeError :
4040 print ('Could not write mutex file' )
4141 return False
4242
4343 @property
4444 def tag (self ) -> str :
4545 return f'{ self .user_id } { datetime .now ().isoformat ()} '
4646
47- def _run_ssh_command (self , command : str ) -> str :
48- ssh_command = ['ssh' , self .host , '-p' , str (self .port ), command ]
49- return subprocess .check_output (ssh_command , stderr = subprocess .DEVNULL ).decode ()
47+ async def _run_ssh_command (self , command : str ) -> str :
48+ process = await asyncio .create_subprocess_exec (
49+ 'ssh' , self .host , '-p' , str (self .port ), command ,
50+ stdout = asyncio .subprocess .PIPE ,
51+ stderr = asyncio .subprocess .DEVNULL ,
52+ )
53+ stdout , _ = await process .communicate ()
54+ if process .returncode != 0 :
55+ raise RuntimeError (f'SSH command failed with return code { process .returncode } ' )
56+ return stdout .decode ()
0 commit comments