// ParseStanza parses a kubernetes stanza
504740
func ParseStanza(c *caddy.Controller) (*Kubernetes, error) {

	k8s := New([]string{""})
	k8s.interfaceAddrsFunc = localPodIP
	k8s.autoPathSearch = searchFromResolvConf()

	opts := dnsControlOpts{
		initEndpointsCache: true,
		ignoreEmptyService: false,
		resyncPeriod:       defaultResyncPeriod,
	}
	k8s.opts = opts

	zones := c.RemainingArgs()

	if len(zones) != 0 {
		k8s.Zones = zones
		for i := 0; i < len(k8s.Zones); i++ {
			k8s.Zones[i] = plugin.Host(k8s.Zones[i]).Normalize()
		}
	} else {
		k8s.Zones = make([]string, len(c.ServerBlockKeys))
		for i := 0; i < len(c.ServerBlockKeys); i++ {
			k8s.Zones[i] = plugin.Host(c.ServerBlockKeys[i]).Normalize()
		}
	}

	k8s.primaryZoneIndex = -1
	for i, z := range k8s.Zones {
		if dnsutil.IsReverse(z) > 0 {
			continue
		}
		k8s.primaryZoneIndex = i
		break
	}

	if k8s.primaryZoneIndex == -1 {
		return nil, errors.New("non-reverse zone name must be used")
	}

	for c.NextBlock() {
		switch c.Val() {
		case "endpoint_pod_names":
			args := c.RemainingArgs()
			if len(args) > 0 {
				return nil, c.ArgErr()
			}
			k8s.endpointNameMode = true
			continue
		case "pods":
			args := c.RemainingArgs()
			if len(args) == 1 {
				switch args[0] {
				case podModeDisabled, podModeInsecure, podModeVerified:
					k8s.podMode = args[0]
				default:
					return nil, fmt.Errorf("wrong value for pods: %s,  must be one of: disabled, verified, insecure", args[0])
				}
				continue
			}
			return nil, c.ArgErr()
		case "namespaces":
			args := c.RemainingArgs()
			if len(args) > 0 {
				for _, a := range args {
					k8s.Namespaces[a] = struct{}{}
				}
				continue
			}
			return nil, c.ArgErr()
		case "endpoint":
			args := c.RemainingArgs()
			if len(args) > 0 {
				// Multiple endoints are deprecated but still could be specified,
				// only the first one be used, though
				k8s.APIServerList = args
				if len(args) > 1 {
					log.Warningf("Multiple endpoints have been deprecated, only the first specified endpoint '%s' is used", args[0])
				}
				continue
			}
			return nil, c.ArgErr()
		case "tls": // cert key cacertfile
			args := c.RemainingArgs()
			if len(args) == 3 {
				k8s.APIClientCert, k8s.APIClientKey, k8s.APICertAuth = args[0], args[1], args[2]
				continue
			}
			return nil, c.ArgErr()
		case "resyncperiod":
			args := c.RemainingArgs()
			if len(args) > 0 {
				rp, err := time.ParseDuration(args[0])
				if err != nil {
					return nil, fmt.Errorf("unable to parse resync duration value: '%v': %v", args[0], err)
				}
				k8s.opts.resyncPeriod = rp
				continue
			}
			return nil, c.ArgErr()
		case "labels":
			args := c.RemainingArgs()
			if len(args) > 0 {
				labelSelectorString := strings.Join(args, " ")
				ls, err := meta.ParseToLabelSelector(labelSelectorString)
				if err != nil {
					return nil, fmt.Errorf("unable to parse label selector value: '%v': %v", labelSelectorString, err)
				}
				k8s.opts.labelSelector = ls
				continue
			}
			return nil, c.ArgErr()
		case "namespace_labels":
			args := c.RemainingArgs()
			if len(args) > 0 {
				namespaceLabelSelectorString := strings.Join(args, " ")
				nls, err := meta.ParseToLabelSelector(namespaceLabelSelectorString)
				if err != nil {
					return nil, fmt.Errorf("unable to parse namespace_label selector value: '%v': %v", namespaceLabelSelectorString, err)
				}
				k8s.opts.namespaceLabelSelector = nls
				continue
			}
			return nil, c.ArgErr()
		case "fallthrough":
			k8s.Fall.SetZonesFromArgs(c.RemainingArgs())
		case "upstream":
			c.RemainingArgs() // eat remaining args
			k8s.Upstream = upstream.New()
		case "ttl":
			args := c.RemainingArgs()
			if len(args) == 0 {
				return nil, c.ArgErr()
			}
			t, err := strconv.Atoi(args[0])
			if err != nil {
				return nil, err
			}
			if t < 0 || t > 3600 {
				return nil, c.Errf("ttl must be in range [0, 3600]: %d", t)
			}
			k8s.ttl = uint32(t)
		case "transfer":
			tos, froms, err := parse.Transfer(c, false)
			if err != nil {
				return nil, err
			}
			if len(froms) != 0 {
				return nil, c.Errf("transfer from is not supported with this plugin")
			}
			k8s.TransferTo = tos
		case "noendpoints":
			if len(c.RemainingArgs()) != 0 {
				return nil, c.ArgErr()
			}
			k8s.opts.initEndpointsCache = false
		case "ignore":
			args := c.RemainingArgs()
			if len(args) > 0 {
				ignore := args[0]
				if ignore == "empty_service" {
					k8s.opts.ignoreEmptyService = true
					continue
				} else {
					return nil, fmt.Errorf("unable to parse ignore value: '%v'", ignore)
				}
			}
		case "kubeconfig":
			args := c.RemainingArgs()
			if len(args) == 2 {
				config := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
					&clientcmd.ClientConfigLoadingRules{ExplicitPath: args[0]},
					&clientcmd.ConfigOverrides{CurrentContext: args[1]},
				)
				k8s.ClientConfig = config
				continue
			}
			return nil, c.ArgErr()
		default:
			return nil, c.Errf("unknown property '%s'", c.Val())
		}
	}

	if len(k8s.Namespaces) != 0 && k8s.opts.namespaceLabelSelector != nil {
		return nil, c.Errf("namespaces and namespace_labels cannot both be set")
	}

	return k8s, nil
}
1140152
func ParseHostSNI(rule string) ([]string, error) {
	parser, err := newTCPParser()
	if err != nil {
		return nil, err
	}

	parse, err := parser.Parse(rule)
	if err != nil {
		return nil, err
	}

	buildTree, ok := parse.(treeBuilder)
	if !ok {
		return nil, errors.New("cannot parse")
	}

	return lower(parseDomain(buildTree())), nil
}
809935
func (f *TimeFuncs) ParseDuration(n interface{}) (gotime.Duration, error) {
	return gotime.ParseDuration(conv.ToString(n))
}
317532
func (m *Main) ParseFlags(args []string) error {
	if s := os.Getenv("FLYNN_REDIS"); s != "" {
		m.ServiceName = s
	}

	if port := os.Getenv("PORT"); port != "" {
		m.Addr = ":" + port
	}
	m.Handler.RedisImageID = os.Getenv("REDIS_IMAGE_ID")

	// Connect to controller.
	client, err := controller.NewClient("", os.Getenv("CONTROLLER_KEY"))
	if err != nil {
		m.Logger.Error("cannot connect to controller", "err", err)
		return err
	}
	m.Handler.ServiceName = m.ServiceName
	m.Handler.ControllerClient = client

	return nil
}
180618
func MustParseSemantic(str string) *Version {
	v, err := ParseSemantic(str)
	if err != nil {
		panic(err)
	}
	return v
}
896463
func (p *Parser) parseStringList() ([]string, error) {
	// Parse first (required) string.
	str, err := p.parseString()
	if err != nil {
		return nil, err
	}
	strs := []string{str}

	// Parse remaining (optional) strings.
	for {
		if tok, _, _ := p.ScanIgnoreWhitespace(); tok != COMMA {
			p.Unscan()
			return strs, nil
		}

		if str, err = p.parseString(); err != nil {
			return nil, err
		}

		strs = append(strs, str)
	}
}
1339664
func parseRepositoryTag(repos string) (string, string) {
	n := strings.Index(repos, "@")
	if n >= 0 {
		parts := strings.Split(repos, "@")
		return parts[0], parts[1]
	}
	n = strings.LastIndex(repos, ":")
	if n < 0 {
		return repos, ""
	}
	if tag := repos[n+1:]; !strings.Contains(tag, "/") {
		return repos[:n], tag
	}
	return repos, ""
}
408548
func parseCluster(itf interface{}, opts *Options) error {
	m, ok := itf.(map[string]interface{})
	if !ok {
		return fmt.Errorf("expected cluster to be a map/struct, got %v", itf)
	}
	opts.Clustering.Clustered = true
	for k, v := range m {
		name := strings.ToLower(k)
		switch name {
		case "node_id":
			if err := checkType(k, reflect.String, v); err != nil {
				return err
			}
			opts.Clustering.NodeID = v.(string)
		case "bootstrap":
			if err := checkType(k, reflect.Bool, v); err != nil {
				return err
			}
			opts.Clustering.Bootstrap = v.(bool)
		case "peers":
			if err := checkType(k, reflect.Slice, v); err != nil {
				return err
			}
			peers := make([]string, len(v.([]interface{})))
			for i, p := range v.([]interface{}) {
				peers[i] = p.(string)
			}
			opts.Clustering.Peers = peers
		case "log_path":
			if err := checkType(k, reflect.String, v); err != nil {
				return err
			}
			opts.Clustering.RaftLogPath = v.(string)
		case "log_cache_size":
			if err := checkType(k, reflect.Int64, v); err != nil {
				return err
			}
			opts.Clustering.LogCacheSize = int(v.(int64))
		case "log_snapshots":
			if err := checkType(k, reflect.Int64, v); err != nil {
				return err
			}
			opts.Clustering.LogSnapshots = int(v.(int64))
		case "trailing_logs":
			if err := checkType(k, reflect.Int64, v); err != nil {
				return err
			}
			opts.Clustering.TrailingLogs = v.(int64)
		case "sync":
			if err := checkType(k, reflect.Bool, v); err != nil {
				return err
			}
			opts.Clustering.Sync = v.(bool)
		case "raft_logging":
			if err := checkType(k, reflect.Bool, v); err != nil {
				return err
			}
			opts.Clustering.RaftLogging = v.(bool)
		case "raft_heartbeat_timeout":
			fallthrough
		case "raft_election_timeout":
			fallthrough
		case "raft_lease_timeout":
			fallthrough
		case "raft_commit_timeout":
			if err := checkType(k, reflect.String, v); err != nil {
				return err
			}
			dur, err := time.ParseDuration(v.(string))
			if err != nil {
				return err
			}
			switch name {
			case "raft_heartbeat_timeout":
				opts.Clustering.RaftHeartbeatTimeout = dur
			case "raft_election_timeout":
				opts.Clustering.RaftElectionTimeout = dur
			case "raft_lease_timeout":
				opts.Clustering.RaftLeaseTimeout = dur
			case "raft_commit_timeout":
				opts.Clustering.RaftCommitTimeout = dur
			}
		}
	}
	return nil
}
1162382
func parseStorage(result *migratorConfig, list *ast.ObjectList, name string) error {
	tmpConfig := new(server.Config)

	if err := server.ParseStorage(tmpConfig, list, name); err != nil {
		return err
	}

	switch name {
	case "storage_source":
		result.StorageSource = tmpConfig.Storage
	case "storage_destination":
		result.StorageDestination = tmpConfig.Storage
	default:
		return fmt.Errorf("unknown storage name: %s", name)
	}

	return nil
}
255443
func ParseWithFuncs(v interface{}, funcMap CustomParsers) error {
	ptrRef := reflect.ValueOf(v)
	if ptrRef.Kind() != reflect.Ptr {
		return ErrNotAStructPtr
	}
	ref := ptrRef.Elem()
	if ref.Kind() != reflect.Struct {
		return ErrNotAStructPtr
	}
	var parsers = defaultCustomParsers()
	for k, v := range funcMap {
		parsers[k] = v
	}
	return doParse(ref, parsers)
}
135953
func MustParseDuration(s string) (dur *Duration) {
	dur = &Duration{}
	if err := dur.Parse(s); err != nil {
		panic(err)
	}
	return dur
}
1355229
func (p *Parser) parseDimension() (*Dimension, error) {
	re, err := p.parseRegex()
	if err != nil {
		return nil, err
	} else if re != nil {
		return &Dimension{Expr: re}, nil
	}

	// Parse the expression first.
	expr, err := p.ParseExpr()
	if err != nil {
		return nil, err
	}

	// Consume all trailing whitespace.
	p.consumeWhitespace()

	return &Dimension{Expr: expr}, nil
}
60231
func MustParse(specifier string) specs.Platform {
	p, err := Parse(specifier)
	if err != nil {
		panic("platform: Parse(" + strconv.Quote(specifier) + "): " + err.Error())
	}
	return p
}
556380
func (p *Tagger) Clusters() (map[string]lingo.Cluster, error) {
	if p.clusters == nil {
		return nil, componentUnavailable("clusters")
	}
	return p.clusters, nil
}
181090
func tryParseClusterInfoFromConfigMap(cm *v1.ConfigMap) (*clientcmdapi.Config, error) {
	kubeConfigString, ok := cm.Data[bootstrapapi.KubeConfigKey]
	if !ok || len(kubeConfigString) == 0 {
		return nil, errors.Errorf("no %s key in ConfigMap", bootstrapapi.KubeConfigKey)
	}
	parsedKubeConfig, err := clientcmd.Load([]byte(kubeConfigString))
	if err != nil {
		return nil, errors.Wrapf(err, "couldn't parse the kubeconfig file in the %s ConfigMap", bootstrapapi.ConfigMapClusterInfo)
	}
	return parsedKubeConfig, nil
}
1258998
func parseKubeHost(host string) (string, error) {
	u, err := url.Parse(host)
	if err != nil {
		return "", trace.Wrap(err, "failed to parse kubernetes host")
	}
	if _, _, err := net.SplitHostPort(u.Host); err != nil {
		// add default HTTPS port
		return fmt.Sprintf("%v:443", u.Host), nil
	}
	return u.Host, nil
}
634919
func ParseInstanceTag(t string) (*api.Tag, error) {
	switch chunks := strings.SplitN(t, ":", 2); {
	case len(chunks) != 2:
		return nil, fmt.Errorf("%q doesn't look like a tag (a key:value pair)", t)
	case len(t) > 400:
		return nil, fmt.Errorf("the tag is too long, should be <=400 chars: %q", t)
	case !tagKeyRe.MatchString(chunks[0]):
		return nil, fmt.Errorf("invalid tag key in %q (should match %q)", t, tagKeyReStr)
	case strings.HasPrefix(chunks[1], " ") || strings.HasSuffix(chunks[1], " "):
		return nil, fmt.Errorf("invalid tag value in %q (should not start or end with ' ')", t)
	case !tagValRe.MatchString(chunks[1]):
		return nil, fmt.Errorf("invalid tag value in %q (should match %q)", t, tagValReStr)
	default:
		return &api.Tag{
			Key:   chunks[0],
			Value: chunks[1],
		}, nil
	}
}