Files
Iris/mopidy_iris/system.py

79 lines
2.4 KiB
Python
Raw Normal View History

2018-11-02 16:10:38 +13:00
from threading import Thread
import os, logging, subprocess, json
# import logger
logger = logging.getLogger(__name__)
2018-11-02 16:10:38 +13:00
class IrisSystemThread(Thread):
def __init__(self, action, callback):
Thread.__init__(self)
self.action = action
self.callback = callback
2018-11-02 21:44:16 +13:00
self.path = os.path.dirname(__file__)
2018-11-02 16:10:38 +13:00
##
# Run the defined action
##
async def run(self):
logger.info("Running system action '"+self.action+"'")
2018-11-02 16:10:38 +13:00
try:
2019-04-04 14:37:40 +13:00
self.can_run()
except Exception as e:
2018-11-02 16:10:38 +13:00
logger.error(e)
2018-11-02 21:44:16 +13:00
error = {
'message': "Permission denied",
'description': str(e)
}
2018-11-02 16:10:38 +13:00
if self.callback:
2018-11-02 21:44:16 +13:00
self.callback(False, error)
2019-04-04 14:37:40 +13:00
return
2018-11-02 16:10:38 +13:00
# Create subprocess
process = await asyncio.create_subprocess_shell(
self.path+"/system.sh "+self.action,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
2018-11-02 16:10:38 +13:00
# Status
print("Started:", command, "(pid = " + str(process.pid) + ")", flush=True)
# Wait for the subprocess to finish
stdout, stderr = await process.communicate()
logger.debug("System action '"+self.action+"' completed with output:")
logger.debug(stdout)
# Some kind of failure, so we can't run any commands this way
if exitCode > 0:
raise Exception("System task '"+self.action+"' failed")
else:
if self.callback:
response = {
'output': str(stdout)
}
self.callback(response, False)
##
2018-11-02 16:10:38 +13:00
# Check if we have access to the system script (system.sh)
#
# @return boolean or exception
##
2019-04-04 14:37:40 +13:00
def can_run(self, *args, **kwargs):
2018-11-02 21:44:16 +13:00
# Attempt an empty call to our system file
process = subprocess.Popen("sudo -n "+self.path+"/system.sh", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
result, error = process.communicate()
exitCode = process.wait()
# Some kind of failure, so we can't run any commands this way
if exitCode > 0:
2019-04-04 14:37:40 +13:00
raise Exception("Password-less access to "+self.path+"/system.sh was refused. Check your /etc/sudoers file.")
else:
return True