Beispiel #1
0
    def apply(self, action, changes = collections.defaultdict(list)):
        """
        Takes a dict of service name to dict.
        Keys we look for are:
            - "enabled" (setting a service to "Automatic")
            - "ensureRunning" (actually start the service)
        """

        if not action.keys():
            log.debug("No Windows services specified")
            return
        
        if not _windows_supported:
            raise ToolError("Cannot modify windows services without pywin32")
        
        manager = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS)
        try:
            for service, serviceProperties in action.iteritems():
                handle = win32service.OpenService(manager, service, win32service.SERVICE_ALL_ACCESS)
                try:
                    if "enabled" in serviceProperties:
                        start_type = win32service.SERVICE_AUTO_START if util.interpret_boolean(serviceProperties["enabled"]) else win32service.SERVICE_DEMAND_START
                        self._set_service_startup_type(handle, start_type)
                    else:
                        log.debug("Not modifying enabled state of service %s", service)
                        
                    if self._detect_required_restart(serviceProperties, changes):
                        log.debug("Restarting %s due to change detected in dependency", service)
                        win32serviceutil.RestartService(service)
                    elif "ensureRunning" in serviceProperties:
                        ensureRunning = util.interpret_boolean(serviceProperties["ensureRunning"])
                        status = win32service.QueryServiceStatus(handle)[1]
                        isRunning = status & win32service.SERVICE_RUNNING or status & win32service.SERVICE_START_PENDING
                                        
                        if ensureRunning and not isRunning:
                            log.debug("Starting service %s as it is not running", service)
                            win32service.StartService(handle, None)
                        elif not ensureRunning and isRunning:
                            log.debug("Stopping service %s as it is running", service)
                            win32service.ControlService(handle, win32service.SERVICE_CONTROL_STOP)
                        else:
                            log.debug("No need to modify running state of service %s", service)
                    else:
                        log.debug("Not modifying running state of service %s", service)
                finally:
                    win32service.CloseServiceHandle(handle)
        finally:
            win32service.CloseServiceHandle(manager)
Beispiel #2
0
    def apply(self, action, changes=collections.defaultdict(list)):
        """
        Takes a dict of service name to dict.
        Keys we look for are:
            - "enabled" (equivalent to /sbin/chkconfig service on)
            - "ensureRunning" (equivalent to /sbin/service service start)
        """

        if not action.keys():
            log.debug("No System V init scripts specified")
            return

        for service, serviceProperties in action.iteritems():
            force_restart = self._detect_required_restart(
                serviceProperties, changes)

            if "enabled" in serviceProperties:
                self._set_service_enabled(
                    service,
                    util.interpret_boolean(serviceProperties["enabled"]))
            else:
                log.debug("Not modifying enabled state of service %s", service)

            if force_restart:
                log.debug("Restarting %s due to change detected in dependency",
                          service)
                self._restart_service(service)
            elif "ensureRunning" in serviceProperties:
                ensureRunning = util.interpret_boolean(
                    serviceProperties["ensureRunning"])
                isRunning = self._is_service_running(service)
                if ensureRunning and not isRunning:
                    log.debug("Starting service %s as it is not running",
                              service)
                    self._start_service(service)
                elif not ensureRunning and isRunning:
                    log.debug("Stopping service %s as it is running", service)
                    self._stop_service(service)
                else:
                    log.debug("No need to modify running state of service %s",
                              service)
            else:
                log.debug("Not modifying running state of service %s", service)
Beispiel #3
0
    def apply(self, action, changes = collections.defaultdict(list)):
        """
        Takes a dict of service name to dict.
        Keys we look for are:
            - "enabled" (equivalent to /sbin/chkconfig service on)
            - "ensureRunning" (equivalent to /sbin/service service start)
        """

        if not action.keys():
            log.debug("No System V init scripts specified")
            return

        for service, serviceProperties in action.iteritems():
            force_restart = self._detect_required_restart(serviceProperties, changes)

            if "enabled" in serviceProperties:
                self._set_service_enabled(service, util.interpret_boolean(serviceProperties["enabled"]))
            else:
                log.debug("Not modifying enabled state of service %s", service)

            if force_restart:
                log.debug("Restarting %s due to change detected in dependency", service)
                self._restart_service(service)
            elif "ensureRunning" in serviceProperties:
                ensureRunning = util.interpret_boolean(serviceProperties["ensureRunning"])
                isRunning = self._is_service_running(service)
                if ensureRunning and not isRunning:
                    log.debug("Starting service %s as it is not running", service)
                    self._start_service(service)
                elif not ensureRunning and isRunning:
                    log.debug("Stopping service %s as it is running", service)
                    self._stop_service(service)
                else:
                    log.debug("No need to modify running state of service %s", service)
            else:
                log.debug("Not modifying running state of service %s", service)
    def apply(self, action):
        """
        Execute a set of commands, returning a list of commands that were executed.

        Arguments:
        action -- a dict of command to attributes, where attributes has keys of:
            command: the command to run (a string or list)
            cwd: working directory (a string)
            env: a dictionary of environment variables
            test: a commmand to run; if it returns zero, the command will run
            ignoreErrors: if true, ignore errors
            waitAfterCompletion: # of seconds to wait after completion (or "forever")
            defaults: a command to run; the stdout will be used to provide defaults

        Exceptions:
        ToolError -- on expected failures
        """

        commands_run = []

        if not action:
            log.debug("No commands specified")
            return commands_run

        for name in sorted(action.keys()):
            log.debug("Running command %s", name)

            attributes = action[name]

            if "defaults" in attributes:
                log.debug("Generating defaults for command %s", name)
                defaultsResult = ProcessHelper(attributes['defaults'], stderr=subprocess.PIPE).call()
                log.debug("Defaults script for %s output: %s", name, defaultsResult.stdout)
                if defaultsResult.returncode:
                    log.error("Defaults script failed for %s: %s", name, defaultsResult.stderr)
                    raise ToolError("Defaults script for command %s failed" % name)

                old_attrs = attributes
                attributes = json.loads(defaultsResult.stdout)
                attributes.update(old_attrs)

            if not "command" in attributes:
                log.error("No command specified for %s", name)
                raise ToolError("%s does not specify the 'command' attribute, which is required" % name)

            cwd = os.path.expanduser(attributes["cwd"]) if "cwd" in attributes else None
            env = attributes.get("env", None)

            if "test" in attributes:
                log.debug("Running test for command %s", name)
                test = attributes["test"]
                testResult = ProcessHelper(test, env=env, cwd=cwd).call()
                log.debug("Test command output: %s", testResult.stdout)
                if testResult.returncode:
                    log.info("Test failed with code %s", testResult.returncode)
                    continue
                else:
                    log.debug("Test for command %s passed", name)
            else:
                log.debug("No test for command %s", name)

            cmd_to_run = attributes["command"]
            if "runas" in attributes:
                if os.name == 'nt':
                    raise ToolError('Command %s specified "runas", which is not supported on Windows' % name)

                if isinstance(cmd_to_run, basestring):
                    cmd_to_run = 'su %s -c %s' % (attributes['runas'], cmd_to_run)
                else:
                    cmd_to_run = ['su', attributes['runas'], '-c'] + cmd_to_run

            commandResult = ProcessHelper(cmd_to_run, env=env, cwd=cwd).call()

            if commandResult.returncode:
                log.error("Command %s (%s) failed", name, attributes["command"])
                log.debug("Command %s output: %s", name, commandResult.stdout)
                if interpret_boolean(attributes.get("ignoreErrors")):
                    log.info("ignoreErrors set to true, continuing build")
                    commands_run.append(name)
                else:
                    raise ToolError("Command %s failed" % name)
            else:
                log.info("Command %s succeeded", name)
                log.debug("Command %s output: %s", name, commandResult.stdout)
                commands_run.append(name)

        return commands_run
Beispiel #5
0
    def apply(self, action):
        """
        Execute a set of commands, returning a list of commands that were executed.

        Arguments:
        action -- a dict of command to attributes, where attributes has keys of:
            command: the command to run (a string or list)
            cwd: working directory (a string)
            env: a dictionary of environment variables
            test: a commmand to run; if it returns zero, the command will run
            ignoreErrors: if true, ignore errors
            waitAfterCompletion: # of seconds to wait after completion (or "forever")
            defaults: a command to run; the stdout will be used to provide defaults

        Exceptions:
        ToolError -- on expected failures
        """

        commands_run = []

        if not action:
            log.debug("No commands specified")
            return commands_run

        for name in sorted(action.keys()):
            log.debug(u"Running command %s", name)

            attributes = action[name]

            if "defaults" in attributes:
                log.debug(u"Generating defaults for command %s", name)
                defaultsResult = ProcessHelper(attributes['defaults'], stderr=subprocess.PIPE).call()
                log.debug(u"Defaults script for %s output: %s", name, defaultsResult.stdout.decode('utf-8'))
                if defaultsResult.returncode:
                    log.error(u"Defaults script failed for %s: %s", name, defaultsResult.stderr.decode('utf-8'))
                    raise ToolError(u"Defaults script for command %s failed" % name)

                default_attrs = attributes
                default_env = default_attrs.get("env",{})
                attributes = json.loads(defaultsResult.stdout)
                user_env = attributes.get("env",{})
                user_env.update(default_env)
                attributes.update(default_attrs)
                attributes["env"] = user_env

            if not "command" in attributes:
                log.error(u"No command specified for %s", name)
                raise ToolError(u"%s does not specify the 'command' attribute, which is required" % name)

            cwd = os.path.expanduser(attributes["cwd"]) if "cwd" in attributes else None
            env = attributes.get("env", None)

            if "test" in attributes:
                log.debug(u"Running test for command %s", name)
                test = attributes["test"]
                testResult = LoggingProcessHelper(test, name=u'Test for Command %s' % name, env=env, cwd=cwd).call()
                log.debug(u"Test command output: %s", testResult.stdout.decode('utf-8'))
                if testResult.returncode:
                    log.info(u"Test failed with code %s", testResult.returncode)
                    continue
                else:
                    log.debug(u"Test for command %s passed", name)
            else:
                log.debug(u"No test for command %s", name)

            cmd_to_run = attributes["command"]
            if "runas" in attributes:
                if os.name == 'nt':
                    raise ToolError(u'Command %s specified "runas", which is not supported on Windows' % name)

                if isinstance(cmd_to_run, basestring):
                    cmd_to_run = u'su %s -c %s' % (attributes['runas'], cmd_to_run)
                else:
                    cmd_to_run = ['su', attributes['runas'], '-c'] + cmd_to_run

            commandResult = LoggingProcessHelper(cmd_to_run, name=u'Command %s' % name, env=env, cwd=cwd).call()

            if commandResult.returncode:
                log.error(u"Command %s (%s) failed", name, attributes["command"])
                log.debug(u"Command %s output: %s", name, commandResult.stdout.decode('utf-8'))
                if interpret_boolean(attributes.get("ignoreErrors")):
                    log.info("ignoreErrors set to true, continuing build")
                    commands_run.append(name)
                else:
                    raise ToolError(u"Command %s failed" % name)
            else:
                log.info(u"Command %s succeeded", name)
                log.debug(u"Command %s output: %s", name, commandResult.stdout.decode('utf-8'))
                commands_run.append(name)

        return commands_run
        if not hooks_config.has_option(section, 'action'):
            logging.error("No action specified for hook %s", section)
            continue

        runas = None
        if hooks_config.has_option(section, 'runas'):
            runas = hooks_config.get(section, 'runas').strip()

        hook = Hook(section,
                    triggers,
                    hooks_config.get(section, 'path').strip(),
                    hooks_config.get(section, 'action'),
                    runas)
        if hook.is_cmd_hook():
            if hooks_config.has_option(section, 'singleton'):
                hook.singleton = util.interpret_boolean(hooks_config.get(section, 'singleton'))
            if hooks_config.has_option(section, 'send_result'):
                hook.send_result = util.interpret_boolean(hooks_config.get(section, 'send_result'))
            cmd_hooks.append(hook)
        else:
            hooks.append(hook)

    if not hooks and not cmd_hooks:
        raise ValueError("No valid hooks found")

    region = 'us-east-1'
    if main_config.has_option('main', 'region'):
        region = main_config.get('main', 'region')

    cfn_url = CloudFormationClient.endpointForRegion(region)
Beispiel #7
0
            continue

        if not hooks_config.has_option(section, 'action'):
            logging.error("No action specified for hook %s", section)
            continue

        runas = None
        if hooks_config.has_option(section, 'runas'):
            runas = hooks_config.get(section, 'runas').strip()

        hook = Hook(section, triggers,
                    hooks_config.get(section, 'path').strip(),
                    hooks_config.get(section, 'action'), runas)
        if hook.is_cmd_hook():
            if hooks_config.has_option(section, 'singleton'):
                hook.singleton = util.interpret_boolean(
                    hooks_config.get(section, 'singleton'))
            if hooks_config.has_option(section, 'send_result'):
                hook.send_result = util.interpret_boolean(
                    hooks_config.get(section, 'send_result'))
            cmd_hooks.append(hook)
        else:
            hooks.append(hook)

    if not hooks and not cmd_hooks:
        raise ValueError("No valid hooks found")

    region = 'us-east-1'
    if main_config.has_option('main', 'region'):
        region = main_config.get('main', 'region')

    cfn_url = CloudFormationClient.endpointForRegion(region)
        if not hooks_config.has_option(section, 'action'):
            logging.error("No action specified for hook %s", section)
            continue

        runas = None
        if hooks_config.has_option(section, 'runas'):
            runas = hooks_config.get(section, 'runas').strip()

        hook = Hook(section,
                    triggers,
                    hooks_config.get(section, 'path').strip(),
                    hooks_config.get(section, 'action'),
                    runas)
        if hook.is_cmd_hook():
            if hooks_config.has_option(section, 'singleton'):
                hook.singleton = util.interpret_boolean(hooks_config.get(section, 'singleton'))
            if hooks_config.has_option(section, 'send_result'):
                hook.send_result = util.interpret_boolean(hooks_config.get(section, 'send_result'))
            cmd_hooks.append(hook)
        else:
            hooks.append(hook)

    if not hooks and not cmd_hooks:
        raise ValueError("No valid hooks found")

    region = 'us-east-1'
    if main_config.has_option('main', 'region'):
        region = main_config.get('main', 'region')

    cfn_url = CloudFormationClient.endpointForRegion(region)
Beispiel #9
0
    def apply(self, action, changes=collections.defaultdict(list)):
        """
        Takes a dict of service name to dict.
        Keys we look for are:
            - "enabled" (setting a service to "Automatic")
            - "ensureRunning" (actually start the service)
        """

        if not action.keys():
            log.debug("No Windows services specified")
            return

        if not _windows_supported:
            raise ToolError("Cannot modify windows services without pywin32")

        manager = win32service.OpenSCManager(
            None, None, win32service.SC_MANAGER_ALL_ACCESS)
        try:
            for service, serviceProperties in action.iteritems():
                handle = win32service.OpenService(
                    manager, service, win32service.SERVICE_ALL_ACCESS)
                try:
                    if "enabled" in serviceProperties:
                        start_type = win32service.SERVICE_AUTO_START if util.interpret_boolean(
                            serviceProperties["enabled"]
                        ) else win32service.SERVICE_DEMAND_START
                        self._set_service_startup_type(handle, start_type)
                    else:
                        log.debug("Not modifying enabled state of service %s",
                                  service)

                    if self._detect_required_restart(serviceProperties,
                                                     changes):
                        log.debug(
                            "Restarting %s due to change detected in dependency",
                            service)
                        win32serviceutil.RestartService(service)
                    elif "ensureRunning" in serviceProperties:
                        ensureRunning = util.interpret_boolean(
                            serviceProperties["ensureRunning"])
                        status = win32service.QueryServiceStatus(handle)[1]
                        isRunning = status & win32service.SERVICE_RUNNING or status & win32service.SERVICE_START_PENDING

                        if ensureRunning and not isRunning:
                            log.debug(
                                "Starting service %s as it is not running",
                                service)
                            win32service.StartService(handle, None)
                        elif not ensureRunning and isRunning:
                            log.debug("Stopping service %s as it is running",
                                      service)
                            win32service.ControlService(
                                handle, win32service.SERVICE_CONTROL_STOP)
                        else:
                            log.debug(
                                "No need to modify running state of service %s",
                                service)
                    else:
                        log.debug("Not modifying running state of service %s",
                                  service)
                finally:
                    win32service.CloseServiceHandle(handle)
        finally:
            win32service.CloseServiceHandle(manager)