import logging from subprocess import Popen, PIPE, STDOUT from ccnode.node import DefaultHandler from ccnode.tags import tag_inspector from ccnode.host import tags logger = logging.getLogger(__name__) class Handler(DefaultHandler): """Handler for host role.""" def __init__(self, *args, **kwargs): DefaultHandler.__init__(self, *args, **kwargs) for t in tag_inspector(tags): self.tags[t.name] = t def execute_command(self, command): """Execute an arbitrary shell command on the host. :param string command: shell command to run """ # return stdout and stderr mixed in return Popen(command, shell=True, bufsize=-1, stdin=PIPE, stdout=PIPE, stderr=STDOUT).communicate()[0] or None def node_shutdown(self, reboot=True, gracefull=True): """Halt/Reboot the node. :param bool reboot: halt/reboot the system :param bool gracefull: force the operation (gracefull == not force) """ args = ['/sbin/shutdown'] if reboot: args.append('-r') if gracefull: logger.info(u'Going to reboot the host...') args.append('-f') else: logger.info(u'Going to force the reboot of the host...') args.append('-n') else: # halt args.append('-h -P') if not gracefull: logger.info(u'Going to halt the host...') args.append('-n') else: logger.info(u'Going to force the halt of the host...') args.append('0') return self.execute_command(' '.join(args))