Beispiel #1
0
func secretAdd(c *cli.Context) error {

	repo := c.Args().First()
	owner, name, err := parseRepo(repo)
	if err != nil {
		return err
	}

	tail := c.Args().Tail()
	if len(tail) != 2 {
		cli.ShowSubcommandHelp(c)
		return nil
	}

	secret := &model.Secret{}
	secret.Name = tail[0]
	secret.Value = tail[1]
	secret.Images = c.StringSlice("image")
	secret.Events = c.StringSlice("event")

	if len(secret.Images) == 0 {
		return fmt.Errorf("Please specify the --image parameter")
	}

	client, err := newClient(c)
	if err != nil {
		return err
	}

	return client.SecretPost(owner, name, secret)
}
Beispiel #2
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)
}
Beispiel #3
0
Datei: issues.go Projekt: nlf/gh
func Issues(c *cli.Context) {
	client := github.GetClient()
	repo := git.GetRepo()

	params := github.IssueParams{
		Milestone: c.String("milestone"),
		State:     c.String("state"),
		Assignee:  c.String("assignee"),
		Creator:   c.String("creator"),
		Mentioned: c.String("mentioned"),
		Labels:    c.StringSlice("label"),
		Sort:      c.String("sort"),
		Direction: c.String("direction"),
		Since:     c.String("since"),
	}

	issues, err := client.GetIssues(repo, params)
	if err != nil {
		log.Fatal(err)
	}

	bold := false

	if len(issues) > 0 {
		PrintHeader()
		for _, issue := range issues {
			PrintIssue(issue, bold)
			bold = !bold
		}
	} else {
		fmt.Println("No issues found")
	}
}
Beispiel #4
0
func run(c *cli.Context) {
	plugin := Plugin{
		Mount:   c.StringSlice("mount"),
		Path:    c.String("path"),
		Repo:    c.String("repo.name"),
		Default: c.String("repo.branch"),
		Branch:  c.String("commit.branch"),
	}

	sftp, err := sftp.New(
		c.String("server"),
		c.String("username"),
		c.String("password"),
		c.String("key"),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer sftp.(io.Closer).Close()

	if c.Bool("rebuild") {
		now := time.Now()
		err = plugin.Rebuild(sftp)
		log.Printf("cache built in %v", time.Since(now))
	}
	if c.Bool("restore") {
		now := time.Now()
		err = plugin.Restore(sftp)
		log.Printf("cache restored in %v", time.Since(now))
	}

	if err != nil {
		log.Println(err) // this plugins does not fail on error
	}
}
Beispiel #5
0
func Setup(c *cli.Context) error {
	if b, ok := Brokers[c.String("broker")]; ok {
		broker.DefaultBroker = b(strings.Split(c.String("broker_address"), ","))
	}

	if r, ok := Registries[c.String("registry")]; ok {
		registry.DefaultRegistry = r(strings.Split(c.String("registry_address"), ","))
	}

	if t, ok := Transports[c.String("transport")]; ok {
		transport.DefaultTransport = t(strings.Split(c.String("transport_address"), ","))
	}

	metadata := make(map[string]string)
	for _, d := range c.StringSlice("server_metadata") {
		var key, val string
		parts := strings.Split(d, "=")
		key = parts[0]
		if len(parts) > 1 {
			val = strings.Join(parts[1:], "=")
		}
		metadata[key] = val
	}

	server.DefaultServer = server.NewServer(
		server.Name(c.String("server_name")),
		server.Id(c.String("server_id")),
		server.Address(c.String("server_address")),
		server.Metadata(metadata),
	)

	client.DefaultClient = client.NewClient()

	return nil
}
Beispiel #6
0
func cmdRun(c *cli.Context) error {
	s, err := openAndCheck(c)
	if err != nil {
		return cli.NewExitError(err.Error(), 3)
	}

	webAddr := c.String("web-addr")
	saslPaths := c.StringSlice("sock")

	var wg sync.WaitGroup
	if webAddr != "" {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if err := runWebAddr(webAddr, s.GetInterface(), c.GlobalString("web-static-dir")); err != nil {
				fmt.Printf("warning running web interface failed: %s\n", err)
			}
		}()
	}
	for _, path := range saslPaths {
		p := path
		wg.Add(1)
		go func() {
			defer wg.Done()
			if err := runSaslAuthSocket(p, s.GetInterface()); err != nil {
				fmt.Printf("warning running auth agent(%s) failed: %s\n", p, err)
			}
		}()
	}
	wg.Wait()

	return cli.NewExitError(fmt.Sprintf("shutting down since all auth sockets have closed."), 0)
}
Beispiel #7
0
func registerAgentFromCli(c *cli.Context) *buildbox.Agent {
	// Init debugging
	if c.Bool("debug") {
		buildbox.LoggerInitDebug()
	}

	agentRegistrationToken := c.String("agent-registration-token")

	// Should we look to the environment for the agent registration token?
	if agentRegistrationToken == AgentRegistrationTokenDefault {
		agentRegistrationToken = os.Getenv(AgentRegistrationTokenDefault)
	}

	if agentRegistrationToken == "" {
		fmt.Println("buildbox-agent: missing agent registration token\nSee 'buildbox-agent register --help'")
		os.Exit(1)
	}

	// Create a client so we can register the agent
	var client buildbox.Client
	client.AuthorizationToken = agentRegistrationToken
	client.URL = c.String("url")

	// Register the agent
	agentAccessToken, err := client.AgentRegister(c.String("name"), c.StringSlice("meta-data"))
	if err != nil {
		buildbox.Logger.Fatal(err)
	}

	// Start the agent using the token we have
	return setupAgent("register", agentAccessToken, c.String("bootstrap-script"), c.String("url"))
}
Beispiel #8
0
func watchEvents(c *cli.Context) {
	var err error
	dockerClient, err = dockeraction.GetDefaultActionClient()
	if err != nil {
		log.Fatal(err)
	}
	token := c.String("token")

	eventChan := make(chan *docker.APIEvents)
	log.Println("Watching for Docker events")
	if err := dockerClient.AddEventListener(eventChan); err != nil {
		log.Fatal(err)
	}

	for event := range eventChan {
		if event.Status == "start" {
			skip := false
			for _, i := range c.StringSlice("ignore") {
				if i == event.From {
					skip = true
					break
				}
			}
			if !skip {
				go logContainer(event.ID[:12], token)
				log.Printf("Log stream for %s started (%s)", event.ID[:12], event.From)
			}
		}
	}
}
func addDevice(spec *specs.LinuxSpec, rspec *specs.LinuxRuntimeSpec, context *cli.Context) error {
	for _, devs := range context.StringSlice("device-add") {
		dev := strings.Split(devs, ":")
		if len(dev) == 8 {
			path := dev[0]
			rtemp := []rune(dev[1])
			typ := rtemp[0]
			major, err := strconv.Atoi(dev[2])
			minor, err := strconv.Atoi(dev[3])
			permi := dev[4]
			filemodle, err := strconv.Atoi(dev[5])
			fm := os.FileMode(filemodle)
			uid, err := strconv.Atoi(dev[6])
			gid, err := strconv.Atoi(dev[7])
			if err != nil {
				return err
			}
			device := specs.Device{path, typ, int64(major), int64(minor), permi, fm, uint32(uid), uint32(gid)}
			rspec.Linux.Devices = append(rspec.Linux.Devices, device)
		} else {
			return fmt.Errorf("Device-add error: %s", devs)
		}
	}
	return nil
}
Beispiel #10
0
func generate(c *cli.Context) error {
	cfg, err := config.LoadConfig()
	if err != nil {
		return err
	}

	generateServer := c.Bool("server")
	outDir := c.String("dir")
	if outDir == "" {
		return fmt.Errorf("out directory (-d, --dir) not specified")
	}
	caCertPath := filepath.Join(outDir, "ca.pem")
	caKeyPath := filepath.Join(outDir, "ca-key.pem")
	certPath := filepath.Join(outDir, "cert.pem")
	keyPath := filepath.Join(outDir, "key.pem")

	if generateServer {
		certPath = filepath.Join(outDir, "server-cert.pem")
		keyPath = filepath.Join(outDir, "server-key.pem")
	}

	if _, err := os.Stat(outDir); os.IsNotExist(err) {
		if err := os.MkdirAll(outDir, 0700); err != nil {
			return err
		}
	}

	if err := writeCaCerts(cfg, caCertPath, caKeyPath); err != nil {
		return err
	}

	hostnames := c.StringSlice("hostname")
	return writeCerts(generateServer, hostnames, cfg, certPath, keyPath, caCertPath, caKeyPath)
}
Beispiel #11
0
// Add the flags accepted by run to the supplied flag set, returning the
// variables into which the flags will parse.
func PopulateFlags(c *cli.Context) (flags *FlagStorage) {
	flags = &FlagStorage{
		// File system
		MountOptions: make(map[string]string),
		DirMode:      os.FileMode(c.Int("dir-mode")),
		FileMode:     os.FileMode(c.Int("file-mode")),
		Uid:          uint32(c.Int("uid")),
		Gid:          uint32(c.Int("gid")),

		// Tuning,
		StatCacheTTL: c.Duration("stat-cache-ttl"),
		TypeCacheTTL: c.Duration("type-cache-ttl"),

		// OSS
		Endpoint:       c.String("endpoint"),
		UsePathRequest: c.Bool("use-path-request"),
		Internal:       c.Bool("internal"),

		// Debugging,
		DebugFuse: c.Bool("debug_fuse"),
		DebugOSS:  c.Bool("debug_oss"),
	}

	// Handle the repeated "-o" flag.
	for _, o := range c.StringSlice("o") {
		parseOptions(flags.MountOptions, o)
	}

	// Get the region/AccessKeyId/AccessKeySecret
	flags.AccessKeyId = os.Getenv("ACCESS_KEY_ID")
	flags.AccessKeySecret = os.Getenv("ACCESS_KEY_SECRET")
	flags.Region = oss.Region(os.Getenv("OSS_REGION"))

	return
}
Beispiel #12
0
// ServerFromCli uses the cli arguments to configure a server instance
func ServerFromCli(c *cli.Context) *gouncer.Server {
	CheckSSL(c)

	// Initialize configuration components from cli
	core := &gouncer.Core{c.String("hostname"), ":" + c.String("port"), c.Bool("jsonp"), c.String("log")}
	ssl := &gouncer.Ssl{c.String("certificate"), c.String("key")}

	backend := &gouncer.Backend{
		Couchdb:  c.String("couchdb"),
		Userdb:   c.String("userdb"),
		Groupdb:  c.String("groupdb"),
		Memcache: c.StringSlice("memcache"),
		Smtp:     c.String("smtp"),
	}

	token := &gouncer.Token{c.String("algorithm"), int32(c.Int("expiration"))}

	// Create configuration
	cfg := &gouncer.Config{
		Core:    core,
		Ssl:     ssl,
		Backend: backend,
		Token:   token,
	}

	return gouncer.NewServer(cfg)
}
Beispiel #13
0
func createMultipPart(c *cli.Context) {
	buffer := bytes.NewBuffer([]byte{})
	mpw := multipart.NewWriter(buffer)

	for _, file := range c.StringSlice("file") {
		w, err := mpw.CreateFormFile("pulse-plugin", file)
		if err != nil {
			panic(err)
		}

		fb, err := ioutil.ReadFile(file)
		if err != nil {
			panic(err)
		}
		w.Write(fb)
	}

	err := mpw.Close()
	if err != nil {
		panic(err)
	}

	//print out the multiart file
	fmt.Println(buffer.String())
}
Beispiel #14
0
func dispatchCommand(c *cli.Context, client *etcd.Client, cmd *command.Command) {
	targets := c.StringSlice("target")
	if targets == nil || len(targets) == 0 {
		log.Warningln("no target set! try to send command to all registered host.")
		targets = fetchHosts(c, client)
	}
	if targets == nil {
		log.Fatalln("no target to send command.")
	} else {
		log.Infoln("send command to: ", targets)
	}
	for _, target := range targets {
		key := fmt.Sprintf("/beacon/commands/single/%s/%s/",
			target, cmd.Id)
		if c.GlobalString("prefix") != "" {
			key = fmt.Sprintf("/%s%s", strings.Trim(c.GlobalString("prefix"), "/"), key)
		}

		if _, err := client.Set(key, cmd.Marshal(), 0); err != nil {
			log.WithFields(log.Fields{
				"error": err.Error(),
			}).Fatalln("send command failed.")
		}
	}
}
Beispiel #15
0
//createServiceLB is a netctl interface routine to delete
//service object
func createServiceLB(ctx *cli.Context) {
	if len(ctx.Args()) != 1 {
		errExit(ctx, exitHelp, "Service name required", true)
	}

	serviceName := ctx.Args()[0]
	serviceSubnet := ctx.String("network")
	tenantName := ctx.String("tenant")
	if len(tenantName) == 0 {
		tenantName = "default"
	}
	selectors := ctx.StringSlice("selector")
	ports := ctx.StringSlice("port")
	ipAddress := ctx.String("preferred-ip")
	service := &contivClient.ServiceLB{
		ServiceName: serviceName,
		TenantName:  tenantName,
		NetworkName: serviceSubnet,
		IpAddress:   ipAddress,
	}
	service.Selectors = append(service.Selectors, selectors...)
	service.Ports = append(service.Ports, ports...)
	errCheck(ctx, getClient(ctx).ServiceLBPost(service))

	fmt.Printf("Creating ServiceLB %s:%s\n", tenantName, serviceName)
}
func addBindMounts(spec *specs.LinuxSpec, rspec *specs.LinuxRuntimeSpec, context *cli.Context) error {
	for _, b := range context.StringSlice("bind") {
		var source, dest string
		options := "ro"
		bparts := strings.SplitN(b, ":", 3)
		switch len(bparts) {
		case 2:
			source, dest = bparts[0], bparts[1]
		case 3:
			source, dest, options = bparts[0], bparts[1], bparts[2]
		default:
			return fmt.Errorf("--bind should have format src:dest:[options]")
		}
		name := filepath.Base(source)
		mntName := fmt.Sprintf("%sbind", name)
		spec.Mounts = append(spec.Mounts, specs.MountPoint{Name: mntName, Path: dest})
		defaultOptions := []string{"bind"}
		rspec.Mounts[mntName] = specs.Mount{
			Type:    "bind",
			Source:  source,
			Options: append(defaultOptions, options),
		}
	}
	return nil
}
Beispiel #17
0
func createExternalContracts(ctx *cli.Context) {
	if len(ctx.Args()) != 1 {
		errExit(ctx, exitHelp, "Contracts group name required", true)
	}

	var contractsType string
	if ctx.Bool("provided") && ctx.Bool("consumed") {
		errExit(ctx, exitHelp, "Cannot use both provided and consumed", false)
	} else if ctx.Bool("provided") {
		contractsType = "provided"
	} else if ctx.Bool("consumed") {
		contractsType = "consumed"
	} else {
		errExit(ctx, exitHelp, "Either provided or consumed must be specified", false)
	}

	tenant := ctx.String("tenant")

	contracts := ctx.StringSlice("contract")
	if len(contracts) == 0 {
		errExit(ctx, exitHelp, "Contracts not provided", false)
	}

	contractsGroupName := ctx.Args()[0]

	errCheck(ctx, getClient(ctx).ExtContractsGroupPost(&contivClient.ExtContractsGroup{
		TenantName:         tenant,
		ContractsGroupName: contractsGroupName,
		ContractsType:      contractsType,
		Contracts:          contracts,
	}))

	fmt.Printf("Creating ExternalContracts %s:%s\n", tenant, contractsGroupName)
}
Beispiel #18
0
Datei: ist.go Projekt: glyn/gosub
func list(c *cli.Context) {
	appPackages := c.StringSlice("app")
	testPackages := c.StringSlice("test")

	appImports, err := getAppImports(appPackages...)
	if err != nil {
		println("failed to detect app imports: " + err.Error())
		os.Exit(1)
	}

	testImports, err := getTestImports(testPackages...)
	if err != nil {
		println("failed to detect test imports: " + err.Error())
		os.Exit(1)
	}

	allImports := append(appImports, testImports...)

	allDeps, err := getAllDeps(allImports...)
	if err != nil {
		println("failed to get deps: " + err.Error())
		os.Exit(1)
	}

	deps, err := filterNonStandard(allDeps...)
	if err != nil {
		println("failed to filter deps: " + err.Error())
		os.Exit(1)
	}

	for _, dep := range deps {
		fmt.Println(dep)
	}
}
Beispiel #19
0
func put(c *cli.Context) {
	var (
		err error
	)

	hosts := c.StringSlice("host")
	if c.IsSet("host") || c.IsSet("H") {
		hosts = hosts[1:]
	}

	key := c.String("key")
	if key == "" {
		log.Fatal("key flag must be set")
	}

	value := []byte(c.String("value"))
	if c.String("value") == "" {
		log.Fatal("value flag must be set")
	}

	client, err := proton.GetRaftClient(hosts[0], 2*time.Second)
	if err != nil {
		log.Fatal("couldn't initialize client connection")
	}

	resp, err := client.PutObject(context.TODO(), &proton.PutObjectRequest{Object: &proton.Pair{Key: key, Value: value}})
	if resp == nil || err != nil {
		log.Fatal("Can't put object in the cluster")
	}
}
Beispiel #20
0
func getStringSliceOption(ctx *cli.Context, flag string, required bool) []string {
	slice := ctx.StringSlice(flag)
	if required && (!ctx.IsSet(flag) || len(slice) == 0) {
		exitOnError(fmt.Errorf("--%s must specify at least one string value", flag))
	}
	return slice
}
Beispiel #21
0
func list(c *cli.Context) {
	var (
		err error
	)

	hosts := c.StringSlice("host")
	if c.IsSet("host") || c.IsSet("H") {
		hosts = hosts[1:]
	}

	client, err := proton.GetRaftClient(hosts[0], 2*time.Second)
	if err != nil {
		log.Fatal("couldn't initialize client connection")
	}

	resp, err := client.ListObjects(context.TODO(), &proton.ListObjectsRequest{})
	if err != nil {
		log.Fatal("Can't list objects in the cluster")
	}

	fmt.Println("Keys:")

	for _, obj := range resp.Objects {
		fmt.Println(":", obj.Key, ":", string(obj.Value))
	}
}
Beispiel #22
0
// Add the flags accepted by run to the supplied flag set, returning the
// variables into which the flags will parse.
func populateFlags(c *cli.Context) (flags *flagStorage) {
	flags = &flagStorage{
		// File system
		MountOptions: make(map[string]string),
		DirMode:      os.FileMode(c.Int("dir-mode")),
		FileMode:     os.FileMode(c.Int("file-mode")),
		Uid:          int64(c.Int("uid")),
		Gid:          int64(c.Int("gid")),

		// GCS,
		KeyFile: c.String("key-file"),
		EgressBandwidthLimitBytesPerSecond: c.Float64("limit-bytes-per-sec"),
		OpRateLimitHz:                      c.Float64("limit-ops-per-sec"),

		// Tuning,
		StatCacheTTL: c.Duration("stat-cache-ttl"),
		TypeCacheTTL: c.Duration("type-cache-ttl"),
		TempDir:      c.String("temp-dir"),
		ImplicitDirs: c.Bool("implicit-dirs"),

		// Debugging,
		DebugFuse:       c.Bool("debug_fuse"),
		DebugGCS:        c.Bool("debug_gcs"),
		DebugHTTP:       c.Bool("debug_http"),
		DebugInvariants: c.Bool("debug_invariants"),
	}

	// Handle the repeated "-o" flag.
	for _, o := range c.StringSlice("o") {
		mountpkg.ParseOptions(flags.MountOptions, o)
	}

	return
}
Beispiel #23
0
func (cmd *Curl) Run(c *cli.Context) {
	path := c.Args()[0]
	method := c.String("X")
	headers := c.StringSlice("H")
	body := c.String("d")
	verbose := c.Bool("v")

	reqHeader := strings.Join(headers, "\n")

	if verbose {
		trace.EnableTrace()
	}

	respHeader, respBody, apiResponse := cmd.curlRepo.Request(method, path, reqHeader, body)
	if apiResponse.IsNotSuccessful() {
		cmd.ui.Failed("Error creating request:\n%s", apiResponse.Message)
		return
	}

	if verbose {
		return
	}

	if c.Bool("i") {
		cmd.ui.Say("%s", respHeader)
	}

	cmd.ui.Say("%s", respBody)
	return
}
Beispiel #24
0
func (cmd *Command) upsertHostAction(c *cli.Context) {
	host, err := engine.NewHost(c.String("name"), engine.HostSettings{})
	if err != nil {
		cmd.printError(err)
		return
	}
	if c.String("cert") != "" || c.String("privateKey") != "" {
		keyPair, err := readKeyPair(c.String("cert"), c.String("privateKey"))
		if err != nil {
			cmd.printError(fmt.Errorf("failed to read key pair: %s", err))
			return
		}
		host.Settings.KeyPair = keyPair
	}
	host.Settings.OCSP = engine.OCSPSettings{
		Enabled:            c.Bool("ocsp"),
		SkipSignatureCheck: c.Bool("ocspSkipCheck"),
		Period:             c.Duration("ocspPeriod").String(),
		Responders:         c.StringSlice("ocspResponder"),
	}
	if err := cmd.client.UpsertHost(*host); err != nil {
		cmd.printError(err)
		return
	}
	cmd.printOk("host added")
}
Beispiel #25
0
func secretParseCmd(name string, value string, c *cli.Context) (*model.Secret, error) {
	secret := &model.Secret{}
	secret.Name = name
	secret.Value = value
	secret.Images = c.StringSlice("image")
	secret.Events = c.StringSlice("event")
	secret.SkipVerify = c.Bool("skip-verify")
	secret.Conceal = c.Bool("conceal")

	if len(secret.Images) == 0 {
		return nil, fmt.Errorf("Please specify the --image parameter")
	}

	// TODO(bradrydzewski) below we use an @ sybmol to denote that the secret
	// value should be loaded from a file (inspired by curl). I'd prefer to use
	// a --input flag to explicitly specify a filepath instead.

	if strings.HasPrefix(secret.Value, "@") {
		path := secret.Value[1:]
		out, ferr := ioutil.ReadFile(path)
		if ferr != nil {
			return nil, ferr
		}
		secret.Value = string(out)
	}

	return secret, nil
}
Beispiel #26
0
func AddAction(ctx *cli.Context, client pb.GoSuvClient) {
	name := ctx.String("name")
	if name == "" {
		name = filepath.Base(ctx.Args()[0])
	}

	dir, _ := os.Getwd()

	if len(ctx.Args()) < 1 {
		log.Fatal("need at least one args")
	}
	cmdName := ctx.Args().First()
	cmdPath, err := exec.LookPath(cmdName)
	if err != nil {
		log.Fatal(err)
	}

	req := new(pb.ProgramInfo)
	req.Name = ctx.String("name")
	req.Directory = dir
	req.Command = append([]string{cmdPath}, ctx.Args().Tail()...)
	req.Environ = ctx.StringSlice("env")

	res, err := client.Create(context.Background(), req)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(res.Message)
}
Beispiel #27
0
// Add the flags accepted by run to the supplied flag set, returning the
// variables into which the flags will parse.
func PopulateFlags(c *cli.Context) (flags *FlagStorage) {
	flags = &FlagStorage{
		// File system
		MountOptions: make(map[string]string),
		DirMode:      os.FileMode(c.Int("dir-mode")),
		FileMode:     os.FileMode(c.Int("file-mode")),
		Uid:          uint32(c.Int("uid")),
		Gid:          uint32(c.Int("gid")),

		// Tuning,
		StatCacheTTL: c.Duration("stat-cache-ttl"),
		TypeCacheTTL: c.Duration("type-cache-ttl"),

		// S3
		Endpoint:       c.String("endpoint"),
		StorageClass:   c.String("storage-class"),
		UsePathRequest: c.Bool("use-path-request"),

		// Debugging,
		DebugFuse:  c.Bool("debug_fuse"),
		DebugS3:    c.Bool("debug_s3"),
		Foreground: c.Bool("f"),
	}

	// Handle the repeated "-o" flag.
	for _, o := range c.StringSlice("o") {
		parseOptions(flags.MountOptions, o)
	}
	return
}
Beispiel #28
0
func (cmd CreateSecurityGroup) Run(context *cli.Context) {
	name := context.Args()[0]
	rules := context.String("rules")
	spaces := context.StringSlice("space")
	spaceGuids := []string{}
	for _, spaceName := range spaces {
		space, err := cmd.spaceRepo.FindByName(spaceName)

		if err != nil {
			cmd.ui.Failed("Could not find space named '%s'", spaceName)
		}

		spaceGuids = append(spaceGuids, space.Guid)
	}

	ruleMaps := []map[string]string{}
	if rules != "" {
		err := json.Unmarshal([]byte(rules), &ruleMaps)
		if err != nil {
			cmd.ui.Failed("Incorrect json format: %s", err.Error())
		}
	}

	cmd.ui.Say("Creating application security group '%s' as '%s', applying to %d spaces", name, cmd.configRepo.Username(), len(spaceGuids))

	err := cmd.appSecurityGroupRepo.Create(name, ruleMaps, spaceGuids)
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	cmd.ui.Ok()
}
Beispiel #29
0
func generate(c *cli.Context) error {
	generateServer := c.Bool("server")
	outDir := c.String("dir")
	hostnames := c.StringSlice("hostname")

	return Generate(generateServer, outDir, hostnames)
}
Beispiel #30
0
func verifyPolicy(ctx *cli.Context) {
	srcInSlice := ctx.StringSlice("source")
	dstInSlice := ctx.StringSlice("destination")

	srcSlice, err := parseAllowedSlice(srcInSlice)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Invalid source: %s\n", err)
		os.Exit(1)
	}

	dstSlice, err := parseAllowedSlice(dstInSlice)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Invalid destination: %s\n", err)
		os.Exit(1)
	}

	searchCtx := policy.SearchContext{
		Trace: policy.TRACE_ENABLED,
		From:  srcSlice,
		To:    dstSlice,
	}

	scr, err := client.PolicyCanConsume(&searchCtx)

	if err != nil {
		fmt.Fprintf(os.Stderr, "Error while retrieving policy consume result: %s\n", err)
		os.Exit(1)
	}
	bytes.NewBuffer(scr.Logging).WriteTo(os.Stdout)
}