// Run : main function for validation a template
341133
func (s *StepValidateTemplate) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	s.Say("Validating deployment template ...")

	err := s.Validate()

	state.Put("ZoneNo", s.zoneNo)

	if s.FeeSystemTypeCode != "" {
		state.Put("FeeSystemTypeCode", s.FeeSystemTypeCode)
	}

	return processStepResult(err, s.Error, state)
}
869432
func (bsd *bsdRecord) Run(e Executable) (string, error) {
	runAction := "Running " + bsd.description + ":"
	e.Run()
	return runAction + " completed.", nil
}
183909
func (e *PaperKeySubmit) Run(m libkb.MetaContext) error {
	me, err := libkb.LoadMe(libkb.NewLoadUserArgWithMetaContext(m))
	if err != nil {
		return err
	}

	e.deviceWithKeys, err = matchPaperKey(m, me, e.paperPhrase)
	if err != nil {
		return err
	}

	m.ActiveDevice().CacheProvisioningKey(m, e.deviceWithKeys)

	// send a notification that a paper key has been cached
	// for rekey purposes
	m.G().NotifyRouter.HandlePaperKeyCached(me.GetUID(), e.deviceWithKeys.EncryptionKey().GetKID(), e.deviceWithKeys.SigningKey().GetKID())

	// XXX - this is temporary until KBFS handles the above notification
	m.G().UserChanged(m.Ctx(), me.GetUID())

	return nil
}
706767
func (m *Main) Run(args ...string) error {
	// Require a command at the beginning.
	if len(args) == 0 || strings.HasPrefix(args[0], "-") {
		fmt.Fprintln(m.Stderr, m.Usage())
		return ErrUsage
	}

	// Execute command.
	switch args[0] {
	case "help":
		fmt.Fprintln(m.Stderr, m.Usage())
		return ErrUsage
	case "bench":
		return newBenchCommand(m).Run(args[1:]...)
	case "check":
		return newCheckCommand(m).Run(args[1:]...)
	case "compact":
		return newCompactCommand(m).Run(args[1:]...)
	case "dump":
		return newDumpCommand(m).Run(args[1:]...)
	case "info":
		return newInfoCommand(m).Run(args[1:]...)
	case "page":
		return newPageCommand(m).Run(args[1:]...)
	case "pages":
		return newPagesCommand(m).Run(args[1:]...)
	case "stats":
		return newStatsCommand(m).Run(args[1:]...)
	default:
		return ErrUnknownCommand
	}
}
887635
func (kubemarkController *KubemarkController) Run(stopCh chan struct{}) {
	nodeTemplate, err := kubemarkController.getNodeTemplate()
	if err != nil {
		klog.Fatalf("failed to get node template: %s", err)
	}
	kubemarkController.nodeTemplate = nodeTemplate

	go kubemarkController.runNodeCreation(stopCh)
	<-stopCh
}
371131
func (config *Config) Run(cmd string) (string, error) {
	if config.DisplayOutput == true {
		fmt.Printf("run: %s\n", cmd)
	}
	return config.doRun(cmd, false)
}
19354
func (pget *Pget) Run() error {
	if err := pget.Ready(); err != nil {
		return pget.ErrTop(err)
	}

	if err := pget.Checking(); err != nil {
		return errors.Wrap(err, "failed to check header")
	}

	if err := pget.Download(); err != nil {
		return err
	}

	if err := pget.Utils.BindwithFiles(pget.Procs); err != nil {
		return err
	}

	return nil
}
383639
func (c *registerCommand) Run(ctx *cmd.Context) error {
	err := c.run(ctx)
	if err != nil && c.onRunError != nil {
		c.onRunError()
	}
	return err
}
304447
func (g *gomplate) runTemplate(t *tplate) error {
	tmpl, err := t.toGoTemplate(g)
	if err != nil {
		return err
	}

	switch t.target.(type) {
	case io.Closer:
		if t.target != os.Stdout {
			// nolint: errcheck
			defer t.target.(io.Closer).Close()
		}
	}
	err = tmpl.Execute(t.target, g.context)
	return err
}
311388
func (r *runner) Run(ctx context.Context, args *pb.RunnerArgs) (*pb.Build, error) {
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	// Validate and normalize parameters.
	args = proto.Clone(args).(*pb.RunnerArgs)
	if err := normalizeArgs(args); err != nil {
		return nil, errors.Annotate(err, "invalid args").Err()
	}

	// Print our input.
	argsJSON, err := indentedJSONPB(args)
	if err != nil {
		return nil, err
	}
	logging.Infof(ctx, "RunnerArgs: %s", argsJSON)

	// Prepare workdir.
	if err := r.setupWorkDir(args.WorkDir); err != nil {
		return nil, err
	}

	// Prepare auth contexts.
	systemAuth, userAuth, err := setupAuth(ctx, args)
	if err != nil {
		return nil, err
	}
	defer systemAuth.Close()
	defer userAuth.Close()

	// Prepare a build listener.
	var listenerErr error
	var listenerErrMU sync.Mutex
	listener := newBuildListener(streamNamePrefix, func(err error) {
		logging.Errorf(ctx, "%s", err)

		listenerErrMU.Lock()
		defer listenerErrMU.Unlock()
		if listenerErr == nil {
			listenerErr = err
			logging.Warningf(ctx, "canceling the user subprocess")
			cancel()
		}
	})

	// Start a local LogDog server.
	logdogServ, err := r.startLogDog(ctx, args, systemAuth, listener)
	if err != nil {
		return nil, errors.Annotate(err, "failed to start local logdog server").Err()
	}
	defer func() {
		if logdogServ != nil {
			_ = logdogServ.Stop()
		}
	}()

	// Run the user executable.
	err = r.runUserExecutable(ctx, args, userAuth, logdogServ, streamNamePrefix)
	if err != nil {
		return nil, err
	}

	// Wait for logdog server to stop before returning the build.
	if err := logdogServ.Stop(); err != nil {
		return nil, errors.Annotate(err, "failed to stop logdog server").Err()
	}
	logdogServ = nil // do not stop for the second time.

	// Check listener error.
	listenerErrMU.Lock()
	err = listenerErr
	listenerErrMU.Unlock()
	if err != nil {
		return nil, err
	}

	// Read the final build state.
	build := listener.Build()
	if build == nil {
		return nil, errors.Reason("user executable did not send a build").Err()
	}

	// Print the final build state.
	buildJSON, err := indentedJSONPB(build)
	if err != nil {
		return build, err
	}
	logging.Infof(ctx, "final build state: %s", buildJSON)

	// TODO(nodir): make a final UpdateBuild call.

	return build, nil
}
1312327
func Run(templatePath string) {
	// Register plain ol' http handlers.
	r := router.New()
	standard.InstallHandlers(r)

	baseMW := standard.Base()
	apiMW := baseMW.Extend(
		middleware.WithContextTimeout(time.Minute),
		withGitMiddleware,
		withBuildbucketClient,
	)
	htmlMW := baseMW.Extend(
		middleware.WithContextTimeout(time.Minute),
		auth.Authenticate(server.CookieAuth, &server.OAuth2Method{Scopes: []string{server.EmailScope}}),
		withAccessClientMiddleware, // This must be called after the auth.Authenticate middleware.
		withGitMiddleware,
		withBuildbucketClient,
		templates.WithTemplates(getTemplateBundle(templatePath)),
	)
	devHtmlMW := baseMW.Extend(
		middleware.WithContextTimeout(time.Minute),
		auth.Authenticate(server.CookieAuth, &server.OAuth2Method{Scopes: []string{server.EmailScope}}),
		withGitMiddleware,
		// TODO(hinoka): Use a mock buildbucket rpc client here.
		templates.WithTemplates(getTemplateBundle(templatePath)),
	)
	projectMW := htmlMW.Extend(projectACLMiddleware)
	backendMW := baseMW.Extend(
		middleware.WithContextTimeout(10*time.Minute),
		withBuildbucketClient)
	cronMW := backendMW.Extend(gaemiddleware.RequireCron, withBuildbucketClient)

	r.GET("/", htmlMW, frontpageHandler)
	r.GET("/p", baseMW, movedPermanently("/"))
	r.GET("/search", htmlMW, searchHandler)
	r.GET("/opensearch.xml", baseMW, searchXMLHandler)

	// Admin and cron endpoints.
	r.GET("/admin/configs", htmlMW, ConfigsHandler)

	// Dev endpoints.
	r.GET("/admin/debug/build/:name", devHtmlMW, handleError(handleDevBuild))

	// Cron endpoints
	r.GET("/internal/cron/stats", cronMW, cronHandler(buildbot.StatsHandler))
	r.GET("/internal/cron/update-config", cronMW, UpdateConfigHandler)
	r.GET("/internal/cron/update-pools", cronMW, cronHandler(buildbucket.UpdatePools))

	// Builds.
	r.GET("/b/:id", htmlMW, handleError(redirectLUCIBuild))
	r.GET("/p/:project/builds/b:id", baseMW, movedPermanently("/b/:id"))
	r.GET("/p/:project/builders/:bucket/:builder/:numberOrId", projectMW, handleError(handleLUCIBuild))

	// Console
	r.GET("/p/:project", projectMW, handleError(func(c *router.Context) error {
		return ConsolesHandler(c, c.Params.ByName("project"))
	}))
	r.GET("/p/:project/", baseMW, movedPermanently("/p/:project"))
	r.GET("/p/:project/g", baseMW, movedPermanently("/p/:project"))
	r.GET("/p/:project/g/:group/console", projectMW, handleError(ConsoleHandler))
	r.GET("/p/:project/g/:group", projectMW, redirect("/p/:project/g/:group/console", http.StatusFound))
	r.GET("/p/:project/g/:group/", baseMW, movedPermanently("/p/:project/g/:group"))

	// Builder list
	r.GET("/p/:project/builders", projectMW, handleError(func(c *router.Context) error {
		return BuildersRelativeHandler(c, c.Params.ByName("project"), "")
	}))
	r.GET("/p/:project/g/:group/builders", projectMW, handleError(func(c *router.Context) error {
		return BuildersRelativeHandler(c, c.Params.ByName("project"), c.Params.ByName("group"))
	}))

	// Swarming
	r.GET(swarming.URLBase+"/:id/steps/*logname", htmlMW, handleError(HandleSwarmingLog))
	r.GET(swarming.URLBase+"/:id", htmlMW, handleError(handleSwarmingBuild))
	// Backward-compatible URLs for Swarming:
	r.GET("/swarming/prod/:id/steps/*logname", htmlMW, handleError(HandleSwarmingLog))
	r.GET("/swarming/prod/:id", htmlMW, handleError(handleSwarmingBuild))

	// Buildbucket
	// If these routes change, also change links in common/model/build_summary.go:getLinkFromBuildID
	// and common/model/builder_summary.go:SelfLink.
	r.GET("/p/:project/builders/:bucket/:builder", projectMW, handleError(func(c *router.Context) error {
		// Handle either v1 or v2 bucket name.
		_, bucket := deprecated.BucketNameToV2(c.Params.ByName("bucket"))
		if bucket == "" {
			bucket = c.Params.ByName("bucket")
		}
		bid := buildbucket.BuilderID{
			buildbucketpb.BuilderID{
				Project: c.Params.ByName("project"),
				Bucket:  bucket,
				Builder: c.Params.ByName("builder"),
			},
		}
		return BuilderHandler(c, buildsource.BuilderID(bid.String()))
	}))
	r.GET("/buildbucket/:bucket/:builder", baseMW, redirectFromProjectlessBuilder)

	// Buildbot
	// If these routes change, also change links in common/model/builder_summary.go:SelfLink.
	r.GET("/buildbot/:master/:builder/:number", htmlMW.Extend(emulationMiddleware), handleError(handleBuildbotBuild))
	r.GET("/buildbot/:master/:builder/", htmlMW.Extend(emulationMiddleware), handleError(func(c *router.Context) error {
		return BuilderHandler(c, buildsource.BuilderID(
			fmt.Sprintf("buildbot/%s/%s", c.Params.ByName("master"), c.Params.ByName("builder"))))
	}))
	r.GET("/buildbot/:master/", baseMW, func(c *router.Context) {
		u := *c.Request.URL
		u.Path = "/search"
		u.RawQuery = fmt.Sprintf("q=%s", c.Params.ByName("master"))
		http.Redirect(c.Writer, c.Request, u.String(), http.StatusMovedPermanently)
	})

	// LogDog Milo Annotation Streams.
	// This mimicks the `logdog://logdog_host/project/*path` url scheme seen on
	// swarming tasks.
	r.GET("/raw/build/:logdog_host/:project/*path", htmlMW, handleError(handleRawPresentationBuild))

	// PubSub subscription endpoints.
	r.POST("/_ah/push-handlers/buildbot", backendMW, buildbot.PubSubHandler)
	r.POST("/_ah/push-handlers/buildbucket", backendMW, buildbucket.PubSubHandler)

	// pRPC style endpoints.
	api := prpc.Server{
		UnaryServerInterceptor: grpcmon.NewUnaryServerInterceptor(nil),
	}

	milo.RegisterBuildbotServer(&api, &milo.DecoratedBuildbot{
		Service: &buildbot.Service{},
		Prelude: buildbotAPIPrelude,
	})
	milo.RegisterBuildInfoServer(&api, &rpc.BuildInfoService{})
	discovery.Enable(&api)
	api.InstallHandlers(r, apiMW)

	http.DefaultServeMux.Handle("/", r)
}
1027343
func Run(t *testing.T, suite TestingSuite) {
	suite.SetT(t)
	defer failOnPanic(t)

	suiteSetupDone := false
	
	methodFinder := reflect.TypeOf(suite)
	tests := []testing.InternalTest{}
	for index := 0; index < methodFinder.NumMethod(); index++ {
		method := methodFinder.Method(index)
		ok, err := methodFilter(method.Name)
		if err != nil {
			fmt.Fprintf(os.Stderr, "testify: invalid regexp for -m: %s\n", err)
			os.Exit(1)
		}
		if !ok {
			continue
		}
		if !suiteSetupDone {
			if setupAllSuite, ok := suite.(SetupAllSuite); ok {
				setupAllSuite.SetupSuite()
			}
			defer func() {
				if tearDownAllSuite, ok := suite.(TearDownAllSuite); ok {
					tearDownAllSuite.TearDownSuite()
				}
			}()
			suiteSetupDone = true
		}
		test := testing.InternalTest{
			Name: method.Name,
			F: func(t *testing.T) {
				parentT := suite.T()
				suite.SetT(t)
				defer failOnPanic(t)

				if setupTestSuite, ok := suite.(SetupTestSuite); ok {
					setupTestSuite.SetupTest()
				}
				if beforeTestSuite, ok := suite.(BeforeTest); ok {
					beforeTestSuite.BeforeTest(methodFinder.Elem().Name(), method.Name)
				}
				defer func() {
					if afterTestSuite, ok := suite.(AfterTest); ok {
						afterTestSuite.AfterTest(methodFinder.Elem().Name(), method.Name)
					}
					if tearDownTestSuite, ok := suite.(TearDownTestSuite); ok {
						tearDownTestSuite.TearDownTest()
					}
					suite.SetT(parentT)
				}()
				method.Func.Call([]reflect.Value{reflect.ValueOf(suite)})
			},
		}
		tests = append(tests, test)
	}
	runTests(t, tests)
}
177660
func (m *Main) Run() error {
	conf := sarama.NewConfig()
	conf.Version = sarama.V0_10_0_0
	conf.Producer.Return.Successes = true
	producer, err := sarama.NewSyncProducer(m.Hosts, conf)
	if err != nil {
		return errors.Wrap(err, "getting new producer")
	}
	defer producer.Close()

	for ticker := time.NewTicker(m.Rate); true; <-ticker.C {
		ev := fake.GenEvent()
		msg := &sarama.ProducerMessage{Topic: m.Topic, Value: JSONEvent(*ev)}
		_, _, err := producer.SendMessage(msg)
		if err != nil {
			log.Printf("Error sending message: '%v', backing off", err)
			time.Sleep(time.Second * 10)
		}
	}
	return nil
}
1092066
func (t *Tool) Run(c context.Context, f Generator) error {
	// Validate arguments.
	if len(t.FileNames) == 0 {
		return fmt.Errorf("files not specified")
	}
	if len(t.Types) == 0 {
		return fmt.Errorf("types not specified")
	}

	// Determine output file name.
	outputName := t.Output
	if outputName == "" {
		if t.Dir == "" {
			return fmt.Errorf("neither output not dir are specified")
		}
		baseName := fmt.Sprintf("%s_%s.go", t.Types[0], t.OutputFilenameSuffix)
		outputName = filepath.Join(t.Dir, strings.ToLower(baseName))
	}

	// Parse Go files and resolve specified types.
	p := &parser{
		fileSet: token.NewFileSet(),
		types:   t.Types,
	}
	if err := p.parsePackage(t.FileNames); err != nil {
		return fmt.Errorf("could not parse .go files: %s", err)
	}
	if err := p.resolveServices(c); err != nil {
		return err
	}

	// Run the generator.
	var buf bytes.Buffer
	genArgs := &GeneratorArgs{
		PackageName:  p.files[0].Name.Name,
		Services:     p.services,
		ExtraImports: importSorted(p.extraImports),
		Out:          &buf,
	}
	if err := f(c, genArgs); err != nil {
		return err
	}

	// Format the output.
	src, err := format.Source(buf.Bytes())
	if err != nil {
		println(buf.String())
		return fmt.Errorf("gofmt: %s", err)
	}

	// Write to file.
	return ioutil.WriteFile(outputName, src, 0644)
}
923491
func (m *Main) Run() error {
	// Open HTTP port.
	ln, err := net.Listen("tcp", m.Addr)
	if err != nil {
		return err
	}
	m.ln = ln

	// Initialize handler logger.
	m.Handler.Logger = m.Logger.New("component", "http")

	// Register service with discoverd.
	hb, err := discoverd.AddServiceAndRegister(m.ServiceName+"-api", m.Addr)
	if err != nil {
		return err
	}
	shutdown.BeforeExit(func() { hb.Close() })

	h := httphelper.ContextInjector(m.ServiceName+"-api", httphelper.NewRequestLogger(m.Handler))
	go func() { http.Serve(ln, h) }()

	return nil
}
543904
func (c *listImagesCommand) Run(ctx *cmd.Context) (err error) {
	api, err := getImageMetadataListAPI(c)
	if err != nil {
		return err
	}
	defer api.Close()

	found, err := api.List(c.Stream, c.Region, c.Series, c.Arches, c.VirtType, c.RootStorageType)
	if err != nil {
		return err
	}
	if len(found) == 0 {
		return nil
	}

	info, errs := convertDetailsToInfo(found)
	if len(errs) > 0 {
		// display individual error
		fmt.Fprintf(ctx.Stderr, strings.Join(errs, "\n"))
	}

	var output interface{}
	switch c.out.Name() {
	case "yaml", "json":
		output = groupMetadata(info)
	default:
		{
			sort.Sort(metadataInfos(info))
			output = info
		}
	}
	return c.out.Write(ctx, output)
}
692712
func (c *showModelCommand) Run(ctx *cmd.Context) error {
	controllerName, err := c.ControllerName()
	if err != nil {
		return errors.Trace(err)
	}
	_, modelDetails, err := c.ModelDetails()
	if err != nil {
		return errors.Trace(err)
	}
	modelTag := names.NewModelTag(modelDetails.ModelUUID)

	api, err := c.getAPI()
	if err != nil {
		return err
	}
	defer api.Close()

	results, err := api.ModelInfo([]names.ModelTag{modelTag})
	if err != nil {
		return err
	}
	if results[0].Error != nil {
		return results[0].Error
	}
	infoMap, err := c.apiModelInfoToModelInfoMap([]params.ModelInfo{*results[0].Result}, controllerName)
	if err != nil {
		return errors.Trace(err)
	}
	return c.out.Write(ctx, infoMap)
}