示例#1
1
func startDirectory(c *cli.Context) {
	fmt.Println("Starting full-blown service-directory")

	// var apiReg = svcreg.NewGenericAPIVersionRegistry()
	// var svcReg = svcreg.NewGenericServiceRegistry()
	// var hostReg = svcreg.NewGenericHostRegistry(svcReg)
	//
	// var outboundEvents = make(chan evntsrc.Event)
	// var handler = evntsrc.NewEventHandler()
	// var dirSvc = svcreg.NewServiceRegistryWebService(outboundEvents, apiReg, svcReg, hostReg)
	// var nsqSink, err = utils.NewNsqSink()
	// if err != nil {
	// 	fmt.Println("Failed to initialize the NSQ communications")
	// 	return
	// }
	// handler.Use("ADD_ServiceDefinition", nsqSink.Publish)
	// var nsqCancelChan = keepProcessing(outboundEvents, handler.Handle)
	//
	// var m = martini.Classic()
	// m.Use(render.Renderer())
	// m.Action(dirSvc.Route().Handle)
	// http.HandleFunc("/service-directory/", func(w http.ResponseWriter, r *http.Request) {
	// 	r.URL, _ = url.Parse(strings.TrimPrefix(r.URL.String(), "/service-directory"))
	// 	m.ServeHTTP(w, r)
	// })

	// TODO (enzian) gracefully stop the service.
	log.Fatal(http.ListenAndServe(c.String("u"), nil))
	// nsqCancelChan <- true
}
示例#2
0
文件: web.go 项目: kuuyee/gogs-learn
func runWeb(ctx *cli.Context) {
	if ctx.IsSet("config") {
		setting.CustomConf = ctx.String("config")
	}
	routers.GlobalInit()
	checkVersion()
}
示例#3
0
func (cmd RepoPlugins) Run(c *cli.Context) {
	var repos []models.PluginRepo
	repoName := c.String("r")

	repos = cmd.config.PluginRepos()

	if repoName == "" {
		cmd.ui.Say(T("Getting plugins from all repositories ... "))
	} else {
		index := cmd.findRepoIndex(repoName)
		if index != -1 {
			cmd.ui.Say(T("Getting plugins from repository '") + repoName + "' ...")
			repos = []models.PluginRepo{repos[index]}
		} else {
			cmd.ui.Failed(repoName + T(" does not exist as an available plugin repo."+"\nTip: use `add-plugin-repo` command to add repos."))
		}
	}

	cmd.ui.Say("")

	repoPlugins, repoError := cmd.pluginRepo.GetPlugins(repos)

	cmd.printTable(repoPlugins)

	cmd.printErrors(repoError)
}
示例#4
0
func getPassword(context *cli.Context) (password string, err error) {
	password = context.String("password")
	if len(password) > 0 {
		return password, nil
	}
	return gopass.GetPass("Plex password: ")
}
func doObjectStoreAddImage(c *cli.Context) error {
	var err error
	v := url.Values{}

	objectstoreUUID, err := getUUID(c, KEY_OBJECTSTORE, true, err)
	imageUUID, err := getUUID(c, KEY_IMAGE, false, err)
	imageName, err := getName(c, "image-name", false, err)
	if err != nil {
		return err
	}
	imageFile := c.String("image-file")
	if imageFile == "" {
		return genRequiredMissingError("image-file")
	}

	imageConfig := api.ObjectStoreImageConfig{
		ImageFile: imageFile,
	}
	if imageUUID != "" {
		v.Set(KEY_IMAGE, imageUUID)
	}
	if imageName != "" {
		v.Set("image-name", imageName)
	}

	request := "/objectstores/" + objectstoreUUID + "/images/add?" + v.Encode()
	return sendRequestAndPrint("POST", request, imageConfig)
}
示例#6
0
文件: login.go 项目: juggernaut/cli
func (cmd Login) setOrganization(c *cli.Context) (isOrgSet bool) {
	orgName := c.String("o")

	if orgName == "" {
		availableOrgs := []models.Organization{}
		apiErr := cmd.orgRepo.ListOrgs(func(o models.Organization) bool {
			availableOrgs = append(availableOrgs, o)
			return len(availableOrgs) < maxChoices
		})
		if apiErr != nil {
			cmd.ui.Failed("Error finding avilable orgs\n%s", apiErr.Error())
		}

		if len(availableOrgs) == 1 {
			cmd.targetOrganization(availableOrgs[0])
			return true
		}

		orgName = cmd.promptForOrgName(availableOrgs)
		if orgName == "" {
			cmd.ui.Say("")
			return false
		}
	}

	org, err := cmd.orgRepo.FindByName(orgName)
	if err != nil {
		cmd.ui.Failed("Error finding org %s\n%s", terminal.EntityNameColor(orgName), err.Error())
	}

	cmd.targetOrganization(org)
	return true
}
示例#7
0
func (cmd CreateOrg) Run(c *cli.Context) {
	name := c.Args()[0]
	cmd.ui.Say(T("Creating org {{.OrgName}} as {{.Username}}...",
		map[string]interface{}{
			"OrgName":  terminal.EntityNameColor(name),
			"Username": terminal.EntityNameColor(cmd.config.Username())}))

	org := models.Organization{OrganizationFields: models.OrganizationFields{Name: name}}

	quotaName := c.String("q")
	if quotaName != "" {
		quota, err := cmd.quotaRepo.FindByName(quotaName)
		if err != nil {
			cmd.ui.Failed(err.Error())
		}

		org.QuotaDefinition.Guid = quota.Guid
	}

	err := cmd.orgRepo.Create(org)
	if err != nil {
		if apiErr, ok := err.(errors.HttpError); ok && apiErr.ErrorCode() == errors.ORG_EXISTS {
			cmd.ui.Ok()
			cmd.ui.Warn(T("Org {{.OrgName}} already exists",
				map[string]interface{}{"OrgName": name}))
			return
		} else {
			cmd.ui.Failed(err.Error())
		}
	}

	cmd.ui.Ok()
	cmd.ui.Say(T("\nTIP: Use '{{.Command}}' to target new org",
		map[string]interface{}{"Command": terminal.CommandColor(cf.Name() + " target -o " + name)}))
}
示例#8
0
文件: restore.go 项目: imikushin/runc
func restoreContainer(context *cli.Context, spec *specs.Spec, config *configs.Config, imagePath string) (code int, err error) {
	var (
		rootuid = 0
		rootgid = 0
		id      = context.Args().First()
	)
	factory, err := loadFactory(context)
	if err != nil {
		return -1, err
	}
	container, err := factory.Load(id)
	if err != nil {
		container, err = factory.Create(id, config)
		if err != nil {
			return -1, err
		}
	}
	options := criuOptions(context)

	status, err := container.Status()
	if err != nil {
		logrus.Error(err)
	}
	if status == libcontainer.Running {
		fatalf("Container with id %s already running", id)
	}

	setManageCgroupsMode(context, options)

	// ensure that the container is always removed if we were the process
	// that created it.
	detach := context.Bool("detach")
	if !detach {
		defer destroy(container)
	}
	process := &libcontainer.Process{}
	tty, err := setupIO(process, rootuid, rootgid, "", false, detach)
	if err != nil {
		return -1, err
	}
	defer tty.Close()
	handler := newSignalHandler(tty, !context.Bool("no-subreaper"))
	if err := container.Restore(process, options); err != nil {
		return -1, err
	}
	if err := tty.ClosePostStart(); err != nil {
		return -1, err
	}
	if pidFile := context.String("pid-file"); pidFile != "" {
		if err := createPidFile(pidFile, process); err != nil {
			process.Signal(syscall.SIGKILL)
			process.Wait()
			return -1, err
		}
	}
	if detach {
		return 0, nil
	}
	return handler.forward(process)
}
// NewDriver creates a new MACVLAN Driver
func NewDriver(version string, ctx *cli.Context) (*Driver, error) {
	docker, err := dockerclient.NewDockerClient("unix:///var/run/docker.sock", nil)
	if err != nil {
		return nil, fmt.Errorf("could not connect to docker: %s", err)
	}
	// lower bound of v4 MTU is 68-bytes per rfc791
	if ctx.Int("mtu") <= 0 {
		cliMTU = defaultMTU
	} else if ctx.Int("mtu") >= minMTU {
		cliMTU = ctx.Int("mtu")
	} else {
		log.Fatalf("The MTU value passed [ %d ] must be greater than [ %d ] bytes per rfc791", ctx.Int("mtu"), minMTU)
	}
	// Set the default mode to bridge
	if ctx.String("mode") == "" {
		macvlanMode = bridgeMode
	}
	switch ctx.String("mode") {
	case bridgeMode:
		macvlanMode = bridgeMode
		// todo: in other modes if relevant
	}
	d := &Driver{
		networks: networkTable{},
		dockerer: dockerer{
			client: docker,
		},
	}
	return d, nil
}
示例#10
0
文件: cli.go 项目: fbernardo/envman
func before(c *cli.Context) error {
	initLogFormatter()
	initHelpAndVersionFlags()
	initAppHelpTemplate()

	// Log level
	if logLevel, err := log.ParseLevel(c.String(LogLevelKey)); err != nil {
		log.Fatal("[BITRISE_CLI] - Failed to parse log level:", err)
	} else {
		log.SetLevel(logLevel)
	}

	// Befor parsing cli, and running command
	// we need to decide wich path will be used by envman
	envman.CurrentEnvStoreFilePath = c.String(PathKey)
	if envman.CurrentEnvStoreFilePath == "" {
		if path, err := envStorePathInCurrentDir(); err != nil {
			log.Fatal("[ENVMAN] - Failed to set envman work path in current dir:", err)
		} else {
			envman.CurrentEnvStoreFilePath = path
		}
	}

	envman.ToolMode = c.Bool(ToolKey)
	if envman.ToolMode {
		log.Info("[ENVMAN] - Tool mode on")
	}

	if _, err := envman.GetConfigs(); err != nil {
		log.Fatal("[ENVMAN] - Failed to init configs:", err)
	}

	return nil
}
示例#11
0
func create(c *cli.Context) {
	f := c.String("config")
	if len(f) == 0 {
		f = "dashing.json"
	}
	conf := Dashing{
		Name:    "Dashing",
		Package: "dashing",
		Index:   "index.html",
		Selectors: map[string]interface{}{
			"title": "Package",
			"dt a":  "Command",
		},
		Ignore: []string{"ABOUT"},
	}
	j, err := json.MarshalIndent(conf, "", "    ")
	if err != nil {
		panic("The programmer did something dumb.")
	}
	err = ioutil.WriteFile(f, j, 0755)
	if err != nil {
		fmt.Errorf("Could not initialize JSON file: %s", err)
		os.Exit(1)
	}
	fmt.Printf("You may now edit %s", f)

}
示例#12
0
// Retrieves tasks from specified flavor
func getFlavorTasks(c *cli.Context, w io.Writer) error {
	err := checkArgNum(c.Args(), 1, "flavor tasks <id> [<options>]")
	if err != nil {
		return err
	}
	id := c.Args().First()

	state := c.String("state")
	options := &photon.TaskGetOptions{
		State: state,
	}

	client.Esxclient, err = client.GetClient(utils.IsNonInteractive(c))
	if err != nil {
		return err
	}

	taskList, err := client.Esxclient.Flavors.GetTasks(id, options)
	if err != nil {
		return err
	}

	err = printTaskList(taskList.Items, c)
	if err != nil {
		return err
	}
	return nil
}
示例#13
0
func newDB(c *cli.Context) *sqlx.DB {
	db := sqlx.MustConnect("postgres", c.String("db"))
	if err := conveyor.MigrateUp(db); err != nil {
		panic(err)
	}
	return db
}
示例#14
0
文件: config.go 项目: Jdesk/os
func runImport(c *cli.Context) {
	var input io.ReadCloser
	var err error
	input = os.Stdin
	cfg, err := config.LoadConfig()

	if err != nil {
		log.Fatal(err)
	}

	inputFile := c.String("input")
	if inputFile != "" {
		input, err = os.Open(inputFile)
		if err != nil {
			log.Fatal(err)
		}
		defer input.Close()
	}

	bytes, err := ioutil.ReadAll(input)
	if err != nil {
		log.Fatal(err)
	}

	cfg, err = cfg.Import(bytes)
	if err != nil {
		log.Fatal(err)
	}

	if err := cfg.Save(); err != nil {
		log.Fatal(err)
	}
}
示例#15
0
文件: main.go 项目: swasd/dpm
func doBuild(c *cli.Context) {
	home := os.Getenv("HOME")
	outputDir := os.ExpandEnv(c.String("dir"))
	sourceDir := "."
	if len(c.Args()) >= 1 {
		sourceDir = c.Args().First()
	}

	p, err := build.BuildPackage(sourceDir)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	err = p.SaveToDir(outputDir)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	err = generateIndex(filepath.Join(home, "/.dpm/cache/"),
		filepath.Join(home, "/.dpm/index/"))
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	packageSpec, err := p.Spec()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Println(packageSpec.Name)
}
示例#16
0
func TestApp_RunAsSubcommandParseFlags(t *testing.T) {
	var context *cli.Context

	a := cli.NewApp()
	a.Commands = []cli.Command{
		{
			Name: "foo",
			Action: func(c *cli.Context) {
				context = c
			},
			Flags: []cli.Flag{
				cli.StringFlag{
					Name:  "lang",
					Value: "english",
					Usage: "language for the greeting",
				},
			},
			Before: func(_ *cli.Context) error { return nil },
		},
	}
	a.Run([]string{"", "foo", "--lang", "spanish", "abcd"})

	expect(t, context.Args().Get(0), "abcd")
	expect(t, context.String("lang"), "spanish")
}
示例#17
0
文件: update.go 项目: sillydong/gogs
func runUpdate(c *cli.Context) {
	if c.IsSet("config") {
		setting.CustomConf = c.String("config")
	}

	setup("update.log")

	if len(os.Getenv("SSH_ORIGINAL_COMMAND")) == 0 {
		log.GitLogger.Trace("SSH_ORIGINAL_COMMAND is empty")
		return
	}

	args := c.Args()
	if len(args) != 3 {
		log.GitLogger.Fatal(2, "Arguments received are not equal to three")
	} else if len(args[0]) == 0 {
		log.GitLogger.Fatal(2, "First argument 'refName' is empty, shouldn't use")
	}

	task := models.UpdateTask{
		UUID:        os.Getenv("uuid"),
		RefName:     args[0],
		OldCommitID: args[1],
		NewCommitID: args[2],
	}

	if err := models.AddUpdateTask(&task); err != nil {
		log.GitLogger.Fatal(2, "AddUpdateTask: %v", err)
	}
}
示例#18
0
func (cmd CreateSecurityGroup) Run(context *cli.Context) {
	name := context.Args()[0]
	pathToJSONFile := context.String("json")
	rules, err := json.ParseJSON(pathToJSONFile)
	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	cmd.ui.Say(T("Creating security group {{.security_group}} as {{.username}}",
		map[string]interface{}{
			"security_group": terminal.EntityNameColor(name),
			"username":       terminal.EntityNameColor(cmd.configRepo.Username()),
		}))

	err = cmd.securityGroupRepo.Create(name, rules)

	httpErr, ok := err.(errors.HttpError)
	if ok && httpErr.ErrorCode() == errors.SECURITY_GROUP_EXISTS {
		cmd.ui.Ok()
		cmd.ui.Warn(T("Security group {{.security_group}} {{.error_message}}",
			map[string]interface{}{
				"security_group": terminal.EntityNameColor(name),
				"error_message":  terminal.WarningColor(T("already exists")),
			}))
		return
	}

	if err != nil {
		cmd.ui.Failed(err.Error())
	}

	cmd.ui.Ok()
}
示例#19
0
文件: update.go 项目: hopehook/gogs
func runUpdate(c *cli.Context) {
	if c.IsSet("config") {
		setting.CustomConf = c.String("config")
	}
	cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
	if cmd == "" {
		return
	}

	setup("update.log")

	args := c.Args()
	if len(args) != 3 {
		log.GitLogger.Fatal(2, "received less 3 parameters")
	} else if args[0] == "" {
		log.GitLogger.Fatal(2, "refName is empty, shouldn't use")
	}

	task := models.UpdateTask{
		UUID:        os.Getenv("uuid"),
		RefName:     args[0],
		OldCommitID: args[1],
		NewCommitID: args[2],
	}

	if err := models.AddUpdateTask(&task); err != nil {
		log.GitLogger.Fatal(2, "AddUpdateTask: %v", err)
	}
}
示例#20
0
文件: flags.go 项目: x5u/goofys
// 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
}
示例#21
0
func (cmd Target) Run(c *cli.Context) {
	orgName := c.String("o")
	spaceName := c.String("s")

	if orgName != "" {
		err := cmd.setOrganization(orgName)
		if err != nil {
			cmd.ui.Failed(err.Error())
		} else if spaceName == "" {
			spaceList, apiErr := cmd.getSpaceList()
			if apiErr == nil && len(spaceList) == 1 {
				cmd.setSpace(spaceList[0].Name)
			}
		}
	}

	if spaceName != "" {
		err := cmd.setSpace(spaceName)
		if err != nil {
			cmd.ui.Failed(err.Error())
		}
	}

	cmd.ui.ShowConfiguration(cmd.config)
	if !cmd.config.IsLoggedIn() {
		cmd.ui.PanicQuietly()
	}
	utils.NotifyUpdateIfNeeded(cmd.ui, cmd.config)
	return
}
示例#22
0
文件: remove.go 项目: axw/lingo
func remove(c *cli.Context) {
	if l := len(c.Args()); l != 1 {
		oserrf("error: expected 1 argument, got %d", l)
		return
	}

	cfgPath, err := tenetCfgPath(c)
	if err != nil {
		oserrf("reading config file: %s", err.Error())
		return
	}
	cfg, err := buildConfig(cfgPath, CascadeNone)
	if err != nil {
		oserrf("reading config file: %s", err.Error())
		return
	}

	imageName := c.Args().First()

	if !cfg.HasTenet(imageName) {
		oserrf(`error: tenet "%s" not found in %q`, imageName, c.GlobalString(tenetCfgFlg.long))
		return
	}

	if err := cfg.RemoveTenet(imageName, c.String("group")); err != nil {
		oserrf(err.Error())
		return
	}

	if err := writeConfigFile(c, cfg); err != nil {
		oserrf(err.Error())
		return
	}
}
示例#23
0
文件: login.go 项目: juggernaut/cli
func (cmd Login) setSpace(c *cli.Context) {
	spaceName := c.String("s")

	if spaceName == "" {
		var availableSpaces []models.Space
		err := cmd.spaceRepo.ListSpaces(func(space models.Space) bool {
			availableSpaces = append(availableSpaces, space)
			return (len(availableSpaces) < maxChoices)
		})
		if err != nil {
			cmd.ui.Failed("Error finding available spaces\n%s", err.Error())
		}

		// Target only space if possible
		if len(availableSpaces) == 1 {
			cmd.targetSpace(availableSpaces[0])
			return
		}

		spaceName = cmd.promptForSpaceName(availableSpaces)
		if spaceName == "" {
			cmd.ui.Say("")
			return
		}
	}

	space, err := cmd.spaceRepo.FindByName(spaceName)
	if err != nil {
		cmd.ui.Failed("Error finding space %s\n%s", terminal.EntityNameColor(spaceName), err.Error())
	}

	cmd.targetSpace(space)
}
示例#24
0
// statusCommandFunc executes the "status" command.
func statusCommandFunc(c *cli.Context, client *client.Client) error {
	var host, owner, repo, branch string
	var args = c.Args()

	if len(args) != 0 {
		host, owner, repo = parseRepo(args[0])
	}

	if c.IsSet("branch") {
		branch = c.String("branch")
	} else {
		branch = "master"
	}

	builds, err := client.Commits.ListBranch(host, owner, repo, branch)
	if err != nil {
		return err
	} else if len(builds) == 0 {
		return nil
	}

	var build = builds[len(builds)-1]
	fmt.Printf("%s\t%s\t%s\t%s\t%v", build.Status, build.ShaShort(), build.Timestamp, build.Author, build.Message)
	return nil
}
示例#25
0
func (cmd CreateUserProvidedService) Run(c *cli.Context) {
	name := c.Args()[0]
	drainUrl := c.String("l")

	params := c.String("p")
	params = strings.Trim(params, `"`)
	paramsMap := make(map[string]interface{})

	err := json.Unmarshal([]byte(params), &paramsMap)
	if err != nil && params != "" {
		paramsMap = cmd.mapValuesFromPrompt(params, paramsMap)
	}

	cmd.ui.Say(T("Creating user provided service {{.ServiceName}} in org {{.OrgName}} / space {{.SpaceName}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"ServiceName": terminal.EntityNameColor(name),
			"OrgName":     terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
			"SpaceName":   terminal.EntityNameColor(cmd.config.SpaceFields().Name),
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))

	apiErr := cmd.userProvidedServiceInstanceRepo.Create(name, drainUrl, paramsMap)
	if apiErr != nil {
		cmd.ui.Failed(apiErr.Error())
		return
	}

	cmd.ui.Ok()
}
示例#26
0
func imagesAction(c *cli.Context) {
	api := getAPI(c)
	meta, err := api.GetImages()
	if err != nil {
		log.Fatalf("Error getting images: %s", err)
	}
	images := meta.Objects
	// check for op
	id := c.String("id")
	color := ""
	if id != "" {
		for _, v := range images {
			if strings.Index(v.ID, id) == 0 {
				LogMessage(fmt.Sprintf("ID: %s", v.ID), color)
				LogMessage(fmt.Sprintf("Host: %s", v.Host.Name), color)
				LogMessage(fmt.Sprintf("Repository: %s", v.Repository), color)
			}
		}
		return
	}
	// no op specified ; show all
	for _, v := range images {
		LogMessage(fmt.Sprintf("%s %s", v.ID[:12], v.Repository), color)
	}
}
示例#27
0
文件: tlsconf.go 项目: rowhit/os
func generate(c *cli.Context) error {
	generateServer := c.Bool("server")
	outDir := c.String("dir")
	hostnames := c.StringSlice("hostname")

	return Generate(generateServer, outDir, hostnames)
}
示例#28
0
func hostsAction(c *cli.Context) {
	api := getAPI(c)
	meta, err := api.GetHosts()
	if err != nil {
		log.Fatalf("Error getting hosts: %s", err)
	}
	hosts := meta.Objects
	// check for container op
	name := c.String("name")
	color := ""
	if name != "" {
		// check for operation
		for _, v := range hosts {
			if v.Name == name {
				LogMessage(fmt.Sprintf("Name: %v", v.Name), color)
				LogMessage(fmt.Sprintf("Hostname: %v", v.Hostname), color)
				LogMessage(fmt.Sprintf("Port: %v", v.Port), color)
				LogMessage(fmt.Sprintf("Enabled: %v", v.Enabled), color)
			}
		}
		return
	}
	// no op specified ; show all
	for _, v := range hosts {
		if !v.Enabled {
			color = ""
		}
		LogMessage(fmt.Sprintf("%v (%v)", v.Name, v.Hostname), color)
	}
}
示例#29
0
func newCassandraDriver(ctx *cli.Context) (drivers.Driver, error) {

	urls := strings.Split(ctx.String("cassandra-hosts"), ",")

	cluster := gocql.NewCluster()
	cluster.Hosts = urls
	cluster.Port = ctx.Int("cassandra-port")
	cluster.Keyspace = ctx.String("cassandra-keyspace")
	cluster.Consistency = gocql.Quorum
	session, err := cluster.CreateSession()

	if err != nil {
		log.Errorf("cassandra.go: Error while creating cassandra cluster: hosts:%v err:%v", cluster.Hosts, err)
		return nil, err
	}

	log.Infoln("cassandra.go: connected to cassandra cluster")

	d := &CassandraDriver{
		Session: session,
		Cluster: cluster,
	}

	return d, nil
}
示例#30
0
func createSigFromArgs(c *cli.Context) (route_service.Signature, error) {
	signature := route_service.Signature{}
	url := c.String("url")

	var sigTime time.Time

	timeStr := c.String("time")

	if timeStr != "" {
		unix, err := strconv.ParseInt(timeStr, 10, 64)
		if err != nil {
			fmt.Printf("Invalid time format: %s", timeStr)
			return signature, err
		}

		sigTime = time.Unix(unix, 0)
	} else {
		sigTime = time.Now()
	}

	return route_service.Signature{
		RequestedTime: sigTime,
		ForwardedUrl:  url,
	}, nil
}