// runs gometalinter on requested packages
347871
func doLint(cmdline []string) {
	flag.CommandLine.Parse(cmdline)

	packages := []string{"./..."}
	if len(flag.CommandLine.Args()) > 0 {
		packages = flag.CommandLine.Args()
	}
	// Get metalinter and install all supported linters
	build.MustRun(goTool("get", "gopkg.in/alecthomas/gometalinter.v2"))
	build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), "--install")

	// Run fast linters batched together
	configs := []string{
		"--vendor",
		"--tests",
		"--deadline=2m",
		"--disable-all",
		"--enable=goimports",
		"--enable=varcheck",
		"--enable=vet",
		"--enable=gofmt",
		"--enable=misspell",
		"--enable=goconst",
		"--min-occurrences=6", // for goconst
	}
	build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)

	// Run slow linters one by one
	for _, linter := range []string{"unconvert", "gosimple"} {
		configs = []string{"--vendor", "--tests", "--deadline=10m", "--disable-all", "--enable=" + linter}
		build.MustRunCommand(filepath.Join(GOBIN, "gometalinter.v2"), append(configs, packages...)...)
	}
}
816999
func (h *healthcheckManager) run() {
	for {
		select {
		case <-h.quit:
			h.unmarkAllBackends()
			h.stopped <- true
		case vc := <-h.vcc:
			h.update(vc.vserverName, vc.checks)
		}
	}
}
949247
func (o *APIVersionsOptions) RunAPIVersions() error {
	// Always request fresh data from the server
	o.discoveryClient.Invalidate()

	groupList, err := o.discoveryClient.ServerGroups()
	if err != nil {
		return fmt.Errorf("couldn't get available api versions from server: %v", err)
	}
	apiVersions := metav1.ExtractGroupVersions(groupList)
	sort.Strings(apiVersions)
	for _, v := range apiVersions {
		fmt.Fprintln(o.Out, v)
	}
	return nil
}
819547
func (m *Main) Run() (err error) {
	go func() {
		fmt.Println(http.ListenAndServe("localhost:6060", nil))
	}()

	schema := gopilosa.NewSchema()
	m.index = schema.Index(m.Index)
	pdk.NewRankedField(m.index, "weather_condition", 0)
	pdk.NewRankedField(m.index, "precipitation_type", 0)
	pdk.NewRankedField(m.index, "precipitation_inches", 0)
	pdk.NewRankedField(m.index, "temp_f", 0)
	pdk.NewRankedField(m.index, "pressure_i", 0)
	pdk.NewRankedField(m.index, "humidity", 0)

	m.importer, err = pdk.SetupPilosa([]string{m.PilosaHost}, m.Index, schema, uint(m.BufferSize))
	if err != nil {
		return errors.Wrap(err, "setting up pilosa")
	}

	pilosaURI, err := gopilosa.NewURIFromAddress(m.PilosaHost)
	if err != nil {
		return fmt.Errorf("interpreting pilosaHost '%v': %v", m.PilosaHost, err)
	}
	setupClient, err := gopilosa.NewClient(pilosaURI)
	if err != nil {
		return fmt.Errorf("setting up client: %v", err)
	}
	m.client = setupClient

	readFieldNames := []string{"cab_type", "passenger_count", "total_amount_dollars", "pickup_time", "pickup_day", "pickup_mday", "pickup_month", "pickup_year", "drop_time", "drop_day", "drop_mday", "drop_month", "drop_year", "dist_miles", "duration_minutes", "speed_mph", "pickup_grid_id", "drop_grid_id"}

	for _, fieldName := range readFieldNames {
		m.index.Field(fieldName)
	}
	err = setupClient.SyncSchema(schema)
	if err != nil {
		return errors.Wrap(err, "synchronizing schema")
	}

	err = m.WeatherCache.ReadAll()
	if err != nil {
		return errors.Wrap(err, "reading weather cache")
	}

	err = m.appendWeatherData()
	if err != nil {
		return errors.Wrap(err, "appending weather data")
	}

	return errors.Wrap(m.importer.Close(), "closing indexer")
}
270348
func (cfg *centOSCloudConfig) PackageMirror() string {
	mirror, _ := cfg.attrs["package_mirror"].(string)
	return mirror
}
82695
func (pb *PackageBuilder) AddMetaToPackage(metaName string, name string) {
	mt := pb.Metadata[metaName]
	if mt.Name == "" {
		mt.Name = metaName
	}

	if !pb.contains(mt.Members, name) {
		mt.Members = append(mt.Members, name)
		pb.Metadata[metaName] = mt
	}
}
936242
func RunMiddleware(c *Context, mc MiddlewareChain, h Handler) {
	runChains(c, mc, MiddlewareChain{}, h)
}
843810
func (e *Kex2Provisionee) Run(m libkb.MetaContext) error {
	m.G().LocalSigchainGuard().Set(m.Ctx(), "Kex2Provisionee")
	defer m.G().LocalSigchainGuard().Clear(m.Ctx(), "Kex2Provisionee")

	// check device struct:
	if len(e.device.Type) == 0 {
		return errors.New("provisionee device requires Type to be set")
	}
	if e.device.ID.IsNil() {
		return errors.New("provisionee device requires ID to be set")
	}

	if m.LoginContext() == nil {
		return errors.New("Kex2Provisionee needs LoginContext set in engine.Context")
	}

	if len(e.secret) == 0 {
		panic("empty secret")
	}

	m, e.kex2Cancel = m.WithContextCancel()
	defer e.kex2Cancel()

	// The MetaContext m is needed in some of the kex2 functions. Make sure to do that
	// after we've added a cancelation above.
	e.mctx = m

	karg := kex2.KexBaseArg{
		Ctx:           m.Ctx(),
		LogCtx:        newKex2LogContext(m.G()),
		Mr:            libkb.NewKexRouter(m),
		DeviceID:      e.device.ID,
		Secret:        e.secret,
		SecretChannel: e.secretCh,
		Timeout:       60 * time.Minute,
	}
	parg := kex2.ProvisioneeArg{
		KexBaseArg:  karg,
		Provisionee: e,
	}
	return kex2.RunProvisionee(parg)
}
1334644
func (e *ClientExtractor) Run(ctx context.Context, inst *model.Instance, pkg *PackageReader) (res Result, err error) {
	// Put fatal errors into 'res' and return transient ones as is.
	defer func() {
		if err != nil && !transient.Tag.In(err) {
			res.Err = err
			err = nil
		}
	}()

	// We use same hash algo for naming the extracted file as was used to name
	// the package instance it is in. This avoid some confusion during the
	// transition to a new hash.
	if err = common.ValidateInstanceID(inst.InstanceID, common.KnownHash); err != nil {
		err = errors.Annotate(err, "unrecognized client instance ID format").Err()
		return
	}
	instRef := common.InstanceIDToObjectRef(inst.InstanceID)

	// We also always calculate all other hashes we know about at the same time,
	// for old bootstrap scripts that may not understand the most recent hash
	// algo.
	hashes := make(map[api.HashAlgo]hash.Hash, len(api.HashAlgo_name))
	for algo := range api.HashAlgo_name {
		if a := api.HashAlgo(algo); a != api.HashAlgo_HASH_ALGO_UNSPECIFIED {
			hashes[a] = common.MustNewHash(a)
		}
	}
	if hashes[instRef.HashAlgo] == nil {
		panic("impossible, inst.InstanceID has already been validated")
	}

	// Start extracting the file.
	reader, size, err := pkg.Open(GetClientBinaryName(inst.Package.StringID()))
	if err != nil {
		err = errors.Annotate(err, "failed to open the file for reading").Err()
		return
	}
	defer reader.Close() // we don't care about errors here

	// Start writing the result to CAS.
	op, err := e.CAS.BeginUpload(ctx, &api.BeginUploadRequest{
		HashAlgo: instRef.HashAlgo,
	})
	if err != nil {
		err = errors.Annotate(err, "failed to open a CAS upload").Tag(transient.Tag).Err()
		return
	}

	// Grab an io.Writer that uploads to Google Storage.
	factory := e.uploader
	if factory == nil {
		factory = gsUploader
	}
	uploader := factory(ctx, size, op.UploadUrl)

	// Copy in 2 Mb chunks by default.
	bufferSize := e.bufferSize
	if bufferSize == 0 {
		bufferSize = 2 * 1024 * 1024
	}

	// Copy, calculating digests on the fly.
	//
	// We use fullReader to make sure we write full 2 Mb chunks to GS. Otherwise
	// 'reader' uses 32 Kb buffers and they are flushed as 32 Kb buffers to Google
	// Storage too (which doesn't work). Remember, in Go an io.Reader can choose
	// to read less than asked and zip readers use 32 Kb buffers. CopyBuffer just
	// sends them to the writer right away.
	//
	// Note that reads from Google Storage are already properly buffered by
	// PackageReader implementation, so it's OK if the zip reader reads small
	// chunks from the underlying file reader. We basically read 512 Kb buffer
	// from GS, then unzip it in memory via small 32 Kb chunks into 2 Mb output
	// buffer, and then flush it to GS.
	writeTo := make([]io.Writer, 0, 1+len(hashes))
	writeTo = append(writeTo, uploader)
	for _, hash := range hashes {
		writeTo = append(writeTo, hash)
	}
	copied, err := io.CopyBuffer(
		io.MultiWriter(writeTo...),
		fullReader{reader},
		make([]byte, bufferSize))
	if err == nil && copied != size {
		err = fmt.Errorf("unexpected file size - expecting %d bytes, read %d bytes", size, copied)
	}

	// If asked to rewind to a faraway offset (should be rare), just restart the
	// whole process from scratch by returning a transient error.
	if _, ok := err.(*gs.RestartUploadError); ok {
		err = errors.Annotate(err, "asked to restart the upload from faraway offset").Tag(transient.Tag).Err()
	}

	if err != nil {
		// Best effort cleanup of the upload session. It's not a big deal if this
		// fails and the upload stays as garbage.
		_, cancelErr := e.CAS.CancelUpload(ctx, &api.CancelUploadRequest{
			UploadOperationId: op.OperationId,
		})
		if cancelErr != nil {
			logging.WithError(cancelErr).Errorf(ctx, "Failed to cancel the upload")
		}
		return
	}

	// Skip the hash calculation in CAS by enforcing the hash, we've just
	// calculated it.
	extractedRef := &api.ObjectRef{
		HashAlgo:  instRef.HashAlgo,
		HexDigest: common.HexDigest(hashes[instRef.HashAlgo]),
	}
	op, err = e.CAS.FinishUpload(ctx, &api.FinishUploadRequest{
		UploadOperationId: op.OperationId,
		ForceHash:         extractedRef,
	})

	// CAS should publish the object right away.
	switch {
	case err != nil:
		err = errors.Annotate(err, "failed to finalize the CAS upload").Tag(transient.Tag).Err()
		return
	case op.Status != api.UploadStatus_PUBLISHED:
		err = errors.Reason("unexpected upload status from CAS %s: %s", op.Status, op.ErrorMessage).Err()
		return
	}

	hexDigests := make(map[string]string, len(hashes))
	for algo, hash := range hashes {
		hexDigests[algo.String()] = common.HexDigest(hash)
	}

	r := ClientExtractorResult{}
	r.ClientBinary.Size = size
	r.ClientBinary.HashAlgo = extractedRef.HashAlgo.String()
	r.ClientBinary.HashDigest = extractedRef.HexDigest
	r.ClientBinary.AllHashDigests = hexDigests

	logging.Infof(ctx, "Uploaded CIPD client binary %s with %s %s (%d bytes)",
		inst.Package.StringID(), extractedRef.HashAlgo, extractedRef.HexDigest, size)

	res.Result = r
	return
}
1108240
func main() {
	// this has no real purpose besides making the import present in this main package.
	// without this line the meta info for the swagger doc wouldn't be discovered
	petstore.APIVersion = Version

	// This servers na hypothetical API
	if err := rest.ServeAPI(); err != nil {
		log.Fatal(err)
	}
}
889741
func (e *SaltpackDecrypt) Run(m libkb.MetaContext) (err error) {
	defer m.Trace("SaltpackDecrypt::Run", func() error { return err })()

	// We don't load this in the --paperkey case.
	var me *libkb.User

	var keyring *saltpackBasic.Keyring
	keyring = saltpackBasic.NewKeyring()

	if e.arg.Opts.UsePaperKey {
		// Prompt the user for a paper key. This doesn't require you to be
		// logged in.
		keypair, _, err := getPaperKey(m, nil, nil)
		if err != nil {
			return err
		}
		encryptionNaclKeyPair := keypair.EncryptionKey().(libkb.NaclDHKeyPair)
		addToKeyring(keyring, &encryptionNaclKeyPair)

		// If a paper key is used, we do not have PUK or an active session, so we cannot talk to the server to resolve pseudonym.
		m.Debug("substituting the default PseudonymResolver as a paper key is being used for decryption")
		e.pnymResolver = &nilPseudonymResolver{}
	} else {
		// This does require you to be logged in.
		if !m.G().ActiveDevice.HaveKeys() {
			return libkb.LoginRequiredError{}
		}

		// Only used in the makeMessageInfo call, which is helpful for old messages (one cannot encrypt messages with visible recipients any more).
		me, err = libkb.LoadMe(libkb.NewLoadUserArgWithMetaContext(m))
		if err != nil {
			return err
		}

		// Get the device encryption key and per user keys.
		var key *libkb.NaclDHKeyPair
		var err error
		key, err = m.G().ActiveDevice.NaclEncryptionKey()
		if err != nil {
			return err
		}
		m.Debug("adding device key for decryption: %v", key.GetKID())
		addToKeyring(keyring, key)

		perUserKeyring, err := m.G().GetPerUserKeyring(m.Ctx())
		if err != nil {
			return err
		}
		pukGen := perUserKeyring.CurrentGeneration()
		for i := 1; i <= int(pukGen); i++ {
			key, err = perUserKeyring.GetEncryptionKeyByGeneration(m, keybase1.PerUserKeyGeneration(i))
			m.Debug("adding per user key at generation %v for decryption: %v", i, key.GetKID())
			if err != nil {
				return err
			}
			addToKeyring(keyring, key)
		}
	}

	// For DH mode.
	hookMki := func(mki *saltpack.MessageKeyInfo) error {
		kidToIdentify := libkb.BoxPublicKeyToKeybaseKID(mki.SenderKey)
		return e.promptForDecrypt(m, kidToIdentify, mki.SenderIsAnon)
	}

	// For signcryption mode.
	hookSenderSigningKey := func(senderSigningKey saltpack.SigningPublicKey) error {
		kidToIdentify := libkb.SigningPublicKeyToKeybaseKID(senderSigningKey)
		// See if the sender signing key is nil or all zeroes.
		isAnon := false
		if senderSigningKey == nil || bytes.Equal(senderSigningKey.ToKID(), make([]byte, len(senderSigningKey.ToKID()))) {
			isAnon = true
		}
		return e.promptForDecrypt(m, kidToIdentify, isAnon)
	}

	m.Debug("| SaltpackDecrypt")
	var mki *saltpack.MessageKeyInfo
	mki, err = libkb.SaltpackDecrypt(m, e.arg.Source, e.arg.Sink, keyring, hookMki, hookSenderSigningKey, e.pnymResolver)
	if decErr, ok := err.(libkb.DecryptionError); ok && decErr.Cause == saltpack.ErrNoDecryptionKey {
		m.Debug("switching cause of libkb.DecryptionError from saltpack.ErrNoDecryptionKey to more specific libkb.NoDecryptionKeyError")
		if e.arg.Opts.UsePaperKey {
			return libkb.DecryptionError{Cause: libkb.NoDecryptionKeyError{Msg: "this message was not directly encrypted for the given paper key. In some cases, you might still be able to decrypt the message from a device provisioned with this key."}}
		}
		err = libkb.DecryptionError{Cause: libkb.NoDecryptionKeyError{Msg: "no suitable key found"}}
	}

	// Since messages recipients are never public any more, this is only meaningful for messages generated by
	// very old clients (or potentially saltpack messages generated for a keybase user by some other app).
	// It's ok if me is nil here.
	e.makeMessageInfo(me, mki)

	return err
}
887042
func (intr *Interpreter) runModule(ctx context.Context, key moduleKey, kind ThreadKind) (starlark.StringDict, error) {
	// Grab the source code.
	dict, src, err := intr.invokeLoader(key)
	switch {
	case err != nil:
		return nil, err
	case dict != nil:
		// This is a native module constructed in Go, no need to interpret it.
		return dict, nil
	}

	// Otherwise make a thread for executing the code. We do not reuse threads
	// between modules. All global state is passed through intr.globals,
	// intr.modules and ctx.
	th := intr.Thread(ctx)
	th.Load = func(th *starlark.Thread, module string) (starlark.StringDict, error) {
		key, err := makeModuleKey(module, th)
		if err != nil {
			return nil, err
		}
		dict, err := intr.LoadModule(ctx, key.pkg, key.path)
		// See comment in execBuiltin about why we extract EvalError backtrace into
		// new error.
		if evalErr, ok := err.(*starlark.EvalError); ok {
			err = fmt.Errorf("%s", evalErr.Backtrace())
		}
		return dict, err
	}

	// Let builtins know what this thread is doing. Some calls (most notably Exec
	// itself) are allowed only from exec'ing threads, not from load'ing ones.
	th.SetLocal(threadKindKey, kind)
	// Let builtins (and in particular makeModuleKey and LoadSource) know the
	// package and the module that the thread executes.
	th.SetLocal(threadModKey, key)

	if kind == ThreadExecing {
		if intr.PreExec != nil {
			intr.PreExec(th, key.pkg, key.path)
		}
		if intr.PostExec != nil {
			defer intr.PostExec(th, key.pkg, key.path)
		}
	}

	// Execute the module. It may 'load' or 'exec' other modules inside, which
	// will either call LoadModule or ExecModule.
	//
	// Use user-friendly module name (with omitted "@__main__") for error messages
	// and stack traces to avoid confusing the user.
	return starlark.ExecFile(th, key.String(), src, intr.globals)
}
1091
func (d *BoundDistributor) Run(desc *dm.Quest_Desc, exAuth *dm.Execution_Auth, prev *dm.JsonResult) (tok distributor.Token, pollbackTime time.Duration, err error) {
	if err = d.RunError; err != nil {
		return
	}
	pollbackTime = d.PollbackTime

	tok = MakeToken(exAuth.Id)

	tsk := &DistributorData{
		Auth:  exAuth,
		Desc:  desc,
		State: prev,
	}
	tsk.NotifyTopic, tsk.NotifyAuth, err = d.cfg.PrepareTopic(d.c, exAuth.Id)
	panicIf(err)

	d.Lock()
	defer d.Unlock()
	if d.tasks == nil {
		d.tasks = map[distributor.Token]*DistributorData{}
	}
	d.tasks[tok] = tsk
	return
}
1330904
func main() {
	env, err := plugins.NewEnvironment()
	env.RespondAndExitIfError(err)

	packageName, err := resolvePackageName(env.Request.OutputPath)
	env.RespondAndExitIfError(err)

	// Use the name used to run the plugin to decide which files to generate.
	var files []string
	switch {
	case strings.Contains(env.Invocation, "gnostic-go-client"):
		files = []string{"client.go", "types.go", "constants.go"}
	case strings.Contains(env.Invocation, "gnostic-go-server"):
		files = []string{"server.go", "provider.go", "types.go", "constants.go"}
	default:
		files = []string{"client.go", "server.go", "provider.go", "types.go", "constants.go"}
	}

	for _, model := range env.Request.Models {
		switch model.TypeUrl {
		case "surface.v1.Model":
			surfaceModel := &surface.Model{}
			err = proto.Unmarshal(model.Value, surfaceModel)
			if err == nil {
				// Customize the code surface model for Go
				NewGoLanguageModel().Prepare(surfaceModel)

				modelJSON, _ := json.MarshalIndent(surfaceModel, "", "  ")
				modelFile := &plugins.File{Name: "model.json", Data: modelJSON}
				env.Response.Files = append(env.Response.Files, modelFile)

				// Create the renderer.
				renderer, err := NewServiceRenderer(surfaceModel)
				renderer.Package = packageName
				env.RespondAndExitIfError(err)

				// Run the renderer to generate files and add them to the response object.
				err = renderer.Render(env.Response, files)
				env.RespondAndExitIfError(err)

				// Return with success.
				env.RespondAndExit()
			}
		}
	}
	err = errors.New("No generated code surface model is available.")
	env.RespondAndExitIfError(err)
}
1149194
func run(program string) (*model.Package, error) {
	f, err := ioutil.TempFile("", "")
	if err != nil {
		return nil, err
	}

	filename := f.Name()
	defer os.Remove(filename)
	if err := f.Close(); err != nil {
		return nil, err
	}

	// Run the program.
	cmd := exec.Command(program, "-output", filename)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		return nil, err
	}

	f, err = os.Open(filename)
	if err != nil {
		return nil, err
	}

	// Process output.
	var pkg model.Package
	if err := gob.NewDecoder(f).Decode(&pkg); err != nil {
		return nil, err
	}

	if err := f.Close(); err != nil {
		return nil, err
	}

	return &pkg, nil
}
84853
func main() {
	logger.Level = golog.INFO

	app.Version("1.0.2")

	// install dependencies
	outputCmd("go", []string{"get", "github.com/ivpusic/rerun"})

	switch kingpin.MustParse(app.Parse(os.Args[1:])) {
	case run.FullCommand():
		handleRunCommand()
	case newCmd.FullCommand():
		handleNewCommand()
	default:
		app.Usage(os.Stdout)
	}
}
723437
func (b *bgpManager) run() {
	ticker := time.NewTicker(b.updateInterval)
	for {
		log.V(1).Infof("Updating BGP state and statistics...")
		b.update()
		<-ticker.C
	}
}