// handleGetScraperTargets is the HTTP handler for the GET /api/v2/scrapertargets route.
339410
func (h *ScraperHandler) handleGetScraperTargets(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	targets, err := h.ScraperStorageService.ListTargets(ctx)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := encodeResponse(ctx, w, http.StatusOK, newListTargetsResponse(targets)); err != nil {
		logEncodingError(h.Logger, r, err)
		return
	}
}
1052654
func FindAllTargets(ctx context.Context, ts Server, cell string, tabletTypes []topodatapb.TabletType) ([]*querypb.Target, error) {
	ksNames, err := ts.GetSrvKeyspaceNames(ctx, cell)
	if err != nil {
		return nil, err
	}

	var targets []*querypb.Target
	var wg sync.WaitGroup
	var mu sync.Mutex
	var errRecorder concurrency.AllErrorRecorder
	for _, ksName := range ksNames {
		wg.Add(1)
		go func(keyspace string) {
			defer wg.Done()

			// Get SrvKeyspace for cell/keyspace.
			ks, err := ts.GetSrvKeyspace(ctx, cell, keyspace)
			if err != nil {
				if topo.IsErrType(err, topo.NoNode) {
					// Possibly a race condition, or leftover
					// crud in the topology service. Just log it.
					log.Warningf("GetSrvKeyspace(%v, %v) returned ErrNoNode, skipping that SrvKeyspace", cell, keyspace)
				} else {
					// More serious error, abort.
					errRecorder.RecordError(err)
				}
				return
			}

			// Get all shard names that are used for serving.
			for _, ksPartition := range ks.Partitions {
				// Check we're waiting for tablets of that type.
				waitForIt := false
				for _, tt := range tabletTypes {
					if tt == ksPartition.ServedType {
						waitForIt = true
					}
				}
				if !waitForIt {
					continue
				}

				// Add all the shards. Note we can't have
				// duplicates, as there is only one entry per
				// TabletType in the Partitions list.
				mu.Lock()
				for _, shard := range ksPartition.ShardReferences {
					targets = append(targets, &querypb.Target{
						Cell:       cell,
						Keyspace:   keyspace,
						Shard:      shard.Name,
						TabletType: ksPartition.ServedType,
					})
				}
				mu.Unlock()
			}
		}(ksName)
	}
	wg.Wait()
	if errRecorder.HasErrors() {
		return nil, errRecorder.Error()
	}

	return targets, nil
}
442595
func (idr *InitDryRunGetter) HandleGetAction(action core.GetAction) (bool, runtime.Object, error) {
	funcs := []func(core.GetAction) (bool, runtime.Object, error){
		idr.handleKubernetesService,
		idr.handleGetNode,
		idr.handleSystemNodesClusterRoleBinding,
		idr.handleGetBootstrapToken,
	}
	for _, f := range funcs {
		handled, obj, err := f(action)
		if handled {
			return handled, obj, err
		}
	}

	return false, nil, nil
}
378296
func (s *Service) RemoveTarget(ctx context.Context, id platform.ID) error {
	if _, pe := s.loadScraperTarget(id); pe != nil {
		return &platform.Error{
			Err: pe,
			Op:  OpPrefix + platform.OpRemoveTarget,
		}
	}
	s.scraperTargetKV.Delete(id.String())
	return nil
}
339732
func (s *Server) HandleGet(w http.ResponseWriter, r *http.Request) {
	ruid := GetRUID(r.Context())
	uri := GetURI(r.Context())
	log.Debug("handle.get", "ruid", ruid, "uri", uri)
	getCount.Inc(1)
	_, pass, _ := r.BasicAuth()

	addr, err := s.api.ResolveURI(r.Context(), uri, pass)
	if err != nil {
		getFail.Inc(1)
		respondError(w, r, fmt.Sprintf("cannot resolve %s: %s", uri.Addr, err), http.StatusNotFound)
		return
	}
	w.Header().Set("Cache-Control", "max-age=2147483648, immutable") // url was of type bzz://<hex key>/path, so we are sure it is immutable.

	log.Debug("handle.get: resolved", "ruid", ruid, "key", addr)

	// if path is set, interpret <key> as a manifest and return the
	// raw entry at the given path

	etag := common.Bytes2Hex(addr)
	noneMatchEtag := r.Header.Get("If-None-Match")
	w.Header().Set("ETag", fmt.Sprintf("%q", etag)) // set etag to manifest key or raw entry key.
	if noneMatchEtag != "" {
		if bytes.Equal(storage.Address(common.Hex2Bytes(noneMatchEtag)), addr) {
			w.WriteHeader(http.StatusNotModified)
			return
		}
	}

	// check the root chunk exists by retrieving the file's size
	reader, isEncrypted := s.api.Retrieve(r.Context(), addr)
	if _, err := reader.Size(r.Context(), nil); err != nil {
		getFail.Inc(1)
		respondError(w, r, fmt.Sprintf("root chunk not found %s: %s", addr, err), http.StatusNotFound)
		return
	}

	w.Header().Set("X-Decrypted", fmt.Sprintf("%v", isEncrypted))

	switch {
	case uri.Raw():
		// allow the request to overwrite the content type using a query
		// parameter
		if typ := r.URL.Query().Get("content_type"); typ != "" {
			w.Header().Set("Content-Type", typ)
		}
		http.ServeContent(w, r, "", time.Now(), reader)
	case uri.Hash():
		w.Header().Set("Content-Type", "text/plain")
		w.WriteHeader(http.StatusOK)
		fmt.Fprint(w, addr)
	}
}
678716
func (p *Panel) GetTargets() *[]Target {
	switch p.OfType {
	case GraphType:
		return &p.GraphPanel.Targets
	case SinglestatType:
		return &p.SinglestatPanel.Targets
	case TableType:
		return &p.TablePanel.Targets
	default:
		return nil
	}
}
803319
func (r *RepoStatus) GetTargetURL() string {
	if r == nil || r.TargetURL == nil {
		return ""
	}
	return *r.TargetURL
}
1344684
func (c *Client) ListTargets(ctx context.Context) (list []platform.ScraperTarget, err error) {
	list = make([]platform.ScraperTarget, 0)
	err = c.db.View(func(tx *bolt.Tx) (err error) {
		cur := tx.Bucket(scraperBucket).Cursor()
		for k, v := cur.First(); k != nil; k, v = cur.Next() {
			target := new(platform.ScraperTarget)
			if err = json.Unmarshal(v, target); err != nil {
				return err
			}
			list = append(list, *target)
		}
		return err
	})
	if err != nil {
		return nil, &platform.Error{
			Op:  getOp(platform.OpListTargets),
			Err: err,
		}
	}
	return list, err
}
80634
func (s *ScraperService) AddTarget(ctx context.Context, target *influxdb.ScraperTarget, userID influxdb.ID) error {
	url, err := newURL(s.Addr, targetsPath)
	if err != nil {
		return err
	}

	if !target.OrgID.Valid() {
		return &influxdb.Error{
			Code: influxdb.EInvalid,
			Msg:  "provided organization ID has invalid format",
			Op:   s.OpPrefix + influxdb.OpAddTarget,
		}
	}
	if !target.BucketID.Valid() {
		return &influxdb.Error{
			Code: influxdb.EInvalid,
			Msg:  "provided bucket ID has invalid format",
			Op:   s.OpPrefix + influxdb.OpAddTarget,
		}
	}

	octets, err := json.Marshal(target)
	if err != nil {
		return err
	}

	req, err := http.NewRequest("POST", url.String(), bytes.NewReader(octets))
	if err != nil {
		return err
	}

	req.Header.Set("Content-Type", "application/json")
	SetToken(s.Token, req)

	hc := newClient(url.Scheme, s.InsecureSkipVerify)

	resp, err := hc.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// TODO(jsternberg): Should this check for a 201 explicitly?
	if err := CheckError(resp); err != nil {
		return err
	}

	targetResp := new(targetResponse)
	if err := json.NewDecoder(resp.Body).Decode(targetResp); err != nil {
		return err
	}

	return nil
}
501474
func (gce *Cloud) ListTargetHTTPSProxies() (*compute.TargetHttpsProxyList, error) {
	// TODO: use PageToken to list all not just the first 500
	return gce.service.TargetHttpsProxies.List(gce.projectID).Do()
}
1122678
func (h *ViewHandler) handleGetViews(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	req := decodeGetViewsRequest(ctx, r)

	views, _, err := h.ViewService.FindViews(ctx, req.filter)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := encodeResponse(ctx, w, http.StatusOK, newGetViewsResponse(views)); err != nil {
		logEncodingError(h.Logger, r, err)
		return
	}
}
1366486
func (h *UserHandler) handleGetUsers(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	req, err := decodeGetUsersRequest(ctx, r)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	users, _, err := h.UserService.FindUsers(ctx, req.filter)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	err = encodeResponse(ctx, w, http.StatusOK, newUsersResponse(users))
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}
}
334253
func (o *DomainTemplate) RedirectionTargetTemplates(info *bambou.FetchingInfo) (RedirectionTargetTemplatesList, *bambou.Error) {

	var list RedirectionTargetTemplatesList
	err := bambou.CurrentSession().FetchChildren(o, RedirectionTargetTemplateIdentity, &list, info)
	return list, err
}
1241303
func WrapRouteHandlerFunc(r http.HandlerFunc) RHandler {
	return func(res http.ResponseWriter, req *http.Request, _ Collector) {
		http.Redirect(res, req, "/404", 302)
	}
}
969801
func (g *Cloud) ListTargetHTTPSProxies() ([]*compute.TargetHttpsProxy, error) {
	ctx, cancel := cloud.ContextWithCallTimeout()
	defer cancel()

	mc := newTargetProxyMetricContext("list")
	v, err := g.c.TargetHttpsProxies().List(ctx, filter.None)
	return v, mc.Observe(err)
}
101905
func (s *Server) getTargetsLocal(ctx context.Context, reqs []models.Req) ([]models.Series, error) {
	log.Debugf("DP getTargetsLocal: handling %d reqs locally", len(reqs))
	responses := make(chan getTargetsResp, len(reqs))

	var wg sync.WaitGroup
	reqLimiter := util.NewLimiter(getTargetsConcurrency)

	rCtx, cancel := context.WithCancel(ctx)
	defer cancel()
LOOP:
	for _, req := range reqs {
		// if there are already getDataConcurrency goroutines running, then block
		// until a slot becomes free or our context is canceled.
		if !reqLimiter.Acquire(rCtx) {
			//request canceled
			break LOOP
		}
		wg.Add(1)
		go func(req models.Req) {
			rCtx, span := tracing.NewSpan(rCtx, s.Tracer, "getTargetsLocal")
			req.Trace(span)
			pre := time.Now()
			points, interval, err := s.getTarget(rCtx, req)
			if err != nil {
				tags.Error.Set(span, true)
				cancel() // cancel all other requests.
				responses <- getTargetsResp{nil, err}
			} else {
				getTargetDuration.Value(time.Now().Sub(pre))
				responses <- getTargetsResp{[]models.Series{{
					Target:       req.Target, // always simply the metric name from index
					Datapoints:   points,
					Interval:     interval,
					QueryPatt:    req.Pattern, // foo.* or foo.bar whatever the etName arg was
					QueryFrom:    req.From,
					QueryTo:      req.To,
					QueryCons:    req.ConsReq,
					Consolidator: req.Consolidator,
				}}, nil}
			}
			wg.Done()
			// pop an item of our limiter so that other requests can be processed.
			reqLimiter.Release()
			span.Finish()
		}(req)
	}
	go func() {
		wg.Wait()
		close(responses)
	}()
	out := make([]models.Series, 0, len(reqs))
	for resp := range responses {
		if resp.err != nil {
			return nil, resp.err
		}
		out = append(out, resp.series...)
	}
	log.Debugf("DP getTargetsLocal: %d series found locally", len(out))
	return out, nil

}
916158
func (gce *Cloud) GetTargetHTTPProxy(name string) (*compute.TargetHttpProxy, error) {
	return gce.service.TargetHttpProxies.Get(gce.projectID, name).Do()
}