Initialize Docker Client
491701
def init_docker!
    Docker.options = @options
    set_docker_url
    LOG.debug { "Docker URL: #{Docker.url}"}
    LOG.debug { "Docker Options: #{Docker.options.inspect}"}
    Docker.validate_version!
  end
1164216
def _init_client():
    
    if client is not None:
        return

    global _mysql_kwargs, _table_name
    _mysql_kwargs = {
        'host': __opts__.get('mysql.host', '127.0.0.1'),
        'user': __opts__.get('mysql.user', None),
        'passwd': __opts__.get('mysql.password', None),
        'db': __opts__.get('mysql.database', _DEFAULT_DATABASE_NAME),
        'port': __opts__.get('mysql.port', 3306),
        'unix_socket': __opts__.get('mysql.unix_socket', None),
        'connect_timeout': __opts__.get('mysql.connect_timeout', None),
        'autocommit': True,
    }
    _table_name = __opts__.get('mysql.table_name', _table_name)
    # TODO: handle SSL connection parameters

    for k, v in _mysql_kwargs.items():
        if v is None:
            _mysql_kwargs.pop(k)
    kwargs_copy = _mysql_kwargs.copy()
    kwargs_copy['passwd'] = "<hidden>"
    log.info("mysql_cache: Setting up client with params: %r", kwargs_copy)
    # The MySQL client is created later on by run_query
    _create_table()
789036
def create(self):
        """"""

        try:
            image_infos = yield from self._get_image_information()
        except DockerHttp404Error:
            log.info("Image %s is missing pulling it from docker hub", self._image)
            yield from self.pull_image(self._image)
            image_infos = yield from self._get_image_information()
            if image_infos is None:
                raise DockerError("Can't get image informations, please try again.")

        params = {
            "Hostname": self._name,
            "Name": self._name,
            "Image": self._image,
            "NetworkDisabled": True,
            "Tty": True,
            "OpenStdin": True,
            "StdinOnce": False,
            "HostConfig": {
                "CapAdd": ["ALL"],
                "Privileged": True,
                "Binds": self._mount_binds(image_infos)
            },
            "Volumes": {},
            "Env": ["container=docker"],  # Systemd compliant: https://github.com/GNS3/gns3-server/issues/573
            "Cmd": [],
            "Entrypoint": image_infos.get("Config", {"Entrypoint": []})["Entrypoint"]
        }

        if params["Entrypoint"] is None:
            params["Entrypoint"] = []
        if self._start_command:
            params["Cmd"] = shlex.split(self._start_command)
        if len(params["Cmd"]) == 0:
            params["Cmd"] = image_infos.get("Config", {"Cmd": []})["Cmd"]
            if params["Cmd"] is None:
                params["Cmd"] = []
        if len(params["Cmd"]) == 0 and len(params["Entrypoint"]) == 0:
            params["Cmd"] = ["/bin/sh"]
        params["Entrypoint"].insert(0, "/gns3/init.sh")  # FIXME /gns3/init.sh is not found?

        # Give the information to the container on how many interface should be inside
        params["Env"].append("GNS3_MAX_ETHERNET=eth{}".format(self.adapters - 1))
        # Give the information to the container the list of volume path mounted
        params["Env"].append("GNS3_VOLUMES={}".format(":".join(self._volumes)))

        if self._environment:
            for e in self._environment.strip().split("\n"):
                e = e.strip()
                if not e.startswith("GNS3_"):
                    params["Env"].append(e)

        if self._console_type == "vnc":
            yield from self._start_vnc()
            params["Env"].append("QT_GRAPHICSSYSTEM=native")  # To fix a Qt issue: https://github.com/GNS3/gns3-server/issues/556
            params["Env"].append("DISPLAY=:{}".format(self._display))
            params["HostConfig"]["Binds"].append("/tmp/.X11-unix/:/tmp/.X11-unix/")

        result = yield from self.manager.query("POST", "containers/create", data=params)
        self._cid = result['Id']
        log.info("Docker container '{name}' [{id}] created".format(
            name=self._name, id=self._id))
        return True
1342451
def _initialize(cls, port, secret):
        
        cls._port = port
        cls._secret = secret
1146447
def Init(service_client=None):
  """"""
  global CONN
  global label_map
  global unknown_label

  if service_client is None:
    service_client_cls = fs_client.InsecureGRPCServiceClient

    fleetspeak_message_listen_address = (
        config.CONFIG["Server.fleetspeak_message_listen_address"] or None)
    fleetspeak_server = config.CONFIG["Server.fleetspeak_server"] or None

    if fleetspeak_message_listen_address is None and fleetspeak_server is None:
      logging.warning(
          "Missing config options `Server.fleetspeak_message_listen_address', "
          "`Server.fleetspeak_server', at least one of which is required to "
          "initialize a connection to Fleetspeak; Not using Fleetspeak.")
      return

    service_client = service_client_cls(
        "GRR",
        fleetspeak_message_listen_address=fleetspeak_message_listen_address,
        fleetspeak_server=fleetspeak_server,
        threadpool_size=50)

  unknown_label = config.CONFIG["Server.fleetspeak_unknown_label"]
  label_map = {}
  for entry in config.CONFIG["Server.fleetspeak_label_map"]:
    key, value = entry.split(":")
    label_map[key] = value

  CONN = service_client
  logging.info("Fleetspeak connector initialized.")
851550
def _start_aux(self):
        

        # We can not use the API because docker doesn't expose a websocket api for exec
        # https://github.com/GNS3/gns3-gui/issues/1039
        process = yield from asyncio.subprocess.create_subprocess_exec(
            "docker", "exec", "-i", self._cid, "/gns3/bin/busybox", "script", "-qfc", "while true; do TERM=vt100 /gns3/bin/busybox sh; done", "/dev/null",
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.STDOUT,
            stdin=asyncio.subprocess.PIPE)
        server = AsyncioTelnetServer(reader=process.stdout, writer=process.stdin, binary=True, echo=True)
        self._telnet_servers.append((yield from asyncio.start_server(server.run, self._manager.port_manager.console_host, self.aux)))
        log.debug("Docker container '%s' started listen for auxilary telnet on %d", self.name, self.aux)
298866
def _startup(self):
        
        status = (True, None)
        try:
            s_dict = {}
            # rewrite the yml file to exclusively lowercase
            with open(self.startup_file, 'r') as sup:
                vent_startup = sup.read()
            with open(self.startup_file, 'w') as sup:
                for line in vent_startup:
                    sup.write(line.lower())
            with open(self.startup_file, 'r') as sup:
                s_dict = yaml.safe_load(sup.read())
            if 'vent.cfg' in s_dict:
                v_cfg = Template(self.vent_config)
                for section in s_dict['vent.cfg']:
                    for option in s_dict['vent.cfg'][section]:
                        val = ('no', 'yes')[
                            s_dict['vent.cfg'][section][option]]
                        v_status = v_cfg.add_option(section, option, value=val)
                        if not v_status[0]:
                            v_cfg.set_option(section, option, val)
                v_cfg.write_config()
                del s_dict['vent.cfg']
            tool_d = {}
            extra_options = ['info', 'service', 'settings', 'docker', 'gpu']
            s_dict_c = copy.deepcopy(s_dict)
            # TODO check for repo or image type
            for repo in s_dict_c:
                repository = Repository(System().manifest)
                repository.repo = repo
                repository._clone()
                repo_path, org, r_name = self.path_dirs.get_path(repo)
                get_tools = []
                for tool in s_dict_c[repo]:
                    t_branch = 'master'
                    t_version = 'HEAD'
                    if 'branch' in s_dict[repo][tool]:
                        t_branch = s_dict[repo][tool]['branch']
                    if 'version' in s_dict[repo][tool]:
                        t_version = s_dict[repo][tool]['version']
                    get_tools.append((tool, t_branch, t_version))

                available_tools = AvailableTools(repo_path, tools=get_tools)
                for tool in s_dict_c[repo]:
                    # if we can't find the tool in that repo, skip over this
                    # tool and notify in the logs
                    t_path, t_path_cased = PathDirs.rel_path(
                        tool, available_tools)
                    if t_path is None:
                        self.logger.error("Couldn't find tool " + tool + ' in'
                                          ' repo ' + repo)
                        continue
                    # ensure no NoneType iteration errors
                    if s_dict_c[repo][tool] is None:
                        s_dict[repo][tool] = {}
                    # check if we need to configure instances along the way
                    instances = 1
                    if 'settings' in s_dict[repo][tool]:
                        if 'instances' in s_dict[repo][tool]['settings']:
                            instances = int(s_dict[repo][tool]
                                            ['settings']['instances'])
                    # add the tool
                    t_branch = 'master'
                    t_version = 'HEAD'
                    t_image = None
                    add_tools = None
                    add_tools = [(t_path_cased, '')]
                    if 'branch' in s_dict[repo][tool]:
                        t_branch = s_dict[repo][tool]['branch']
                    if 'version' in s_dict[repo][tool]:
                        t_version = s_dict[repo][tool]['version']
                    if 'image' in s_dict[repo][tool]:
                        t_image = s_dict[repo][tool]['image']
                    repository.add(
                        repo, add_tools, branch=t_branch, version=t_version, image_name=t_image)
                    manifest = Template(self.manifest)
                    # update the manifest with extra defined runtime settings
                    base_section = ':'.join([org, r_name, t_path,
                                             t_branch, t_version])
                    for option in extra_options:
                        if option in s_dict[repo][tool]:
                            opt_dict = manifest.option(base_section, option)
                            # add new values defined into default options for
                            # that tool, don't overwrite them
                            if opt_dict[0]:
                                opt_dict = json.loads(opt_dict[1])
                            else:
                                opt_dict = {}
                            # stringify values for vent
                            for v in s_dict[repo][tool][option]:
                                pval = s_dict[repo][tool][option][v]
                                s_dict[repo][tool][option][v] = json.dumps(
                                    pval)
                            opt_dict.update(s_dict[repo][tool][option])
                            manifest.set_option(base_section, option,
                                                json.dumps(opt_dict))
                    # copy manifest info into new sections if necessary
                    if instances > 1:
                        for i in range(2, instances + 1):
                            i_section = base_section.rsplit(':', 2)
                            i_section[0] += str(i)
                            i_section = ':'.join(i_section)
                            manifest.add_section(i_section)
                            for opt_val in manifest.section(base_section)[1]:
                                if opt_val[0] == 'name':
                                    manifest.set_option(i_section, opt_val[0],
                                                        opt_val[1] + str(i))
                                else:
                                    manifest.set_option(i_section, opt_val[0],
                                                        opt_val[1])
                    manifest.write_config()

            tool_d = {}
            tools = Tools()
            # start tools, if necessary
            for repo in s_dict:
                for tool in s_dict[repo]:
                    if 'start' in s_dict[repo][tool]:
                        if s_dict[repo][tool]['start']:
                            local_instances = 1
                            if 'settings' in s_dict[repo][tool] and 'instances' in s_dict[repo][tool]['settings']:
                                local_instances = int(
                                    s_dict[repo][tool]['settings']['instances'])
                            t_branch = 'master'
                            t_version = 'HEAD'
                            if 'branch' in s_dict[repo][tool]:
                                t_branch = s_dict[repo][tool]['branch']
                            if 'version' in s_dict[repo][tool]:
                                t_version = s_dict[repo][tool]['version']
                            for i in range(1, local_instances + 1):
                                i_name = tool + str(i) if i != 1 else tool
                                i_name = i_name.replace('@', '')
                                tool_d.update(
                                    tools._prep_start(repo, i_name)[1])

            if tool_d:
                tools.start(tool_d, None, is_tool_d=True)
        except Exception as e:  # pragma: no cover
            self.logger.error('Startup failed because: {0}'.format(str(e)))
            status = (False, str(e))
        return status
723488
def create(output_dir):
    """"""
    template_path = os.path.join(os.path.dirname(__file__), 'project_template')

    click.secho('Let\'s create a new component!', fg='green')
    name = click.prompt('What is the name of this component (ex. python-pip)?')

    click.secho('')
    click.secho('We assume this will be pushed to GitHub and Docker Hub eventually, but these don\'t have to exist yet.', fg='green')
    repo_owner = click.prompt('GitHub repo owner (i.e. your username or organization name)')
    repo_name = click.prompt('GitHub repo name', default=name)
    dockerhub_owner = click.prompt('Docker Hub repo owner', default=repo_owner)
    dockerhub_name = click.prompt('Docker Hub repo name', default=repo_name)

    license_owner = click.prompt('Who should be the copyright owner on project?', default=repo_owner)

    extra_context = {
        'name': name,
        'name_shields_io': name.replace('-', '--'),
        'current_year': datetime.datetime.now().year,
        'dependencies_cli_version': __version__,
        'repo_owner': repo_owner,
        'repo_name': repo_name,
        'dockerhub_owner': dockerhub_owner,
        'dockerhub_name': dockerhub_name,
        'license_owner': license_owner,
    }
    project_dir = cookiecutter(template_path, no_input=True, extra_context=extra_context, output_dir=output_dir)

    click.secho('')
    click.secho('{name} is ready to go, `cd {project_dir}` and try running `dependencies test`!'.format(name=name, project_dir=project_dir), fg='green')
    click.secho(
        'We started you out with a fully functioning component based in python.\n' +
        'Once you\'ve got a handle on how it works then you can change it to whatever language you want.'
    )
221533
def _container_init(self):
        
        if ENV_CONTAINER in os.environ:
            if os.environ[ENV_CONTAINER] in ['docker', 'oci']:
                self._in_container = True
        if ENV_HOST_SYSROOT in os.environ:
            self._host_sysroot = os.environ[ENV_HOST_SYSROOT]
        use_sysroot = self._in_container and self._host_sysroot != '/'
        if use_sysroot:
            host_tmp_dir = os.path.abspath(self._host_sysroot + self._tmp_dir)
            self._tmp_dir = host_tmp_dir
        return self._host_sysroot if use_sysroot else None
992922
def main(args):
  """"""

  grr_config.CONFIG.AddContext(contexts.CLIENT_BUILD_CONTEXT)

  if args.subparser_name == "generate_client_config":
    # We don't need a full init to just build a config.
    GetClientConfig(args.client_config_output)
    return

  # TODO(user): Find out if adding the client-builder context is still
  # necessary.
  context = FLAGS.context
  context.append(contexts.CLIENT_BUILD_CONTEXT)

  config_lib.SetPlatformArchContext()
  config_lib.ParseConfigCommandLine()

  # Use basic console output logging so we can see what is happening.
  logger = logging.getLogger()
  handler = logging.StreamHandler()
  handler.setLevel(logging.DEBUG if FLAGS.verbose else logging.INFO)
  logger.handlers = [handler]

  if args.subparser_name == "build":
    if grr_config.CONFIG["Client.fleetspeak_enabled"]:
      if grr_config.CONFIG.ContextApplied("Platform:Darwin"):
        if not args.fleetspeak_service_config:
          raise RuntimeError("--fleetspeak_service_config must be provided.")
        if not grr_config.CONFIG.Get("ClientBuilder.install_dir"):
          raise RuntimeError("ClientBuilder.install_dir must be set.")
        if not grr_config.CONFIG.Get("ClientBuilder.fleetspeak_plist_path"):
          raise RuntimeError("ClientBuilder.fleetspeak_plist_path must be set.")
      grr_config.CONFIG.Set("ClientBuilder.client_path",
                            "grr_response_client.grr_fs_client")
    TemplateBuilder().BuildTemplate(
        context=context,
        output=args.output,
        fleetspeak_service_config=args.fleetspeak_service_config)
  elif args.subparser_name == "repack":
    if args.debug_build:
      context.append("DebugClientBuild Context")
    result_path = repacking.TemplateRepacker().RepackTemplate(
        args.template,
        args.output_dir,
        context=context,
        sign=args.sign,
        signed_template=args.signed_template)

    if not result_path:
      raise ErrorDuringRepacking(" ".join(sys.argv[:]))
  elif args.subparser_name == "repack_multiple":

    # Resolve globs manually on Windows.
    templates = []
    for template in args.templates:
      if "*" in template:
        templates.extend(glob.glob(template))
      else:
        # This could go through glob but then we'd swallow errors for
        # non existing files.
        templates.append(template)

    repack_configs = []
    for repack_config in args.repack_configs:
      if "*" in repack_config:
        repack_configs.extend(glob.glob(repack_config))
      else:
        # This could go through glob but then we'd swallow errors for
        # non existing files.
        repack_configs.append(repack_config)

    MultiTemplateRepacker().RepackTemplates(
        repack_configs,
        templates,
        args.output_dir,
        config=FLAGS.config,
        sign=args.sign,
        signed_template=args.signed_template)
  elif args.subparser_name == "sign_template":
    repacking.TemplateRepacker().SignTemplate(
        args.template, args.output_file, context=context)
    if not os.path.exists(args.output_file):
      raise RuntimeError("Signing failed: output not written")
731573
def connect(self):
        """"""
        try:
            ret = docker.from_env()
        except Exception as e:
            logger.error("docker plugin - Can not connect to Docker ({})".format(e))
            ret = None

        return ret
14780
def load(self):
        
        if self.exists():
            with open(self.dot_file, 'r') as handle:
                self.update(json.load(handle))
        if self.options['context'] is not None:
            self['context'] = self.options['context']
        else:
            self.options['context'] = self['context']
        if self.options['defaults'] is not None:
            self['defaults'] = self.options['defaults']
        else:
            self.options['defaults'] = self['defaults']
        if self.options['output'] is not None:
            self['output'] = self.options['output']

        if self.options.get('inclusive', False):
            self['inclusive'] = True

        if self.options.get('exclude', []):
            self['exclude'].extend(self.options['exclude'])

        if self['output'] is None:
            self['output'] = os.path.join(os.getcwd(), 'dockerstache-output')
        self['output_path'] = self.abs_output_dir()
        self['input_path'] = self.abs_input_dir()
        if self['context'] is not None:
            self['context_path'] = absolute_path(self['context'])
        if self['defaults'] is not None:
            self['defaults_path'] = absolute_path(self['defaults'])
283877
def _initialize_connection(api_key, app_key):
    '''
    
    '''
    if api_key is None:
        raise SaltInvocationError('api_key must be specified')
    if app_key is None:
        raise SaltInvocationError('app_key must be specified')
    options = {
        'api_key': api_key,
        'app_key': app_key
    }
    datadog.initialize(**options)
486754
def start(client, container, interactive=True, stdout=None, stderr=None, stdin=None, logs=None):
    

    operation = RunOperation(client, container, interactive=interactive, stdout=stdout,
                             stderr=stderr, stdin=stdin, logs=logs)

    PseudoTerminal(client, operation).start()
1093805
def init(*args, **kwargs):
    
    global _initial_client
    client = Client(*args, **kwargs)
    Hub.current.bind_client(client)
    rv = _InitGuard(client)
    if client is not None:
        _initial_client = weakref.ref(client)
    return rv
843395
public function init()
    {
        $this->socketurl = sprintf($this->config->mastersocket->value,
            crc32(Daemon::$config->pidfile->value . "\x00" . Daemon::$config->user->value . "\x00" . Daemon::$config->group->value));
        if (Daemon::$process instanceof Thread\IPC) {
            $this->pool = MasterPool::getInstance(['listen' => $this->socketurl]);
            $this->pool->appInstance = $this;
            $this->pool->onReady();
        }
    }
233158
private com.github.dockerjava.api.DockerClient createDockerClient() {
        return DockerClientImpl.getInstance(getDockerClientConfig())
                .withDockerCmdExecFactory(new JerseyDockerCmdExecFactory());
    }