// SerialCtxDeps is like CtxDeps except it runs each dependency serially,
// instead of in parallel. This can be useful for resource intensive
// dependencies that shouldn't be run at the same time.
358950
func SerialCtxDeps(ctx context.Context, fns ...interface{}) {
	types := checkFns(fns)
	for i := range fns {
		runDeps(ctx, types[i:i+1], fns[i:i+1])
	}
}
261229
func GetDeps(name string) (*Deps, error) {
	task, err := TaskCreateNamed(deviceDeps, name)
	if task == nil {
		return nil, err
	}
	if err := task.run(); err != nil {
		return nil, err
	}
	return task.getDeps()
}
51843
func fixupTxnOps(raw interface{}) error {
	rawSlice, ok := raw.([]interface{})
	if !ok {
		return fmt.Errorf("unexpected raw type: %t", raw)
	}
	for _, rawOp := range rawSlice {
		if err := fixupTxnOp(rawOp); err != nil {
			return err
		}
	}
	return nil
}
1097540
func NewCtxQueue() *CtxQueue {
	return &CtxQueue{
		c:          make(chan ctxQueueMessage),
		o:          &sync.Once{},
		startC:     sync.NewCond(&sync.Mutex{}),
		statListen: astistat.NewDurationRatioStat(),
	}
}
262666
func compileRegexps(regexpStrings []string) ([]*regexp.Regexp, error) {
	regexps := []*regexp.Regexp{}
	for _, regexpStr := range regexpStrings {
		r, err := regexp.Compile(regexpStr)
		if err != nil {
			return []*regexp.Regexp{}, err
		}
		regexps = append(regexps, r)
	}
	return regexps, nil
}
151466
func addDepfileDeps(bc *build.Context, ctx *Context) (Importer, error) {
	i := Importer(new(nullImporter))
	df, err := readDepfile(ctx)
	if err != nil {
		if !os.IsNotExist(errors.Cause(err)) {
			return nil, errors.Wrap(err, "could not parse depfile")
		}
		ctx.debug("no depfile, nothing to do.")
		return i, nil
	}
	re := regexp.MustCompile(semverRegex)
	for prefix, kv := range df {
		if version, ok := kv["version"]; ok {
			if !re.MatchString(version) {
				return nil, errors.Errorf("%s: %q is not a valid SemVer 2.0.0 version", prefix, version)
			}
			root := filepath.Join(cachePath(), hash(prefix, version))
			dest := filepath.Join(root, "src", filepath.FromSlash(prefix))
			fi, err := os.Stat(dest)
			if err == nil {
				if !fi.IsDir() {
					return nil, errors.Errorf("%s is not a directory", dest)
				}
			}
			if err != nil {
				if !os.IsNotExist(err) {
					return nil, err
				}
				if err := fetchVersion(root, dest, prefix, version); err != nil {
					return nil, err
				}
			}
			i = &_importer{
				Importer: i,
				im: importer{
					Context: bc,
					Root:    root,
				},
			}
			ctx.debug("add importer for %q: %v", prefix+" "+version, root)
		}

		if tag, ok := kv["tag"]; ok {
			root := filepath.Join(cachePath(), hash(prefix, tag))
			dest := filepath.Join(root, "src", filepath.FromSlash(prefix))
			fi, err := os.Stat(dest)
			if err == nil {
				if !fi.IsDir() {
					return nil, errors.Errorf("%s is not a directory", dest)
				}
			}
			if err != nil {
				if !os.IsNotExist(err) {
					return nil, err
				}
				if err := fetchTag(root, dest, prefix, tag); err != nil {
					return nil, err
				}
			}
			i = &_importer{
				Importer: i,
				im: importer{
					Context: bc,
					Root:    root,
				},
			}
			ctx.debug("add importer for %q: %v", prefix+" "+tag, root)
		}
	}
	return i, nil
}
134868
func TraceCtx(ctx context.Context, message string, data Data) {
	correlationKey := common.GetRequestId(ctx)
	TraceC(correlationKey, message, data)
}
196052
func (v *MockVsccValidator) VSCCValidateTx(seq int, payload *common.Payload, envBytes []byte, block *common.Block) (error, peer.TxValidationCode) {
	return nil, peer.TxValidationCode_VALID
}
1032854
func (s *AutomationExecution) SetStepExecutions(v []*StepExecution) *AutomationExecution {
	s.StepExecutions = v
	return s
}
1288541
func (s *ExplainService) XSourceExclude(xSourceExclude ...string) *ExplainService {
	s.xSourceExclude = make([]string, 0)
	s.xSourceExclude = append(s.xSourceExclude, xSourceExclude...)
	return s
}
125301
func (idx *Indexer) reindexConv(ctx context.Context, rconv types.RemoteConversation, uid gregor1.UID,
	numJobs int, inboxIndexStatus *inboxIndexStatus) (completedJobs int, err error) {
	conv := rconv.Conv
	convID := conv.GetConvID()
	md, err := idx.store.GetMetadata(ctx, uid, convID)
	if err != nil {
		return 0, err
	}
	missingIDs := md.MissingIDForConv(conv)
	if len(missingIDs) == 0 {
		return 0, nil
	}
	minIdxID := missingIDs[0]
	maxIdxID := missingIDs[len(missingIDs)-1]

	defer idx.Trace(ctx, func() error { return err },
		fmt.Sprintf("Indexer.reindex: conv: %v, minID: %v, maxID: %v, numMissing: %v",
			rconv.GetName(), minIdxID, maxIdxID, len(missingIDs)))()

	reason := chat1.GetThreadReason_INDEXED_SEARCH
	if len(missingIDs) < idx.pageSize {
		msgs, err := idx.G().ConvSource.GetMessages(ctx, conv, uid, missingIDs, &reason)
		if err != nil {
			if utils.IsPermanentErr(err) {
				return 0, err
			}
			return 0, nil
		}
		if err := idx.Add(ctx, convID, uid, msgs); err != nil {
			return 0, err
		}
		completedJobs++
	} else {
		query := &chat1.GetThreadQuery{
			DisablePostProcessThread: true,
			MarkAsRead:               false,
		}
		for i := minIdxID; i < maxIdxID; i += chat1.MessageID(idx.pageSize) {
			select {
			case <-ctx.Done():
				return 0, ctx.Err()
			default:
			}
			pagination := utils.MessageIDControlToPagination(ctx, idx.DebugLabeler, &chat1.MessageIDControl{
				Num:   idx.pageSize,
				Pivot: &i,
				Mode:  chat1.MessageIDControlMode_NEWERMESSAGES,
			}, nil)
			tv, err := idx.G().ConvSource.Pull(ctx, convID, uid, reason, query, pagination)
			if err != nil {
				if utils.IsPermanentErr(err) {
					return 0, err
				}
				continue
			}
			if err := idx.Add(ctx, convID, uid, tv.Messages); err != nil {
				return 0, err
			}
			completedJobs++
			if numJobs > 0 && completedJobs >= numJobs {
				break
			}
			if inboxIndexStatus != nil {
				md, err := idx.store.GetMetadata(ctx, uid, conv.GetConvID())
				if err != nil {
					idx.Debug(ctx, "updateInboxIndex: unable to GetMetadata %v", err)
					continue
				}
				inboxIndexStatus.addConv(md, conv)
				percentIndexed, err := inboxIndexStatus.updateUI(ctx)
				if err != nil {
					idx.Debug(ctx, "unable to update ui %v", err)
				} else {
					idx.Debug(ctx, "%v is %d%% indexed", rconv.GetName(), percentIndexed)
				}
			}
		}
	}
	if idx.reindexCh != nil {
		idx.reindexCh <- convID
	}
	return completedJobs, nil
}
389252
func (s *Sender) SendCtx(ctx context.Context, req *http.Request) (resp *http.Response, err error) {
	return s.ExecWithRetry(fmt.Sprintf("%s request to %s", req.Method, req.URL), func() (*http.Response, error) { return ctxhttp.Do(ctx, s.client, req) })
}
1131884
func runDeps(ctx context.Context, types []funcType, fns []interface{}) {
	mu := &sync.Mutex{}
	var errs []string
	var exit int
	wg := &sync.WaitGroup{}
	for i, f := range fns {
		fn := addDep(ctx, types[i], f)
		wg.Add(1)
		go func() {
			defer func() {
				if v := recover(); v != nil {
					mu.Lock()
					if err, ok := v.(error); ok {
						exit = changeExit(exit, ExitStatus(err))
					} else {
						exit = changeExit(exit, 1)
					}
					errs = append(errs, fmt.Sprint(v))
					mu.Unlock()
				}
				wg.Done()
			}()
			if err := fn.run(); err != nil {
				mu.Lock()
				errs = append(errs, fmt.Sprint(err))
				exit = changeExit(exit, ExitStatus(err))
				mu.Unlock()
			}
		}()
	}

	wg.Wait()
	if len(errs) > 0 {
		panic(Fatal(exit, strings.Join(errs, "\n")))
	}
}
765800
func (u *Unit) assertCharmOps(ch *Charm) []txn.Op {
	ops := []txn.Op{{
		C:      unitsC,
		Id:     u.doc.Name,
		Assert: bson.D{{"charmurl", u.doc.CharmURL}},
	}}
	if _, ok := u.CharmURL(); !ok {
		appName := u.ApplicationName()
		ops = append(ops, txn.Op{
			C:      applicationsC,
			Id:     appName,
			Assert: bson.D{{"charmurl", ch.URL()}},
		})
	}
	return ops
}
54888
func MaybeBeginTx(ctx context.Context, storage interface{}) (context.Context, error) {
	// the type assertion checks whether the dynamic type of `storage` implements `Transactional`
	txnStorage, transactional := storage.(Transactional)
	if transactional {
		return txnStorage.BeginTX(ctx)
	} else {
		return ctx, nil
	}
}
190007
func ensureDependencies(series string) error {
	if series == "precise" {
		return errors.NotSupportedf(`LXD containers on series "precise"`)
	}

	if lxdViaSnap() {
		logger.Infof("LXD snap is installed; skipping package installation")
		return nil
	}

	pacman, err := getPackageManager(series)
	if err != nil {
		return errors.Trace(err)
	}
	pacconfer, err := getPackagingConfigurer(series)
	if err != nil {
		return errors.Trace(err)
	}

	for _, pack := range requiredPackages {
		pkg := pack
		if config.SeriesRequiresCloudArchiveTools(series) &&
			pacconfer.IsCloudArchivePackage(pack) {
			pkg = strings.Join(pacconfer.ApplyCloudArchiveTarget(pack), " ")
		}

		if config.RequiresBackports(series, pack) {
			pkg = fmt.Sprintf("--target-release %s-backports %s", series, pkg)
		}

		if err := pacman.Install(pkg); err != nil {
			return errors.Trace(err)
		}
	}

	return errors.Trace(err)
}
718422
func PostTxnsCtx(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		req := apitypes.Txns{}
		body, err := ioutil.ReadAll(r.Body)
		r.Body.Close()
		if err != nil {
			apiLog.Debugf("No/invalid txns: %v", err)
			http.Error(w, "error reading JSON message", http.StatusBadRequest)
			return
		}
		err = json.Unmarshal(body, &req)
		if err != nil {
			apiLog.Debugf("failed to unmarshal JSON request to apitypes.Txns: %v", err)
			http.Error(w, "failed to unmarshal JSON request", http.StatusBadRequest)
			return
		}
		// Successful extraction of body JSON
		ctx := context.WithValue(r.Context(), ctxTxns, req.Transactions)

		next.ServeHTTP(w, r.WithContext(ctx))
	})
}