send updated configurtaion information to a container and hup the internal daemon process
557511
function hup(mode, target, system, containerDef, container, newConfig, out, cb) {
    var executor = prepareAndGetExecutor(target, out, 'hup');
    executor.hup(mode, target, system, containerDef, container, out, newConfig, function(err) {
      cb(err);
    });
  }
334963
public function send()
    {
        // We don't want any accidental sending of beacons if the installation has explicitly said no.
        if (!$this->enabled()) {
            return;
        }

        $setting = app(Setting::class);

        if (!$installId = $setting->get('install_id', null)) {
            $installId = sha1(Str::random(20));

            $setting->set('install_id', $installId);
        }

        $payload = [
            'install_id' => $installId,
            'version'    => CACHET_VERSION,
            'docker'     => $this->config->get('cachet.is_docker'),
            'database'   => $this->config->get('database.default'),
            'data'       => [
                'components' => Component::all()->count(),
                'incidents'  => Incident::all()->count(),
                'metrics'    => Metric::all()->count(),
                'users'      => User::all()->count(),
                'actions'    => Action::all()->count(),
                'tags'       => Tag::all()->count(),
                'schedules'  => Schedule::all()->count(),
            ],
        ];

        try {
            $client = new Client();
            $client->post(self::URL, [
                'headers' => ['Accept' => 'application/json', 'User-Agent' => defined('CACHET_VERSION') ? 'cachet/'.constant('CACHET_VERSION') : 'cachet'],
                'json'    => $payload,
            ]);
        } catch (Exception $e) {
            event(new BeaconFailedToSendEvent());

            return;
        }

        event(new BeaconWasSentEvent());
    }
995856
def remote_daemon(conf_file):
    

    eventlet.monkey_patch()
    conf = config.Config(conf_file=conf_file)
    daemon = remote.RemoteControlDaemon(None, conf)
    daemon.serve()
945949
function setupSystemD (name, options, callback) {
  options.stdOut = (options.logDir && `${options.logDir}/${name}-out.log`) || null
  options.stdErr = (options.logDir && `${options.logDir}/${name}-err.log`) || null

  const filepath = `/etc/systemd/system/${name}.service`

  const script = systemdTemplate(options)

  if (options.dryRun) {
    console.log(script)
    return
  }

  console.log(`Installing service on: ${filepath}`)
  fs.exists(filepath, exists => {
    if(!exists) {
      fs.writeFile(filepath,script, err => {
        if (err) {
          callback(err)
          return
        }

        fs.chmod(filepath,'755', err => {
          if (err) {
            callback(err)
            return
          }

          let cmd = 'systemctl daemon-reload'
          console.log('Running %s...', cmd)
          exec(cmd, err => {
            callback(err, 'SystemD service registered succesfully')
          })
        })
      })
    } else {
      callback('Service already exists, please uninstall first')
    }
  })
}
1232325
def _nodedev_event_update_cb(conn, dev, opaque):
    '''
    
    '''
    _salt_send_event(opaque, conn, {
        'nodedev': {
            'name': dev.name()
        },
        'event': opaque['event']
    })
499414
def handle(cls, vm, args):
        
        docker = Iaas.info(vm)
        if not docker:
            raise Exception('docker vm %s not found' % vm)

        if docker['state'] != 'running':
            Iaas.start(vm)

        # XXX
        remote_addr = docker['ifaces'][0]['ips'][0]['ip']

        port = unixpipe.setup(remote_addr, 'root', '/var/run/docker.sock')

        os.environ['DOCKER_HOST'] = 'tcp://localhost:%d' % port
        cls.echo('using DOCKER_HOST=%s' % os.environ['DOCKER_HOST'])

        subprocess.call(['docker'] + list(args))
1316995
def update(self, source_zip=None, no_upload=False):
        

        if not source_zip:
            # Make sure we're in a venv.
            self.check_venv()

            # Execute the prebuild script
            if self.prebuild_script:
                self.execute_prebuild_script()

            # Temporary version check
            try:
                updated_time = 1472581018
                function_response = self.zappa.lambda_client.get_function(FunctionName=self.lambda_name)
                conf = function_response['Configuration']
                last_updated = parser.parse(conf['LastModified'])
                last_updated_unix = time.mktime(last_updated.timetuple())
            except botocore.exceptions.BotoCoreError as e:
                click.echo(click.style(type(e).__name__, fg="red") + ": " + e.args[0])
                sys.exit(-1)
            except Exception as e:
                click.echo(click.style("Warning!", fg="red") + " Couldn't get function " + self.lambda_name +
                           " in " + self.zappa.aws_region + " - have you deployed yet?")
                sys.exit(-1)

            if last_updated_unix <= updated_time:
                click.echo(click.style("Warning!", fg="red") +
                           " You may have upgraded Zappa since deploying this application. You will need to " +
                           click.style("redeploy", bold=True) + " for this deployment to work properly!")

            # Make sure the necessary IAM execution roles are available
            if self.manage_roles:
                try:
                    self.zappa.create_iam_roles()
                except botocore.client.ClientError:
                    click.echo(click.style("Failed", fg="red") + " to " + click.style("manage IAM roles", bold=True) + "!")
                    click.echo("You may " + click.style("lack the necessary AWS permissions", bold=True) +
                               " to automatically manage a Zappa execution role.")
                    click.echo("To fix this, see here: " +
                               click.style("https://github.com/Miserlou/Zappa#custom-aws-iam-roles-and-policies-for-deployment",
                                           bold=True))
                    sys.exit(-1)

            # Create the Lambda Zip,
            if not no_upload:
                self.create_package()
                self.callback('zip')

            # Upload it to S3
            if not no_upload:
                success = self.zappa.upload_to_s3(self.zip_path, self.s3_bucket_name, disable_progress=self.disable_progress)
                if not success:  # pragma: no cover
                    raise ClickException("Unable to upload project to S3. Quitting.")

                # If using a slim handler, upload it to S3 and tell lambda to use this slim handler zip
                if self.stage_config.get('slim_handler', False):
                    # https://github.com/Miserlou/Zappa/issues/510
                    success = self.zappa.upload_to_s3(self.handler_path, self.s3_bucket_name, disable_progress=self.disable_progress)
                    if not success:  # pragma: no cover
                        raise ClickException("Unable to upload handler to S3. Quitting.")

                    # Copy the project zip to the current project zip
                    current_project_name = '{0!s}_{1!s}_current_project.tar.gz'.format(self.api_stage, self.project_name)
                    success = self.zappa.copy_on_s3(src_file_name=self.zip_path, dst_file_name=current_project_name,
                                                    bucket_name=self.s3_bucket_name)
                    if not success:  # pragma: no cover
                        raise ClickException("Unable to copy the zip to be the current project. Quitting.")

                    handler_file = self.handler_path
                else:
                    handler_file = self.zip_path

        # Register the Lambda function with that zip as the source
        # You'll also need to define the path to your lambda_handler code.
        kwargs = dict(
            bucket=self.s3_bucket_name,
            function_name=self.lambda_name,
            num_revisions=self.num_retained_versions
        )
        if source_zip and source_zip.startswith('s3://'):
            bucket, key_name = parse_s3_url(source_zip)
            kwargs.update(dict(
                bucket=bucket,
                s3_key=key_name
            ))
            self.lambda_arn = self.zappa.update_lambda_function(**kwargs)
        elif source_zip and not source_zip.startswith('s3://'):
            with open(source_zip, mode='rb') as fh:
                byte_stream = fh.read()
            kwargs['local_zip'] = byte_stream
            self.lambda_arn = self.zappa.update_lambda_function(**kwargs)
        else:
            if not no_upload:
                kwargs['s3_key'] = handler_file
                self.lambda_arn = self.zappa.update_lambda_function(**kwargs)

        # Remove the uploaded zip from S3, because it is now registered..
        if not source_zip and not no_upload:
            self.remove_uploaded_zip()

        # Update the configuration, in case there are changes.
        self.lambda_arn = self.zappa.update_lambda_configuration(
                                                        lambda_arn=self.lambda_arn,
                                                        function_name=self.lambda_name,
                                                        handler=self.lambda_handler,
                                                        description=self.lambda_description,
                                                        vpc_config=self.vpc_config,
                                                        timeout=self.timeout_seconds,
                                                        memory_size=self.memory_size,
                                                        runtime=self.runtime,
                                                        aws_environment_variables=self.aws_environment_variables,
                                                        aws_kms_key_arn=self.aws_kms_key_arn
                                                    )

        # Finally, delete the local copy our zip package
        if not source_zip and not no_upload:
            if self.stage_config.get('delete_local_zip', True):
                self.remove_local_zip()

        if self.use_apigateway:

            self.zappa.create_stack_template(
                                            lambda_arn=self.lambda_arn,
                                            lambda_name=self.lambda_name,
                                            api_key_required=self.api_key_required,
                                            iam_authorization=self.iam_authorization,
                                            authorizer=self.authorizer,
                                            cors_options=self.cors,
                                            description=self.apigateway_description,
                                            endpoint_configuration=self.endpoint_configuration
                                        )
            self.zappa.update_stack(
                                    self.lambda_name,
                                    self.s3_bucket_name,
                                    wait=True,
                                    update_only=True,
                                    disable_progress=self.disable_progress)

            api_id = self.zappa.get_api_id(self.lambda_name)

            # Update binary support
            if self.binary_support:
                self.zappa.add_binary_support(api_id=api_id, cors=self.cors)
            else:
                self.zappa.remove_binary_support(api_id=api_id, cors=self.cors)

            if self.stage_config.get('payload_compression', True):
                self.zappa.add_api_compression(
                    api_id=api_id,
                    min_compression_size=self.stage_config.get('payload_minimum_compression_size', 0))
            else:
                self.zappa.remove_api_compression(api_id=api_id)

            # It looks a bit like we might actually be using this just to get the URL,
            # but we're also updating a few of the APIGW settings.
            endpoint_url = self.deploy_api_gateway(api_id)

            if self.stage_config.get('domain', None):
                endpoint_url = self.stage_config.get('domain')

        else:
            endpoint_url = None

        self.schedule()

        # Update any cognito pool with the lambda arn
        # do this after schedule as schedule clears the lambda policy and we need to add one
        self.update_cognito_triggers()

        self.callback('post')

        if endpoint_url and 'https://' not in endpoint_url:
            endpoint_url = 'https://' + endpoint_url

        if self.base_path:
            endpoint_url += '/' + self.base_path

        deployed_string = "Your updated Zappa deployment is " + click.style("live", fg='green', bold=True) + "!"
        if self.use_apigateway:
            deployed_string = deployed_string + ": " + click.style("{}".format(endpoint_url), bold=True)

            api_url = None
            if endpoint_url and 'amazonaws.com' not in endpoint_url:
                api_url = self.zappa.get_api_url(
                    self.lambda_name,
                    self.api_stage)

                if endpoint_url != api_url:
                    deployed_string = deployed_string + " (" + api_url + ")"

            if self.stage_config.get('touch', True):
                if api_url:
                    self.touch_endpoint(api_url)
                elif endpoint_url:
                    self.touch_endpoint(endpoint_url)

        click.echo(deployed_string)
481962
def build(self, shutit):
		
		if shutit.build['delivery'] in ('docker','dockerfile'):
			if shutit.get_current_shutit_pexpect_session_environment().install_type == 'apt':
				shutit.add_to_bashrc('export DEBIAN_FRONTEND=noninteractive')
				if not shutit.command_available('lsb_release'):
					shutit.install('lsb-release')
				shutit.lsb_release()
			elif shutit.get_current_shutit_pexpect_session_environment().install_type == 'yum':
				# yum updates are so often "bad" that we let exit codes of 1 through.
				# TODO: make this more sophisticated
				shutit.send('yum update -y', timeout=9999, exit_values=['0', '1'])
			shutit.pause_point('Anything you want to do to the target host ' + 'before the build starts?', level=2)
		return True
605082
def do_cli(function_identifier,  # pylint: disable=too-many-locals
           template,
           base_dir,
           build_dir,
           clean,
           use_container,
           manifest_path,
           docker_network,
           skip_pull_image,
           parameter_overrides,
           mode):
    

    LOG.debug("'build' command is called")

    if use_container:
        LOG.info("Starting Build inside a container")

    with BuildContext(function_identifier,
                      template,
                      base_dir,
                      build_dir,
                      clean=clean,
                      manifest_path=manifest_path,
                      use_container=use_container,
                      parameter_overrides=parameter_overrides,
                      docker_network=docker_network,
                      skip_pull_image=skip_pull_image,
                      mode=mode) as ctx:
        try:
            builder = ApplicationBuilder(ctx.functions_to_build,
                                         ctx.build_dir,
                                         ctx.base_dir,
                                         manifest_path_override=ctx.manifest_path_override,
                                         container_manager=ctx.container_manager,
                                         mode=ctx.mode)
        except FunctionNotFound as ex:
            raise UserException(str(ex))

        try:
            artifacts = builder.build()
            modified_template = builder.update_template(ctx.template_dict,
                                                        ctx.original_template_path,
                                                        artifacts)

            move_template(ctx.original_template_path,
                          ctx.output_template_path,
                          modified_template)

            click.secho("\nBuild Succeeded", fg="green")

            msg = gen_success_msg(os.path.relpath(ctx.build_dir),
                                  os.path.relpath(ctx.output_template_path),
                                  os.path.abspath(ctx.build_dir) == os.path.abspath(DEFAULT_BUILD_DIR))

            click.secho(msg, fg="yellow")

        except (UnsupportedRuntimeException, BuildError, UnsupportedBuilderLibraryVersionError,
                ContainerBuildNotSupported) as ex:
            click.secho("\nBuild Failed", fg="red")
            raise UserException(str(ex))
502336
def send_config_set(self, config_commands=None, exit_config_mode=True, **kwargs):
        """"""
        if self.username == "root":
            exit_config_mode = False
        return super(LinuxSSH, self).send_config_set(
            config_commands=config_commands, exit_config_mode=exit_config_mode, **kwargs
        )
685247
public function daemonRunCommand(): void
    {
        $ret = ProcessUtil::daemonRun(function ($pid){
            $this->output->info("will running background by new process: $pid");
        });

        if ($ret === 0) {
            $this->output->liteError('current env is not support process create.');
        }
    }
1328992
def update():
    '''
    
    '''
    # data for the fileserver event
    data = {'changed': False,
            'backend': 'hgfs'}
    # _clear_old_remotes runs init(), so use the value from there to avoid a
    # second init()
    data['changed'], repos = _clear_old_remotes()
    for repo in repos:
        if os.path.exists(repo['lockfile']):
            log.warning(
                'Update lockfile is present for hgfs remote %s, skipping. '
                'If this warning persists, it is possible that the update '
                'process was interrupted. Removing %s or running '
                '\'salt-run fileserver.clear_lock hgfs\' will allow updates '
                'to continue for this remote.', repo['url'], repo['lockfile']
            )
            continue
        _, errors = lock(repo)
        if errors:
            log.error(
                'Unable to set update lock for hgfs remote %s, skipping.',
                repo['url']
            )
            continue
        log.debug('hgfs is fetching from %s', repo['url'])
        repo['repo'].open()
        curtip = repo['repo'].tip()
        try:
            repo['repo'].pull()
        except Exception as exc:
            log.error(
                'Exception %s caught while updating hgfs remote %s',
                exc, repo['url'], exc_info_on_loglevel=logging.DEBUG
            )
        else:
            newtip = repo['repo'].tip()
            if curtip[1] != newtip[1]:
                data['changed'] = True
        repo['repo'].close()
        clear_lock(repo)

    env_cache = os.path.join(__opts__['cachedir'], 'hgfs/envs.p')
    if data.get('changed', False) is True or not os.path.isfile(env_cache):
        env_cachedir = os.path.dirname(env_cache)
        if not os.path.exists(env_cachedir):
            os.makedirs(env_cachedir)
        new_envs = envs(ignore_cache=True)
        serial = salt.payload.Serial(__opts__)
        with salt.utils.files.fopen(env_cache, 'wb+') as fp_:
            fp_.write(serial.dumps(new_envs))
            log.trace('Wrote env cache data to %s', env_cache)

    # if there is a change, fire an event
    if __opts__.get('fileserver_events', False):
        event = salt.utils.event.get_event(
                'master',
                __opts__['sock_dir'],
                __opts__['transport'],
                opts=__opts__,
                listen=False)
        event.fire_event(data, tagify(['hgfs', 'update'], prefix='fileserver'))
    try:
        salt.fileserver.reap_fileserver_cache_dir(
            os.path.join(__opts__['cachedir'], 'hgfs/hash'),
            find_file
        )
    except (IOError, OSError):
        # Hash file won't exist if no files have yet been served up
        pass
98024
public function onConfigUpdated()
    {
        parent::onConfigUpdated();
        if (Daemon::$process instanceof \PHPDaemon\Thread\Worker) {
            $pool = $this;
            FileSystem::readfile($this->config->file->value, function ($file, $data) use ($pool) {
                $pool->policyData = $data;
                $pool->enable();
            });
        }
    }
317189
def update(self, reconfigure=False):
        
        try:
            self.phase = PHASE.UPDATE
            self.logger.info("Updating environment %s..." % self.namespace)
            self.install_sandboxes()
            self.instantiate_features()
            # We don't grab inputs, only on install
            # updates inputs are grabbed on demand
            # self.grab_inputs(reconfigure=reconfigure)
            if reconfigure:
                self.grab_inputs(reconfigure=True)
            else:
                self._copy_source_to_target()
            self._specialize(reconfigure=reconfigure)
            for feature in self.features.run_order:
                self.run_action(feature, 'sync')
            self.inject_environment_config()
            self._finalize()
        except Exception:
            self.logger.debug("", exc_info=sys.exc_info())
            et, ei, tb = sys.exc_info()
            reraise(et, ei, tb)
345803
def configure
      @web_server.mount('/alive', Alive)
      @web_server.mount('/tasks/new', NewTask, self)
      @web_server.mount('/shutdown', Shutdown)
      @web_server.mount('/response_from_device', ResponseFromDevice, self)
      @web_server.mount('/auto_update_pid', AutoUpdatePID, self)
    end
401562
def update_frontend(self, info):
        
        headers = {'Content-Type': 'text/event-stream'}
        if info.get('when'):
            info['when'] = info['when'].isoformat()
        requests.post(self.base_url + '/publish', data=json.dumps(info), headers=headers)
1220092
def _send_config(self):
        
        serialized = self._generate_config()
        self._log.debug("Configuration has been serialized")
        try:
            self._conn.flushInput()
            self._conn.flushOutput()
            self._conn.write(serialized)
            return True
        except Exception as e:
            self._log.error(e)
            raise Exception(e)