// populateGUIArchive stores the uploaded Juju GUI archive in provider storage,
// updates the GUI metadata and set the current Juju GUI version.
185255
func (c *BootstrapCommand) populateGUIArchive(st *state.State, env environs.BootstrapEnviron) error {
	agentConfig := c.CurrentConfig()
	dataDir := agentConfig.DataDir()
	guistorage, err := st.GUIStorage()
	if err != nil {
		return errors.Trace(err)
	}
	defer guistorage.Close()
	gui, err := agenttools.ReadGUIArchive(dataDir)
	if err != nil {
		return errors.Annotate(err, "cannot fetch GUI info")
	}
	f, err := os.Open(filepath.Join(agenttools.SharedGUIDir(dataDir), "gui.tar.bz2"))
	if err != nil {
		return errors.Annotate(err, "cannot read GUI archive")
	}
	defer f.Close()
	if err := guistorage.Add(f, binarystorage.Metadata{
		Version: gui.Version.String(),
		Size:    gui.Size,
		SHA256:  gui.SHA256,
	}); err != nil {
		return errors.Annotate(err, "cannot store GUI archive")
	}
	if err = st.GUISetVersion(gui.Version); err != nil {
		return errors.Annotate(err, "cannot set current GUI version")
	}
	return nil
}
1108648
func loadArchiveFiles(in io.Reader) ([]*BufferedFile, error) {
	unzipped, err := gzip.NewReader(in)
	if err != nil {
		return nil, err
	}
	defer unzipped.Close()

	files := []*BufferedFile{}
	tr := tar.NewReader(unzipped)
	for {
		b := bytes.NewBuffer(nil)
		hd, err := tr.Next()
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, err
		}

		if hd.FileInfo().IsDir() {
			// Use this instead of hd.Typeflag because we don't have to do any
			// inference chasing.
			continue
		}

		switch hd.Typeflag {
		// We don't want to process these extension header files.
		case tar.TypeXGlobalHeader, tar.TypeXHeader:
			continue
		}

		// Archive could contain \ if generated on Windows
		delimiter := "/"
		if strings.ContainsRune(hd.Name, '\\') {
			delimiter = "\\"
		}

		parts := strings.Split(hd.Name, delimiter)
		n := strings.Join(parts[1:], delimiter)

		// Normalize the path to the / delimiter
		n = strings.Replace(n, delimiter, "/", -1)

		if path.IsAbs(n) {
			return nil, errors.New("chart illegally contains absolute paths")
		}

		n = path.Clean(n)
		if n == "." {
			// In this case, the original path was relative when it should have been absolute.
			return nil, errors.New("chart illegally contains empty path")
		}
		if strings.HasPrefix(n, "..") {
			return nil, errors.New("chart illegally references parent directory")
		}

		// In some particularly arcane acts of path creativity, it is possible to intermix
		// UNIX and Windows style paths in such a way that you produce a result of the form
		// c:/foo even after all the built-in absolute path checks. So we explicitly check
		// for this condition.
		if drivePathPattern.MatchString(n) {
			return nil, errors.New("chart contains illegally named files")
		}

		if parts[0] == "Chart.yaml" {
			return nil, errors.New("chart yaml not in base directory")
		}

		if _, err := io.Copy(b, tr); err != nil {
			return files, err
		}

		files = append(files, &BufferedFile{Name: n, Data: b.Bytes()})
		b.Reset()
	}

	if len(files) == 0 {
		return nil, errors.New("no files in chart archive")
	}
	return files, nil
}
227689
func Populate(context *project.Context, c *cli.Context) {
	// urfave/cli does not distinguish whether the first string in the slice comes from the envvar
	// or is from a flag. Worse off, it appends the flag values to the envvar value instead of
	// overriding it. To ensure the multifile envvar case is always handled, the first string
	// must always be split. It gives a more consistent behavior, then, to split each string in
	// the slice.
	for _, v := range c.GlobalStringSlice("file") {
		context.ComposeFiles = append(context.ComposeFiles, strings.Split(v, string(os.PathListSeparator))...)
	}

	if len(context.ComposeFiles) == 0 {
		context.ComposeFiles = []string{"docker-compose.yml"}
		if _, err := os.Stat("docker-compose.override.yml"); err == nil {
			context.ComposeFiles = append(context.ComposeFiles, "docker-compose.override.yml")
		}
	}

	context.ProjectName = c.GlobalString("project-name")
}
594177
func (c *Client) GetArchive(user, repo, ref, format string) ([]byte, error) {
	if format != ".zip" && format != ".tar.gz" {
		return nil, fmt.Errorf("invalid format: %s (must be .zip or .tar.gz)", format)
	}
	return c.getResponse("GET", fmt.Sprintf("/repos/%s/%s/archive/%s%s", user, repo, ref, format), nil, nil)
}
208637
func PopulateFlags(c *cli.Context) (ret *FlagStorage) {
	flags := &FlagStorage{
		// File system
		MountOptions: make(map[string]string),
		DirMode:      os.FileMode(c.Int("dir-mode")),
		FileMode:     os.FileMode(c.Int("file-mode")),
		Uid:          uint32(c.Int("uid")),
		Gid:          uint32(c.Int("gid")),

		// Tuning,
		Cheap:        c.Bool("cheap"),
		ExplicitDir:  c.Bool("no-implicit-dir"),
		StatCacheTTL: c.Duration("stat-cache-ttl"),
		TypeCacheTTL: c.Duration("type-cache-ttl"),
		HTTPTimeout:  c.Duration("http-timeout"),

		// S3
		Endpoint:       c.String("endpoint"),
		Region:         c.String("region"),
		RegionSet:      c.IsSet("region"),
		StorageClass:   c.String("storage-class"),
		Profile:        c.String("profile"),
		UseContentType: c.Bool("use-content-type"),
		UseSSE:         c.Bool("sse"),
		UseKMS:         c.IsSet("sse-kms"),
		KMSKeyID:       c.String("sse-kms"),
		ACL:            c.String("acl"),

		// Debugging,
		DebugFuse:  c.Bool("debug_fuse"),
		DebugS3:    c.Bool("debug_s3"),
		Foreground: c.Bool("f"),
	}

	// Handle the repeated "-o" flag.
	for _, o := range c.StringSlice("o") {
		parseOptions(flags.MountOptions, o)
	}

	flags.MountPointArg = c.Args()[1]
	flags.MountPoint = flags.MountPointArg
	var err error

	defer func() {
		if err != nil {
			flags.Cleanup()
		}
	}()

	if c.IsSet("cache") {
		cache := c.String("cache")
		cacheArgs := strings.Split(c.String("cache"), ":")
		cacheDir := cacheArgs[len(cacheArgs)-1]
		cacheArgs = cacheArgs[:len(cacheArgs)-1]

		fi, err := os.Stat(cacheDir)
		if err != nil || !fi.IsDir() {
			io.WriteString(cli.ErrWriter,
				fmt.Sprintf("Invalid value \"%v\" for --cache: not a directory\n\n",
					cacheDir))
			return nil
		}

		if _, ok := flags.MountOptions["allow_other"]; !ok {
			flags.MountPointCreated, err = ioutil.TempDir("", ".goofys-mnt")
			if err != nil {
				io.WriteString(cli.ErrWriter,
					fmt.Sprintf("Unable to create temp dir: %v", err))
				return nil
			}
			flags.MountPoint = flags.MountPointCreated
		}

		cacheArgs = append([]string{"--test", "-f"}, cacheArgs...)

		if flags.MountPointArg == flags.MountPoint {
			cacheArgs = append(cacheArgs, "-ononempty")
		}

		cacheArgs = append(cacheArgs, "--")
		cacheArgs = append(cacheArgs, flags.MountPoint)
		cacheArgs = append(cacheArgs, cacheDir)
		cacheArgs = append(cacheArgs, flags.MountPointArg)

		fuseLog.Debugf("catfs %v", cacheArgs)
		catfs := exec.Command("catfs", cacheArgs...)
		_, err = catfs.Output()
		if err != nil {
			if ee, ok := err.(*exec.Error); ok {
				io.WriteString(cli.ErrWriter,
					fmt.Sprintf("--cache requires catfs (%v) but %v\n\n",
						"http://github.com/kahing/catfs",
						ee.Error()))
			} else if ee, ok := err.(*exec.ExitError); ok {
				io.WriteString(cli.ErrWriter,
					fmt.Sprintf("Invalid value \"%v\" for --cache: %v\n\n",
						cache, string(ee.Stderr)))
			}
			return nil
		}

		flags.Cache = cacheArgs[1:]
	}

	// KMS implies SSE
	if flags.UseKMS {
		flags.UseSSE = true
	}

	return flags
}
586614
func (m *UnpartitionedMemoryIdx) UpdateArchive(archive idx.Archive) {
	m.Lock()
	defer m.Unlock()
	if _, ok := m.defById[archive.Id]; !ok {
		return
	}
	*(m.defById[archive.Id]) = archive
}
254806
func (w *unixConfigure) setUpGUI() (func(), error) {
	if w.icfg.Bootstrap.GUI == nil {
		// No GUI archives were found on simplestreams, and no development
		// GUI path has been passed with the JUJU_GUI environment variable.
		return nil, nil
	}
	u, err := url.Parse(w.icfg.Bootstrap.GUI.URL)
	if err != nil {
		return nil, errors.Annotate(err, "cannot parse Juju GUI URL")
	}
	guiJson, err := json.Marshal(w.icfg.Bootstrap.GUI)
	if err != nil {
		return nil, errors.Trace(err)
	}
	guiDir := w.icfg.GUITools()
	w.conf.AddScripts(
		"gui="+shquote(guiDir),
		"mkdir -p $gui",
	)
	if u.Scheme == "file" {
		// Upload the GUI from a local archive file.
		guiData, err := ioutil.ReadFile(filepath.FromSlash(u.Path))
		if err != nil {
			return nil, errors.Annotate(err, "cannot read Juju GUI archive")
		}
		w.conf.AddRunBinaryFile(path.Join(guiDir, "gui.tar.bz2"), guiData, 0644)
	} else {
		// Download the GUI from simplestreams.
		command := "curl -sSf -o $gui/gui.tar.bz2 --retry 10"
		if w.icfg.DisableSSLHostnameVerification {
			command += " --insecure"
		}
		curlProxyArgs := w.formatCurlProxyArguments()
		command += curlProxyArgs
		command += " " + shquote(u.String())
		// A failure in fetching the Juju GUI archive should not prevent the
		// model to be bootstrapped. Better no GUI than no Juju at all.
		command += " || echo Unable to retrieve Juju GUI"
		w.conf.AddRunCmd(command)
	}
	w.conf.AddScripts(
		"[ -f $gui/gui.tar.bz2 ] && sha256sum $gui/gui.tar.bz2 > $gui/jujugui.sha256",
		fmt.Sprintf(
			`[ -f $gui/jujugui.sha256 ] && (grep '%s' $gui/jujugui.sha256 && printf %%s %s > $gui/downloaded-gui.txt || echo Juju GUI checksum mismatch)`,
			w.icfg.Bootstrap.GUI.SHA256, shquote(string(guiJson))),
	)
	return func() {
		// Don't remove the GUI archive until after bootstrap agent runs,
		// so it has a chance to add it to its catalogue.
		w.conf.AddRunCmd("rm -f $gui/gui.tar.bz2 $gui/jujugui.sha256 $gui/downloaded-gui.txt")
	}, nil

}
342829
func (h *guiArchiveHandler) handleGet(w http.ResponseWriter, req *http.Request) error {
	// Open the GUI archive storage.
	st, err := h.ctxt.stateForRequestUnauthenticated(req)
	if err != nil {
		return errors.Annotate(err, "cannot open state")
	}
	defer st.Release()
	storage, err := st.GUIStorage()
	if err != nil {
		return errors.Annotate(err, "cannot open GUI storage")
	}
	defer storage.Close()

	// Retrieve metadata information.
	allMeta, err := storage.AllMetadata()
	if err != nil {
		return errors.Annotate(err, "cannot retrieve GUI metadata")
	}

	// Prepare and send the response.
	var currentVersion string
	vers, err := st.GUIVersion()
	if err == nil {
		currentVersion = vers.String()
	} else if !errors.IsNotFound(err) {
		return errors.Annotate(err, "cannot retrieve current GUI version")
	}
	versions := make([]params.GUIArchiveVersion, len(allMeta))
	for i, m := range allMeta {
		vers, err := version.Parse(m.Version)
		if err != nil {
			return errors.Annotate(err, "cannot parse GUI version")
		}
		versions[i] = params.GUIArchiveVersion{
			Version: vers,
			SHA256:  m.SHA256,
			Current: m.Version == currentVersion,
		}
	}
	return errors.Trace(sendStatusAndJSON(w, http.StatusOK, params.GUIArchiveResponse{
		Versions: versions,
	}))
}
611728
func populateGithubClaims(client githubAPIClientI) (*services.GithubClaims, error) {
	// find out the username
	user, err := client.getUser()
	if err != nil {
		return nil, trace.Wrap(err, "failed to query Github user info")
	}
	// build team memberships
	teams, err := client.getTeams()
	if err != nil {
		return nil, trace.Wrap(err, "failed to query Github user teams")
	}
	log.Debugf("Retrieved %v teams for GitHub user %v.", len(teams), user.Login)

	orgToTeams := make(map[string][]string)
	for _, team := range teams {
		orgToTeams[team.Org.Login] = append(
			orgToTeams[team.Org.Login], team.Slug)
	}
	if len(orgToTeams) == 0 {
		return nil, trace.AccessDenied(
			"list of user teams is empty, did you grant access?")
	}
	claims := &services.GithubClaims{
		Username:            user.Login,
		OrganizationToTeams: orgToTeams,
	}
	log.WithFields(logrus.Fields{trace.Component: "github"}).Debugf(
		"Claims: %#v.", claims)
	return claims, nil
}
725253
func remoteArchiveMetadata() ([]*gui.Metadata, error) {
	source := gui.NewDataSource(common.GUIDataSourceBaseURL())
	allMeta, err := guiFetchMetadata(gui.ReleasedStream, source)
	if err != nil {
		return nil, errors.Annotate(err, "cannot retrieve Juju GUI archive info")
	}
	if len(allMeta) == 0 {
		return nil, errors.New("no available Juju GUI archives found")
	}
	return allMeta, nil
}
1372713
func populateNewBindVariable(
	bindVariableName string,
	bindVariableValue *querypb.BindVariable,
	resultBindVariables map[string]*querypb.BindVariable) {
	_, alreadyInMap := resultBindVariables[bindVariableName]
	if alreadyInMap {
		panic(fmt.Sprintf(
			"bindVariable %v already exists in map: %v. bindVariableValue given: %v",
			bindVariableName,
			resultBindVariables,
			bindVariableValue))
	}
	resultBindVariables[bindVariableName] = bindVariableValue
}
702010
func guiVersionAndHash(st *state.State, storage binarystorage.Storage) (vers, hash string, err error) {
	currentVers, err := st.GUIVersion()
	if errors.IsNotFound(err) {
		return "", "", errors.NotFoundf("Juju GUI")
	}
	if err != nil {
		return "", "", errors.Annotate(err, "cannot retrieve current GUI version")
	}
	metadata, err := storage.Metadata(currentVers.String())
	if err != nil {
		return "", "", errors.Annotate(err, "cannot retrieve GUI metadata")
	}
	return metadata.Version, metadata.SHA256, nil
}
280512
func (ix *Index) populateFile(ctx context.Context, fetcher blob.Fetcher, b *schema.Blob, mm *mutationMap) (err error) {
	var times []time.Time // all creation or mod times seen; may be zero
	times = append(times, b.ModTime())

	blobRef := b.BlobRef()
	tf := &trackErrorsFetcher{f: fetcher.(*missTrackFetcher)}
	fr, err := b.NewFileReader(tf)
	if err != nil {
		return err
	}
	defer fr.Close()
	mimeType, mr := magic.MIMETypeFromReader(fr)
	if mimeType == "" {
		mimeType = magic.MIMETypeByExtension(filepath.Ext(b.FileName()))
	}

	h := blob.NewHash()
	var copyDest io.Writer = h
	var imageBuf *keepFirstN // or nil
	if strings.HasPrefix(mimeType, "image/") {
		imageBuf = &keepFirstN{N: 512 << 10}
		copyDest = io.MultiWriter(copyDest, imageBuf)
	}
	size, err := io.Copy(copyDest, mr)
	if err != nil {
		if tf.hasErrNotExist() {
			return errMissingDep
		}
		return err
	}
	wholeRef := blob.RefFromHash(h)

	if imageBuf != nil {
		var conf images.Config
		decodeConfig := func(r filePrefixReader) error {
			conf, err = images.DecodeConfig(r)
			return err
		}
		if err := readPrefixOrFile(imageBuf.Bytes, fetcher, b, decodeConfig); err == nil {
			mm.Set(keyImageSize.Key(blobRef), keyImageSize.Val(fmt.Sprint(conf.Width), fmt.Sprint(conf.Height)))
		} else if debugEnv {
			log.Printf("index: WARNING: image decodeConfig: %v", err)
		}

		exifData := imageBuf.Bytes
		if conf.HEICEXIF != nil {
			exifData = conf.HEICEXIF
		}
		var ft time.Time
		fileTime := func(r filePrefixReader) error {
			ft, err = schema.FileTime(r)
			return err
		}

		if err = readPrefixOrFile(exifData, fetcher, b, fileTime); err == nil {
			times = append(times, ft)
		} else if debugEnv {
			log.Printf("index: WARNING: image fileTime: %v", err)

		}
		if exifDebug {
			log.Printf("filename %q exif = %v, %v", b.FileName(), ft, err)
		}

		// TODO(mpl): find (generate?) more broken EXIF images to experiment with.
		indexEXIFData := func(r filePrefixReader) error {
			return indexEXIF(wholeRef, r, mm)
		}
		if err = readPrefixOrFile(exifData, fetcher, b, indexEXIFData); err != nil {
			if exifDebug {
				log.Printf("error parsing EXIF: %v", err)
			}
		}
	}

	var sortTimes []time.Time
	for _, t := range times {
		if !t.IsZero() {
			sortTimes = append(sortTimes, t)
		}
	}
	sort.Sort(types.ByTime(sortTimes))
	var time3339s string
	switch {
	case len(sortTimes) == 1:
		time3339s = types.Time3339(sortTimes[0]).String()
	case len(sortTimes) >= 2:
		oldest, newest := sortTimes[0], sortTimes[len(sortTimes)-1]
		// Common enough exception: unset creation time from an MSDOS
		// system (which is the default in zip files). So if we have
		// another time to use, just ignore the MSDOS epoch one.
		if oldest.After(msdosEpochTime) {
			time3339s = types.Time3339(oldest).String() + "," + types.Time3339(newest).String()
		} else {
			time3339s = types.Time3339(newest).String()
		}
	}

	mm.Set(keyWholeToFileRef.Key(wholeRef, blobRef), "1")
	mm.Set(keyFileInfo.Key(blobRef), keyFileInfo.Val(size, b.FileName(), mimeType, wholeRef))
	mm.Set(keyFileTimes.Key(blobRef), keyFileTimes.Val(time3339s))

	if strings.HasPrefix(mimeType, "audio/") {
		indexMusic(io.NewSectionReader(fr, 0, fr.Size()), wholeRef, mm)
	}

	return nil
}
1132393
func (p *ProjectCardOptions) GetArchived() bool {
	if p == nil || p.Archived == nil {
		return false
	}
	return *p.Archived
}
1129784
func (c *DaemonConfig) Populate() {
	c.AccessLog = viper.GetString(AccessLog)
	c.AgentLabels = viper.GetStringSlice(AgentLabels)
	c.AllowLocalhost = viper.GetString(AllowLocalhost)
	c.BPFCompilationDebug = viper.GetBool(BPFCompileDebugName)
	c.CTMapEntriesGlobalTCP = viper.GetInt(CTMapEntriesGlobalTCPName)
	c.CTMapEntriesGlobalAny = viper.GetInt(CTMapEntriesGlobalAnyName)
	c.BPFRoot = viper.GetString(BPFRoot)
	c.CGroupRoot = viper.GetString(CGroupRoot)
	c.ClusterID = viper.GetInt(ClusterIDName)
	c.ClusterName = viper.GetString(ClusterName)
	c.ClusterMeshConfig = viper.GetString(ClusterMeshConfigName)
	c.DatapathMode = viper.GetString(DatapathMode)
	c.Debug = viper.GetBool(DebugArg)
	c.DebugVerbose = viper.GetStringSlice(DebugVerbose)
	c.Device = viper.GetString(Device)
	c.DisableConntrack = viper.GetBool(DisableConntrack)
	c.EnableIPv4 = getIPv4Enabled()
	c.EnableIPv6 = viper.GetBool(EnableIPv6Name)
	c.EnableIPSec = viper.GetBool(EnableIPSecName)
	c.DevicePreFilter = viper.GetString(PrefilterDevice)
	c.DisableCiliumEndpointCRD = viper.GetBool(DisableCiliumEndpointCRDName)
	c.DisableK8sServices = viper.GetBool(DisableK8sServices)
	c.EnableLegacyServices = viper.GetBool(EnableLegacyServices)
	c.EnableHostReachableServices = viper.GetBool(EnableHostReachableServices)
	c.DockerEndpoint = viper.GetString(Docker)
	c.EnableAutoDirectRouting = viper.GetBool(EnableAutoDirectRoutingName)
	c.EnableHealthChecking = viper.GetBool(EnableHealthChecking)
	c.EnablePolicy = strings.ToLower(viper.GetString(EnablePolicy))
	c.EnableTracing = viper.GetBool(EnableTracing)
	c.EncryptInterface = viper.GetString(EncryptInterface)
	c.EnvoyLogPath = viper.GetString(EnvoyLog)
	c.HostDevice = getHostDevice()
	c.HTTPIdleTimeout = viper.GetInt(HTTPIdleTimeout)
	c.HTTPMaxGRPCTimeout = viper.GetInt(HTTPMaxGRPCTimeout)
	c.HTTPRequestTimeout = viper.GetInt(HTTPRequestTimeout)
	c.HTTPRetryCount = viper.GetInt(HTTPRetryCount)
	c.HTTPRetryTimeout = viper.GetInt(HTTPRetryTimeout)
	c.IPv4ClusterCIDRMaskSize = viper.GetInt(IPv4ClusterCIDRMaskSize)
	c.IdentityChangeGracePeriod = viper.GetDuration(IdentityChangeGracePeriod)
	c.IPv4Range = viper.GetString(IPv4Range)
	c.IPv4NodeAddr = viper.GetString(IPv4NodeAddr)
	c.IPv4ServiceRange = viper.GetString(IPv4ServiceRange)
	c.IPv6ClusterAllocCIDR = viper.GetString(IPv6ClusterAllocCIDRName)
	c.IPv6NodeAddr = viper.GetString(IPv6NodeAddr)
	c.IPv6Range = viper.GetString(IPv6Range)
	c.IPv6ServiceRange = viper.GetString(IPv6ServiceRange)
	c.K8sAPIServer = viper.GetString(K8sAPIServer)
	c.K8sKubeConfigPath = viper.GetString(K8sKubeConfigPath)
	c.K8sRequireIPv4PodCIDR = viper.GetBool(K8sRequireIPv4PodCIDRName)
	c.K8sRequireIPv6PodCIDR = viper.GetBool(K8sRequireIPv6PodCIDRName)
	c.K8sForceJSONPatch = viper.GetBool(K8sForceJSONPatch)
	c.K8sEventHandover = viper.GetBool(K8sEventHandover)
	c.K8sWatcherQueueSize = uint(viper.GetInt(K8sWatcherQueueSize))
	c.K8sWatcherEndpointSelector = viper.GetString(K8sWatcherEndpointSelector)
	c.KeepTemplates = viper.GetBool(KeepBPFTemplates)
	c.KeepConfig = viper.GetBool(KeepConfig)
	c.KVStore = viper.GetString(KVStore)
	c.KVstorePeriodicSync = viper.GetDuration(KVstorePeriodicSync)
	c.LabelPrefixFile = viper.GetString(LabelPrefixFile)
	c.Labels = viper.GetStringSlice(Labels)
	c.LBInterface = viper.GetString(LB)
	c.LibDir = viper.GetString(LibDir)
	c.LogDriver = viper.GetStringSlice(LogDriver)
	c.LogSystemLoadConfig = viper.GetBool(LogSystemLoadConfigName)
	c.Logstash = viper.GetBool(Logstash)
	c.Masquerade = viper.GetBool(Masquerade)
	c.InstallIptRules = viper.GetBool(InstallIptRules)
	c.ModePreFilter = viper.GetString(PrefilterMode)
	c.MonitorAggregation = viper.GetString(MonitorAggregationName)
	c.MonitorQueueSize = viper.GetInt(MonitorQueueSizeName)
	c.MTU = viper.GetInt(MTUName)
	c.NAT46Range = viper.GetString(NAT46Range)
	c.FlannelMasterDevice = viper.GetString(FlannelMasterDevice)
	c.FlannelUninstallOnExit = viper.GetBool(FlannelUninstallOnExit)
	c.FlannelManageExistingContainers = viper.GetBool(FlannelManageExistingContainers)
	c.PProf = viper.GetBool(PProf)
	c.PreAllocateMaps = viper.GetBool(PreAllocateMapsName)
	c.PrependIptablesChains = viper.GetBool(PrependIptablesChainsName)
	c.PrometheusServeAddr = getPrometheusServerAddr()
	c.ProxyConnectTimeout = viper.GetInt(ProxyConnectTimeout)
	c.RestoreState = viper.GetBool(Restore)
	c.RunDir = viper.GetString(StateDir)
	c.SidecarIstioProxyImage = viper.GetString(SidecarIstioProxyImage)
	c.UseSingleClusterRoute = viper.GetBool(SingleClusterRouteName)
	c.SocketPath = viper.GetString(SocketPath)
	c.SockopsEnable = viper.GetBool(SockopsEnableName)
	c.TracePayloadlen = viper.GetInt(TracePayloadlen)
	c.Tunnel = viper.GetString(TunnelName)
	c.Version = viper.GetString(Version)
	c.Workloads = viper.GetStringSlice(ContainerRuntime)

	// toFQDNs options
	// When the poller is enabled, the default MinTTL is lowered. This is to
	// avoid caching large sets of identities generated by a poller (it runs
	// every 5s). Without the poller, a longer default is better because it
	// avoids confusion about dropped connections.
	c.ToFQDNsEnablePoller = viper.GetBool(ToFQDNsEnablePoller)
	c.ToFQDNsEnablePollerEvents = viper.GetBool(ToFQDNsEnablePollerEvents)
	c.ToFQDNsMaxIPsPerHost = viper.GetInt(ToFQDNsMaxIPsPerHost)
	userSetMinTTL := viper.GetInt(ToFQDNsMinTTL)
	switch {
	case userSetMinTTL != 0: // set by user
		c.ToFQDNsMinTTL = userSetMinTTL
	case c.ToFQDNsEnablePoller:
		c.ToFQDNsMinTTL = defaults.ToFQDNsMinTTLPoller
	default:
		c.ToFQDNsMinTTL = defaults.ToFQDNsMinTTL
	}
	c.ToFQDNsProxyPort = viper.GetInt(ToFQDNsProxyPort)
	c.ToFQDNsPreCache = viper.GetString(ToFQDNsPreCache)

	// Map options
	if m := viper.GetStringMapString(ContainerRuntimeEndpoint); len(m) != 0 {
		c.ContainerRuntimeEndpoint = m
	}

	if m := viper.GetStringMapString(FixedIdentityMapping); len(m) != 0 {
		c.FixedIdentityMapping = m
	}

	if m := viper.GetStringMapString(KVStoreOpt); len(m) != 0 {
		c.KVStoreOpt = m
	}

	if m := viper.GetStringMapString(LogOpt); len(m) != 0 {
		c.LogOpt = m
	}

	if val := viper.GetInt(ConntrackGarbageCollectorIntervalDeprecated); val != 0 {
		c.ConntrackGCInterval = time.Duration(val) * time.Second
	} else {
		c.ConntrackGCInterval = viper.GetDuration(ConntrackGCInterval)
	}

	// Hidden options
	c.ConfigFile = viper.GetString(ConfigFile)
	c.HTTP403Message = viper.GetString(HTTP403Message)
	c.DisableEnvoyVersionCheck = viper.GetBool(DisableEnvoyVersionCheck)
	c.K8sNamespace = viper.GetString(K8sNamespaceName)
	c.MaxControllerInterval = viper.GetInt(MaxCtrlIntervalName)
	c.SidecarHTTPProxy = viper.GetBool(SidecarHTTPProxy)
	c.CMDRefDir = viper.GetString(CMDRef)
	c.PolicyQueueSize = sanitizeIntParam(PolicyQueueSize, defaults.PolicyQueueSize)
	c.EndpointQueueSize = sanitizeIntParam(EndpointQueueSize, defaults.EndpointQueueSize)
	c.SelectiveRegeneration = viper.GetBool(SelectiveRegeneration)
}
535238
func (d *driver) populateNetworks() error {
	kvol, err := d.store.List(datastore.Key(macvlanPrefix), &configuration{})
	if err != nil && err != datastore.ErrKeyNotFound {
		return fmt.Errorf("failed to get macvlan network configurations from store: %v", err)
	}
	// If empty it simply means no macvlan networks have been created yet
	if err == datastore.ErrKeyNotFound {
		return nil
	}
	for _, kvo := range kvol {
		config := kvo.(*configuration)
		if err = d.createNetwork(config); err != nil {
			logrus.Warnf("Could not create macvlan network for id %s from persistent state", config.ID)
		}
	}

	return nil
}
924297
func (ic *ImageCache) Populate(image *image.Image) {
	ic.sources = append(ic.sources, image)
}