Example #1
0
func newCache(c *cli.Context, client *doarama.Client) (doaramacache.ActivityCreator, error) {
	dataSourceName := c.GlobalString("cache")
	if dataSourceName == "" {
		return client, nil
	}
	return doaramacache.NewSQLite3(dataSourceName, client)
}
Example #2
0
func connectPeer(ctx *cli.Context) error {
	ctxb := context.Background()
	client := getClient(ctx)

	targetAddress := ctx.Args().Get(0)
	splitAddr := strings.Split(targetAddress, "@")
	if len(splitAddr) != 2 {
		return fmt.Errorf("target address expected in format: " +
			"pubkey@host:port")
	}

	addr := &lnrpc.LightningAddress{
		Pubkey: splitAddr[0],
		Host:   splitAddr[1],
	}
	req := &lnrpc.ConnectPeerRequest{addr}

	lnid, err := client.ConnectPeer(ctxb, req)
	if err != nil {
		return err
	}

	printRespJson(lnid)
	return nil
}
Example #3
0
// Simple wrapper to add multiple resources
func AutoAddResources(fileName string, keys []string, c *cli.Context) error {
	setStoreFormatFromFileName(fileName)
	config := util.Config{
		IgnoreList: c.GlobalStringSlice("exclude-attr"),
		Timeout:    int(c.Duration("timeout") / time.Millisecond),
	}

	var gossConfig GossConfig
	if _, err := os.Stat(fileName); err == nil {
		gossConfig = ReadJSON(fileName)
	} else {
		gossConfig = *NewGossConfig()
	}

	sys := system.New(c)

	for _, key := range keys {
		if err := AutoAddResource(fileName, gossConfig, key, c, config, sys); err != nil {
			return err
		}
	}
	WriteJSON(fileName, gossConfig)

	return nil
}
Example #4
0
func printVersionCmd(c *cli.Context) error {
	fullVersion := c.Bool("full")

	if err := output.ConfigureOutputFormat(c); err != nil {
		log.Fatalf("Failed to configure output format, error: %s", err)
	}

	versionOutput := VersionOutputModel{
		Version: version.VERSION,
	}

	if fullVersion {
		versionOutput.FormatVersion = models.Version
		versionOutput.BuildNumber = version.BuildNumber
		versionOutput.Commit = version.Commit
	}

	if output.Format == output.FormatRaw {
		if fullVersion {
			fmt.Fprintf(c.App.Writer, "version: %v\nformat version: %v\nbuild number: %v\ncommit: %v\n", versionOutput.Version, versionOutput.FormatVersion, versionOutput.BuildNumber, versionOutput.Commit)
		} else {
			fmt.Fprintf(c.App.Writer, "%v\n", versionOutput.Version)
		}
	} else {
		output.Print(versionOutput, output.Format)
	}

	return nil
}
func Init(c *cli.Context, reg *harness.MetricRegistry) (harness.Collector, error) {
	args := c.Args()

	if len(args) < 2 {
		cli.ShowAppHelp(c)
		return nil, fmt.Errorf("not enough arguments")
	}

	var (
		endpoint   = args[0]
		configPath = args[1]
	)

	configs, err := loadConfig(configPath)
	if err != nil {
		return nil, err
	}

	scrapers := make([]JsonScraper, len(configs))
	for i, config := range configs {
		tpe := ScrapeTypes[config.Type]
		if tpe == nil {
			return nil, fmt.Errorf("unknown scrape type;type:<%s>", config.Type)
		}
		tpe.Configure(config, reg)
		scraper, err := tpe.NewScraper(config)
		if err != nil {
			return nil, fmt.Errorf("failed to create scraper;name:<%s>,err:<%s>", config.Name, err)
		}
		scrapers[i] = scraper
	}

	return NewCollector(endpoint, scrapers), nil
}
Example #6
0
func startContainer(context *cli.Context, spec *specs.Spec, create bool) (int, error) {
	id := context.Args().First()
	if id == "" {
		return -1, errEmptyID
	}
	container, err := createContainer(context, id, spec)
	if err != nil {
		return -1, err
	}
	// Support on-demand socket activation by passing file descriptors into the container init process.
	listenFDs := []*os.File{}
	if os.Getenv("LISTEN_FDS") != "" {
		listenFDs = activation.Files(false)
	}
	r := &runner{
		enableSubreaper: !context.Bool("no-subreaper"),
		shouldDestroy:   true,
		container:       container,
		listenFDs:       listenFDs,
		console:         context.String("console"),
		detach:          context.Bool("detach"),
		pidFile:         context.String("pid-file"),
		create:          create,
	}
	return r.run(&spec.Process)
}
Example #7
0
func deleteStepLib(c *cli.Context) error {
	// Input validation
	collectionURI := c.String(CollectionKey)
	if collectionURI == "" {
		return fmt.Errorf("Missing required input: collection")
	}

	log.Infof("Delete StepLib: %s", collectionURI)

	route, found := stepman.ReadRoute(collectionURI)
	if !found {
		log.Warnf("No route found for collection: %s, cleaning up routing..", collectionURI)
		if err := stepman.CleanupDanglingLib(collectionURI); err != nil {
			log.Errorf("Error cleaning up lib: %s", collectionURI)
		}
		log.Infof("Call 'stepman setup -c %s' for a clean setup", collectionURI)
		return nil
	}

	if err := stepman.CleanupRoute(route); err != nil {
		return fmt.Errorf("Failed to cleanup route for StepLib: %s", collectionURI)
	}

	return nil
}
// deleteAllGCPPrinterJobs finds all GCP printer jobs associated with a
// a given printer id and deletes them.
func deleteAllGCPPrinterJobs(context *cli.Context) {
	config := getConfig(context)
	gcp := getGCP(config)

	jobs, err := gcp.Fetch(context.String("printer-id"))
	if err != nil {
		log.Fatalln(err)
	}

	if len(jobs) == 0 {
		fmt.Printf("No queued jobs\n")
	}

	ch := make(chan bool)
	for _, job := range jobs {
		go func(gcpJobID string) {
			err := gcp.DeleteJob(gcpJobID)
			if err != nil {
				fmt.Printf("Failed to delete GCP job %s: %s\n", gcpJobID, err)
			} else {
				fmt.Printf("Deleted GCP job %s\n", gcpJobID)
			}
			ch <- true
		}(job.GCPJobID)
	}

	for _ = range jobs {
		<-ch
	}
}
Example #9
0
func getGossConfig(c *cli.Context) GossConfig {
	// handle stdin
	var fh *os.File
	var err error
	var path, source string
	specFile := c.GlobalString("gossfile")
	if specFile == "-" {
		source = "STDIN"
		fh = os.Stdin
	} else {
		source = specFile
		path = filepath.Dir(specFile)
		fh, err = os.Open(specFile)
		if err != nil {
			fmt.Printf("Error: %v\n", err)
			os.Exit(1)
		}
	}
	data, err := ioutil.ReadAll(fh)
	if err != nil {
		fmt.Printf("Error: %v\n", err)
		os.Exit(1)
	}
	gossConfig := mergeJSONData(ReadJSONData(data), 0, path)
	if len(gossConfig.Resources()) == 0 {
		fmt.Printf("Error: found 0 tests, source: %v\n", source)
		os.Exit(1)
	}
	return gossConfig
}
Example #10
0
func startNATSServer(context *cli.Context) (e *stand.StanServer, err error) {
	eventsURL, err := url.Parse(context.GlobalString("events-address"))
	if err != nil {
		return nil, err
	}

	no := stand.DefaultNatsServerOptions
	nOpts := &no
	nOpts.NoSigs = true
	parts := strings.Split(eventsURL.Host, ":")
	nOpts.Host = parts[0]
	if len(parts) == 2 {
		nOpts.Port, err = strconv.Atoi(parts[1])
	} else {
		nOpts.Port = nats.DefaultPort
	}
	defer func() {
		if r := recover(); r != nil {
			e = nil
			if _, ok := r.(error); !ok {
				err = fmt.Errorf("failed to start NATS server: %v", r)
			} else {
				err = r.(error)
			}
		}
	}()
	s := stand.RunServerWithOpts(nil, nOpts)

	return s, nil
}
Example #11
0
File: exec.go Project: x1022as/runc
func execProcess(context *cli.Context) (int, error) {
	container, err := getContainer(context)
	if err != nil {
		return -1, err
	}
	path := context.String("process")
	if path == "" && len(context.Args()) == 1 {
		return -1, fmt.Errorf("process args cannot be empty")
	}
	detach := context.Bool("detach")
	state, err := container.State()
	if err != nil {
		return -1, err
	}
	bundle := utils.SearchLabels(state.Config.Labels, "bundle")
	p, err := getProcess(context, bundle)
	if err != nil {
		return -1, err
	}
	r := &runner{
		enableSubreaper: false,
		shouldDestroy:   false,
		container:       container,
		console:         context.String("console"),
		detach:          detach,
		pidFile:         context.String("pid-file"),
	}
	return r.run(p)
}
Example #12
0
func cmdTypeAdd(c *cli.Context) error {
	// Get loggers
	printUserMsg, printError := getLoggers()

	// Check obligatory flags (file, name)
	if c.String("file") == NotSetStringValue {
		printError.Fatalln(errMissingFileFlag)

	}
	if c.String("type") == NotSetStringValue {
		printError.Fatalln(errMissingTypeFlag)
	}

	// Open data file
	f := gsqlitehandler.New(c.String("file"), dataFileProperties)
	if err := f.Open(); err != nil {
		printError.Fatalln(err)
	}
	defer f.Close()

	// Add new type
	sqlAddType := fmt.Sprintf("INSERT INTO bicycle_types VALUES (NULL, '%s');", c.String("type"))
	if _, err := f.Handler.Exec(sqlAddType); err != nil {
		printError.Fatalln(errWritingToFile)
	}

	// Show summary
	printUserMsg.Printf("added new bicycle type: %s\n", c.String("type"))

	return nil
}
Example #13
0
// initRobotAccount creates a GCP robot account for this connector.
func initRobotAccount(context *cli.Context, userClient *http.Client) (string, string) {
	params := url.Values{}
	params.Set("oauth_client_id", context.String("gcp-oauth-client-id"))

	url := fmt.Sprintf("%s%s?%s", lib.DefaultConfig.GCPBaseURL, "createrobot", params.Encode())
	response, err := userClient.Get(url)
	if err != nil {
		log.Fatalln(err)
	}
	if response.StatusCode != http.StatusOK {
		log.Fatalf("Failed to initialize robot account: %s\n", response.Status)
	}

	var robotInit struct {
		Success  bool   `json:"success"`
		Message  string `json:"message"`
		XMPPJID  string `json:"xmpp_jid"`
		AuthCode string `json:"authorization_code"`
	}

	if err = json.NewDecoder(response.Body).Decode(&robotInit); err != nil {
		log.Fatalln(err)
	}
	if !robotInit.Success {
		log.Fatalf("Failed to initialize robot account: %s\n", robotInit.Message)
	}

	return robotInit.XMPPJID, robotInit.AuthCode
}
Example #14
0
func activityCreate(c *cli.Context) error {
	ctx := context.Background()
	client, err := doaramacli.NewAuthenticatedDoaramaClient(c)
	if err != nil {
		return err
	}
	defer client.Close()
	activityType, err := doarama.DefaultActivityTypes.Find(doaramacli.ActivityType(c))
	if err != nil {
		return err
	}
	activityInfo := &doarama.ActivityInfo{
		TypeID: activityType.ID,
	}
	cache, err := newCache(c, client)
	if err != nil {
		return err
	}
	defer cache.Close()
	for _, arg := range c.Args() {
		a, err := activityCreateOne(ctx, cache, arg, activityInfo)
		if err != nil {
			log.Print(err)
			continue
		}
		fmt.Printf("ActivityId: %d\n", a.ID)
	}
	return nil
}
Example #15
0
func doGroupMemberList(c *cli.Context) error {
	srv, err := NewService()
	if err != nil {
		return nil
	}

	groupKey := c.String("key")

	r, err := srv.directory.Members.List(groupKey).Do()
	if err != nil {
		log.Fatalf("Unable to retrieve group members in domain. %v", err)
		return nil
	}

	count := len(r.Members)
	if count == 0 {
		fmt.Print("No group members found.\n")
	} else {
		for _, m := range r.Members {
			fmt.Printf("%v, %v\n", m.Email, m.Role)
		}
	}

	return nil
}
Example #16
0
// Version prints the libcompose version number and additionnal informations.
func Version(c *cli.Context) error {
	if c.Bool("short") {
		fmt.Println(version.VERSION)
		return nil
	}

	tmpl, err := template.New("").Parse(versionTemplate)
	if err != nil {
		logrus.Fatal(err)
	}

	v := struct {
		Version   string
		GitCommit string
		GoVersion string
		BuildTime string
		Os        string
		Arch      string
	}{
		Version:   version.VERSION,
		GitCommit: version.GITCOMMIT,
		GoVersion: runtime.Version(),
		BuildTime: version.BUILDTIME,
		Os:        runtime.GOOS,
		Arch:      runtime.GOARCH,
	}

	if err := tmpl.Execute(os.Stdout, v); err != nil {
		logrus.Fatal(err)
	}
	fmt.Printf("\n")
	return nil
}
Example #17
0
//Generate generates a migration on the migrations folder
func Generate(c *cli.Context) {
	setupTestingEnv()
	base := os.Getenv("TRANS_TESTING_FOLDER")

	name := "migration"
	if c.App != nil && len(c.Args()) > 0 {
		name = c.Args().First()
	}

	name = snaker.CamelToSnake(name)
	identifier := time.Now().UnixNano()

	migration := MigrationData{
		Identifier: identifier,
		Name:       name,
	}

	buff := bytes.NewBufferString("")
	tmpl, _ := template.New("migration").Parse(utils.MigrationTemplate)
	_ = tmpl.Execute(buff, migration)

	fileName := strconv.FormatInt(identifier, 10) + "_" + name + ".go"
	path := filepath.Join(base, "db", "migrations", fileName)

	err := ioutil.WriteFile(path, buff.Bytes(), generatedFilePermissions)
	if err != nil {
		log.Println(err)
		log.Println("| Could not write migration file, please check db/migrations folder exists")
	}
}
func (cmd *CatalogShow) show(c *cli.Context) error {
	if len(c.Args()) != 2 {
		return errors.New(c.App.Name + " " + showCommandName + catalogItemTypesUsage + " ITEM[:VERSION]")
	}
	catalogType, err := GetCatalogType(c)
	if err != nil {
		return err
	}
	item := c.Args().Get(1)
	var version string
	if strings.Contains(item, ":") {
		itemVersion := strings.Split(item, ":")
		item = itemVersion[0]
		version = itemVersion[1]
	}
	switch catalogType {
	case ApplicationsItemType:
		return cmd.showCatalogApplication(c, item, version)
	case EntitiesItemType:
		return cmd.showCatalogEntity(c, item, version)
	case LocationsItemType:
		return cmd.showCatalogLocation(c, item, version)
	case PoliciesItemType:
		return cmd.showPolicy(c, item, version)
	}
	return errors.New("Unrecognised argument")
}
Example #19
0
func pluginInstall(c *cli.Context) error {
	// Input validation
	pluginSource := c.String("source")
	if pluginSource == "" {
		log.Fatal("Missing required input: source")
	}

	pluginVersionTag := c.String("version")

	// Install
	if pluginVersionTag == "" {
		log.Infof("=> Installing plugin from (%s) with latest version...", pluginSource)
	} else {
		log.Infof("=> Installing plugin (%s) with version (%s)...", pluginSource, pluginVersionTag)
	}

	plugin, version, err := plugins.InstallPlugin(pluginSource, pluginVersionTag)
	if err != nil {
		log.Fatalf("Failed to install plugin from (%s), error: %s", pluginSource, err)
	}

	fmt.Println()
	log.Infoln(colorstring.Greenf("Plugin (%s) with version (%s) installed ", plugin.Name, version))

	if len(plugin.Description) > 0 {
		fmt.Println()
		fmt.Println(plugin.Description)
		fmt.Println()
	}

	return nil
}
Example #20
0
func (cmd *Config) Run(scope scope.Scope, c *cli.Context) {
	if err := net.VerifyLoginURL(cmd.network); err != nil {
		error_handler.ErrorExit(err)
	}
	if c.Args().Present() {
		configValue, err := entity_config.ConfigValue(cmd.network, scope.Application, scope.Entity, c.Args().First())

		if nil != err {
			error_handler.ErrorExit(err)
		}
		displayValue, err := stringRepresentation(configValue)
		if nil != err {
			error_handler.ErrorExit(err)
		}
		fmt.Println(displayValue)

	} else {
		config, err := entity_config.ConfigCurrentState(cmd.network, scope.Application, scope.Entity)
		if nil != err {
			error_handler.ErrorExit(err)
		}
		table := terminal.NewTable([]string{"Key", "Value"})
		for key, value := range config {
			table.Add(key, fmt.Sprintf("%v", value))
		}
		table.Print()
	}
}
func (exp *exporter) main(c *cli.Context) {
	setupLogging(c)

	registry := newRegistry()

	collector, err := exp.Init(c, registry)
	if err != nil {
		log.Fatal(err)
	}

	if exp.Tick {
		collector.Collect(registry)
		interval := c.Int("interval")
		go func() {
			for _ = range time.Tick(time.Duration(interval) * time.Second) {
				if exp.ResetOnTick {
					registry.Reset()
				}
				collector.Collect(registry)
			}
		}()
	}

	http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		w.Header().Add("Location", exp.MetricsPath)
		w.WriteHeader(http.StatusFound)
	})
	http.Handle(exp.MetricsPath, prometheus.Handler())
	if err := http.ListenAndServe(fmt.Sprintf(":%d", c.Int("port")), nil); err != nil {
		log.Fatal(err)
	}
}
Example #22
0
func CmdUntaint(c *cli.Context) error {
	operation := initialize(c, "untaint")
	operation.extraArgs = strings.Join(c.Args()[1:], " ")
	run(operation)
	resync(operation)
	return nil
}
Example #23
0
func revoke(c *cli.Context) error {

	conf, _, client := setup(c)

	err := checkFolder(conf.CertPath())
	if err != nil {
		logger().Fatalf("Could not check/create path: %s", err.Error())
	}

	for _, domain := range c.GlobalStringSlice("domains") {
		logger().Printf("Trying to revoke certificate for domain %s", domain)

		certPath := path.Join(conf.CertPath(), domain+".crt")
		certBytes, err := ioutil.ReadFile(certPath)

		err = client.RevokeCertificate(certBytes)
		if err != nil {
			logger().Fatalf("Error while revoking the certificate for domain %s\n\t%s", domain, err.Error())
		} else {
			logger().Print("Certificate was revoked.")
		}
	}

	return nil
}
Example #24
0
func (cmd *Restart) Run(scope scope.Scope, c *cli.Context) {
	if err := net.VerifyLoginURL(cmd.network); err != nil {
		error_handler.ErrorExit(err)
	}
	parms := c.StringSlice("param")
	invoke(cmd.network, scope.Application, scope.Entity, restartEffector, parms)
}
Example #25
0
func newClient(c *cli.Context) (client.Client, error) {
	eps, err := getEndpoints(c)
	if err != nil {
		return nil, err
	}

	tr, err := getTransport(c)
	if err != nil {
		return nil, err
	}

	cfg := client.Config{
		Transport:               tr,
		Endpoints:               eps,
		HeaderTimeoutPerRequest: c.GlobalDuration("timeout"),
	}

	uFlag := c.GlobalString("username")

	if uFlag == "" {
		uFlag = os.Getenv("ETCDCTL_USERNAME")
	}

	if uFlag != "" {
		username, password, err := getUsernamePasswordFromFlag(uFlag)
		if err != nil {
			return nil, err
		}
		cfg.Username = username
		cfg.Password = password
	}

	return client.New(cfg)
}
Example #26
0
func cmdInfo(c *cli.Context) error {
	conf, err := config.Open(c.GlobalString("config"))
	if err != nil {
		Logger.Fatalf("Cannot load configuration: %v", err)
		return nil
	}

	fmt.Printf("Debug mode (client): %v\n", os.Getenv("ASSH_DEBUG") == "1")
	cliPath, _ := osext.Executable()
	fmt.Printf("CLI Path: %s\n", cliPath)
	fmt.Printf("Go version: %s\n", runtime.Version())
	fmt.Printf("OS/Arch: %s/%s\n", runtime.GOOS, runtime.GOARCH)
	fmt.Println("")
	fmt.Printf("RC files:\n")
	homeDir := utils.GetHomeDir()
	for _, filename := range conf.IncludedFiles() {
		relativeFilename := strings.Replace(filename, homeDir, "~", -1)
		fmt.Printf("- %s\n", relativeFilename)
	}
	fmt.Println("")
	fmt.Println("Statistics:")
	fmt.Printf("- %d hosts\n", len(conf.Hosts))
	fmt.Printf("- %d templates\n", len(conf.Templates))
	fmt.Printf("- %d included files\n", len(conf.IncludedFiles()))
	// FIXME: print info about connections/running processes
	// FIXME: print info about current config file version

	return nil
}
Example #27
0
func newAddress(ctx *cli.Context) error {
	client := getClient(ctx)

	stringAddrType := ctx.Args().Get(0)

	// Map the string encoded address type, to the concrete typed address
	// type enum. An unrecognized address type will result in an error.
	var addrType lnrpc.NewAddressRequest_AddressType
	switch stringAddrType { // TODO(roasbeef): make them ints on the cli?
	case "p2wkh":
		addrType = lnrpc.NewAddressRequest_WITNESS_PUBKEY_HASH
	case "np2wkh":
		addrType = lnrpc.NewAddressRequest_NESTED_PUBKEY_HASH
	case "p2pkh":
		addrType = lnrpc.NewAddressRequest_PUBKEY_HASH
	default:
		return fmt.Errorf("invalid address type %v, support address type "+
			"are: p2wkh, np2wkh, p2pkh", stringAddrType)
	}

	ctxb := context.Background()
	addr, err := client.NewAddress(ctxb, &lnrpc.NewAddressRequest{
		Type: addrType,
	})
	if err != nil {
		return err
	}

	printRespJson(addr)
	return nil
}
Example #28
0
File: list.go Project: dnaeon/gru
// Executes the "list" command
func execListCommand(c *cli.Context) error {
	klient := newEtcdMinionClientFromFlags(c)

	cFlag := c.String("with-classifier")
	minions, err := parseClassifierPattern(klient, cFlag)

	// Ignore errors about missing minion directory
	if err != nil {
		if eerr, ok := err.(client.Error); !ok || eerr.Code != client.ErrorCodeKeyNotFound {
			return cli.NewExitError(err.Error(), 1)
		}
	}

	if len(minions) == 0 {
		return nil
	}

	table := uitable.New()
	table.MaxColWidth = 80
	table.AddRow("MINION", "NAME")
	for _, minion := range minions {
		name, err := klient.MinionName(minion)
		if err != nil {
			return cli.NewExitError(err.Error(), 1)
		}

		table.AddRow(minion, name)
	}

	fmt.Println(table)

	return nil
}
Example #29
0
func getCheckpointImagePath(context *cli.Context) string {
	imagePath := context.String("image-path")
	if imagePath == "" {
		imagePath = getDefaultImagePath(context)
	}
	return imagePath
}
Example #30
0
//
// deleteFile removes a file from the bucket
//
func deleteFile(o *formatter, cx *cli.Context, cmd *cliCommand) error {
	if len(cx.Args()) <= 0 {
		return fmt.Errorf("you have not specified any files to delete")
	}

	bucket := cx.String("bucket")
	// step: ensure the bucket exists
	if found, err := cmd.hasBucket(bucket); err != nil {
		return err
	} else if !found {
		return fmt.Errorf("the bucket: %s does not exist", bucket)
	}

	for _, path := range getPaths(cx) {
		if err := cmd.removeFile(bucket, path); err != nil {
			o.fields(map[string]interface{}{
				"action": "delete",
				"bucket": bucket,
				"path":   path,
				"error":  err.Error(),
			}).log("failed to remove s3://%s/%s, error: %s", bucket, path, err)
			continue
		}
		o.fields(map[string]interface{}{
			"action": "delete",
			"bucket": bucket,
			"path":   path,
		}).log("successfully deleted the file s3://%s/%s\n", bucket, path)
	}

	return nil
}