Identical to :meth:`docker.api.container.ContainerApiMixin.start` with additional logging.
514496
def start(self, container, **kwargs):
        
        self.push_log("Starting container '{0}'.".format(container))
        super(DockerFabricClient, self).start(container, **kwargs)
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
145119
public void start() {
        addSymbolsFromSettings();
        File rep = new File(context.getSettings().getTargetPath());
        rep.mkdirs();
        try {
            java4cppLog = new FileWriter(new File(getPath(JAVA4CPP_LOG)));
        } catch (IOException e) {
            System.err.println("Can't create log file: " + e.getMessage());
        }
        try {
            File[] existings = rep.listFiles(new SourceFilter());
            if (existings != null) {
                oldFiles = new ArrayList<File>(Arrays.asList(existings));
            }
            java4cppHash = new File(getPath(JAVA4CPP_HASH));
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(java4cppHash));
            oldHashes.load(in);
            in.close();
            java4cppHash.delete();
        } catch (IOException e) {
            logInfo("no java4cpp.hash file, regenerating all files");
        }
    }
845390
@Override
    protected void startUp() {
        long traceId = LoggerHelpers.traceEnterWithContext(log, this.objectId, "startUp");
        try {
            log.info("Starting REST server listening on port: {}", this.restServerConfig.getPort());
            if (restServerConfig.isTlsEnabled()) {
                SSLContextConfigurator contextConfigurator = new SSLContextConfigurator();
                contextConfigurator.setKeyStoreFile(restServerConfig.getKeyFilePath());
                contextConfigurator.setKeyStorePass(JKSHelper.loadPasswordFrom(restServerConfig.getKeyFilePasswordPath()));
                httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig, true,
                        new SSLEngineConfigurator(contextConfigurator, false, false, false));
            } else {
                httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig, true);
            }
        } finally {
            LoggerHelpers.traceLeave(log, this.objectId, "startUp", traceId);
        }
    }
492611
def start(self):
        """"""
        error, output = None, None
        try:
            time.sleep(0.1)
            output = self.method(*self.args, **self.kwargs)
        except Exception as err:
            logger.debug(str((self.method.__module__, self.method.__name__,
                              err)))
            error = str(err)
            error = error.replace('(', '')
            error = error.replace(')', '')
#            try:
#                error = err[0]
#            except Exception:
#                try:
#                    error = err.message
#                except Exception as err2:
#                    error = ''

        self.sig_finished.emit(self, output, str(error))
        self._is_finished = True
243831
def tune_in(self, start=True):
        '''
        
        '''
        self._pre_tune()

        log.debug('Minion \'%s\' trying to tune in', self.opts['id'])

        if start:
            if self.opts.get('beacons_before_connect', False):
                self.setup_beacons(before_connect=True)
            if self.opts.get('scheduler_before_connect', False):
                self.setup_scheduler(before_connect=True)
            self.sync_connect_master()
        if self.connected:
            self._fire_master_minion_start()
            log.info('Minion is ready to receive requests!')

        # Make sure to gracefully handle SIGUSR1
        enable_sigusr1_handler()

        # Make sure to gracefully handle CTRL_LOGOFF_EVENT
        if HAS_WIN_FUNCTIONS:
            salt.utils.win_functions.enable_ctrl_logoff_handler()

        # On first startup execute a state run if configured to do so
        self._state_run()

        self.setup_beacons()
        self.setup_scheduler()

        # schedule the stuff that runs every interval
        ping_interval = self.opts.get('ping_interval', 0) * 60
        if ping_interval > 0 and self.connected:
            def ping_master():
                try:
                    def ping_timeout_handler(*_):
                        if self.opts.get('auth_safemode', False):
                            log.error('** Master Ping failed. Attempting to restart minion**')
                            delay = self.opts.get('random_reauth_delay', 5)
                            log.info('delaying random_reauth_delay %ss', delay)
                            try:
                                self.functions['service.restart'](service_name())
                            except KeyError:
                                # Probably no init system (running in docker?)
                                log.warning(
                                    'ping_interval reached without response '
                                    'from the master, but service.restart '
                                    'could not be run to restart the minion '
                                    'daemon. ping_interval requires that the '
                                    'minion is running under an init system.'
                                )

                    self._fire_master('ping', 'minion_ping', sync=False, timeout_handler=ping_timeout_handler)
                except Exception:
                    log.warning('Attempt to ping master failed.', exc_on_loglevel=logging.DEBUG)
            self.periodic_callbacks['ping'] = tornado.ioloop.PeriodicCallback(ping_master, ping_interval * 1000)
            self.periodic_callbacks['ping'].start()

        # add handler to subscriber
        if hasattr(self, 'pub_channel') and self.pub_channel is not None:
            self.pub_channel.on_recv(self._handle_payload)
        elif self.opts.get('master_type') != 'disable':
            log.error('No connection to master found. Scheduled jobs will not run.')

        if start:
            try:
                self.io_loop.start()
                if self.restart:
                    self.destroy()
            except (KeyboardInterrupt, RuntimeError):  # A RuntimeError can be re-raised by Tornado on shutdown
                self.destroy()
905604
def start():
    
    pool = gevent.threadpool.ThreadPool(len(ENTRYPOINTS))
    for entrypoint, callback, args, kwargs in ENTRYPOINTS:
        cname = callback.__name__
        #1. Retrieve the class which owns the callback
        for name, klass in inspect.getmembers(sys.modules[callback.__module__], inspect.isclass):
            if hasattr(klass, cname):
                service_name = name.lower()
                break
        #2.Start the entrypoint
        callback = getattr(klass(), cname)
        kwargs.update({'service':service_name, 'callback':callback, 'callback_name': cname})
        LOGGER.info('Start service %s[%s].', service_name.capitalize(), cname)
        obj = entrypoint(*args, **kwargs)
        pool.spawn(obj.start, *args, **kwargs)
    pool.join()
    return True
325399
def startup(api=None):
    """"""
    def startup_wrapper(startup_function):
        apply_to_api = hug.API(api) if api else hug.api.from_object(startup_function)
        apply_to_api.add_startup_handler(startup_function)
        return startup_function
    return startup_wrapper
589857
def start_supporting_containers(self, log_syslog=False):
        
        log_syslog = True if self.always_prod else log_syslog
        # in production we always use log_syslog driver (to aggregate all the logs)
        task.start_supporting_containers(
            self.sitedir,
            self.target,
            self.passwords,
            self._get_container_name,
            self.extra_containers,
            log_syslog=log_syslog
            )
568962
function start(mode, target, system, containerDef, container, out, cb) {
    if (mode !== 'preview') {
      main.setup(config, mode, target, system, containerDef, container, out, cb);
    } else {
      cb();
    }
  }
822753
def start(self):
        '''
        
        '''
        # counter metrics for messages
        c_logs_ingested = Counter(
            'napalm_logs_listener_logs_ingested',
            'Count of ingested log messages',
            ['listener_type', 'address', 'port'],
        )
        c_messages_published = Counter(
            'napalm_logs_listener_messages_published',
            'Count of published messages',
            ['listener_type', 'address', 'port'],
        )
        self._setup_ipc()
        log.debug('Using the %s listener', self._listener_type)
        self._setup_listener()
        self.listener.start()
        # Start suicide polling thread
        thread = threading.Thread(target=self._suicide_when_without_parent, args=(os.getppid(),))
        thread.start()
        signal.signal(signal.SIGTERM, self._exit_gracefully)
        self.__up = True
        while self.__up:
            try:
                log_message, log_source = self.listener.receive()
            except ListenerException as lerr:
                if self.__up is False:
                    log.info('Exiting on process shutdown')
                    return
                else:
                    log.error(lerr, exc_info=True)
                    raise NapalmLogsExit(lerr)
            log.debug('Received %s from %s. Queueing to the server.', log_message, log_source)
            if not log_message:
                log.info('Empty message received from %s. Not queueing to the server.', log_source)
                continue
            c_logs_ingested.labels(listener_type=self._listener_type, address=self.address, port=self.port).inc()
            self.pub.send(umsgpack.packb((log_message, log_source)))
            c_messages_published.labels(listener_type=self._listener_type, address=self.address, port=self.port).inc()
636996
def start(self, *args, **kwargs):#pylint:disable=unused-argument
        
        restart = kwargs.get('restart', True)
        return self.run(restart)
470395
private Queue<ImageConfiguration> prepareStart(ServiceHub hub, QueryService queryService, RunService runService, Set<String> imageAliases)
        throws DockerAccessException, MojoExecutionException {
        final Queue<ImageConfiguration> imagesWaitingToStart = new ArrayDeque<>();
        for (StartOrderResolver.Resolvable resolvable : runService.getImagesConfigsInOrder(queryService, getResolvedImages())) {
            final ImageConfiguration imageConfig = (ImageConfiguration) resolvable;

            // Still to check: How to work with linking, volumes, etc ....
            //String imageName = new ImageName(imageConfig.getName()).getFullNameWithTag(registry);
            RunImageConfiguration runConfig = imageConfig.getRunConfiguration();

            RegistryService.RegistryConfig registryConfig = getRegistryConfig(pullRegistry);
            ImagePullManager pullManager = getImagePullManager(determinePullPolicy(runConfig), autoPull);

            hub.getRegistryService().pullImageWithPolicy(imageConfig.getName(), pullManager, registryConfig,
                                                         queryService.hasImage(imageConfig.getName()));

            NetworkConfig config = runConfig.getNetworkingConfig();
            List<String> bindMounts = extractBindMounts(runConfig.getVolumeConfiguration());
            List<VolumeConfiguration> volumes = getVolumes();
            if(!bindMounts.isEmpty() && volumes != null) {
                runService.createVolumesAsPerVolumeBinds(hub, bindMounts, volumes);
            }
            if (autoCreateCustomNetworks && config.isCustomNetwork()) {
                runService.createCustomNetworkIfNotExistant(config.getCustomNetwork());
            }
            imagesWaitingToStart.add(imageConfig);
            updateAliasesSet(imageAliases, imageConfig.getAlias());
        }
        return imagesWaitingToStart;
    }
959209
public synchronized void startup(AppContextWrapper context) {
		ContainerRegistryBuilder cb;
		try {
			cb = (ContainerRegistryBuilder) context.getAttribute(ContainerRegistryBuilder.APPLICATION_CONTEXT_ATTRIBUTE_NAME);
			if (cb == null) {
				Debug.logError("[JdonFramework] at first call prepare method");
				return;
			}
			if (cb.isKernelStartup())
				return;
			ContainerDirector cd = new ContainerDirector(cb);
			cd.startup();
		} catch (Exception ex) {
			Debug.logError(ex, module);
		}
	}
1028162
def start(self, ignore_state=False):
        """"""
        self.logger.debug("Start service")
        self._toggle_running(True, ignore_state)
1060845
def _start(self):
        """"""
        assert self._tempdir is not None
        assert self._process is None
        self._process = subprocess.Popen(
            [
                self.paths.slapd,
                '-f', self._slapd_conf,
                '-h', self.uri,
                '-d', str(self.slapd_debug),
            ],
            stdout=sys.stdout,
            stderr=sys.stderr,
        )
        self._poll_slapd(timeout=self.max_server_startup_delay)
63870
def build_and_start(query, directory):
    """"""

    Async(target=grep, args=[query, directory]).start()