// GetDockercfgAuth reads a ~/.dockercfg file and returns the username and password
// of the given docker index server.
325444
func GetAuthInfo(indexServer string) (string, string, error) {
	// official docker registry
	if indexServer == defaultIndexURL {
		indexServer = defaultIndexURLAuth
	}
	dockerCfgPath := path.Join(getHomeDir(), ".docker", dockercfgFileName)
	if _, err := os.Stat(dockerCfgPath); err == nil {
		j, err := ioutil.ReadFile(dockerCfgPath)
		if err != nil {
			return "", "", err
		}
		var dockerAuth types.DockerConfigFile
		if err := json.Unmarshal(j, &dockerAuth); err != nil {
			return "", "", err
		}
		// try the normal case
		if c, ok := dockerAuth.AuthConfigs[indexServer]; ok {
			return decodeDockerAuth(c.Auth)
		}
	} else if os.IsNotExist(err) {
		oldDockerCfgPath := path.Join(getHomeDir(), dockercfgFileNameOld)
		if _, err := os.Stat(oldDockerCfgPath); err != nil {
			return "", "", nil //missing file is not an error
		}
		j, err := ioutil.ReadFile(oldDockerCfgPath)
		if err != nil {
			return "", "", err
		}
		var dockerAuthOld map[string]types.DockerAuthConfigOld
		if err := json.Unmarshal(j, &dockerAuthOld); err != nil {
			return "", "", err
		}
		if c, ok := dockerAuthOld[indexServer]; ok {
			return decodeDockerAuth(c.Auth)
		}
	} else {
		// if file is there but we can't stat it for any reason other
		// than it doesn't exist then stop
		return "", "", fmt.Errorf("%s - %v", dockerCfgPath, err)
	}
	return "", "", nil
}
296317
func getDockerClient(dockerEndpoint string) (*dockerapi.Client, error) {
	if len(dockerEndpoint) > 0 {
		klog.Infof("Connecting to docker on %s", dockerEndpoint)
		return dockerapi.NewClient(dockerEndpoint, "", nil, nil)
	}
	return dockerapi.NewEnvClient()
}
524695
func GetDockerNetworkName(nwID string) (string, string, string, error) {
	// first see if we can find the network in docknet oper state
	dnetOper, err := docknet.FindDocknetByUUID(nwID)
	if err == nil {
		return dnetOper.TenantName, dnetOper.NetworkName, dnetOper.ServiceName, nil
	}
	if pluginMode == core.SwarmMode {
		log.Errorf("Unable to find docknet info in objstore")
		return "", "", "", err
	}

	// create docker client
	docker, err := dockerclient.NewClient("unix:///var/run/docker.sock", "", nil, nil)
	if err != nil {
		log.Errorf("Unable to connect to docker. Error %v", err)
		return "", "", "", errors.New("unable to connect to docker")
	}

	nwIDFilter := filters.NewArgs()
	nwIDFilter.Add("id", nwID)
	nwList, err := docker.NetworkList(context.Background(), types.NetworkListOptions{Filters: nwIDFilter})
	if err != nil {
		log.Infof("Error: %v", err)
		return "", "", "", err
	}

	if len(nwList) != 1 {
		if len(nwList) == 0 {
			err = errors.New("network UUID not found")
		} else {
			err = errors.New("more than one network found with the same ID")
		}
		return "", "", "", err
	}
	nw := nwList[0]
	log.Infof("Returning network name %s for ID %s", nw.Name, nwID)

	// parse the network name
	var tenantName, netName, serviceName string
	names := strings.Split(nw.Name, "/")
	if len(names) == 2 {
		// has service.network/tenant format.
		tenantName = names[1]

		// parse service and network names
		sNames := strings.Split(names[0], ".")
		if len(sNames) == 2 {
			// has service.network format
			netName = sNames[1]
			serviceName = sNames[0]
		} else {
			netName = sNames[0]
		}
	} else if len(names) == 1 {
		// has service.network in default tenant
		tenantName = defaultTenantName

		// parse service and network names
		sNames := strings.Split(names[0], ".")
		if len(sNames) == 2 {
			// has service.network format
			netName = sNames[1]
			serviceName = sNames[0]
		} else {
			netName = sNames[0]
		}
	} else {
		log.Errorf("Invalid network name format for network %s", nw.Name)
		return "", "", "", errors.New("invalid format")
	}

	return tenantName, netName, serviceName, nil
}
1053902
func (m *MockAPICalls) GetContainerProfileInfo(arg0 names_v2.MachineTag) ([]*provisioner.LXDProfileResult, error) {
	ret := m.ctrl.Call(m, "GetContainerProfileInfo", arg0)
	ret0, _ := ret[0].([]*provisioner.LXDProfileResult)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
238469
func (e *DockerRegistryServiceController) getDockerRegistryLocations() []string {
	ret := append([]string{}, e.additionalRegistryURLs...)
	for _, location := range serviceLocations {
		ret = append(ret, getDockerRegistryLocations(e.serviceLister, location, e.clusterDNSSuffix)...)
	}
	klog.V(4).Infof("found docker registry urls: %v", ret)
	return ret
}
674232
func getRegistryClient(clientConfig *restclient.Config, registryCABundle string, registryInsecure bool) (*http.Client, error) {
	var (
		err                      error
		cadata                   []byte
		registryCABundleIncluded = false
		token                    = clientConfig.BearerToken
	)

	if len(token) == 0 {
		return nil, errNoToken
	}

	if len(registryCABundle) > 0 {
		cadata, err = ioutil.ReadFile(registryCABundle)
		if err != nil {
			return nil, fmt.Errorf("failed to read registry ca bundle: %v", err)
		}
	}

	// copy the config
	registryClientConfig := *clientConfig
	registryClientConfig.TLSClientConfig.Insecure = registryInsecure

	// zero out everything we don't want to use
	registryClientConfig.BearerToken = ""
	registryClientConfig.CertFile = ""
	registryClientConfig.CertData = []byte{}
	registryClientConfig.KeyFile = ""
	registryClientConfig.KeyData = []byte{}

	if registryInsecure {
		// it's not allowed to specify insecure flag together with CAs
		registryClientConfig.CAFile = ""
		registryClientConfig.CAData = []byte{}

	} else if len(cadata) > 0 && len(registryClientConfig.CAData) == 0 {
		// If given, we want to append cabundle to the resulting tlsConfig.RootCAs. However, if we
		// leave CAData unset, tlsConfig may not be created. We could append the caBundle to the
		// CAData here directly if we were ok doing a binary magic, which is not the case.
		registryClientConfig.CAData = cadata
		registryCABundleIncluded = true
	}

	// we have to set a username to something for the Docker login but it's not actually used
	registryClientConfig.Username = "unused"

	// set the "password" to be the token
	registryClientConfig.Password = token

	tlsConfig, err := restclient.TLSConfigFor(&registryClientConfig)
	if err != nil {
		return nil, err
	}

	// Add the CA bundle to the client config's CA roots if provided and we haven't done that already.
	// FIXME: handle registryCABundle on one place
	if tlsConfig != nil && len(cadata) > 0 && !registryCABundleIncluded && !registryInsecure {
		if tlsConfig.RootCAs == nil {
			tlsConfig.RootCAs = x509.NewCertPool()
		}
		tlsConfig.RootCAs.AppendCertsFromPEM(cadata)
	}

	transport := knet.SetTransportDefaults(&http.Transport{
		TLSClientConfig: tlsConfig,
	})

	wrappedTransport, err := restclient.HTTPWrappersForConfig(&registryClientConfig, transport)
	if err != nil {
		return nil, err
	}

	return &http.Client{
		Transport: wrappedTransport,
	}, nil
}
813621
func getConfig(c context.Context) config.ConfigurationServer {
	return c.Value(&cfgKey).(config.ConfigurationServer)
}
319556
func GetDocknetName(tenantName, networkName, epgName string) string {

	netName := ""
	// if epg is specified, always use that, else use nw
	if epgName == "" {
		netName = networkName
	} else {
		netName = epgName
	}

	// add tenant suffix if not the default tenant
	if tenantName != defaultTenantName {
		netName = netName + "/" + tenantName
	}

	return netName
}
626078
func getDockerOS(serverHeader string) string {
	var osType string
	matches := headerRegexp.FindStringSubmatch(serverHeader)
	if len(matches) > 0 {
		osType = matches[1]
	}
	return osType
}
1371531
func GetInfo() string {
	if metadata.Version == "" {
		metadata.Version = "development build"
	}

	ccinfo := fmt.Sprintf(" Base Image Version: %s\n"+
		"  Base Docker Namespace: %s\n"+
		"  Base Docker Label: %s\n"+
		"  Docker Namespace: %s\n",
		metadata.BaseVersion, metadata.BaseDockerNamespace,
		metadata.BaseDockerLabel, metadata.DockerNamespace)

	return fmt.Sprintf("%s:\n Version: %s\n Commit SHA: %s\n Go version: %s\n"+
		" OS/Arch: %s\n"+
		" Chaincode:\n %s\n",
		ProgramName, metadata.Version, metadata.CommitSHA, runtime.Version(),
		fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH), ccinfo)
}
1018900
func GetOrRegisterGauge(name string, r Registry) Gauge {
	if nil == r {
		r = DefaultRegistry
	}
	return r.GetOrRegister(name, NewGauge).(Gauge)
}
397564
func handleDockercfgContent(username, password, email, server string) ([]byte, error) {
	dockercfgAuth := credentialprovider.DockerConfigEntry{
		Username: username,
		Password: password,
		Email:    email,
	}

	dockerCfg := map[string]credentialprovider.DockerConfigEntry{server: dockercfgAuth}

	return json.Marshal(dockerCfg)
}
319453
func (r *Registry) Token(ctx context.Context, url string) (string, error) {
	r.Logf("registry.token url=%s", url)

	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return "", err
	}

	client := http.DefaultClient
	if r.Opt.Insecure {
		client = &http.Client{
			Timeout: r.Opt.Timeout,
			Transport: &http.Transport{
				TLSClientConfig: &tls.Config{
					InsecureSkipVerify: true,
				},
			},
		}
	}

	resp, err := client.Do(req.WithContext(ctx))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusForbidden && gcrMatcher.MatchString(url) {
		// GCR is not sending HTTP 401 on missing credentials but a HTTP 403 without
		// any further information about why the request failed. Sending the credentials
		// from the Docker config fixes this.
		return "", ErrBasicAuth
	}

	a, err := isTokenDemand(resp)
	if err != nil {
		return "", err
	}

	if a == nil {
		r.Logf("registry.token authService=nil")
		return "", nil
	}

	authReq, err := a.Request(r.Username, r.Password)
	if err != nil {
		return "", err
	}
	resp, err = http.DefaultClient.Do(authReq.WithContext(ctx))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("getting token failed with StatusCode != StatusOK but %d", resp.StatusCode)
	}

	var authToken authToken
	if err := json.NewDecoder(resp.Body).Decode(&authToken); err != nil {
		return "", err
	}

	return authToken.String()
}
639142
func getPidForContainer(id string) (int, error) {
	pid := 0

	// memory is chosen randomly, any cgroup used by docker works
	cgroupType := "memory"

	cgroupRoot, err := findCgroupMountpoint(cgroupType)
	if err != nil {
		return pid, err
	}

	cgroupThis, err := getThisCgroup(cgroupType)
	if err != nil {
		return pid, err
	}

	id += "*"

	attempts := []string{
		filepath.Join(cgroupRoot, cgroupThis, id, "tasks"),
		// With more recent lxc versions use, cgroup will be in lxc/
		filepath.Join(cgroupRoot, cgroupThis, "lxc", id, "tasks"),
		// With more recent docker, cgroup will be in docker/
		filepath.Join(cgroupRoot, cgroupThis, "docker", id, "tasks"),
		// Even more recent docker versions under systemd use docker-<id>.scope/
		filepath.Join(cgroupRoot, "system.slice", "docker-"+id+".scope", "tasks"),
		// Even more recent docker versions under cgroup/systemd/docker/<id>/
		filepath.Join(cgroupRoot, "..", "systemd", "docker", id, "tasks"),
		// Kubernetes with docker and CNI is even more different
		filepath.Join(cgroupRoot, "..", "systemd", "kubepods", "*", "pod*", id, "tasks"),
		// Another flavor of containers location in recent kubernetes 1.11+
		filepath.Join(cgroupRoot, cgroupThis, "kubepods.slice", "kubepods-besteffort.slice", "*", "docker-"+id+".scope", "tasks"),
		// When runs inside of a container with recent kubernetes 1.11+
		filepath.Join(cgroupRoot, "kubepods.slice", "kubepods-besteffort.slice", "*", "docker-"+id+".scope", "tasks"),
	}

	var filename string
	for _, attempt := range attempts {
		filenames, _ := filepath.Glob(attempt)
		if len(filenames) > 1 {
			return pid, fmt.Errorf("Ambiguous id supplied: %v", filenames)
		} else if len(filenames) == 1 {
			filename = filenames[0]
			break
		}
	}

	if filename == "" {
		return pid, fmt.Errorf("Unable to find container: %v", id[:len(id)-1])
	}

	output, err := ioutil.ReadFile(filename)
	if err != nil {
		return pid, err
	}

	result := strings.Split(string(output), "\n")
	if len(result) == 0 || len(result[0]) == 0 {
		return pid, fmt.Errorf("No pid found for container")
	}

	pid, err = strconv.Atoi(result[0])
	if err != nil {
		return pid, fmt.Errorf("Invalid pid '%s': %s", result[0], err)
	}

	return pid, nil
}
1282609
func getCgroupStats(cadvisor cadvisor.Interface, containerName string, updateStats bool) (*cadvisorapiv2.ContainerStats, error) {
	info, err := getCgroupInfo(cadvisor, containerName, updateStats)
	if err != nil {
		return nil, err
	}
	stats, found := latestContainerStats(info)
	if !found {
		return nil, fmt.Errorf("failed to get latest stats from container info for %q", containerName)
	}
	return stats, nil
}
968225
func (a *AgentServer) GetDockerLogs(dockerID string, logs *string) error {
	cmd := exec.Command("docker", "logs", "--tail=2000", dockerID)
	output, err := cmd.CombinedOutput()
	if err != nil {
		plog.WithError(err).WithField("dockerid", dockerID).Error("Unable to retrieve logs from docker")
		return err
	}
	*logs = string(output)
	return nil
}
16617
func GetFromDocker(id string) (NsHandle, error) {
	pid, err := getPidForContainer(id)
	if err != nil {
		return -1, err
	}
	return GetFromPid(pid)
}