Enable passive service check submission (globally)
        Format of the line that triggers function call::

        START_ACCEPTING_PASSIVE_SVC_CHECKS

        :return: None
14298
def start_accepting_passive_svc_checks(self):
        
        # todo: #783 create a dedicated brok for global parameters
        if not self.my_conf.accept_passive_service_checks:
            self.my_conf.modified_attributes |= DICT_MODATTR["MODATTR_PASSIVE_CHECKS_ENABLED"].value
            self.my_conf.accept_passive_service_checks = True
            self.my_conf.explode_global_conf()
            self.daemon.update_program_status()
1112908
def handle_check(self, command, **options):
        """"""
        passed = True
        client = DjangoClient(metrics_interval="0ms")

        def is_set(x):
            return x and x != "None"

        # check if org/app is set:
        if is_set(client.config.service_name):
            self.write("Service name is set, good job!", green)
        else:
            passed = False
            self.write("Configuration errors detected!", red, ending="\n\n")
            self.write("  * SERVICE_NAME not set! ", red, ending="\n")
            self.write(CONFIG_EXAMPLE)

        # secret token is optional but recommended
        if not is_set(client.config.secret_token):
            self.write("  * optional SECRET_TOKEN not set", yellow, ending="\n")
        self.write("")

        server_url = client.config.server_url
        if server_url:
            parsed_url = urlparse.urlparse(server_url)
            if parsed_url.scheme.lower() in ("http", "https"):
                # parse netloc, making sure people did not supply basic auth
                if "@" in parsed_url.netloc:
                    credentials, _, path = parsed_url.netloc.rpartition("@")
                    passed = False
                    self.write("Configuration errors detected!", red, ending="\n\n")
                    if ":" in credentials:
                        self.write("  * SERVER_URL cannot contain authentication " "credentials", red, ending="\n")
                    else:
                        self.write(
                            "  * SERVER_URL contains an unexpected at-sign!"
                            " This is usually used for basic authentication, "
                            "but the colon is left out",
                            red,
                            ending="\n",
                        )
                else:
                    self.write("SERVER_URL {0} looks fine".format(server_url), green)
                # secret token in the clear not recommended
                if is_set(client.config.secret_token) and parsed_url.scheme.lower() == "http":
                    self.write("  * SECRET_TOKEN set but server not using https", yellow, ending="\n")
            else:
                self.write(
                    "  * SERVER_URL has scheme {0} and we require " "http or https!".format(parsed_url.scheme),
                    red,
                    ending="\n",
                )
                passed = False
        else:
            self.write("Configuration errors detected!", red, ending="\n\n")
            self.write("  * SERVER_URL appears to be empty", red, ending="\n")
            passed = False
        self.write("")

        # check if we're disabled due to DEBUG:
        if settings.DEBUG:
            if getattr(settings, "ELASTIC_APM", {}).get("DEBUG"):
                self.write(
                    "Note: even though you are running in DEBUG mode, we will "
                    'send data to the APM Server, because you set ELASTIC_APM["DEBUG"] to '
                    "True. You can disable ElasticAPM while in DEBUG mode like this"
                    "\n\n",
                    yellow,
                )
                self.write(
                    "   ELASTIC_APM = {\n"
                    '       "DEBUG": False,\n'
                    "       # your other ELASTIC_APM settings\n"
                    "   }"
                )
            else:
                self.write(
                    "Looks like you're running in DEBUG mode. ElasticAPM will NOT "
                    "gather any data while DEBUG is set to True.\n\n",
                    red,
                )
                self.write(
                    "If you want to test ElasticAPM while DEBUG is set to True, you"
                    " can force ElasticAPM to gather data by setting"
                    ' ELASTIC_APM["DEBUG"] to True, like this\n\n'
                    "   ELASTIC_APM = {\n"
                    '       "DEBUG": True,\n'
                    "       # your other ELASTIC_APM settings\n"
                    "   }"
                )
                passed = False
        else:
            self.write("DEBUG mode is disabled! Looking good!", green)
        self.write("")

        # check if middleware is set, and if it is at the first position
        middleware_attr = "MIDDLEWARE" if getattr(settings, "MIDDLEWARE", None) is not None else "MIDDLEWARE_CLASSES"
        middleware = list(getattr(settings, middleware_attr))
        try:
            pos = middleware.index("elasticapm.contrib.django.middleware.TracingMiddleware")
            if pos == 0:
                self.write("Tracing middleware is configured! Awesome!", green)
            else:
                self.write("Tracing middleware is configured, but not at the first position\n", yellow)
                self.write("ElasticAPM works best if you add it at the top of your %s setting" % middleware_attr)
        except ValueError:
            self.write("Tracing middleware not configured!", red)
            self.write(
                "\n"
                "Add it to your %(name)s setting like this:\n\n"
                "    %(name)s = (\n"
                '        "elasticapm.contrib.django.middleware.TracingMiddleware",\n'
                "        # your other middleware classes\n"
                "    )\n" % {"name": middleware_attr}
            )
        self.write("")
        if passed:
            self.write("Looks like everything should be ready!", green)
        else:
            self.write("Please fix the above errors.", red)
        self.write("")
        client.close()
        return passed
801690
def set_shell(self, svc_ref):
        
        if svc_ref is None:
            return

        with self._lock:
            # Get the service
            self._shell_ref = svc_ref
            self._shell = self._context.get_service(self._shell_ref)

            # Set the readline completer
            if readline is not None:
                readline.set_completer(self.readline_completer)

            # Set the flag
            self._shell_event.set()
752312
def enable_passive_host_checks(self, host):
        
        if not host.passive_checks_enabled:
            host.modified_attributes |= \
                DICT_MODATTR["MODATTR_PASSIVE_CHECKS_ENABLED"].value
            host.passive_checks_enabled = True
            self.send_an_element(host.get_update_status_brok())
975791
def enable_host_svc_checks(self, host):
        
        for service_id in host.services:
            if service_id in self.daemon.services:
                service = self.daemon.services[service_id]
                self.enable_svc_check(service)
                self.send_an_element(service.get_update_status_brok())
70277
def enable_logging(self):
        
        handler = logging.FileHandler(self.log_fname)
        handler.setLevel(logging.INFO)
        run_id = self.id

        class WBFilter(logging.Filter):
            def filter(self, record):
                record.run_id = run_id
                return True

        formatter = logging.Formatter(
            '%(asctime)s %(levelname)-7s %(threadName)-10s:%(process)d [%(run_id)s:%(filename)s:%(funcName)s():%(lineno)s] %(message)s')
        handler.setFormatter(formatter)
        handler.addFilter(WBFilter())

        root = logging.getLogger()
        root.addHandler(handler)
1240867
def _disable(name, started, result=True, skip_verify=False, **kwargs):
    '''
    
    '''
    ret = {}

    if not skip_verify:
        # is service available?
        try:
            if not _available(name, ret):
                ret['result'] = True
                return ret
        except CommandExecutionError as exc:
            ret['result'] = False
            ret['comment'] = exc.strerror
            return ret

    # Set default expected result
    ret['result'] = result

    # is enable/disable available?
    if 'service.disable' not in __salt__ or 'service.disabled' not in __salt__:
        if started is True:
            ret['comment'] = ('Disable is not available on this minion,'
                              ' service {0} started').format(name)
        elif started is None:
            ret['comment'] = ('Disable is not available on this minion,'
                              ' service {0} is in the desired state'
                              ).format(name)
        else:
            ret['comment'] = ('Disable is not available on this minion,'
                              ' service {0} is dead').format(name)
        return ret

    # Service can be disabled
    if salt.utils.platform.is_windows():
        # service.disabled in Windows returns True for services that are set to
        # Manual start, so we need to check specifically for Disabled
        before_toggle_disable_status = __salt__['service.info'](name)['StartType'] in ['Disabled']
    else:
        before_toggle_disable_status = __salt__['service.disabled'](name)
    if before_toggle_disable_status:
        # Service is disabled
        if started is True:
            ret['comment'] = ('Service {0} is already disabled,'
                              ' and is running').format(name)
        elif started is None:
            # always be sure in this case to reset the changes dict
            ret['changes'] = {}
            ret['comment'] = ('Service {0} is already disabled,'
                              ' and is in the desired state').format(name)
        else:
            ret['comment'] = ('Service {0} is already disabled,'
                              ' and is dead').format(name)
        return ret

    # Service needs to be disabled
    if __opts__['test']:
        ret['result'] = None
        ret['comment'] = 'Service {0} set to be disabled'.format(name)
        return ret

    if __salt__['service.disable'](name, **kwargs):
        # Service has been disabled
        ret['changes'] = {}
        after_toggle_disable_status = __salt__['service.disabled'](name)
        # on upstart, certain services like apparmor will always return
        # False, even if correctly activated
        # do not trigger a change
        if before_toggle_disable_status != after_toggle_disable_status:
            ret['changes'][name] = True
        if started is True:
            ret['comment'] = ('Service {0} has been disabled,'
                              ' and is running').format(name)
        elif started is None:
            ret['comment'] = ('Service {0} has been disabled,'
                              ' and is in the desired state').format(name)
        else:
            ret['comment'] = ('Service {0} has been disabled,'
                              ' and is dead').format(name)
        return ret

    # Service failed to be disabled
    ret['result'] = False
    if started is True:
        ret['comment'] = ('Failed when setting service {0} to not start'
                          ' at boot, and is running').format(name)
    elif started is None:
        ret['comment'] = ('Failed when setting service {0} to not start'
                          ' at boot, but the service was already running'
                          ).format(name)
    else:
        ret['comment'] = ('Failed when setting service {0} to not start'
                          ' at boot, and the service is dead').format(name)
    return ret
1036095
def joinCommissioned(self, strPSKd='threadjpaketest', waitTime=20):
        
        print '%s call joinCommissioned' % self.port
        cmd = WPANCTL_CMD + 'joiner --start %s %s' %(strPSKd, self.provisioningUrl)
        print cmd
        if self.__sendCommand(cmd)[0] != "Fail":
            if self.__getJoinerState():
                self.__sendCommand(WPANCTL_CMD + 'joiner --attach')
                time.sleep(30)
                return True
            else:
                return False
        else:
            return False
1063050
def disable_checker_on_env(func):
    
    @wraps(func)
    def func_wrapper(*args, **kwargs):
        # pylint: disable=C0111, C0103
        function_name = func.__name__
        CHECKERS_DISABLED = os.getenv('CHECKERS_DISABLED', '')
        disabled_functions = [x.strip() for x in CHECKERS_DISABLED.split(',')]

        force_run = kwargs.get('force_run', False)

        if function_name in disabled_functions and not force_run:
            return True
        else:
            return func(*args, **kwargs)

    return func_wrapper
316178
def _sysv_enable(name):
    '''
    
    '''
    if not _service_is_chkconfig(name) and not _chkconfig_add(name):
        return False
    cmd = '/sbin/chkconfig {0} on'.format(name)
    return not __salt__['cmd.retcode'](cmd, python_shell=False)
871738
def SvcStop(self) -> None:
        
        # tell the SCM we're shutting down
        # noinspection PyUnresolvedReferences
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        # fire the stop event
        win32event.SetEvent(self.h_stop_event)
1249265
def pause(self, pause=True):
        
        url: str = get_url("/remote/pause.json")
        params = {
            "oauth": self._oauth_token,
            "csrf": self._csrf_token,
            "pause": "true" if pause else "false",
        }
        self._request(url=url, params=params)
1106140
def task_submission_options(f):
    

    def notify_opt_callback(ctx, param, value):
        """
        Parse --notify
        - "" is the same as "off"
        - parse by lowercase, comma-split, strip spaces
        - "off,x" is invalid for any x
        - "on,x" is valid for any valid x (other than "off")
        - "failed", "succeeded", "inactive" are normal vals

        In code, produces True, False, or a set
        """
        # if no value was set, don't set any explicit options
        # the API default is "everything on"
        if value is None:
            return {}

        value = value.lower()
        value = [x.strip() for x in value.split(",")]
        # [""] is what you'll get if value is "" to start with
        # special-case it into "off", which helps avoid surprising scripts
        # which take a notification settings as inputs and build --notify
        if value == [""]:
            value = ["off"]

        off = "off" in value
        on = "on" in value
        # set-ize it -- duplicates are fine
        vals = set([x for x in value if x not in ("off", "on")])

        if (vals or on) and off:
            raise click.UsageError('--notify cannot accept "off" and another value')

        allowed_vals = set(("on", "succeeded", "failed", "inactive"))
        if not vals <= allowed_vals:
            raise click.UsageError(
                "--notify received at least one invalid value among {}".format(
                    list(vals)
                )
            )

        # return the notification options to send!
        # on means don't set anything (default)
        if on:
            return {}
        # off means turn off everything
        if off:
            return {
                "notify_on_succeeded": False,
                "notify_on_failed": False,
                "notify_on_inactive": False,
            }
        # otherwise, return the exact set of values seen
        else:
            return {
                "notify_on_succeeded": "succeeded" in vals,
                "notify_on_failed": "failed" in vals,
                "notify_on_inactive": "inactive" in vals,
            }

    f = click.option(
        "--dry-run",
        is_flag=True,
        help=("Don't actually submit the task, print submission " "data instead"),
    )(f)
    f = click.option(
        "--notify",
        callback=notify_opt_callback,
        help=(
            "Comma separated list of task events which notify by email. "
            "'on' and 'off' may be used to enable or disable notifications "
            "for all event types. Otherwise, use 'succeeded', 'failed', or "
            "'inactive'"
        ),
    )(f)
    f = click.option(
        "--submission-id",
        help=(
            "Task submission ID, as generated by `globus task "
            "generate-submission-id`. Used for safe resubmission in the "
            "presence of network failures."
        ),
    )(f)
    f = click.option("--label", default=None, help="Set a label for this task.")(f)
    f = click.option(
        "--deadline",
        default=None,
        type=ISOTimeType(),
        help="Set a deadline for this to be canceled if not completed by.",
    )(f)
    f = click.option(
        "--skip-activation-check",
        is_flag=True,
        help=("Submit the task even if the endpoint(s) " "aren't currently activated."),
    )(f)

    return f
205356
def check_enable_mode(self, check_string=""):
        
        self.write_channel(self.RETURN)
        output = self.read_until_prompt()
        return check_string in output
952897
def stop_executing_host_checks(self):
        
        if self.my_conf.execute_host_checks:
            self.my_conf.modified_attributes |= DICT_MODATTR["MODATTR_ACTIVE_CHECKS_ENABLED"].value
            self.my_conf.execute_host_checks = False
            self.my_conf.explode_global_conf()
            self.daemon.update_program_status()
879621
def _send_start_ok(self, frame_in):
        
        mechanisms = try_utf8_decode(frame_in.mechanisms)
        if 'EXTERNAL' in mechanisms:
            mechanism = 'EXTERNAL'
            credentials = '\0\0'
        elif 'PLAIN' in mechanisms:
            mechanism = 'PLAIN'
            credentials = self._plain_credentials()
        else:
            exception = AMQPConnectionError(
                'Unsupported Security Mechanism(s): %s' %
                frame_in.mechanisms
            )
            self._connection.exceptions.append(exception)
            return
        start_ok_frame = specification.Connection.StartOk(
            mechanism=mechanism,
            client_properties=self._client_properties(),
            response=credentials,
            locale=LOCALE
        )
        self._write_frame(start_ok_frame)
394673
def enable_host_svc_notifications(self, host):
        
        for service_id in host.services:
            if service_id in self.daemon.services:
                service = self.daemon.services[service_id]
                self.enable_svc_notifications(service)
                self.send_an_element(service.get_update_status_brok())