示例#1
0
func (c *NozzlerCmd) Run(cliConnection plugin.CliConnection, args []string) {
	var debug bool
	if args[0] != "nozzle" {
		return
	}
	c.ui = terminal.NewUI(os.Stdin, terminal.NewTeePrinter())

	fc := flags.NewFlagContext(setupFlags())
	err := fc.Parse(args[1:]...)
	if err != nil {
		c.ui.Failed(err.Error())
	}
	if fc.IsSet("debug") {
		debug = fc.Bool("debug")
	}

	dopplerEndpoint, err := cliConnection.DopplerEndpoint()
	if err != nil {
		c.ui.Failed(err.Error())
	}

	authToken, err := cliConnection.AccessToken()
	if err != nil {
		c.ui.Failed(err.Error())
	}

	client := firehose.NewClient(authToken, dopplerEndpoint, debug, c.ui)
	client.Start()
}
func NewListAppsCommand(cliConnection api.Connection, orgName string, spaceName string, runtime ui.Runtime) (ui.ListAppsCommand, error) {
	username, err := cliConnection.Username()
	if err != nil {
		return ui.ListAppsCommand{}, err
	}

	if spaceName != "" {
		space, err := cliConnection.GetSpace(spaceName)
		if err != nil || space.Guid == "" {
			return ui.ListAppsCommand{}, err
		}
		orgName = space.Organization.Name
	}

	traceEnv := os.Getenv("CF_TRACE")
	traceLogger := trace.NewLogger(false, traceEnv, "")
	tUI := terminal.NewUI(os.Stdin, terminal.NewTeePrinter(), traceLogger)

	cmd := ui.ListAppsCommand{
		Username:     username,
		Organization: orgName,
		Space:        spaceName,
		UI:           tUI,
		Runtime:      runtime,
	}
	return cmd, nil
}
示例#3
0
文件: abclient.go 项目: glyn/bloblets
func newRequestForFile(method, fullUrl string, body *os.File) (req *Request, apiErr error) {
	ui := terminal.NewUI(os.Stdin, &cliutil.NonPrinter{})
	progressReader := net.NewProgressReader(body, ui, 5*time.Second)
	progressReader.Seek(0, 0)
	fileStats, err := body.Stat()

	if err != nil {
		apiErr = fmt.Errorf("%s: %s", "Error getting file info", err.Error())
		return
	}

	request, err := http.NewRequest(method, fullUrl, progressReader)
	if err != nil {
		apiErr = fmt.Errorf("%s: %s", "Error building request", err.Error())
		return
	}

	fileSize := fileStats.Size()
	progressReader.SetTotalSize(fileSize)
	request.ContentLength = fileSize

	if err != nil {
		apiErr = fmt.Errorf("%s: %s", "Error building request", err.Error())
		return
	}

	return newRequest(request, progressReader)
}
示例#4
0
文件: main.go 项目: matanzit/cli
func setupDependencies() (deps *cliDependencies) {
	deps = new(cliDependencies)

	deps.termUI = terminal.NewUI(os.Stdin)

	deps.manifestRepo = manifest.NewManifestDiskRepository()

	deps.configRepo = configuration.NewRepositoryFromFilepath(configuration.DefaultFilePath(), func(err error) {
		if err != nil {
			deps.termUI.Failed(fmt.Sprintf("Config error: %s", err))
		}
	})

	i18n.T = i18n.Init(deps.configRepo)

	terminal.UserAskedForColors = deps.configRepo.ColorEnabled()
	terminal.InitColorSupport()

	if os.Getenv("CF_TRACE") != "" {
		trace.Logger = trace.NewLogger(os.Getenv("CF_TRACE"))
	} else {
		trace.Logger = trace.NewLogger(deps.configRepo.Trace())
	}

	deps.gateways = map[string]net.Gateway{
		"auth":             net.NewUAAGateway(deps.configRepo),
		"cloud-controller": net.NewCloudControllerGateway(deps.configRepo, time.Now),
		"uaa":              net.NewUAAGateway(deps.configRepo),
	}
	deps.apiRepoLocator = api.NewRepositoryLocator(deps.configRepo, deps.gateways)

	return
}
示例#5
0
func (s *FirehoseStatsCmd) Run(cliConnection plugin.CliConnection, args []string) {

	if args[0] != "firehose-stats" {
		return
	}

	s.cfUI = terminal.NewUI(os.Stdin, terminal.NewTeePrinter())

	dopplerEndpoint, err := cliConnection.DopplerEndpoint()
	if err != nil {
		s.cfUI.Failed(err.Error())
	}

	authToken, err := cliConnection.AccessToken()
	if err != nil {
		s.cfUI.Failed(err.Error())
	}
	firehoseChan := make(chan *events.Envelope)
	client := firehose.NewClient(authToken, dopplerEndpoint, s.cfUI, firehoseChan)
	client.Start()

	statsUI := stats.New(client, s.cfUI, cliConnection)
	statsUI.Start()

}
示例#6
0
func (cmd *CliRpcCmd) CallCoreCommand(args []string, retVal *bool) error {
	defer func() {
		recover()
	}()

	var err error
	cmdRegistry := command_registry.Commands

	cmd.outputBucket = &[]string{}
	cmd.outputCapture.SetOutputBucket(cmd.outputBucket)

	if cmdRegistry.CommandExists(args[0]) {
		deps := command_registry.NewDependency()

		//set deps objs to be the one used by all other codegangsta commands
		//once all commands are converted, we can make fresh deps for each command run
		deps.Config = cmd.cliConfig
		deps.RepoLocator = cmd.repoLocator
		deps.Ui = terminal.NewUI(os.Stdin, cmd.outputCapture.(*terminal.TeePrinter))

		err = cmd.newCmdRunner.Command(args, deps, false)
	} else {
		//call codegangsta command
		err = cmd.coreCommandRunner.Run(append([]string{"CF_NAME"}, args...))
	}

	if err != nil {
		*retVal = false
		return err
	}

	*retVal = true
	return nil
}
示例#7
0
func NewDependency() Dependency {
	deps := Dependency{}
	deps.TeePrinter = terminal.NewTeePrinter()
	deps.Ui = terminal.NewUI(os.Stdin, deps.TeePrinter)
	deps.ManifestRepo = manifest.NewManifestDiskRepository()

	errorHandler := func(err error) {
		if err != nil {
			deps.Ui.Failed(fmt.Sprintf("Config error: %s", err))
		}
	}
	deps.Config = core_config.NewRepositoryFromFilepath(config_helpers.DefaultFilePath(), errorHandler)
	deps.PluginConfig = plugin_config.NewPluginConfig(errorHandler)
	deps.Detector = &detection.JibberJabberDetector{}

	terminal.UserAskedForColors = deps.Config.ColorEnabled()
	terminal.InitColorSupport()

	if os.Getenv("CF_TRACE") != "" {
		trace.Logger = trace.NewLogger(os.Getenv("CF_TRACE"))
	} else {
		trace.Logger = trace.NewLogger(deps.Config.Trace())
	}

	deps.Gateways = map[string]net.Gateway{
		"auth":             net.NewUAAGateway(deps.Config, deps.Ui),
		"cloud-controller": net.NewCloudControllerGateway(deps.Config, time.Now, deps.Ui),
		"uaa":              net.NewUAAGateway(deps.Config, deps.Ui),
	}
	deps.RepoLocator = api.NewRepositoryLocator(deps.Config, deps.Gateways)

	deps.PluginModels = &pluginModels{Application: nil}

	return deps
}
示例#8
0
func (c *NozzlerCmd) Run(cliConnection plugin.CliConnection, args []string) {
	var options *firehose.ClientOptions

	traceLogger := trace.NewLogger(os.Stdout, true, os.Getenv("CF_TRACE"), "")
	c.ui = terminal.NewUI(os.Stdin, os.Stdout, terminal.NewTeePrinter(os.Stdout), traceLogger)

	switch args[0] {
	case "nozzle":
		options = c.buildClientOptions(args)
	case "app-nozzle":
		options = c.buildClientOptions(args)
		appModel, err := cliConnection.GetApp(args[1])
		if err != nil {
			c.ui.Warn(err.Error())
			return
		}

		options.AppGUID = appModel.Guid
	default:
		return
	}

	dopplerEndpoint, err := cliConnection.DopplerEndpoint()
	if err != nil {
		c.ui.Failed(err.Error())
	}

	authToken, err := cliConnection.AccessToken()
	if err != nil {
		c.ui.Failed(err.Error())
	}

	client := firehose.NewClient(authToken, dopplerEndpoint, options, c.ui)
	client.Start()
}
func (cmd *Wildcard) WildcardCommandApps(cliConnection plugin.CliConnection, args []string) {
	InitializeCliDependencies()
	defer panic.HandlePanics()
	cmd.getMatchedApps(cliConnection, args)
	cmd.ui = terminal.NewUI(os.Stdin, terminal.NewTeePrinter())
	table := terminal.NewTable(cmd.ui, []string{T("name"), T("requested state"), T("instances"), T("memory"), T("disk"), T("urls")})
	for _, app := range cmd.matchedApps {
		var urls []string
		for _, route := range app.Routes {
			if route.Host == "" {
				urls = append(urls, route.Domain.Name)
			}
			urls = append(urls, fmt.Sprintf("%s.%s", route.Host, route.Domain.Name))
		}
		table.Add(
			app.Name,
			app.State,
			strconv.Itoa(app.RunningInstances),
			formatters.ByteSize(app.Memory*formatters.MEGABYTE),
			formatters.ByteSize(app.DiskQuota*formatters.MEGABYTE),
			strings.Join(urls, ", "),
		)
	}
	table.Print()
}
示例#10
0
文件: main.go 项目: matanzit/cli
func handlePanics() {
	panic_printer.UI = terminal.NewUI(os.Stdin)

	commandArgs := strings.Join(os.Args, " ")
	stackTrace := generateBacktrace()

	err := recover()
	panic_printer.DisplayCrashDialog(err, commandArgs, stackTrace)

	if err != nil {
		os.Exit(1)
	}
}
示例#11
0
文件: cmd.go 项目: Reejoshi/cli
func handlePanics(args []string, printer terminal.Printer, logger trace.Printer) {
	panicPrinter := panicprinter.NewPanicPrinter(terminal.NewUI(os.Stdin, Writer, printer, logger))

	commandArgs := strings.Join(args, " ")
	stackTrace := generateBacktrace()

	err := recover()
	panicPrinter.DisplayCrashDialog(err, commandArgs, stackTrace)

	if err != nil {
		os.Exit(1)
	}
}
示例#12
0
/*
*	This function must be implemented by any plugin because it is part of the
*	plugin interface defined by the core CLI.
*
*	Run(....) is the entry point when the core CLI is invoking a command defined
*	by a plugin. The first parameter, plugin.CliConnection, is a struct that can
*	be used to invoke cli commands. The second paramter, args, is a slice of
*	strings. args[0] will be the name of the command, and will be followed by
*	any additional arguments a cli user typed in.
*
*	Any error handling should be handled with the plugin itself (this means printing
*	user facing errors). The CLI will exit 0 if the plugin exits 0 and will exit
*	1 should the plugin exits nonzero.
 */
func (c *DoctorPlugin) Run(cliConnection plugin.CliConnection, args []string) {
	fmt.Printf("\n\n")
	var triageApps []string
	var triageRoutes []string
	var triageServices []string

	c.ui = terminal.NewUI(os.Stdin, terminal.NewTeePrinter())
	c.ui.Say(terminal.WarningColor("doctor: time to triage cloudfoundry"))
	fmt.Printf("\n")
	c.CFMainChecks(cliConnection)

	listOfRunningApps := c.AppsStateRunning(cliConnection)
	listOfStoppedApps := c.AppsStateStopped(cliConnection)
	triageApps = c.CheckUpApps(cliConnection, triageApps, listOfRunningApps, listOfStoppedApps)
	triageRoutes = c.CheckUpRoutes(cliConnection, triageRoutes)
	triageServices = c.CheckUpServices(cliConnection, triageServices)

	if len(triageApps) == 0 && len(triageRoutes) == 0 && len(triageServices) == 0 {
		c.ui.Say(terminal.SuccessColor("doctor: Everything looks OK!"))
		return
	}

	// doctor run results
	if len(triageApps) > 0 {
		c.ui.Say(terminal.WarningColor("Detected triage points for apps: "))
		for _, v := range triageApps {

			c.ui.Say(terminal.LogStderrColor(strings.Split(v, "___")[0]+" <---> ") + terminal.LogStderrColor(strings.Split(v, "___")[1]))
		}
	}
	c.ui.Say(" ")

	if len(triageRoutes) > 0 {
		c.ui.Say(terminal.WarningColor("Following routes do not have any app bound to them:"))

		for _, y := range triageRoutes {
			c.ui.Say(terminal.LogStderrColor(y))
		}
	}
	fmt.Printf("\n")
	if len(triageServices) > 0 {
		c.ui.Say(terminal.WarningColor("Following services do not have any app bound to them:"))

		for _, y := range triageServices {
			c.ui.Say(terminal.LogStderrColor(y))
		}
	}
}
示例#13
0
func New(ccTarget string, uaaTarget string, username string, password string) (*CFServices, error) {
	cfs := CFServices{
		CCTarget:  ccTarget,
		UAATarget: uaaTarget,
		Username:  username,
		Password:  password,
		SessionID: uuid.New(),
	}
	cfs.gateways = make(map[string]net.Gateway)
	cfs.configFilePath = strings.Replace(config_helpers.DefaultFilePath(), ".json", "."+cfs.SessionID+".json", -1)
	cfs.config = core_config.NewRepositoryFromFilepath(cfs.configFilePath,
		func(err error) {
			if err != nil {
				fmt.Printf("Config error: %s", err)
			}
		})
	cfs.config.SetApiEndpoint(ccTarget)
	cfs.config.SetAuthenticationEndpoint(uaaTarget)
	cfs.config.SetUaaEndpoint(uaaTarget)
	cfs.config.SetSSLDisabled(true)

	cfs.teePrinter = terminal.NewTeePrinter()
	cfs.termUI = terminal.NewUI(os.Stdin, cfs.teePrinter)
	cfs.detector = &detection.JibberJabberDetector{}

	T = Init(cfs.config, cfs.detector)
	terminal.UserAskedForColors = cfs.config.ColorEnabled()
	terminal.InitColorSupport()

	cfs.gateways["cloud-controller"] = net.NewCloudControllerGateway(cfs.config, time.Now, cfs.termUI)
	cfs.gateways["auth"] = net.NewUAAGateway(cfs.config, cfs.termUI)
	cfs.gateways["uaa"] = net.NewUAAGateway(cfs.config, cfs.termUI)

	cfs.authRepo = authentication.NewUAAAuthenticationRepository(cfs.gateways["uaa"], cfs.config)

	cfs.Organizations = organizations.NewCloudControllerOrganizationRepository(cfs.config, cfs.gateways["cloud-controller"])
	cfs.Spaces = spaces.NewCloudControllerSpaceRepository(cfs.config, cfs.gateways["cloud-controller"])
	cfs.Services = api.NewCloudControllerServiceRepository(cfs.config, cfs.gateways["cloud-controller"])
	cfs.Plans = api.NewCloudControllerServicePlanRepository(cfs.config, cfs.gateways["cloud-controller"])

	err := cfs.authRepo.Authenticate(map[string]string{
		"username": username,
		"password": password,
	})

	return &cfs, err
}
示例#14
0
func (cmd *CliRpcCmd) GetOrg(orgName string, retVal *plugin_models.GetOrg_Model) error {
	defer func() {
		recover()
	}()

	deps := commandregistry.NewDependency(cmd.stdout, cmd.logger, dialTimeout)

	//set deps objs to be the one used by all other commands
	//once all commands are converted, we can make fresh deps for each command run
	deps.Config = cmd.cliConfig
	deps.RepoLocator = cmd.repoLocator
	deps.PluginModels.Organization = retVal
	cmd.terminalOutputSwitch.DisableTerminalOutput(true)
	deps.UI = terminal.NewUI(os.Stdin, cmd.stdout, cmd.terminalOutputSwitch.(*terminal.TeePrinter), cmd.logger)

	return cmd.newCmdRunner.Command([]string{"org", orgName}, deps, true)
}
示例#15
0
func (cmd *CliRpcCmd) GetSpaceUsers(args []string, retVal *[]plugin_models.User) error {
	defer func() {
		recover()
	}()

	deps := command_registry.NewDependency()

	//set deps objs to be the one used by all other codegangsta commands
	//once all commands are converted, we can make fresh deps for each command run
	deps.Config = cmd.cliConfig
	deps.RepoLocator = cmd.repoLocator
	deps.PluginModels.Users = retVal
	cmd.terminalOutputSwitch.DisableTerminalOutput(true)
	deps.Ui = terminal.NewUI(os.Stdin, cmd.terminalOutputSwitch.(*terminal.TeePrinter))

	return cmd.newCmdRunner.Command(append([]string{"space-users"}, args...), deps, true)
}
func (cmd *CliRpcCmd) GetService(serviceInstance string, retVal *plugin_models.GetService_Model) error {
	defer func() {
		recover()
	}()

	deps := command_registry.NewDependency(cmd.logger)

	//set deps objs to be the one used by all other commands
	//once all commands are converted, we can make fresh deps for each command run
	deps.Config = cmd.cliConfig
	deps.RepoLocator = cmd.repoLocator
	deps.PluginModels.Service = retVal
	cmd.terminalOutputSwitch.DisableTerminalOutput(true)
	deps.Ui = terminal.NewUI(os.Stdin, cmd.terminalOutputSwitch.(*terminal.TeePrinter), cmd.logger)

	return cmd.newCmdRunner.Command([]string{"service", serviceInstance}, deps, true)
}
示例#17
0
/*
*	This function must be implemented by any plugin because it is part of the
*	plugin interface defined by the core CLI.
*
*	Run(....) is the entry point when the core CLI is invoking a command defined
*	by a plugin. The first parameter, plugin.CliConnection, is a struct that can
*	be used to invoke cli commands. The second paramter, args, is a slice of
*	strings. args[0] will be the name of the command, and will be followed by
*	any additional arguments a cli user typed in.
*
*	Any error handling should be handled with the plugin itself (this means printing
*	user facing errors). The CLI will exit 0 if the plugin exits 0 and will exit
*	1 should the plugin exits nonzero.
 */
func (c *FastPushPlugin) Run(cliConnection plugin.CliConnection, args []string) {
	// Ensure that the user called the command fast-push
	// alias fp is auto mapped
	var dryRun bool
	c.ui = terminal.NewUI(os.Stdin, terminal.NewTeePrinter())

	cliLogged, err := cliConnection.IsLoggedIn()
	if err != nil {
		c.ui.Failed(err.Error())
	}

	if cliLogged == false {
		panic("cannot perform fast-push without being logged in to CF")
	}

	if args[0] == "fast-push" || args[0] == "fp" {
		if len(args) == 1 {
			c.showUsage(args)
			return
		}
		// set flag for dry run
		fc := flags.New()
		fc.NewBoolFlag("dry", "d", "bool dry run flag")

		err := fc.Parse(args[1:]...)
		if err != nil {
			c.ui.Failed(err.Error())
		}
		// check if the user asked for a dry run or not
		if fc.IsSet("dry") {
			dryRun = fc.Bool("dry")
		} else {
			c.ui.Warn("warning: dry run not set, commencing fast push")
		}

		c.ui.Say("Running the fast-push command")
		c.ui.Say("Target app: %s \n", args[1])
		c.FastPush(cliConnection, args[1], dryRun)
	} else if args[0] == "fast-push-status" || args[0] == "fps" {
		c.FastPushStatus(cliConnection, args[1])
	} else {
		return
	}

}
示例#18
0
文件: main.go 项目: raghulsid/cli
func setupDependencies() (deps *cliDependencies) {
	deps = new(cliDependencies)

	deps.teePrinter = terminal.NewTeePrinter()

	deps.termUI = terminal.NewUI(os.Stdin, deps.teePrinter)

	deps.manifestRepo = manifest.NewManifestDiskRepository()

	errorHandler := func(err error) {
		if err != nil {
			deps.termUI.Failed(fmt.Sprintf("Config error: %s", err))
		}
	}
	deps.configRepo = core_config.NewRepositoryFromFilepath(config_helpers.DefaultFilePath(), errorHandler)
	deps.pluginConfig = plugin_config.NewPluginConfig(errorHandler)
	deps.detector = &detection.JibberJabberDetector{}

	T = Init(deps.configRepo, deps.detector)

	terminal.UserAskedForColors = deps.configRepo.ColorEnabled()
	terminal.InitColorSupport()

	if os.Getenv("CF_TRACE") != "" {
		trace.Logger = trace.NewLogger(os.Getenv("CF_TRACE"))
	} else {
		trace.Logger = trace.NewLogger(deps.configRepo.Trace())
	}

	deps.gateways = map[string]net.Gateway{
		"auth":             net.NewUAAGateway(deps.configRepo, deps.termUI),
		"cloud-controller": net.NewCloudControllerGateway(deps.configRepo, time.Now, deps.termUI),
		"uaa":              net.NewUAAGateway(deps.configRepo, deps.termUI),
	}
	deps.apiRepoLocator = api.NewRepositoryLocator(deps.configRepo, deps.gateways)

	return
}
func (cmd *CliRpcCmd) CallCoreCommand(args []string, retVal *bool) error {
	defer func() {
		recover()
	}()

	var err error
	cmdRegistry := command_registry.Commands

	cmd.outputBucket = &[]string{}
	cmd.outputCapture.SetOutputBucket(cmd.outputBucket)

	if cmdRegistry.CommandExists(args[0]) {
		deps := command_registry.NewDependency(cmd.logger)

		//set deps objs to be the one used by all other commands
		//once all commands are converted, we can make fresh deps for each command run
		deps.Config = cmd.cliConfig
		deps.RepoLocator = cmd.repoLocator

		//set command ui's TeePrinter to be the one used by RpcService, for output to be captured
		deps.Ui = terminal.NewUI(os.Stdin, cmd.outputCapture.(*terminal.TeePrinter), cmd.logger)

		err = cmd.newCmdRunner.Command(args, deps, false)
	} else {
		*retVal = false
		return nil
	}

	if err != nil {
		*retVal = false
		return err
	}

	*retVal = true
	return nil
}
示例#20
0
func main() {
	plugin.Start(&watch.Plugin{
		Session: &scp.Session{},
		UI:      terminal.NewUI(os.Stdin, terminal.NewTeePrinter()),
	})
}
func NewDependency(logger trace.Printer) Dependency {
	deps := Dependency{}
	deps.TeePrinter = terminal.NewTeePrinter()
	deps.Ui = terminal.NewUI(os.Stdin, deps.TeePrinter, logger)

	errorHandler := func(err error) {
		if err != nil {
			deps.Ui.Failed(fmt.Sprintf("Config error: %s", err))
		}
	}
	deps.Config = core_config.NewRepositoryFromFilepath(config_helpers.DefaultFilePath(), errorHandler)

	deps.ManifestRepo = manifest.NewManifestDiskRepository()
	deps.AppManifest = manifest.NewGenerator()
	deps.PluginConfig = plugin_config.NewPluginConfig(errorHandler)

	terminal.UserAskedForColors = deps.Config.ColorEnabled()
	terminal.InitColorSupport()

	deps.Gateways = map[string]net.Gateway{
		"cloud-controller": net.NewCloudControllerGateway(deps.Config, time.Now, deps.Ui, logger),
		"uaa":              net.NewUAAGateway(deps.Config, deps.Ui, logger),
		"routing-api":      net.NewRoutingApiGateway(deps.Config, time.Now, deps.Ui, logger),
	}
	deps.RepoLocator = api.NewRepositoryLocator(deps.Config, deps.Gateways, logger)

	deps.PluginModels = &PluginModels{Application: nil}

	deps.PlanBuilder = plan_builder.NewBuilder(
		deps.RepoLocator.GetServicePlanRepository(),
		deps.RepoLocator.GetServicePlanVisibilityRepository(),
		deps.RepoLocator.GetOrganizationRepository(),
	)

	deps.ServiceBuilder = service_builder.NewBuilder(
		deps.RepoLocator.GetServiceRepository(),
		deps.PlanBuilder,
	)

	deps.BrokerBuilder = broker_builder.NewBuilder(
		deps.RepoLocator.GetServiceBrokerRepository(),
		deps.ServiceBuilder,
	)

	deps.PluginRepo = plugin_repo.NewPluginRepo()

	deps.ServiceHandler = actors.NewServiceHandler(
		deps.RepoLocator.GetOrganizationRepository(),
		deps.BrokerBuilder,
		deps.ServiceBuilder,
	)

	deps.ServicePlanHandler = actors.NewServicePlanHandler(
		deps.RepoLocator.GetServicePlanRepository(),
		deps.RepoLocator.GetServicePlanVisibilityRepository(),
		deps.RepoLocator.GetOrganizationRepository(),
		deps.PlanBuilder,
		deps.ServiceBuilder,
	)

	deps.WordGenerator = generator.NewWordGenerator()

	deps.AppZipper = app_files.ApplicationZipper{}
	deps.AppFiles = app_files.ApplicationFiles{}

	deps.PushActor = actors.NewPushActor(deps.RepoLocator.GetApplicationBitsRepository(), deps.AppZipper, deps.AppFiles)

	deps.ChecksumUtil = utils.NewSha1Checksum("")

	deps.Logger = logger

	return deps
}
示例#22
0
func (cmd *LogalyzerCmd) Run(cliConnection plugin.CliConnection, args []string) {
	port := 8080
	aggregationWindow := 2 * time.Second
	bufferSize := 100

	cmd.ui = terminal.NewUI(os.Stdin, terminal.NewTeePrinter())
	cmd.sendChan = make(chan []byte, 256)

	if len(args) < 2 {
		cmd.ui.Say("Usage: %s\n", cmd.Usage())
		cmd.ui.Failed("No App Name given")
	}

	fc := flags.NewFlagContext(setupFlags())
	err := fc.Parse(args[2:]...)
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	if fc.IsSet("p") {
		port = fc.Int("p")
	}

	if fc.IsSet("agg-window") {
		aggregationWindow = time.Duration(fc.Int("agg-window")) * time.Second
	}

	if fc.IsSet("buffer-size") {
		bufferSize = fc.Int("buffer-size")
	}

	appName := args[1]

	dopplerEndpoint, err := cliConnection.DopplerEndpoint()
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	appModel, err := cliConnection.GetApp(appName)
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	authToken, err := cliConnection.AccessToken()
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	outputChan := make(chan *events.LogMessage)
	errorChan := make(chan error)
	dopplerConnection := noaa.NewConsumer(dopplerEndpoint, &tls.Config{InsecureSkipVerify: true}, nil)
	go dopplerConnection.TailingLogs(appModel.Guid, authToken, outputChan, errorChan)

	go cmd.happyCalcer(aggregationWindow, bufferSize)

	go cmd.startServer(cmd.getAssetsDir(), port)
	cmd.ui.Say("Webserver is started at http://localhost:%d", port)

	for {
		select {
		case log := <-outputChan:
			if log.GetMessageType() == events.LogMessage_ERR {
				cmd.errCount++
			}
			cmd.logCount++
			cmd.sendChan <- log.GetMessage()
		case err := <-errorChan:
			cmd.ui.Failed(err.Error())
		}
	}
}
示例#23
0
   "type":"object",
   "properties":{
      "stringtest":{
         "type":"string"
      }
   },
   "required":[
      "stringtest"
   ]
}`

				out := bytes.Buffer{}

				ui := term.NewUI(
					&bytes.Buffer{},
					&out,
					term.NewTeePrinter(&out),
					nil,
				)

				schema.NewSchemaParser(ui).ParseSchema(str)

				Expect(out.String()).To(ContainSubstring("Insert string value for /stringtest [required]"))
			})
		})
	})

	Describe("Test if schema asks correctly for a integer", func() {
		Context("ask for integer", func() {
			It("should be Insert integer value for /integertest [required]", func() {

				str := `{
示例#24
0
文件: cmd.go 项目: Reejoshi/cli
func Main(traceEnv string, args []string) {

	//handle `cf -v` for cf version
	if len(args) == 2 && (args[1] == "-v" || args[1] == "--version") {
		args[1] = "version"
	}

	//handles `cf`
	if len(args) == 1 {
		args = []string{args[0], "help"}
	}

	//handles `cf [COMMAND] -h ...`
	//rearrange args to `cf help COMMAND` and let `command help` to print out usage
	args = append([]string{args[0]}, handleHelp(args[1:])...)

	newArgs, isVerbose := handleVerbose(args)
	args = newArgs

	errFunc := func(err error) {
		if err != nil {
			ui := terminal.NewUI(
				os.Stdin,
				Writer,
				terminal.NewTeePrinter(Writer),
				trace.NewLogger(Writer, isVerbose, traceEnv, ""),
			)
			ui.Failed(fmt.Sprintf("Config error: %s", err))
		}
	}

	// Only used to get Trace, so our errorHandler doesn't matter, since it's not used
	configPath, err := confighelpers.DefaultFilePath()
	if err != nil {
		errFunc(err)
	}
	config := coreconfig.NewRepositoryFromFilepath(configPath, errFunc)
	defer config.Close()

	traceConfigVal := config.Trace()

	// Writer is assigned in writer_unix.go/writer_windows.go
	traceLogger := trace.NewLogger(Writer, isVerbose, traceEnv, traceConfigVal)

	deps := commandregistry.NewDependency(Writer, traceLogger, os.Getenv("CF_DIAL_TIMEOUT"))
	defer handlePanics(args, deps.TeePrinter, deps.Logger)
	defer deps.Config.Close()

	//handle `cf --build`
	if len(args) == 2 && (args[1] == "--build" || args[1] == "-b") {
		deps.UI.Say(T("{{.CFName}} was built with Go version: {{.GoVersion}}",
			map[string]interface{}{
				"CFName":    args[0],
				"GoVersion": runtime.Version(),
			}))
		os.Exit(0)
	}

	warningProducers := []net.WarningProducer{}
	for _, warningProducer := range deps.Gateways {
		warningProducers = append(warningProducers, warningProducer)
	}

	warningsCollector := net.NewWarningsCollector(deps.UI, warningProducers...)

	commandsloader.Load()

	//run core command
	cmdName := args[1]
	cmd := cmdRegistry.FindCommand(cmdName)
	if cmd != nil {
		meta := cmd.MetaData()
		flagContext := flags.NewFlagContext(meta.Flags)
		flagContext.SkipFlagParsing(meta.SkipFlagParsing)

		cmdArgs := args[2:]
		err = flagContext.Parse(cmdArgs...)
		if err != nil {
			usage := cmdRegistry.CommandUsage(cmdName)
			deps.UI.Failed(T("Incorrect Usage") + "\n\n" + err.Error() + "\n\n" + usage)
		}

		cmd = cmd.SetDependency(deps, false)
		cmdRegistry.SetCommand(cmd)

		requirementsFactory := requirements.NewFactory(deps.Config, deps.RepoLocator)
		reqs := cmd.Requirements(requirementsFactory, flagContext)

		for _, req := range reqs {
			err = req.Execute()
			if err != nil {
				deps.UI.Failed(err.Error())
			}
		}

		err = cmd.Execute(flagContext)
		if err != nil {
			ui := terminal.NewUI(os.Stdin, Writer, terminal.NewTeePrinter(Writer), traceLogger)
			ui.Failed(err.Error())
		}

		warningsCollector.PrintWarnings()

		os.Exit(0)
	}

	//non core command, try plugin command
	server := netrpc.NewServer()
	rpcService, err := rpc.NewRpcService(deps.TeePrinter, deps.TeePrinter, deps.Config, deps.RepoLocator, rpc.NewCommandRunner(), deps.Logger, Writer, server)
	if err != nil {
		deps.UI.Say(T("Error initializing RPC service: ") + err.Error())
		os.Exit(1)
	}

	pluginPath := filepath.Join(confighelpers.PluginRepoDir(), ".cf", "plugins")
	pluginConfig := pluginconfig.NewPluginConfig(
		func(err error) {
			deps.UI.Failed(fmt.Sprintf("Error read/writing plugin config: %s, ", err.Error()))
		},
		configuration.NewDiskPersistor(filepath.Join(pluginPath, "config.json")),
		pluginPath,
	)
	pluginList := pluginConfig.Plugins()

	ran := rpc.RunMethodIfExists(rpcService, args[1:], pluginList)
	if !ran {
		deps.UI.Say("'" + args[1] + T("' is not a registered command. See 'cf help'"))
		suggestCommands(cmdName, deps.UI, append(cmdRegistry.ListCommands(), pluginConfig.ListCommands()...))
		os.Exit(1)
	}
}
示例#25
0
var _ = Describe("Firehose", func() {
	var printer *fakes.FakePrinter
	var ui terminal.UI
	var stdin *fakeStdin
	var stdout string

	BeforeEach(func() {
		printer = new(fakes.FakePrinter)
		stdout = ""
		printer.PrintfStub = func(format string, a ...interface{}) (n int, err error) {
			stdout += fmt.Sprintf(format, a...)
			return len(stdout), nil
		}
		stdin = &fakeStdin{[]byte{'\n'}, false}
		ui = terminal.NewUI(stdin, printer)
	})

	Context("Start", func() {
		Context("when the connection to doppler cannot be established", func() {
			It("shows a meaningful error", func() {
				client := firehose.NewClient("invalidToken", "badEndpoint", false, ui)
				client.Start()
				Expect(stdout).To(ContainSubstring("Error dialing traffic controller server"))
			})

		})
		Context("when the connection to doppler works", func() {
			var fakeFirehose *testhelpers.FakeFirehose
			BeforeEach(func() {
				fakeFirehose = testhelpers.NewFakeFirehose("ACCESS_TOKEN")
示例#26
0
文件: dependency.go 项目: jsloyer/cli
func NewDependency(writer io.Writer, logger trace.Printer) Dependency {
	deps := Dependency{}
	deps.TeePrinter = terminal.NewTeePrinter(writer)
	deps.UI = terminal.NewUI(os.Stdin, writer, deps.TeePrinter, logger)

	errorHandler := func(err error) {
		if err != nil {
			deps.UI.Failed(fmt.Sprintf("Config error: %s", err))
		}
	}

	configPath, err := confighelpers.DefaultFilePath()
	if err != nil {
		errorHandler(err)
	}
	deps.Config = coreconfig.NewRepositoryFromFilepath(configPath, errorHandler)

	deps.ManifestRepo = manifest.NewDiskRepository()
	deps.AppManifest = manifest.NewGenerator()

	pluginPath := filepath.Join(confighelpers.PluginRepoDir(), ".cf", "plugins")
	deps.PluginConfig = pluginconfig.NewPluginConfig(
		errorHandler,
		configuration.NewDiskPersistor(filepath.Join(pluginPath, "config.json")),
		pluginPath,
	)

	terminal.UserAskedForColors = deps.Config.ColorEnabled()
	terminal.InitColorSupport()

	deps.Gateways = map[string]net.Gateway{
		"cloud-controller": net.NewCloudControllerGateway(deps.Config, time.Now, deps.UI, logger),
		"uaa":              net.NewUAAGateway(deps.Config, deps.UI, logger),
		"routing-api":      net.NewRoutingAPIGateway(deps.Config, time.Now, deps.UI, logger),
	}
	deps.RepoLocator = api.NewRepositoryLocator(deps.Config, deps.Gateways, logger)

	deps.PluginModels = &PluginModels{Application: nil}

	deps.PlanBuilder = planbuilder.NewBuilder(
		deps.RepoLocator.GetServicePlanRepository(),
		deps.RepoLocator.GetServicePlanVisibilityRepository(),
		deps.RepoLocator.GetOrganizationRepository(),
	)

	deps.ServiceBuilder = servicebuilder.NewBuilder(
		deps.RepoLocator.GetServiceRepository(),
		deps.PlanBuilder,
	)

	deps.BrokerBuilder = brokerbuilder.NewBuilder(
		deps.RepoLocator.GetServiceBrokerRepository(),
		deps.ServiceBuilder,
	)

	deps.PluginRepo = pluginrepo.NewPluginRepo()

	deps.ServiceHandler = actors.NewServiceHandler(
		deps.RepoLocator.GetOrganizationRepository(),
		deps.BrokerBuilder,
		deps.ServiceBuilder,
	)

	deps.ServicePlanHandler = actors.NewServicePlanHandler(
		deps.RepoLocator.GetServicePlanRepository(),
		deps.RepoLocator.GetServicePlanVisibilityRepository(),
		deps.RepoLocator.GetOrganizationRepository(),
		deps.PlanBuilder,
		deps.ServiceBuilder,
	)

	deps.WordGenerator = generator.NewWordGenerator()

	deps.AppZipper = appfiles.ApplicationZipper{}
	deps.AppFiles = appfiles.ApplicationFiles{}

	deps.PushActor = actors.NewPushActor(deps.RepoLocator.GetApplicationBitsRepository(), deps.AppZipper, deps.AppFiles)

	deps.ChecksumUtil = utils.NewSha1Checksum("")

	deps.Logger = logger

	return deps
}
		stdin  *syncedBuffer
		stdout *syncedBuffer
	)

	BeforeEach(func() {
		stdin = &syncedBuffer{}
		stdout = &syncedBuffer{}

		printer = new(fakes.FakePrinter)
		printer.PrintfStub = func(format string, a ...interface{}) (n int, err error) {
			return fmt.Fprintf(stdout, format, a...)
		}
		tracePrinter = new(tracefakes.FakePrinter)

		ui = terminal.NewUI(stdin, stdout, printer, tracePrinter)
	})

	Describe("Start", func() {
		var options *firehose.ClientOptions
		Context("for app connections", func() {
			BeforeEach(func() {
				options = &firehose.ClientOptions{AppGUID: "spring-music", Debug: false, NoFilter: true}
			})
			Context("when the connection to doppler cannot be established", func() {
				It("shows a meaningful error", func() {
					client := firehose.NewClient("invalidToken", "badEndpoint", options, ui)
					client.Start()
					Expect(stdout).To(ContainSubstring("Error dialing trafficcontroller server"))
				})
			})