// Run starts the http(s) server for the cli
4541
func Run() {
	mux := NewServeMux(viper.GetString("static"))
	err := ServeMux(
		mux,
		viper.GetString("addr"),
		viper.GetString("port"),
		viper.GetString("cert"),
		viper.GetString("key"),
	)
	if err != nil {
		log.Println(err)
		return
	}
}
572579
func (c *disableCommand) Run(ctx *cmd.Context) error {
	api, err := c.apiFunc(c)
	if err != nil {
		return errors.Annotate(err, "cannot connect to the API")
	}
	defer api.Close()

	return api.SwitchBlockOn(c.target, c.message)
}
1088122
func (c *RFCCommand) Run(args []string) int {
	if len(args) == 0 {
		c.Ui.Error(c.Help())
		return 1
	}

	c.InitOpts()
	unprocessedArgs, err := c.parseOpts(args)
	if err != nil {
		if errwrap.Contains(err, "flag: help requested") {
			return 0
		}
		return 1
	}

	switch numArgs := len(unprocessedArgs); {
	case numArgs != 2 && numArgs != 0:
		c.Ui.Error(`ERROR: Need an RFC Number and an IP address to test.`)
		c.Ui.Error(c.Help())
		fallthrough
	case numArgs == 0:
		return 1
	}

	// Parse the RFC Number
	rfcNum, err := strconv.ParseUint(unprocessedArgs[0], 10, 32)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("ERROR: Invalid RFC Number %+q: %v", unprocessedArgs[0], err))
		return 2
	}

	// Parse the IP address
	ipAddr, err := sockaddr.NewIPAddr(unprocessedArgs[1])
	if err != nil {
		c.Ui.Error(fmt.Sprintf("ERROR: Invalid IP address %+q: %v", unprocessedArgs[1], err))
		return 3
	}

	switch inRFC := sockaddr.IsRFC(uint(rfcNum), ipAddr); {
	case inRFC && !c.silentMode:
		c.Ui.Output(fmt.Sprintf("%s is part of RFC %d", ipAddr, rfcNum))
		fallthrough
	case inRFC:
		return 0
	case !inRFC && !c.silentMode:
		c.Ui.Output(fmt.Sprintf("%s is not part of RFC %d", ipAddr, rfcNum))
		fallthrough
	case !inRFC:
		return 1
	default:
		panic("bad")
	}
}
30484
func (c *MockSSHClient) Run(command string, stdout io.Writer, stderr io.Writer) error {
	if c.MockRun != nil {
		return c.MockRun(command, stdout, stderr)
	}
	return ErrNotImplemented
}
980114
func (c *setPlanCommand) Run(ctx *cmd.Context) error {
	root, err := c.NewAPIRoot()
	if err != nil {
		return errors.Trace(err)
	}
	client := application.NewClient(root)
	credentials, err := c.requestMetricCredentials(client, ctx)
	if err != nil {
		return errors.Trace(err)
	}
	err = client.SetMetricCredentials(c.Application, credentials)
	if err != nil {
		return errors.Trace(err)
	}
	return nil
}
274796
func (cli *CLI) Run(args []string) int {
	kingpin.Version(version)
	kingpin.Parse()

	//Setup Logging
	loggingClient := logging.NewLogging(*syslogServer, *syslogProtocol, *logFormatterType, *certPath, *debug, *skipSSLSyslog)
	logging.LogStd(fmt.Sprintf("Starting firehose-to-syslog %s ", version), true)
	//
	// if *modeProf != "" {
	// 	switch *modeProf {
	// 	case "cpu":
	// 		defer profile.Start(profile.CPUProfile, profile.ProfilePath(*pathProf)).Stop()
	// 	case "mem":
	// 		defer profile.Start(profile.MemProfile, profile.ProfilePath(*pathProf)).Stop()
	// 	case "block":
	// 		defer profile.Start(profile.BlockProfile, profile.ProfilePath(*pathProf)).Stop()
	// 	default:
	// 		// do nothing
	// 	}
	// }

	c := cfclient.Config{
		ApiAddress:        *apiEndpoint,
		ClientID:          *clientID,
		ClientSecret:      *clientSecret,
		SkipSslValidation: *skipSSLValidation,
		UserAgent:         "firehose-to-syslog/" + version,
	}
	cfClient, err := cfclient.NewClient(&c)
	if err != nil {
		logging.LogError("New Client: ", err)
		return ExitCodeError

	}
	if len(*dopplerEndpoint) > 0 {
		cfClient.Endpoint.DopplerEndpoint = *dopplerEndpoint
	}
	fmt.Println(cfClient.Endpoint.DopplerEndpoint)
	logging.LogStd(fmt.Sprintf("Using %s as doppler endpoint", cfClient.Endpoint.DopplerEndpoint), true)

	//Creating Caching
	var cacheStore caching.CacheStore
	switch {
	case boltDatabasePath != nil && *boltDatabasePath != "":
		cacheStore = &caching.BoltCacheStore{
			Path: *boltDatabasePath,
		}
	default:
		cacheStore = &caching.MemoryCacheStore{}
	}

	if err := cacheStore.Open(); err != nil {
		logging.LogError("Error open cache: ", err)
		return ExitCodeError
	}
	defer cacheStore.Close()

	cachingClient := caching.NewCacheLazyFill(
		&caching.CFClientAdapter{
			CF: cfClient,
		},
		cacheStore,
		&caching.CacheLazyFillConfig{
			IgnoreMissingApps:  *ignoreMissingApps,
			CacheInvalidateTTL: *tickerTime,
			StripAppSuffixes:   strings.Split(*stripAppSuffixes, ","),
		})

	if caching.IsNeeded(*wantedEvents) {
		// Bootstrap cache
		logging.LogStd("Pre-filling cache...", true)
		err = cachingClient.FillCache()
		if err != nil {
			logging.LogError("Error pre-filling cache: ", err)
			return ExitCodeError
		}
		logging.LogStd("Cache filled.", true)
	}

	//Adding Stats
	statistic := stats.NewStats()
	go statistic.PerSec()

	////Starting Http Server for Stats
	if *statServer {
		Server := &stats.Server{
			Logger: log.New(os.Stdout, "", 1),
			Stats:  statistic,
		}

		go Server.Start()
	}

	//Creating Events
	eventFilters := []eventRouting.EventFilter{eventRouting.HasIgnoreField, eventRouting.NotInCertainOrgs(*orgs)}
	events := eventRouting.NewEventRouting(cachingClient, loggingClient, statistic, eventFilters)
	err = events.SetupEventRouting(*wantedEvents)
	if err != nil {
		logging.LogError("Error setting up event routing: ", err)
		return ExitCodeError
	}

	//Set extrafields if needed
	events.SetExtraFields(*extraFields)

	firehoseConfig := &firehoseclient.FirehoseConfig{
		RLPAddr:                strings.Replace(cfClient.Config.ApiAddress, "api", "log-stream", 1),
		InsecureSSLSkipVerify:  *skipSSLValidation,
		FirehoseSubscriptionID: *subscriptionId,
		BufferSize:             *bufferSize,
	}

	if loggingClient.Connect() || *debug {
		logging.LogStd("Connected to Syslog Server! Connecting to Firehose...", true)
	} else {
		logging.LogError("Failed connecting to the Syslog Server...Please check settings and try again!", "")
		return ExitCodeError
	}

	uaa, err := uaago.NewClient(cfClient.Endpoint.AuthEndpoint)
	if err != nil {
		logging.LogError(fmt.Sprint("Failed connecting to Get token from UAA..", err), "")
	}

	ac := authclient.NewHttp(uaa, *clientID, *clientSecret, *skipSSLValidation)
	firehoseClient := firehoseclient.NewFirehoseNozzle(events, firehoseConfig, statistic, ac)
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	firehoseClient.Start(ctx)

	signalChan := make(chan os.Signal, 1)
	cleanupDone := make(chan bool)
	signal.Notify(signalChan, os.Interrupt, os.Kill)
	go func() {
		for range signalChan {
			fmt.Println("\nSignal Received, Stop reading and starting Draining...")
			firehoseClient.StopReading()
			cctx, tcancel := context.WithTimeout(context.TODO(), 30*time.Second)
			tcancel()
			firehoseClient.Draining(cctx)
			cleanupDone <- true
		}
	}()

	<-cleanupDone

	return ExitCodeOk
}
559063
func (c *DeleteHostCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
	ctx := cli.GetContext(app, c, env)
	// TODO(smut): Validate required fields client-side.
	client := getClient(ctx)
	_, err := client.DeleteHost(ctx, &c.req)
	if err != nil {
		errors.Log(ctx, err)
		return 1
	}
	return 0
}
1227581
func (e *EventServer) Run(ctx context.Context) error {

	// Create the handler
	e.server = &http.Server{
		Handler: e,
	}

	// Start a custom listener
	addr, _ := net.ResolveUnixAddr("unix", e.socketPath)
	nl, err := net.ListenUnix("unix", addr)
	if err != nil {
		return fmt.Errorf("Unable to start API server: %s", err)
	}

	// We make the socket accesible to all users of the system.
	// TODO: create a trireme group for this
	if err := os.Chmod(addr.String(), 0766); err != nil {
		return fmt.Errorf("Cannot make the socket accessible to all users: %s", err)
	}

	listener := &UIDListener{nl}

	// Start serving HTTP requests in the background
	go e.server.Serve(listener) // nolint

	// Listen for context cancellation to close the socket.
	go func() {
		<-ctx.Done()
		nl.Close() // nolint
	}()

	return nil
}
330660
func (c *CmdSimpleFSHistory) Run() error {
	cli, err := GetSimpleFSClient(c.G())
	if err != nil {
		return err
	}

	if c.path == (keybase1.Path{}) {
		history, err := cli.SimpleFSUserEditHistory(context.TODO())
		if err != nil {
			return err
		}
		for _, h := range history {
			c.output(h)
		}
	} else {
		history, err := cli.SimpleFSFolderEditHistory(context.TODO(), c.path)
		if err != nil {
			return err
		}
		c.output(history)
	}

	return err
}
196784
func (c *CmdSimpleFSRemove) Run() error {
	cli, err := GetSimpleFSClient(c.G())
	if err != nil {
		return err
	}

	ctx := context.TODO()

	paths, err := doSimpleFSGlob(ctx, c.G(), cli, c.paths)
	if err != nil {
		return err
	}

	for _, path := range paths {
		opid, err2 := cli.SimpleFSMakeOpid(ctx)
		if err2 != nil {
			return err2
		}
		defer cli.SimpleFSClose(ctx, opid)
		c.G().Log.Debug("SimpleFSRemove %s", path.Kbfs())
		err = cli.SimpleFSRemove(ctx, keybase1.SimpleFSRemoveArg{
			OpID:      opid,
			Path:      path,
			Recursive: c.recurse,
		})
		if err != nil {
			break
		}
		err = cli.SimpleFSWait(ctx, opid)
		if err != nil {
			break
		}
	}
	return err
}
1284696
func (c *CmdSimpleFSSymlink) Run() error {
	cli, err := GetSimpleFSClient(c.G())
	if err != nil {
		return err
	}

	ctx := context.TODO()
	arg := keybase1.SimpleFSSymlinkArg{
		Target: c.target,
		Link:   c.link,
	}

	return cli.SimpleFSSymlink(ctx, arg)
}
941904
func (c *ReloadCommand) Run(ctx *cmd.Context) error {
	return c.RunWithAPI(ctx, func(api SpaceAPI, ctx *cmd.Context) error {
		err := api.ReloadSpaces()
		if err != nil {
			if errors.IsNotSupported(err) {
				ctx.Infof("cannot reload spaces: %v", err)
			}
			return errors.Annotate(err, "cannot reload spaces")
		}
		return nil
	})
}
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
}
728109
func (s *Service) Run(ctx context.Context, commandParts []string, options options.Run) (int, error) {
	err := s.ensureImageExists(ctx, false, false)
	if err != nil {
		return -1, err
	}

	client := s.clientFactory.Create(s)

	namer, err := NewNamer(ctx, client, s.project.Name, s.name, true)
	if err != nil {
		return -1, err
	}

	configOverride := &config.ServiceConfig{Command: commandParts, Tty: !options.DisableTty, StdinOpen: !options.DisableTty}

	c, err := s.createContainer(ctx, namer, "", configOverride, true)
	if err != nil {
		return -1, err
	}

	if err := s.connectContainerToNetworks(ctx, c, true); err != nil {
		return -1, err
	}

	if options.Detached {
		logrus.Infof("%s", c.Name())
		return 0, c.Start(ctx)
	}
	return c.Run(ctx, configOverride)
}
556140
func Run() {
	cli.HelpFlag = cli.BoolFlag{Name: HelpKey + ", " + helpKeyShort, Usage: "Show help."}
	cli.AppHelpTemplate = helpTemplate

	cli.VersionFlag = cli.BoolFlag{Name: VersionKey + ", " + versionKeyShort, Usage: "Print the version."}
	cli.VersionPrinter = func(c *cli.Context) { fmt.Println(c.App.Version) }

	app := cli.NewApp()
	app.Name = path.Base(os.Args[0])
	app.Usage = "Environment variable manager"
	app.Version = version.VERSION

	app.Author = ""
	app.Email = ""

	app.Before = before

	app.Flags = flags
	app.Commands = commands

	if err := app.Run(os.Args); err != nil {
		log.Fatal("[ENVMAN] - Finished:", err)
	}
}
464387
func (c *CLI) Run() (int, error) {
	c.once.Do(c.init)

	// If this is a autocompletion request, satisfy it. This must be called
	// first before anything else since its possible to be autocompleting
	// -help or -version or other flags and we want to show completions
	// and not actually write the help or version.
	if c.Autocomplete && c.autocomplete.Complete() {
		return 0, nil
	}

	// Just show the version and exit if instructed.
	if c.IsVersion() && c.Version != "" {
		c.HelpWriter.Write([]byte(c.Version + "\n"))
		return 0, nil
	}

	// Just print the help when only '-h' or '--help' is passed.
	if c.IsHelp() && c.Subcommand() == "" {
		c.HelpWriter.Write([]byte(c.HelpFunc(c.helpCommands(c.Subcommand())) + "\n"))
		return 0, nil
	}

	// If we're attempting to install or uninstall autocomplete then handle
	if c.Autocomplete {
		// Autocomplete requires the "Name" to be set so that we know what
		// command to setup the autocomplete on.
		if c.Name == "" {
			return 1, fmt.Errorf(
				"internal error: CLI.Name must be specified for autocomplete to work")
		}

		// If both install and uninstall flags are specified, then error
		if c.isAutocompleteInstall && c.isAutocompleteUninstall {
			return 1, fmt.Errorf(
				"Either the autocomplete install or uninstall flag may " +
					"be specified, but not both.")
		}

		// If the install flag is specified, perform the install or uninstall
		if c.isAutocompleteInstall {
			if err := c.autocompleteInstaller.Install(c.Name); err != nil {
				return 1, err
			}

			return 0, nil
		}

		if c.isAutocompleteUninstall {
			if err := c.autocompleteInstaller.Uninstall(c.Name); err != nil {
				return 1, err
			}

			return 0, nil
		}
	}

	// Attempt to get the factory function for creating the command
	// implementation. If the command is invalid or blank, it is an error.
	raw, ok := c.commandTree.Get(c.Subcommand())
	if !ok {
		c.HelpWriter.Write([]byte(c.HelpFunc(c.helpCommands(c.subcommandParent())) + "\n"))
		return 127, nil
	}

	command, err := raw.(CommandFactory)()
	if err != nil {
		return 1, err
	}

	// If we've been instructed to just print the help, then print it
	if c.IsHelp() {
		c.commandHelp(command)
		return 0, nil
	}

	// If there is an invalid flag, then error
	if len(c.topFlags) > 0 {
		c.HelpWriter.Write([]byte(
			"Invalid flags before the subcommand. If these flags are for\n" +
				"the subcommand, please put them after the subcommand.\n\n"))
		c.commandHelp(command)
		return 1, nil
	}

	code := command.Run(c.SubcommandArgs())
	if code == RunResultHelp {
		// Requesting help
		c.commandHelp(command)
		return 1, nil
	}

	return code, nil
}
1041697
func Run(addr string, timeout time.Duration, n http.Handler) {
	srv := &Server{
		Timeout:      timeout,
		TCPKeepAlive: 3 * time.Minute,
		Server:       &http.Server{Addr: addr, Handler: n},
		// Logger:       DefaultLogger(),
	}

	if err := srv.ListenAndServe(); err != nil {
		if opErr, ok := err.(*net.OpError); !ok || (ok && opErr.Op != "accept") {
			srv.logf("%s", err)
			os.Exit(1)
		}
	}

}