// Execute invokes in order supplied to New, returning the first error
// encountered.
493673
func (app *App) executeInvokes() error {
	// TODO: consider taking a context to limit the time spent running invocations.
	var err error

	for _, fn := range app.invokes {
		fname := fxreflect.FuncName(fn)
		app.logger.Printf("INVOKE\t\t%s", fname)

		if _, ok := fn.(Option); ok {
			err = fmt.Errorf("fx.Option should be passed to fx.New directly, not to fx.Invoke: fx.Invoke received %v", fn)
		} else {
			err = app.container.Invoke(fn)
		}

		if err != nil {
			app.logger.Printf("Error during %q invoke: %v", fname, err)
			break
		}
	}

	return err
}
331154
func (c *DriverSet) Execute(args []string) error {
	App.initializeLogging()
	path := string(c.Args.Path)
	if _, err := InitDriverIfExists(path); err == volume.ErrDriverNotInit {
		log.Fatalf("Driver not initialized. Use `%s driver init %s TYPE [OPTIONS]`", "."+App.name, path)
	}
	usr, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}
	if err := ioutil.WriteFile(filepath.Join(usr.HomeDir, App.name), []byte(path), 0644); err != nil {
		log.Fatal(err)
	}
	return nil
}
376457
func (p *PreparedQuery) Execute(args *structs.PreparedQueryExecuteRequest,
	reply *structs.PreparedQueryExecuteResponse) error {
	if done, err := p.srv.forward("PreparedQuery.Execute", args, args, reply); done {
		return err
	}
	defer metrics.MeasureSince([]string{"prepared-query", "execute"}, time.Now())

	// We have to do this ourselves since we are not doing a blocking RPC.
	p.srv.setQueryMeta(&reply.QueryMeta)
	if args.RequireConsistent {
		if err := p.srv.consistentRead(); err != nil {
			return err
		}
	}

	// Try to locate the query.
	state := p.srv.fsm.State()
	_, query, err := state.PreparedQueryResolve(args.QueryIDOrName, args.Agent)
	if err != nil {
		return err
	}
	if query == nil {
		return ErrQueryNotFound
	}

	// Execute the query for the local DC.
	if err := p.execute(query, reply, args.Connect); err != nil {
		return err
	}

	// If they supplied a token with the query, use that, otherwise use the
	// token passed in with the request.
	token := args.QueryOptions.Token
	if query.Token != "" {
		token = query.Token
	}
	if err := p.srv.filterACL(token, &reply.Nodes); err != nil {
		return err
	}

	// TODO (slackpad) We could add a special case here that will avoid the
	// fail over if we filtered everything due to ACLs. This seems like it
	// might not be worth the code complexity and behavior differences,
	// though, since this is essentially a misconfiguration.

	// Shuffle the results in case coordinates are not available if they
	// requested an RTT sort.
	reply.Nodes.Shuffle()

	// Build the query source. This can be provided by the client, or by
	// the prepared query. Client-specified takes priority.
	qs := args.Source
	if qs.Datacenter == "" {
		qs.Datacenter = args.Agent.Datacenter
	}
	if query.Service.Near != "" && qs.Node == "" {
		qs.Node = query.Service.Near
	}

	// Respect the magic "_agent" flag.
	if qs.Node == "_agent" {
		qs.Node = args.Agent.Node
	} else if qs.Node == "_ip" {
		if args.Source.Ip != "" {
			_, nodes, err := state.Nodes(nil)
			if err != nil {
				return err
			}

			for _, node := range nodes {
				if args.Source.Ip == node.Address {
					qs.Node = node.Node
					break
				}
			}
		} else {
			p.srv.logger.Printf("[WARN] Prepared Query using near=_ip requires " +
				"the source IP to be set but none was provided. No distance " +
				"sorting will be done.")

		}

		// Either a source IP was given but we couldnt find the associated node
		// or no source ip was given. In both cases we should wipe the Node value
		if qs.Node == "_ip" {
			qs.Node = ""
		}
	}

	// Perform the distance sort
	err = p.srv.sortNodesByDistanceFrom(qs, reply.Nodes)
	if err != nil {
		return err
	}

	// If we applied a distance sort, make sure that the node queried for is in
	// position 0, provided the results are from the same datacenter.
	if qs.Node != "" && reply.Datacenter == qs.Datacenter {
		for i, node := range reply.Nodes {
			if node.Node.Node == qs.Node {
				reply.Nodes[0], reply.Nodes[i] = reply.Nodes[i], reply.Nodes[0]
				break
			}

			// Put a cap on the depth of the search. The local agent should
			// never be further in than this if distance sorting was applied.
			if i == 9 {
				break
			}
		}
	}

	// Apply the limit if given.
	if args.Limit > 0 && len(reply.Nodes) > args.Limit {
		reply.Nodes = reply.Nodes[:args.Limit]
	}

	// In the happy path where we found some healthy nodes we go with that
	// and bail out. Otherwise, we fail over and try remote DCs, as allowed
	// by the query setup.
	if len(reply.Nodes) == 0 {
		wrapper := &queryServerWrapper{p.srv}
		if err := queryFailover(wrapper, query, args, reply); err != nil {
			return err
		}
	}

	return nil
}
376092
func (p *queryPlan) Execute(ctx context.Context) (*table.Table, error) {
	// Fetch and cache graph instances.
	tracer.Trace(p.tracer, func() []string {
		return []string{fmt.Sprintf("Caching graph instances for graphs %v", p.stm.InputGraphNames())}
	})
	if err := p.stm.Init(ctx, p.store); err != nil {
		return nil, err
	}
	p.grfs = p.stm.InputGraphs()
	// Retrieve the data.
	lo := p.stm.GlobalLookupOptions()
	tracer.Trace(p.tracer, func() []string {
		return []string{"Setting global lookup options to " + lo.String()}
	})
	if err := p.processGraphPattern(ctx, lo); err != nil {
		return nil, err
	}
	if err := p.projectAndGroupBy(); err != nil {
		return nil, err
	}
	p.orderBy()
	err := p.having()
	if err != nil {
		return nil, err
	}
	p.limit()
	if p.tbl.NumRows() == 0 {
		// Correct the bindings.
		t, err := table.New(p.stm.OutputBindings())
		if err != nil {
			return nil, err
		}
		p.tbl = t
	}
	return p.tbl, nil
}
1099989
func (i *Interpreter) Execute(
	expression string,
	ctx *el.Context) (interface{}, error) {
	expr, err := eval.ParseString(expression, "")
	if err != nil {
		return nil, fmt.Errorf("structor parse: <<%s>>: %v", ctx.LongName, err)
	}
	funcEval := func(intrpr, expr string) interface{} {
		res, err := ctx.EvalExpr(intrpr, expr, ctx)
		if err != nil {
			panic(err)
		}
		return res
	}
	args := eval.Args{
		"eval":      eval.MakeDataRegularInterface(funcEval),
		"ctx":       eval.MakeDataRegularInterface(ctx),
		"ctxStruct": eval.MakeTypeInterface(ctx.Struct),
	}
	if ctx.Extra != nil {
		args["ctxExtra"] = eval.MakeTypeInterface(ctx.Extra)
	}
	if ctx.Sub != nil {
		args["ctxSub"] = eval.MakeTypeInterface(ctx.Sub)
	}
	for k, v := range i.Args {
		args[k] = wrapFunc(v)
	}
	res, err := expr.EvalToInterface(args)
	if err != nil {
		return nil, fmt.Errorf("structor eval: <<%s>>: %v", ctx.LongName, err)
	}
	return res, nil
}
814978
func (c *NamenodeConnection) Execute(method string, req proto.Message, resp proto.Message) error {
	c.reqLock.Lock()
	defer c.reqLock.Unlock()

	c.currentRequestID++

	for {
		err := c.resolveConnection()
		if err != nil {
			return err
		}

		err = c.writeRequest(method, req)
		if err != nil {
			c.markFailure(err)
			continue
		}

		err = c.readResponse(method, resp)
		if err != nil {
			// Only retry on a standby exception.
			if nerr, ok := err.(*NamenodeError); ok && nerr.exception == standbyExceptionClass {
				c.markFailure(err)
				continue
			}

			return err
		}

		break
	}

	return nil
}
988560
func (e *HashAggExec) execute(ctx context.Context) (err error) {
	inputIter := chunk.NewIterator4Chunk(e.childResult)
	for {
		err := e.children[0].Next(ctx, chunk.NewRecordBatch(e.childResult))
		if err != nil {
			return err
		}

		failpoint.Inject("unparallelHashAggError", func(val failpoint.Value) {
			if val.(bool) {
				failpoint.Return(errors.New("HashAggExec.unparallelExec error"))
			}
		})

		// no more data.
		if e.childResult.NumRows() == 0 {
			return nil
		}
		for row := inputIter.Begin(); row != inputIter.End(); row = inputIter.Next() {
			groupKey, err := e.getGroupKey(row)
			if err != nil {
				return err
			}
			if !e.groupSet.Exist(groupKey) {
				e.groupSet.Insert(groupKey)
				e.groupKeys = append(e.groupKeys, groupKey)
			}
			partialResults := e.getPartialResults(groupKey)
			for i, af := range e.PartialAggFuncs {
				err = af.UpdatePartialResult(e.ctx, []chunk.Row{row}, partialResults[i])
				if err != nil {
					return err
				}
			}
		}
	}
}
127705
func (c *Client) execute(rw *bufio.ReadWriter, a ...interface{}) (interface{}, error) {
	//fmt.Printf("\nSending: %#v\n", a)
	// old redis protocol.
	_, err := fmt.Fprintf(rw, strings.Join(viface2vstr(a), " ")+"\r\n")
	if err != nil {
		return nil, err
	}
	if err = rw.Flush(); err != nil {
		return nil, err
	}
	return c.parseResponse(rw.Reader)
}
326671
func (s *ServeCmd) Execute(args []string) error {
	if len(args) == 0 {
		return errors.New("specify the spec to serve as argument to the serve command")
	}

	specDoc, err := loads.Spec(args[0])
	if err != nil {
		return err
	}
	b, err := json.MarshalIndent(specDoc.Spec(), "", "  ")
	if err != nil {
		return err
	}

	basePath := s.BasePath
	if basePath == "" {
		basePath = "/"
	}

	listener, err := net.Listen("tcp4", net.JoinHostPort(s.Host, strconv.Itoa(s.Port)))
	if err != nil {
		return err
	}
	sh, sp, err := swag.SplitHostPort(listener.Addr().String())
	if err != nil {
		return err
	}
	if sh == "0.0.0.0" {
		sh = "localhost"
	}

	visit := s.DocURL
	handler := http.NotFoundHandler()
	if !s.NoUI {
		if s.Flavor == "redoc" {
			handler = middleware.Redoc(middleware.RedocOpts{
				BasePath: basePath,
				SpecURL:  path.Join(basePath, "swagger.json"),
				Path:     "docs",
			}, handler)
			visit = fmt.Sprintf("http://%s:%d%s", sh, sp, path.Join(basePath, "docs"))
		} else if visit != "" || s.Flavor == "swagger" {
			if visit == "" {
				visit = "http://petstore.swagger.io/"
			}
			u, err := url.Parse(visit)
			if err != nil {
				return err
			}
			q := u.Query()
			q.Add("url", fmt.Sprintf("http://%s:%d%s", sh, sp, path.Join(basePath, "swagger.json")))
			u.RawQuery = q.Encode()
			visit = u.String()
		}
	}

	handler = handlers.CORS()(middleware.Spec(basePath, b, handler))
	errFuture := make(chan error)
	go func() {
		docServer := new(http.Server)
		docServer.SetKeepAlivesEnabled(true)
		docServer.Handler = handler

		errFuture <- docServer.Serve(listener)
	}()

	if !s.NoOpen && !s.NoUI {
		err := webbrowser.Open(visit)
		if err != nil {
			return err
		}
	}
	log.Println("serving docs at", visit)
	return <-errFuture
}
730938
func (c *Cluster) Execute(command Command) error {
	if command == nil {
		return ErrClusterCommandRequired
	}
	async := &Async{
		Command: command,
	}
	c.execute(async)
	if async.Error != nil {
		return async.Error
	}
	if cerr := command.Error(); cerr != nil {
		return cerr
	}
	return nil
}
297534
func (command *ClientCommand) Execute() error {
	log.Debug("Generating a rest client for ", command.Language)
	apiDef := new(raml.APIDefinition)
	err := raml.ParseFile(command.RamlFile, apiDef)
	if err != nil {
		return err
	}
	conf := codegen.ClientConfig{
		Dir:                      command.Dir,
		PackageName:              command.PackageName,
		Lang:                     command.Language,
		RootImportPath:           command.ImportPath,
		Kind:                     command.Kind,
		LibRootURLs:              strings.Split(command.LibRootURLs, ","),
		PythonUnmarshallResponse: command.PythonUnmarshallResponse,
	}

	return codegen.GenerateClient(apiDef, conf)
}
988589
func (ins *Insert) Execute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool) (*sqltypes.Result, error) {
	if ins.QueryTimeout != 0 {
		cancel := vcursor.SetContextTimeout(time.Duration(ins.QueryTimeout) * time.Millisecond)
		defer cancel()
	}

	switch ins.Opcode {
	case InsertUnsharded:
		return ins.execInsertUnsharded(vcursor, bindVars)
	case InsertSharded, InsertShardedIgnore:
		return ins.execInsertSharded(vcursor, bindVars)
	default:
		// Unreachable.
		return nil, fmt.Errorf("unsupported query route: %v", ins)
	}
}
732899
func (ps *PulloutSubquery) Execute(vcursor VCursor, bindVars map[string]*querypb.BindVariable, wantfields bool) (*sqltypes.Result, error) {
	combinedVars, err := ps.execSubquery(vcursor, bindVars)
	if err != nil {
		return nil, err
	}
	return ps.Underlying.Execute(vcursor, combinedVars, wantfields)
}
869268
func (e Executor) Execute() error {
	e.SilenceUsage = true
	e.SilenceErrors = true
	err := e.Command.Execute()
	if err != nil {
		if viper.GetBool(TraceFlag) {
			fmt.Fprintf(os.Stderr, "ERROR: %+v\n", err)
		} else {
			fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
		}

		// return error code 1 by default, can override it with a special error type
		exitCode := 1
		if ec, ok := err.(ExitCoder); ok {
			exitCode = ec.ExitCode()
		}
		e.Exit(exitCode)
	}
	return err
}
624668
func (db *DB) Execute(stmt Executable, args ...interface{}) (sql.Result, error) {
	s, params, err := db.compile(stmt)
	if err != nil {
		return nil, err
	}

	// Use any arguments given to Execute() over compiled arguments
	if len(args) == 0 {
		args = params.args
	}
	return db.conn.Exec(s, args...)
}
1346321
func (al *acceptLeadership) Execute(state State) (*State, error) {
	return nil, errors.New("prepare always errors; Execute is never valid")
}
1072270
func (s *Script) Execute(conn *Conn, keyCount int, keysAndArgs ...interface{}) (*Reply, error) {
	s.lock.RLock()
	defer s.lock.RUnlock()
	if s.body == "" {
		return nil, ErrEmptyScript
	}
	args := make([]interface{}, len(keysAndArgs)+2)
	args[0] = s.sha
	args[1] = keyCount
	for i := range keysAndArgs {
		args[i+2] = keysAndArgs[i]
	}
	rep, err := NewCommand("EVALSHA", args...).Run(conn)
	if err != nil {
		return nil, err
	}
	if !rep.IsError() {
		return rep, nil
	}
	errorMessage, _ := rep.Error()
	if !strings.HasPrefix(errorMessage, "NOSCRIPT") {
		return rep, nil
	}
	args[0] = s.body
	return NewCommand("EVAL", args...).Run(conn)
}