// FetchStaticChanBackups will return a plaintext static channel back up for
// all known active/open channels within the passed channel source.
507887
func FetchStaticChanBackups(chanSource LiveChannelSource) ([]Single, error) {
	// First, we'll query the backup source for information concerning all
	// currently open and available channels.
	openChans, err := chanSource.FetchAllChannels()
	if err != nil {
		return nil, err
	}

	// Now that we have all the channels, we'll use the chanSource to
	// obtain any auxiliary information we need to craft a backup for each
	// channel.
	staticChanBackups := make([]Single, len(openChans))
	for i, openChan := range openChans {
		chanBackup, err := assembleChanBackup(chanSource, openChan)
		if err != nil {
			return nil, err
		}

		staticChanBackups[i] = *chanBackup
	}

	return staticChanBackups, nil
}
1119467
func (h *SourceHandler) handleGetSourcesBuckets(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

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

	s, err := h.SourceService.FindSourceByID(ctx, req.SourceID)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	bucketSvc, err := h.NewBucketService(s)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}
	bs, _, err := bucketSvc.FindBuckets(ctx, req.filter)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := encodeResponse(ctx, w, http.StatusOK, bs); err != nil {
		logEncodingError(h.Logger, r, err)
		return
	}
}
429431
func Static(opts ...StaticOptions) HandlerFunc {
	return func(ctx *Context) {
		if ctx.Req().Method != "GET" && ctx.Req().Method != "HEAD" {
			ctx.Next()
			return
		}

		opt := prepareStaticOptions(opts)

		var rPath = ctx.Req().URL.Path
		// if defined prefix, then only check prefix
		if opt.Prefix != "" {
			if !strings.HasPrefix(ctx.Req().URL.Path, opt.Prefix) {
				ctx.Next()
				return
			}

			if len(opt.Prefix) == len(ctx.Req().URL.Path) {
				rPath = ""
			} else {
				rPath = ctx.Req().URL.Path[len(opt.Prefix):]
			}
		}

		f, err := opt.FileSystem.Open(strings.TrimLeft(rPath, "/"))
		if err != nil {
			if os.IsNotExist(err) {
				if opt.Prefix != "" {
					ctx.Result = NotFound()
				} else {
					ctx.Next()
					return
				}
			} else {
				ctx.Result = InternalServerError(err.Error())
			}
			ctx.HandleError()
			return
		}
		defer f.Close()

		finfo, err := f.Stat()
		if err != nil {
			ctx.Result = InternalServerError(err.Error())
			ctx.HandleError()
			return
		}

		if !finfo.IsDir() {
			if len(opt.FilterExts) > 0 && !opt.IsFilterExt(rPath) {
				ctx.Next()
				return
			}

			http.ServeContent(ctx, ctx.Req(), finfo.Name(), finfo.ModTime(), f)
			return
		}

		// try serving index.html or index.htm
		if len(opt.IndexFiles) > 0 {
			for _, index := range opt.IndexFiles {
				fi, err := opt.FileSystem.Open(strings.TrimLeft(path.Join(rPath, index), "/"))
				if err != nil {
					if !os.IsNotExist(err) {
						ctx.Result = InternalServerError(err.Error())
						ctx.HandleError()
						return
					}
				} else {
					finfo, err = fi.Stat()
					if err != nil {
						fi.Close()
						ctx.Result = InternalServerError(err.Error())
						ctx.HandleError()
						return
					}
					if !finfo.IsDir() {
						http.ServeContent(ctx, ctx.Req(), finfo.Name(), finfo.ModTime(), fi)
						fi.Close()
						return
					}
					fi.Close()
				}
			}
		}

		// list dir files
		if opt.ListDir {
			ctx.Header().Set("Content-Type", "text/html; charset=UTF-8")
			ctx.WriteString(`<ul style="list-style-type:none;line-height:32px;">`)
			if rPath != "/" {
				ctx.WriteString(`<li>&nbsp; &nbsp; <a href="` + path.Join("/", opt.Prefix, filepath.Dir(rPath)) + `">..</a></li>`)
			}

			fs, err := f.Readdir(0)
			if err != nil {
				ctx.Result = InternalServerError(err.Error())
				ctx.HandleError()
				return
			}

			for _, fi := range fs {
				if fi.IsDir() {
					ctx.WriteString(`<li>┖ <a href="` + path.Join("/", opt.Prefix, rPath, fi.Name()) + `">` + path.Base(fi.Name()) + `</a></li>`)
				} else {
					if len(opt.FilterExts) > 0 && !opt.IsFilterExt(fi.Name()) {
						continue
					}

					ctx.WriteString(`<li>&nbsp; &nbsp; <a href="` + path.Join("/", opt.Prefix, rPath, fi.Name()) + `">` + filepath.Base(fi.Name()) + `</a></li>`)
				}
			}
			ctx.WriteString("</ul>")
			return
		}

		ctx.Next()
	}
}
12928
func fetchConfigs(c context.Context, f policy.ConfigFetcher) (policy.ConfigBundle, error) {
	cfg := &admin.ServiceAccountsPermissions{}
	if err := f.FetchTextProto(c, serviceAccountsCfg, cfg); err != nil {
		return nil, err
	}
	return policy.ConfigBundle{serviceAccountsCfg: cfg}, nil
}
116829
func (c *Client) GetBackups(id string, backupid string) ([]Backup, error) {
	var backupMap map[string]Backup
	values := url.Values{
		"SUBID":    {id},
		"BACKUPID": {backupid},
	}

	if err := c.post(`backup/list`, values, &backupMap); err != nil {
		return nil, err
	}

	var backup []Backup
	for _, b := range backupMap {
		fmt.Println(b)
		backup = append(backup, b)
	}
	sort.Sort(backups(backup))
	return backup, nil
}
795010
func (p *peerConnection) FetchHeaders(from uint64, count int) error {
	// Sanity check the protocol version
	if p.version < 62 {
		panic(fmt.Sprintf("header fetch [eth/62+] requested on eth/%d", p.version))
	}
	// Short circuit if the peer is already fetching
	if !atomic.CompareAndSwapInt32(&p.headerIdle, 0, 1) {
		return errAlreadyFetching
	}
	p.headerStarted = time.Now()

	// Issue the header retrieval request (absolut upwards without gaps)
	go p.peer.RequestHeadersByNumber(from, count, 0, false)

	return nil
}
1339535
func (entity *AEBackupKind) FetchChildren(c context.Context) error {
	g := goon.FromContext(c)

	// AEBackupInformationKindTypeInfoList の処理
	{
		var backupInfoKindTypesList []*AEBackupInformationKindTypeInfo
		qb := newAEBackupInformationKindTypeInfoQueryBuilder().Ancestor(g.Key(entity))
		_, err := g.GetAll(qb.Query(), &backupInfoKindTypesList)
		if err != nil {
			return err
		}
		for _, backupInfoKindTypes := range backupInfoKindTypesList {
			err := backupInfoKindTypes.FetchChildren(c)
			if err != nil {
				return err
			}
		}
		entity.AEBackupInformationKindTypeInfoList = backupInfoKindTypesList
	}

	return nil
}
558422
func (env *maasEnviron) fetchAllSubnets(ctx context.ProviderCallContext) ([]gomaasapi.JSONObject, error) {
	client := env.getMAASClient().GetSubObject("subnets")

	json, err := client.CallGet("", nil)
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return nil, errors.Trace(err)
	}
	return json.GetArray()
}
200134
func NewStaticTokens(spec StaticTokensSpecV2) (StaticTokens, error) {
	st := StaticTokensV2{
		Kind:    KindStaticTokens,
		Version: V2,
		Metadata: Metadata{
			Name:      MetaNameStaticTokens,
			Namespace: defaults.Namespace,
		},
		Spec: spec,
	}
	if err := st.CheckAndSetDefaults(); err != nil {
		return nil, trace.Wrap(err)
	}

	return &st, nil
}
28814
func NewStaticUpstreams(c caddyfile.Dispenser) ([]Upstream, error) {
	var upstreams []Upstream
	for c.Next() {
		upstream := &staticUpstream{
			from:              "",
			upstreamHeaders:   make(http.Header),
			downstreamHeaders: make(http.Header),
			Hosts:             nil,
			Policy:            &Random{},
			MaxFails:          1,
			TryInterval:       250 * time.Millisecond,
			MaxConns:          0,
			KeepAlive:         http.DefaultMaxIdleConnsPerHost,
			Timeout:           30 * time.Second,
		}

		if !c.Args(&upstream.from) {
			return upstreams, c.ArgErr()
		}

		var to []string
		for _, t := range c.RemainingArgs() {
			parsed, err := parseUpstream(t)
			if err != nil {
				return upstreams, err
			}
			to = append(to, parsed...)
		}

		for c.NextBlock() {
			switch c.Val() {
			case "upstream":
				if !c.NextArg() {
					return upstreams, c.ArgErr()
				}
				parsed, err := parseUpstream(c.Val())
				if err != nil {
					return upstreams, err
				}
				to = append(to, parsed...)
			default:
				if err := parseBlock(&c, upstream); err != nil {
					return upstreams, err
				}
			}
		}

		if len(to) == 0 {
			return upstreams, c.ArgErr()
		}

		upstream.Hosts = make([]*UpstreamHost, len(to))
		for i, host := range to {
			uh, err := upstream.NewHost(host)
			if err != nil {
				return upstreams, err
			}
			upstream.Hosts[i] = uh
		}

		if upstream.HealthCheck.Path != "" {
			upstream.HealthCheck.Client = http.Client{
				Timeout: upstream.HealthCheck.Timeout,
			}
			go upstream.HealthCheckWorker(nil)
		}
		upstreams = append(upstreams, upstream)
	}
	return upstreams, nil
}
386035
func fetchMasterHDKeys(ns walletdb.ReadBucket) ([]byte, []byte, error) {
	bucket := ns.NestedReadBucket(mainBucketName)

	var masterHDPrivEnc, masterHDPubEnc []byte

	// First, we'll try to fetch the master private key. If this database
	// is watch only, or the master has been neutered, then this won't be
	// found on disk.
	key := bucket.Get(masterHDPrivName)
	if key != nil {
		masterHDPrivEnc = make([]byte, len(key))
		copy(masterHDPrivEnc[:], key)
	}

	key = bucket.Get(masterHDPubName)
	if key != nil {
		masterHDPubEnc = make([]byte, len(key))
		copy(masterHDPubEnc[:], key)
	}

	return masterHDPrivEnc, masterHDPubEnc, nil
}
1034543
func FetchKeys(ctx context.Context, name string) ([]string, error) {
	keys := PfconfigKeys{PfconfigNS: name}
	err := FetchDecodeSocket(ctx, &keys)
	if err != nil {
		return nil, err
	}

	return keys.Keys, nil
}
206852
func FetchFiles(client *http.Client, files []RawFile, header http.Header) error {
	ch := make(chan error, len(files))
	for i := range files {
		go func(i int) {
			p, err := HttpGetBytes(client, files[i].RawUrl(), nil)
			if err != nil {
				ch <- err
				return
			}
			files[i].SetData(p)
			ch <- nil
		}(i)
	}
	for _ = range files {
		if err := <-ch; err != nil {
			return err
		}
	}
	return nil
}
393417
func (c *Client) DeleteStaticTokens() error {
	_, err := c.Delete(c.Endpoint("configuration", "static_tokens"))
	return trace.Wrap(err)
}
1329767
func NewStaticUpstreams(c *caddyfile.Dispenser) ([]Upstream, error) {
	var upstreams []Upstream
	for c.Next() {
		upstream := &staticUpstream{
			from: ".",
			HealthCheck: healthcheck.HealthCheck{
				FailTimeout: 5 * time.Second,
				MaxFails:    3,
			},
			ex: newDNSEx(),
		}

		if !c.Args(&upstream.netsource) {
			return upstreams, c.ArgErr()
		}

		_, _, err := net.ParseCIDR(upstream.netsource)

		if err != nil {
			upstream.from = upstream.netsource
			upstream.netsource = ""
		}

		upstream.from = plugin.Host(upstream.from).Normalize()

		to := c.RemainingArgs()
		if len(to) == 0 {
			return upstreams, c.ArgErr()
		}

		// process the host list, substituting in any nameservers in files
		toHosts, err := dnsutil.ParseHostPortOrFile(to...)
		if err != nil {
			return upstreams, err
		}

		for c.NextBlock() {
			if err := parseBlock(c, upstream); err != nil {
				return upstreams, err
			}
		}

		upstream.Hosts = make([]*healthcheck.UpstreamHost, len(toHosts))

		for i, host := range toHosts {
			uh := &healthcheck.UpstreamHost{
				Name:        host,
				FailTimeout: upstream.FailTimeout,
				CheckDown:   checkDownFunc(upstream),
			}
			upstream.Hosts[i] = uh
		}
		upstream.Start()

		upstreams = append(upstreams, upstream)
	}
	return upstreams, nil
}
326201
func WithStaticConnectors(s Storage, staticConnectors []Connector) Storage {
	connectorsByID := make(map[string]Connector, len(staticConnectors))
	for _, c := range staticConnectors {
		connectorsByID[c.ID] = c
	}
	return staticConnectorsStorage{s, staticConnectors, connectorsByID}
}
1092100
func getIPResources(hostID string, hostIP string, staticIPs ...string) ([]HostIPResource, error) {

	//make a map of all ipaddresses to interface
	ifacemap, err := getInterfaceMap()
	if err != nil {
		return nil, err
	}
	hostLogger := plog.WithFields(log.Fields{
		"hostid": hostID,
		"hostip": hostIP,
	})
	hostLogger.WithFields(log.Fields{
		"interfaces": ifacemap,
	}).Debug("Interfaces on this host")

	// Get a unique list of ips from staticIPs and hostIP.
	ips := func() []string {
		for _, ip := range staticIPs {
			if hostIP == ip {
				return staticIPs
			}
		}
		return append(staticIPs, hostIP)
	}()

	hostIPResources := make([]HostIPResource, len(ips))
	for i, ip := range ips {
		hostLogger.WithFields(log.Fields{
			"ip": ip,
		}).Debug("Checking IP")
		if iface, ok := ifacemap[ip]; ok {
			if isLoopBack(ip) {
				return nil, IsLoopbackError(ip)
			}
			hostIPResource := HostIPResource{
				HostID:        hostID,
				IPAddress:     ip,
				InterfaceName: iface.Name,
				MACAddress:    iface.HardwareAddr.String(),
			}
			hostIPResources[i] = hostIPResource
		} else {
			return nil, InvalidIPAddress(ip)
		}
	}

	return hostIPResources, nil
}