starts a container in daemon mode
492815
def start(name, config_file=None):
    '''
    
    '''
    if not exists(name):
        raise ContainerNotExists("The container (%s) does not exist!" % name)
    if name in running():
        raise ContainerAlreadyRunning('The container %s is already started!' % name)
    cmd = ['lxc-start', '-n', name, '-d']
    if config_file:
        cmd += ['-f', config_file]
    subprocess.check_call(cmd)
115314
function() {

    // Automatically return true if we are in the GUI and on linux because
    // this requires SUDO and because the daemon should always be running on nix
    if (mode === 'gui' && process.platform === 'linux') {
      return Promise.resolve(true);
    }

    // Get status
    return isDown()

    // Only start if we aren't already
    .then(function(isDown) {
      if (isDown) {
        var opts = (process.platform === 'win32') ? {detached: true} : {};
        return serviceCmd(['start'], opts);
      }
    })

    // Wait for the daemon to respond
    .retry(function() {
      log.debug('Trying to connect to daemon.');
      return bin.sh([DOCKER_EXECUTABLE, 'info'], {mode: 'collect'});
    }, {max: 25, backoff: 1000})

    // Wrap errors.
    .catch(function(err) {
      throw new VError(err, 'Error bringing daemon up.');
    });

  }
66555
async def start(self):
        """"""
        # arguments passed to the Docker command
        command_args = {
            'command': self.command,
            'container_image': self.requirements.get('image', constants.DEFAULT_CONTAINER_IMAGE),
        }

        # Get limit defaults.
        limit_defaults = SETTINGS.get('FLOW_PROCESS_RESOURCE_DEFAULTS', {})

        # Set resource limits.
        limits = []
        # Each core is equivalent to 1024 CPU shares. The default for Docker containers
        # is 1024 shares (we don't need to explicitly set that).
        limits.append('--cpu-shares={}'.format(int(self.process['resource_limits']['cores']) * 1024))

        # Some SWAP is needed to avoid OOM signal. Swappiness is low to prevent
        # extensive usage of SWAP (this would reduce the performance).
        memory = self.process['resource_limits']['memory'] + DOCKER_MEMORY_HARD_LIMIT_BUFFER
        memory_swap = int(memory * DOCKER_MEMORY_SWAP_RATIO)

        limits.append('--memory={}m'.format(memory))
        limits.append('--memory-swap={}m'.format(memory_swap))
        limits.append('--memory-reservation={}m'.format(self.process['resource_limits']['memory']))
        limits.append('--memory-swappiness={}'.format(DOCKER_MEMORY_SWAPPINESS))

        # Set ulimits for interactive processes to prevent them from running too long.
        if self.process['scheduling_class'] == PROCESS_META['SCHEDULING_CLASS_INTERACTIVE']:
            # TODO: This is not very good as each child gets the same limit.
            limits.append('--ulimit cpu={}'.format(limit_defaults.get('cpu_time_interactive', 30)))

        command_args['limits'] = ' '.join(limits)

        # set container name
        self.container_name_prefix = SETTINGS.get('FLOW_EXECUTOR', {}).get('CONTAINER_NAME_PREFIX', 'resolwe')
        command_args['container_name'] = '--name={}'.format(self._generate_container_name())

        if 'network' in self.resources:
            # Configure Docker network mode for the container (if specified).
            # By default, current Docker versions use the 'bridge' mode which
            # creates a network stack on the default Docker bridge.
            network = SETTINGS.get('FLOW_EXECUTOR', {}).get('NETWORK', '')
            command_args['network'] = '--net={}'.format(network) if network else ''
        else:
            # No network if not specified.
            command_args['network'] = '--net=none'

        # Security options.
        security = []

        # Generate and set seccomp policy to limit syscalls.
        policy_file = tempfile.NamedTemporaryFile(mode='w')
        json.dump(SECCOMP_POLICY, policy_file)
        policy_file.file.flush()
        if not SETTINGS.get('FLOW_DOCKER_DISABLE_SECCOMP', False):
            security.append('--security-opt seccomp={}'.format(policy_file.name))
        self.temporary_files.append(policy_file)

        # Drop all capabilities and only add ones that are needed.
        security.append('--cap-drop=all')

        command_args['security'] = ' '.join(security)

        # Setup Docker volumes.
        def new_volume(kind, base_dir_name, volume, path=None, read_only=True):
            """Generate a new volume entry.

            :param kind: Kind of volume, which is used for getting extra options from
                settings (the ``FLOW_DOCKER_VOLUME_EXTRA_OPTIONS`` setting)
            :param base_dir_name: Name of base directory setting for volume source path
            :param volume: Destination volume mount point
            :param path: Optional additional path atoms appended to source path
            :param read_only: True to make the volume read-only
            """
            if path is None:
                path = []

            path = [str(atom) for atom in path]

            options = set(SETTINGS.get('FLOW_DOCKER_VOLUME_EXTRA_OPTIONS', {}).get(kind, '').split(','))
            options.discard('')
            # Do not allow modification of read-only option.
            options.discard('ro')
            options.discard('rw')

            if read_only:
                options.add('ro')
            else:
                options.add('rw')

            return {
                'src': os.path.join(SETTINGS['FLOW_EXECUTOR'].get(base_dir_name, ''), *path),
                'dest': volume,
                'options': ','.join(options),
            }

        volumes = [
            new_volume(
                'data', 'DATA_DIR', constants.DATA_VOLUME, [DATA_LOCATION['subpath']], read_only=False
            ),
            new_volume('data_all', 'DATA_DIR', constants.DATA_ALL_VOLUME),
            new_volume('upload', 'UPLOAD_DIR', constants.UPLOAD_VOLUME, read_only=False),
            new_volume(
                'secrets',
                'RUNTIME_DIR',
                constants.SECRETS_VOLUME,
                [DATA_LOCATION['subpath'], ExecutorFiles.SECRETS_DIR]
            ),
        ]

        # Generate dummy passwd and create mappings for it. This is required because some tools
        # inside the container may try to lookup the given UID/GID and will crash if they don't
        # exist. So we create minimal user/group files.
        passwd_file = tempfile.NamedTemporaryFile(mode='w')
        passwd_file.write('root:x:0:0:root:/root:/bin/bash\n')
        passwd_file.write('user:x:{}:{}:user:/:/bin/bash\n'.format(os.getuid(), os.getgid()))
        passwd_file.file.flush()
        self.temporary_files.append(passwd_file)

        group_file = tempfile.NamedTemporaryFile(mode='w')
        group_file.write('root:x:0:\n')
        group_file.write('user:x:{}:user\n'.format(os.getgid()))
        group_file.file.flush()
        self.temporary_files.append(group_file)

        volumes += [
            new_volume('users', None, '/etc/passwd', [passwd_file.name]),
            new_volume('users', None, '/etc/group', [group_file.name]),
        ]

        # Create volumes for tools.
        # NOTE: To prevent processes tampering with tools, all tools are mounted read-only
        self.tools_volumes = []
        for index, tool in enumerate(self.get_tools_paths()):
            self.tools_volumes.append(new_volume(
                'tools',
                None,
                os.path.join('/usr/local/bin/resolwe', str(index)),
                [tool]
            ))

        volumes += self.tools_volumes

        # Create volumes for runtime (all read-only).
        runtime_volume_maps = SETTINGS.get('RUNTIME_VOLUME_MAPS', None)
        if runtime_volume_maps:
            for src, dst in runtime_volume_maps.items():
                volumes.append(new_volume(
                    'runtime',
                    'RUNTIME_DIR',
                    dst,
                    [DATA_LOCATION['subpath'], src],
                ))

        # Add any extra volumes verbatim.
        volumes += SETTINGS.get('FLOW_DOCKER_EXTRA_VOLUMES', [])

        # Make sure that tmp dir exists.
        os.makedirs(constants.TMPDIR, mode=0o755, exist_ok=True)

        # Create Docker --volume parameters from volumes.
        command_args['volumes'] = ' '.join(['--volume="{src}":"{dest}":{options}'.format(**volume)
                                            for volume in volumes])

        # Set working directory to the data volume.
        command_args['workdir'] = '--workdir={}'.format(constants.DATA_VOLUME)

        # Change user inside the container.
        command_args['user'] = '--user={}:{}'.format(os.getuid(), os.getgid())

        # A non-login Bash shell should be used here (a subshell will be spawned later).
        command_args['shell'] = '/bin/bash'

        # Check if image exists locally. If not, command will exit with non-zero returncode
        check_command = '{command} image inspect {container_image}'.format(**command_args)

        logger.debug("Checking existence of docker image: {}".format(command_args['container_image']))

        check_proc = await subprocess.create_subprocess_exec(  # pylint: disable=no-member
            *shlex.split(check_command),
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )
        await check_proc.communicate()

        if check_proc.returncode != 0:
            pull_command = '{command} pull {container_image}'.format(**command_args)

            logger.info("Pulling docker image: {}".format(command_args['container_image']))

            pull_proc = await subprocess.create_subprocess_exec(  # pylint: disable=no-member
                *shlex.split(pull_command),
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE
            )
            _, stderr = await pull_proc.communicate()

            if pull_proc.returncode != 0:
                error_msg = "Docker failed to pull {} image.".format(command_args['container_image'])
                if stderr:
                    error_msg = '\n'.join([error_msg, stderr.decode('utf-8')])
                raise RuntimeError(error_msg)

        docker_command = (
            '{command} run --rm --interactive {container_name} {network} {volumes} {limits} '
            '{security} {workdir} {user} {container_image} {shell}'.format(**command_args)
        )

        logger.info("Starting docker container with command: {}".format(docker_command))
        start_time = time.time()

        # Workaround for pylint issue #1469
        # (https://github.com/PyCQA/pylint/issues/1469).
        self.proc = await subprocess.create_subprocess_exec(  # pylint: disable=no-member
            *shlex.split(docker_command),
            limit=4 * (2 ** 20),  # 4MB buffer size for line buffering
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT
        )

        stdout = []

        async def wait_for_container():
            """Wait for Docker container to start to avoid blocking the code that uses it."""
            self.proc.stdin.write(('echo PING' + os.linesep).encode('utf-8'))
            await self.proc.stdin.drain()
            while True:
                line = await self.proc.stdout.readline()
                stdout.append(line)
                if line.rstrip() == b'PING':
                    break
                if self.proc.stdout.at_eof():
                    raise RuntimeError()

        try:
            await asyncio.wait_for(wait_for_container(), timeout=DOCKER_START_TIMEOUT)
        except (asyncio.TimeoutError, RuntimeError):
            error_msg = "Docker container has not started for {} seconds.".format(DOCKER_START_TIMEOUT)
            stdout = ''.join([line.decode('utf-8') for line in stdout if line])
            if stdout:
                error_msg = '\n'.join([error_msg, stdout])
            raise RuntimeError(error_msg)

        end_time = time.time()
        logger.info("It took {:.2f}s for Docker container to start".format(end_time - start_time))

        self.stdout = self.proc.stdout
945402
def start(self, timeout=None):
        

        # we lazily create our process delegate (with same arguments)
        if self.daemon:
            daemonic = True
        else:
            daemonic = False

        pargs = self._pargs.copy()
        pargs.pop('daemonic', None)

        self._process = multiprocessing.Process(**pargs)

        self._process.daemon = daemonic

        if self.is_alive():
            # if already started, we shutdown and join before restarting
            # not timeout will bock here (default join behavior).
            # otherwise we simply use the same timeout.
            self.shutdown(join=True, timeout=timeout)  # TODO : only restart if no error (check exitcode)
            self.start(timeout=timeout)  # recursive to try again if needed
        else:
            self._process.start()

        # timeout None means we want to wait and ensure it has started
        # deterministic behavior, like is_alive() from multiprocess.Process is always true after start()
        if self.started.wait(timeout=timeout):  # blocks until we know true or false


            return True
            # return self._svc_address  # returning the zmp url as a way to connect to the node
            # CAREFUL : doesnt make sense if this node only run a one-time task...
        # TODO: futures and ThreadPoolExecutor (so we dont need to manage the pool ourselves)
        else:
            return False
1318526
function start(mode, target, system, containerDef, container, out, cb) {

    out.preview({cmd: 'start instances', host: null, user: null, keyPath: null});
    if (mode === 'preview') {
      return cb(null);
    }

    var instanceType = container.specific.InstanceType ||
                       container.specific.instanceType ||
                       config.defaultInstanceType ||
                       'm3.medium';

    var imageId = container.specific.ImageId ||
                  container.specific.imageId ||
                  config.defaultImageId;

    var params = {'MaxCount': 1,
                  'MinCount': 1,
                  'EbsOptimized': false,
                  'InstanceInitiatedShutdownBehavior': 'stop',
                  'InstanceType': instanceType,
                  'ImageId': imageId,
                  'KeyName': config.defaultKeyName,
                  'SubnetId': config.defaultSubnetId,
                  'Monitoring': { Enabled: false }};
                  /*'EbsOptimized': container.specific.ebsOptimized,
                  'InstanceInitiatedShutdownBehavior': container.specific.instanceInitiatedShutdownBehavior,
                  'InstanceType': container.specific.instanceType,
                  'KeyName': container.specific.keyName,
                  'Monitoring': container.specific.monitoring};*/

    if (system.topology.containers[container.containedBy].type === 'aws-sg') {
      params.SecurityGroupIds = [system.topology.containers[container.containedBy].nativeId];
    }

    _ec2.runInstances(params, function(err, data) {
      if (err) { return cb(err, null); }
      var instance = data.Instances[0];

      pollInstanceStart(instance, function(err, newSpecific) {
        if (err) { return cb(err); }
        var tagParams = {Resources: [instance.InstanceId], Tags: container.specific.tags || []};
        tagParams.Tags.push({Key: 'nscale-system', Value: system.name + '-' + system.topology.name});
        tagParams.Tags.push({Key: 'nscale-id', Value: system.name + '-' + system.topology.name + '-' + container.id});
        if (containerDef.name) {
          tagParams.Tags.push({Key: 'Name', Value: container.id});
        }
        _ec2.createTags(tagParams, function() {
          if (err) { return cb(err); }
          var c = _.find(system.topology.containers, function(cont) { return cont.id === container.id; });
          c.nativeId = instance.InstanceId;
          c.specific = newSpecific;
          system.dirty = true;
          cb(null, system);
        });
      });
    });
  }
1022744
def start(self):
        
        # Check for a pidfile to see if the daemon already runs
        logger.info('Starting daemon')
        try:
            with open(self.pidfile, 'r') as fd:
                pid = int(fd.read().strip())
        except IOError:
            pid = None

        if pid:
            message = "pidfile %s already exist. Daemon already running?\n"
            sys.stderr.write(message % self.pidfile)
            sys.exit(1)

        # 
        pid = self.daemonize()
        if pid:
            return pid
        self.run()
1047117
def main():
    
    try:
        if get_global_option('show_config'):
            print json.dumps(config.get_configuration(), indent=2)
        elif get_global_option('daemon'):
            daemon = DynamicDynamoDBDaemon(
                '{0}/dynamic-dynamodb.{1}.pid'.format(
                    get_global_option('pid_file_dir'),
                    get_global_option('instance')))

            if get_global_option('daemon') == 'start':
                logger.debug('Starting daemon')
                try:
                    daemon.start()
                    logger.info('Daemon started')
                except IOError as error:
                    logger.error('Could not create pid file: {0}'.format(error))
                    logger.error('Daemon not started')
            elif get_global_option('daemon') == 'stop':
                logger.debug('Stopping daemon')
                daemon.stop()
                logger.info('Daemon stopped')
                sys.exit(0)

            elif get_global_option('daemon') == 'restart':
                logger.debug('Restarting daemon')
                daemon.restart()
                logger.info('Daemon restarted')

            elif get_global_option('daemon') in ['foreground', 'fg']:
                logger.debug('Starting daemon in foreground')
                daemon.run()
                logger.info('Daemon started in foreground')

            else:
                print(
                    'Valid options for --daemon are start, '
                    'stop, restart, and foreground')
                sys.exit(1)
        else:
            if get_global_option('run_once'):
                execute()
            else:
                while True:
                    execute()

    except Exception as error:
        logger.exception(error)
717338
def container(self, cls, **kwargs):
        """"""
        self.start_container(cls, **kwargs)
        yield
        self.end_container()
1146416
public static function start()
    {
        if (Bootstrap::$pid && Thread\Generic::ifExistsByPid(Bootstrap::$pid)) {
            Daemon::log('[START] phpDaemon with pid-file \'' . Daemon::$config->pidfile->value . '\' is running already (PID ' . Bootstrap::$pid . ')');
            exit(6);
        }

        Daemon::init();
        $pid = Daemon::spawnMaster();
        file_put_contents(Daemon::$config->pidfile->value, $pid);
    }
706498
def restart(self):
        """"""
        yield from self.manager.query("POST", "containers/{}/restart".format(self._cid))
        log.info("Docker container '{name}' [{image}] restarted".format(
            name=self._name, image=self._image))
1278061
def init():
    
    su()
    args = sys.argv
    args.pop(0)
    cmd = "{0}sun_daemon".format(bin_path)
    if len(args) == 1:
        if args[0] == "start":
            print("Starting SUN daemon:  {0} &".format(cmd))
            subprocess.call("{0} &".format(cmd), shell=True)
        elif args[0] == "stop":
            print("Stopping SUN daemon:  {0}".format(cmd))
            subprocess.call("killall sun_daemon", shell=True)
        elif args[0] == "restart":
            print("Stopping SUN daemon:  {0}".format(cmd))
            subprocess.call("killall sun_daemon", shell=True)
            print("Starting SUN daemon:  {0} &".format(cmd))
            subprocess.call("{0} &".format(cmd), shell=True)
        elif args[0] == "check":
            _init_check_upodates()
        elif args[0] == "status":
            print(daemon_status())
        elif args[0] == "help":
            usage()
        elif args[0] == "info":
            print(os_info())
        else:
            print("try: 'sun help'")
    elif len(args) == 2 and args[0] == "start" and args[1] == "--gtk":
        subprocess.call("{0} {1}".format(cmd, "start--gtk"), shell=True)
    else:
        print("try: 'sun help'")
291791
private void startContainer() throws DockerException {
        final long startTime = System.currentTimeMillis();
        try {
            LOGGER.info("Starting container {} with id {}", containerConfig.image(), containerId);
            client.startContainer(containerId);
        } catch (DockerException | InterruptedException e) {
            throw new DockerException(
                    "Unable to start container " + containerConfig.image() + " with id " + containerId, e);
        } finally {
            final long elapsedMillis = System.currentTimeMillis() - startTime;
            LOGGER.info("Container {} started in {}ms", containerConfig.image(), elapsedMillis);
        }
    }
233453
def restart(self, container, **kwargs):
        
        self.push_log("Restarting container '{0}'.".format(container))
        super(DockerFabricClient, self).restart(container, **kwargs)
1210830
def _start_container(self, container, tool_d, s_containers, f_containers):
        
        # use section to add info to manifest
        section = tool_d[container]['section']
        del tool_d[container]['section']
        manifest = Template(self.manifest)
        try:
            # try to start an existing container first
            c = self.d_client.containers.get(container)
            c.start()
            s_containers.append(container)
            manifest.set_option(section, 'running', 'yes')
            self.logger.info('started ' + str(container) +
                             ' with ID: ' + str(c.short_id))
        except Exception as err:
            s_containers, f_containers = self._run_container(
                container, tool_d, section, s_containers, f_containers)

        # save changes made to manifest
        manifest.write_config()
        return s_containers, f_containers
1160770
def start(self):
        
        self._timer = Timer(self.time, self.handler)
        self._timer.daemon = True
        self._timer.start()
        return
1373599
def daemon(args):
    
    if os.environ.get(DVC_DAEMON):
        logger.debug("skipping launching a new daemon.")
        return

    cmd = [sys.executable]
    if not is_binary():
        cmd += ["-m", "dvc"]
    cmd += ["daemon", "-q"] + args

    env = fix_env()
    file_path = os.path.abspath(inspect.stack()[0][1])
    env[cast_bytes_py2("PYTHONPATH")] = cast_bytes_py2(
        os.path.dirname(os.path.dirname(file_path))
    )
    env[cast_bytes_py2(DVC_DAEMON)] = cast_bytes_py2("1")

    _spawn(cmd, env)
988815
def start(self, *args, **kw):
        
        # Check for a pidfile to see if the daemon already runs
        try:
            pidfile = file(self.pidfile, 'r')
            pid = int(pidfile.read().strip())
            pidfile.close()
        except IOError:
            pid = None

        if pid:
            message = "pidfile %s already exist. Daemon already running?\n"
            sys.stderr.write(message % self.pidfile)
            sys.exit(1)

        # 
        self.daemonize()
        self.run(*args, **kw)