// ResolveServicePath resolves a service path (e.g., "infrastructure/mariadb")
// to zero or more service details with their ancestry populated.
16936
func (f *Facade) ResolveServicePath(ctx datastore.Context, svcPath string, noprefix bool) ([]service.ServiceDetails, error) {
	defer ctx.Metrics().Stop(ctx.Metrics().Start("Facade.ResolveServicePath"))
	var (
		parent  string
		current string
		result  = []service.ServiceDetails{}
	)
	plog := plog.WithFields(log.Fields{
		"svcpath": svcPath,
	})

	// Empty paths match nothing
	if isEmptyPath(svcPath) {
		plog.Debug("Empty path produced empty result")
		return result, nil
	}

	// Clean up trailing slashes and lowercase the requested path
	svcPath = strings.TrimRight(svcPath, "/")
	svcPath = strings.ToLower(svcPath)

	// First pass: get all services that match either ID exactly or name by regex.
	// The default matching is to use a "contains" regex. This is overridable
	// via the noprefix boolean which changes the regex to an "ends with" match
	parent, current = path.Split(svcPath)

	details, err := f.serviceStore.GetServiceDetailsByIDOrName(ctx, current, noprefix)
	if err != nil {
		return nil, err
	}
	plog.WithFields(log.Fields{
		"svcPath": svcPath,
		"current": current,
		"noprefix":  noprefix,
		"matches": len(details),
	}).Debug("Found possible service matches")

	// Populate the ancestry for all of the found services, so we can check
	// their parents
	for _, detail := range details {
		d, err := f.GetServiceDetailsAncestry(ctx, detail.ID)
		if err != nil {
			return nil, err
		}
		result = append(result, *d)
	}

	// Now walk up the path, filtering parents as we go
	level := 1
	for !isEmptyPath(parent) {
		// Split the path to get the segment at this level
		parent, current = path.Split(strings.TrimRight(parent, "/"))

		// Technically this won't ever be needed, as it gets lowered in cli/cmd
		// before it gets here, but for the sake of local clarity...
		current = strings.ToLower(current)

		filtered := make([]service.ServiceDetails, 0)

		// Walk up parents to the current level and check their names to filter
		// the list of potentials
		for _, d := range result {
			p := &d
			for i := 0; i < level; i++ {
				p = p.Parent
				if p == nil {
					break
				}
			}

			// If the parent name at this level matches OR this is the last
			// segment and it matches the deployment ID, it's considered
			// a match
			if (p != nil && strings.ToLower(p.Name) == current) || (isEmptyPath(parent) && strings.ToLower(d.DeploymentID) == current) {
				filtered = append(filtered, d)
			}
		}
		result = filtered
		level++
	}
	plog.WithField("results", len(result)).Debug("Filtered service matches by parent")

	return result, nil
}
993174
func (s *Sprocket) resolvePath(assetPath string, baseDir string, forceRebuild bool) (string, *types.ExtensionInfo, error) {
	var err error
	ext := filepath.Ext(assetPath)
	extInfo := s.getExtensionInfoOrDefault(ext)
	if forceRebuild == false {
		assetPublicPath, _ := s.checkPublicPath(assetPath, baseDir)
		if len(assetPublicPath) > 0 {
			return assetPublicPath, extInfo, nil
		}
	}
	assetPath, ext, err = resolvePath(extInfo, assetPath, baseDir)
	if err != nil {
		return "", nil, err
	}
	return assetPath, s.getExtensionInfoOrDefault(ext), nil
}
1164292
func (c *ServicedCli) searchForService(keyword string, prefix bool) (*service.ServiceDetails, int, error) {

	// If the last segment is an integer, it is an instance ID
	servicepath, instanceIDString := path.Split(keyword)
	instanceID := -1
	if num, err := strconv.Atoi(instanceIDString); err != nil {
		// It's not an integer, so just use the original path
		servicepath = keyword
	} else {
		instanceID = num
	}

	matches, err := c.driver.ResolveServicePath(servicepath, prefix)
	if err != nil {
		return nil, 0, err
	}

	// check the number of matches
	if count := len(matches); count == 0 {
		return nil, 0, errors.New("service not found")
	} else if count == 1 {
		return &matches[0], instanceID, nil
	}

	// more than one match, display a dialog
	var svcpath func(*service.ServiceDetails) string
	svcpath = func(svc *service.ServiceDetails) string {
		parent := svc.Parent
		if parent != nil {
			return path.Join(svcpath(parent), svc.Name)
		}
		return path.Join(svc.DeploymentID, svc.Name)
	}

	t := NewTable("Name,ServiceID,DepID/Path")
	t.Padding = 6
	for _, row := range matches {
		t.AddRow(map[string]interface{}{
			"Name":       row.Name,
			"ServiceID":  row.ID,
			"PoolID":     row.PoolID,
			"DepID/Path": svcpath(&row),
		})
	}
	t.Print()
	return nil, 0, fmt.Errorf("multiple results found; select one from list")
}
833136
func ResolveEndpoint(services listersv1.ServiceLister, endpoints listersv1.EndpointsLister, namespace, id string, port int32) (*url.URL, error) {
	svc, err := services.Services(namespace).Get(id)
	if err != nil {
		return nil, err
	}

	svcPort, err := findServicePort(svc, port)
	if err != nil {
		return nil, err
	}

	switch {
	case svc.Spec.Type == v1.ServiceTypeClusterIP, svc.Spec.Type == v1.ServiceTypeLoadBalancer, svc.Spec.Type == v1.ServiceTypeNodePort:
		// these are fine
	default:
		return nil, fmt.Errorf("unsupported service type %q", svc.Spec.Type)
	}

	eps, err := endpoints.Endpoints(namespace).Get(svc.Name)
	if err != nil {
		return nil, err
	}
	if len(eps.Subsets) == 0 {
		return nil, errors.NewServiceUnavailable(fmt.Sprintf("no endpoints available for service %q", svc.Name))
	}

	// Pick a random Subset to start searching from.
	ssSeed := rand.Intn(len(eps.Subsets))

	// Find a Subset that has the port.
	for ssi := 0; ssi < len(eps.Subsets); ssi++ {
		ss := &eps.Subsets[(ssSeed+ssi)%len(eps.Subsets)]
		if len(ss.Addresses) == 0 {
			continue
		}
		for i := range ss.Ports {
			if ss.Ports[i].Name == svcPort.Name {
				// Pick a random address.
				ip := ss.Addresses[rand.Intn(len(ss.Addresses))].IP
				port := int(ss.Ports[i].Port)
				return &url.URL{
					Scheme: "https",
					Host:   net.JoinHostPort(ip, strconv.Itoa(port)),
				}, nil
			}
		}
	}
	return nil, errors.NewServiceUnavailable(fmt.Sprintf("no endpoints available for service %q", id))
}
108734
func resolveResourceKindPath(f kcmdutil.Factory, path, namespace string) (string, error) {
	parts := strings.SplitN(path, ":", 2)
	if !isPathForPod(path) {
		return path, nil
	}

	podName := parts[0]

	// if the specified pod name is given in the <kind>/<name> format
	// validate the podName without the <kind/> segment.
	if podSegs := strings.Split(podName, "/"); len(podSegs) > 1 {
		podName = podSegs[1]
	}

	r := f.NewBuilder().
		WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
		NamespaceParam(namespace).
		SingleResourceType().
		ResourceNames("pods", podName).
		Do()

	if err := r.Err(); err != nil {
		return "", err
	}
	infos, err := r.Infos()
	if err != nil {
		return "", err
	}

	// if there were no errors, we should expect
	// one resource to exist
	if len(infos) == 0 || infos[0].Mapping.Resource.GroupResource() != (schema.GroupResource{Resource: "pods"}) {
		return "", fmt.Errorf("error: expected resource to be of type pod, got %q", infos[0].Mapping.Resource)
	}

	return fmt.Sprintf("%s:%s", podName, parts[1]), nil
}
209421
func (cr *ConflictResolver) makePostResolutionPaths(ctx context.Context,
	md *RootMetadata, unmergedChains, mergedChains *crChains,
	mergedPaths map[data.BlockPointer]data.Path) (map[data.BlockPointer]data.Path, error) {
	err := cr.checkDone(ctx)
	if err != nil {
		return nil, err
	}

	session, err := cr.config.KBPKI().GetCurrentSession(ctx)
	if err != nil {
		return nil, err
	}

	// No need to run any identifies on these chains, since we
	// have already finished all actions.
	resolvedChains, err := newCRChains(
		ctx, cr.config.Codec(), cr.config,
		[]chainMetadata{rootMetadataWithKeyAndTimestamp{md,
			session.VerifyingKey, cr.config.Clock().Now()}},
		&cr.fbo.blocks, false)
	if err != nil {
		return nil, err
	}

	// If there are no renames, we don't need to fix any of the paths
	if len(resolvedChains.renamedOriginals) == 0 {
		return mergedPaths, nil
	}

	resolvedPaths := make(map[data.BlockPointer]data.Path)
	for ptr, oldP := range mergedPaths {
		p, err := cr.resolveOnePath(ctx, ptr, unmergedChains, mergedChains,
			resolvedChains, mergedPaths, resolvedPaths)
		if err != nil {
			return nil, err
		}
		cr.log.CDebugf(ctx, "Resolved path for %v from %v to %v",
			ptr, oldP.Path, p.Path)
	}

	return resolvedPaths, nil
}
609596
func (schema *Schema) resolveJSONPointer(ref string) (result *Schema, err error) {
	parts := strings.Split(ref, "#")
	if len(parts) == 2 {
		documentName := parts[0] + "#"
		if documentName == "#" && schema.ID != nil {
			documentName = *(schema.ID)
		}
		path := parts[1]
		document := schemas[documentName]
		pathParts := strings.Split(path, "/")

		// we currently do a very limited (hard-coded) resolution of certain paths and log errors for missed cases
		if len(pathParts) == 1 {
			return document, nil
		} else if len(pathParts) == 3 {
			switch pathParts[1] {
			case "definitions":
				dictionary := document.Definitions
				for _, pair := range *dictionary {
					if pair.Name == pathParts[2] {
						result = pair.Value
					}
				}
			case "properties":
				dictionary := document.Properties
				for _, pair := range *dictionary {
					if pair.Name == pathParts[2] {
						result = pair.Value
					}
				}
			default:
				break
			}
		}
	}
	if result == nil {
		return nil, fmt.Errorf("unresolved pointer: %+v", ref)
	}
	return result, nil
}
768980
func (r *ProquintResolver) Resolve(ctx context.Context, name string, options ...opts.ResolveOpt) (path.Path, error) {
	return resolve(ctx, r, name, opts.ProcessOpts(options))
}
746220
func (s *Service) ServiceConfigPath() (cfglib.Set, string) {
	return cfglib.ServiceSet(s.serviceID), svcconfig.ServiceConfigPath
}
475251
func resolveService(src ast.ServiceReference, scope Scope) (*ServiceSpec, error) {
	s, err := scope.LookupService(src.Name)
	if err == nil {
		err = s.Link(scope)
		return s, err
	}

	mname, iname := splitInclude(src.Name)
	if len(mname) == 0 {
		return nil, referenceError{
			Target:    src.Name,
			Line:      src.Line,
			ScopeName: scope.GetName(),
			Reason:    err,
		}
	}

	includedScope, err := getIncludedScope(scope, mname)
	if err != nil {
		return nil, referenceError{
			Target:    src.Name,
			Line:      src.Line,
			ScopeName: scope.GetName(),
			Reason:    err,
		}
	}

	return resolveService(ast.ServiceReference{Name: iname}, includedScope)
}
1051377
func (s *Service) path() string {
	return fmt.Sprintf("%s/%s:%d", RegistryPath, s.Name, s.Port)
}
776124
func (api *NameAPI) Resolve(ctx context.Context, name string, opts ...caopts.NameResolveOption) (coreiface.Path, error) {
	results, err := api.Search(ctx, name, opts...)
	if err != nil {
		return nil, err
	}

	err = coreiface.ErrResolveFailed
	var p coreiface.Path

	for res := range results {
		p, err = res.Path, res.Err
		if err != nil {
			break
		}
	}

	return p, err
}
884757
func resolveServiceIDs(c context.Context, urls []string, out *identityset.Set) error {
	// URL fetch calls below should be extra fast. If they get stuck, something is
	// horribly wrong, better to abort soon.
	c, abort := clock.WithTimeout(c, 5*time.Second)
	defer abort()

	type Result struct {
		URL string
		ID  identity.Identity
		Err error
	}

	ch := make(chan Result, len(urls))

	for _, url := range urls {
		go func(url string) {
			id, err := fetchLUCIServiceIdentity(c, url)
			ch <- Result{url, id, err}
		}(url)
	}

	for i := 0; i < len(urls); i++ {
		result := <-ch
		if result.Err != nil {
			if transient.Tag.In(result.Err) {
				return result.Err
			}
			return fmt.Errorf("could not resolve %q to service ID - %s", result.URL, result.Err)
		}
		out.AddIdentity(result.ID)
	}

	return nil
}
17716
func (ns NameSpace) resolve(path string) []mountedFS {
	path = ns.clean(path)
	for {
		if m := ns[path]; m != nil {
			if debugNS {
				fmt.Printf("resolve %s: %v\n", path, m)
			}
			return m
		}
		if path == "/" {
			break
		}
		path = pathpkg.Dir(path)
	}
	return nil
}
509332
func ResolveIPNS(ctx context.Context, nsys namesys.NameSystem, p path.Path) (path.Path, error) {
	if strings.HasPrefix(p.String(), "/ipns/") {
		evt := log.EventBegin(ctx, "resolveIpnsPath")
		defer evt.Done()
		// resolve ipns paths

		// TODO(cryptix): we should be able to query the local cache for the path
		if nsys == nil {
			evt.Append(logging.LoggableMap{"error": ErrNoNamesys.Error()})
			return "", ErrNoNamesys
		}

		seg := p.Segments()

		if len(seg) < 2 || seg[1] == "" { // just "/<protocol/>" without further segments
			evt.Append(logging.LoggableMap{"error": path.ErrNoComponents.Error()})
			return "", path.ErrNoComponents
		}

		extensions := seg[2:]
		resolvable, err := path.FromSegments("/", seg[0], seg[1])
		if err != nil {
			evt.Append(logging.LoggableMap{"error": err.Error()})
			return "", err
		}

		respath, err := nsys.Resolve(ctx, resolvable.String())
		if err != nil {
			evt.Append(logging.LoggableMap{"error": err.Error()})
			return "", err
		}

		segments := append(respath.Segments(), extensions...)
		p, err = path.FromSegments("/", segments...)
		if err != nil {
			evt.Append(logging.LoggableMap{"error": err.Error()})
			return "", err
		}
	}
	return p, nil
}
1030259
func (r Route) ResolvePath(args ...string) string {
	rpath, formattedPath := r.Path, r.FormattedPath
	if rpath == formattedPath {
		// static, no need to pass args
		return rpath
	}
	// check if we have /*, if yes then join all arguments to one as path and pass that as parameter
	if rpath[len(rpath)-1] == WildcardParamStart[0] {
		parameter := strings.Join(args, "/")
		return fmt.Sprintf(formattedPath, parameter)
	}
	// else return the formattedPath with its args,
	// the order matters.
	for _, s := range args {
		formattedPath = strings.Replace(formattedPath, "%v", s, 1)
	}
	return formattedPath
}
652197
func (nsr *NamespaceResolver) ResolveName(nameNode node.Node, aliasType string) {
	resolved, err := nsr.Namespace.ResolveName(nameNode, aliasType)
	if err == nil {
		nsr.ResolvedNames[nameNode] = resolved
	}
}