Пример #1
0
func (c Command) Run(args []string) {
	var err error

	cmd, err := c.Application.Parse(args[1:])
	c.Client.DebugMode(*c.GlobalOptions.Debug)

	switch kingpin.MustParse(cmd, err) {
	case c.GenerateFile.FullCommand():
		err = c.GenerateFileRunner.Run(c.Client, c.GlobalOptions, c.Out)
	case c.CreatePost.FullCommand():
		err = c.CreatePostRunner.Run(c.Client, c.GlobalOptions, c.Out)
	case c.ShowPost.FullCommand():
		err = c.ShowPostRunner.Run(c.Client, c.GlobalOptions, c.Out)
	case c.ShowPosts.FullCommand():
		err = c.ShowPostsRunner.Run(c.Client, c.GlobalOptions, c.Out)
	case c.FetchPost.FullCommand():
		err = c.FetchPostRunner.Run(c.Client, c.GlobalOptions, c.Out)
	case c.FetchPosts.FullCommand():
		err = c.FetchPostsRunner.Run(c.Client, c.GlobalOptions, c.Out)
	case c.UpdatePost.FullCommand():
		err = c.UpdatePostRunner.Run(c.Client, c.GlobalOptions, c.Out)
	case c.DeletePost.FullCommand():
		err = c.DeletePostRunner.Run(c.Client, c.GlobalOptions, c.Out)
	}

	if err != nil {
		fmt.Fprintf(c.Error, "%s\n", err)
	}
}
Пример #2
0
func main() {
	app := kingpin.New("minicdn", "Master node which manage slaves")
	app.Flag("cachedir", "Cache file directory").Short('d').Default("cache").ExistingDirVar(&mOpts.CacheDir) //.StringVar(&mOpts.CacheDir)
	app.Flag("secret", "Secret key for server").Short('s').Default("sandy mandy").StringVar(&mOpts.Secret)

	ma := app.Command("master", "CDN Master")
	ma.Flag("addr", "Listen address").Default(":7010").StringVar(&mOpts.ListenAddr)
	ma.Flag("log", "Log file, - for stdout").Short('l').Default("-").StringVar(&mOpts.LogFile)
	ma.Flag("mirror", "Mirror http address, ex: http://t.co/").Required().URLVar(&mOpts.MirrorAddr)

	sa := app.Command("slave", "Slave node")
	sa.Flag("addr", "Listen address").Default(":7020").StringVar(&sOpts.ListenAddr)
	sa.Flag("maddr", "Master server address, ex: localhost:7010").Short('m').Required().URLVar(&sOpts.MasterAddr)

	app.Version(VERSION).Author("codeskyblue")
	app.HelpFlag.Short('h')
	app.VersionFlag.Short('v')
	kingpin.CommandLine.Help = "The very simple and mini CDN"

	// parse command line
	cmdName := kingpin.MustParse(app.Parse(os.Args[1:]))

	sOpts.CacheDir = mOpts.CacheDir
	sOpts.Secret = mOpts.Secret

	switch cmdName {
	case ma.FullCommand():
		runMaster(mOpts)
	case sa.FullCommand():
		runSlave(sOpts)
	default:
		log.Fatalf("Unknown command: %s", cmdName)
	}
}
Пример #3
0
func main() {
	app := kingpin.New("Cache", "A generic cache control system")

	configureCmdList(app)
	configureCmdRestore(app)
	configureCmdSnapshot(app)

	kingpin.MustParse(app.Parse(os.Args[1:]))
}
Пример #4
0
func Main() error {
	switch kingpin.MustParse(cli.Parse(os.Args[1:])) {
	case server.FullCommand():
		blob.StateDir = *serverStateDir
		return ListenAndServe(*serverAddr)
	default:
		return errors.New("not implemented")
	}
}
Пример #5
0
func main() {
	switch kingpin.MustParse(app.Parse(os.Args[1:])) {
	case "flat2folder":
		logg.LogTo("DATA_CONVERTER", "do flat2folder")
		doFlat2folder(*sourceDir, *labelIndex, *destDir)
	default:
		kingpin.UsageErrorf("Invalid / missing command")
	}
}
Пример #6
0
Файл: bnp.go Проект: pmezard/bnp
func dispatch() error {
	cmd := kingpin.MustParse(app.Parse(os.Args[1:]))
	switch cmd {
	case parseCmd.FullCommand():
		return parseFn()
	case webCmd.FullCommand():
		return webFn()
	}
	return nil
}
Пример #7
0
func main() {
	kingpin.MustParse(app.Parse(os.Args[1:]))
	server := NewServer()

	if *logfile != "" {
		server.SetLogfile(*logfile)
	}

	server.Start()
}
Пример #8
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	switch kingpin.MustParse(app.Parse(os.Args[1:])) {
	case "host":
		StartHost()
	case "recv":
		StartRecv()
	default:
		kingpin.Usage()
	}

}
Пример #9
0
func main() {
	switch kingpin.MustParse(app.Parse(os.Args[1:])) {
	case "stress":
		logg.LogTo("CLI", "do stress test")
		stressTestLauncher()
	case "upload":
		logg.LogTo("CLI", "do upload")
		uploadLauncher()
	default:
		logg.LogTo("CLI", "oops, nothing to do")
	}
}
Пример #10
0
func main() {
	switch kingpin.MustParse(app.Parse(os.Args[1:])) {
	// Register user
	case register.FullCommand():
		println(*registerNick)

	// Post message
	case post.FullCommand():
		if *postImage != nil {
		}
		text := strings.Join(*postText, " ")
		println("Post:", text)
	}
}
Пример #11
0
func main() {
	app := kingpin.New("completion", "My application with bash completion.")
	app.Flag("flag-1", "").String()
	app.Flag("flag-2", "").HintOptions("opt1", "opt2").String()

	configureNetcatCommand(app)

	// Add some additional top level commands
	addSubCommand(app, "ls", "Additional top level command to show command completion")
	addSubCommand(app, "ping", "Additional top level command to show command completion")
	addSubCommand(app, "nmap", "Additional top level command to show command completion")

	kingpin.MustParse(app.Parse(os.Args[1:]))
}
Пример #12
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	switch kingpin.MustParse(app.Parse(os.Args[1:])) {
	case "ls":
		Ls(*lsS3Uri, *lsSearchDepth, *lsRecurse, *humanReadable, *withDate)
	case "del":
		Del(*delPrefixes, *lsSearchDepth, *delRecurse)
	case "get":
		Get(*getS3Uris, *getSearchDepth)
	case "stream":
		Stream(*streamS3Uris, *streamSearchDepth, *streamKeyRegex, *streamIncludeKeyName)
	case "init":
		Init()
	}
}
Пример #13
0
func dispatch() error {
	cmd := kingpin.MustParse(app.Parse(os.Args[1:]))
	if *prof {
		defer profile.Start(profile.CPUProfile).Stop()
	}
	cfg := NewConfig(*dataDir)
	switch cmd {
	case crawlCmd.FullCommand():
		return crawlFn(cfg)
	case indexCmd.FullCommand():
		return indexOffers(cfg)
	case searchCmd.FullCommand():
		return search(cfg)
	case webCmd.FullCommand():
		return web(cfg)
	case geocodeCmd.FullCommand():
		return geocode(cfg)
	case upgradeCmd.FullCommand():
		return upgrade(cfg)
	case dumpDeletedCmd.FullCommand():
		return dumpDeletedOffersFn(cfg)
	case changesCmd.FullCommand():
		return changesFn(cfg)
	case spatialCmd.FullCommand():
		return spatialFn(cfg)
	case debugQueryCmd.FullCommand():
		return debugQueryFn(cfg)
	case analyzeCmd.FullCommand():
		return analyzeFn(cfg)
	case geocodedCmd.FullCommand():
		return geocodedFn(cfg)
	case densityCmd.FullCommand():
		return densityFn(cfg)
	case histogramCmd.FullCommand():
		return histogramFn(cfg)
	case indexStatsCmd.FullCommand():
		return indexStatsFn(cfg)
	case listDeletedCmd.FullCommand():
		return listDeletedFn(cfg)
	case duplicatesCmd.FullCommand():
		return duplicatesFn(cfg)
	case dumpOfferCmd.FullCommand():
		return dumpOfferFn(cfg)
	}
	return fmt.Errorf("unknown command: %s", cmd)
}
Пример #14
0
func main() {
	log15.Info("Welcome to Listless!", log15.Ctx{"context": "setup"})
	cmd := kingpin.MustParse(app.Parse(os.Args[1:]))
	switch cmd {
	case loopMode.FullCommand():
		loopModeF()
	case execMode.FullCommand():
		execModeF()
	case subUpdateAction.FullCommand():
		subUpdateModeF()
	case subRemoveAction.FullCommand():
		subRemoveModeF()
	case subListMode.FullCommand():
		subListModeF()
	default:
		log.Fatal("No valid command given. Try '--help' for ideas.")
	}
}
Пример #15
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	app.Version(appVersion)
	cmd := kingpin.MustParse(app.Parse(os.Args[1:]))
	initGlog()
	defer glog.Flush()
	printAppValues()
	checkDir(props.Workspace)
	switch cmd {

	case config.FullCommand():
		glog.V(3).Info("start config command")

	case rand.FullCommand():
		glog.V(3).Info("start rand command")

	case "train gaussian":
		var m model.Trainer
		*numIter = 1
		m = gaussian.NewModel(*dim, gaussian.Name(*modelName))
		doTrain(m)

	case "train gmm":
		var m model.Trainer
		m = gmm.NewModel(*dim, *numGMM, gmm.Name(*modelName))
		doTrain(m)

	case "train hmm":
		var m model.Trainer
		m = hmm.NewModel(hmmOptions()...)
		doTrain(m)

	default:
		app.Usage(os.Stderr)
	}
}
Пример #16
0
func runCli() {
	switch kingpin.MustParse(app.Parse(os.Args[1:])) {

	case liftCommand.FullCommand():
		commandAction(*liftTargetArg, func(uow *UnitOfWork) {
			uow.Lift(*liftCmdArg, *liftNoCacheFlag, *liftParallelFlag)
		}, true)

	case versionCommand.FullCommand():
		fmt.Println("v2.10.2")

	case statsCommand.FullCommand():
		commandAction(*statsTargetArg, func(uow *UnitOfWork) {
			uow.Stats(*statsNoStreamFlag)
		}, false)

	case statusCommand.FullCommand():
		commandAction(*statusTargetArg, func(uow *UnitOfWork) {
			uow.Status(*noTruncFlag)
		}, false)

	case pushCommand.FullCommand():
		commandAction(*pushTargetArg, func(uow *UnitOfWork) {
			uow.Push()
		}, false)

	case unpauseCommand.FullCommand():
		commandAction(*unpauseTargetArg, func(uow *UnitOfWork) {
			uow.Unpause()
		}, false)

	case pauseCommand.FullCommand():
		commandAction(*pauseTargetArg, func(uow *UnitOfWork) {
			uow.Pause()
		}, false)

	case startCommand.FullCommand():
		commandAction(*startTargetArg, func(uow *UnitOfWork) {
			uow.Start()
		}, true)

	case stopCommand.FullCommand():
		commandAction(*stopTargetArg, func(uow *UnitOfWork) {
			uow.Stop()
		}, false)

	case killCommand.FullCommand():
		commandAction(*killTargetArg, func(uow *UnitOfWork) {
			uow.Kill()
		}, false)

	case execCommand.FullCommand():
		commandAction(*execTargetArg, func(uow *UnitOfWork) {
			uow.Exec(*execCmdArg)
		}, false)

	case rmCommand.FullCommand():
		commandAction(*rmTargetArg, func(uow *UnitOfWork) {
			uow.Rm(*forceRmFlag)
		}, false)

	case runCommand.FullCommand():
		commandAction(*runTargetArg, func(uow *UnitOfWork) {
			uow.Run(*runCmdArg)
		}, true)

	case createCommand.FullCommand():
		commandAction(*createTargetArg, func(uow *UnitOfWork) {
			uow.Create(*createCmdArg)
		}, true)

	case provisionCommand.FullCommand():
		commandAction(*provisionTargetArg, func(uow *UnitOfWork) {
			uow.Provision(*provisionNoCacheFlag, *provisionParallelFlag)
		}, false)

	case pullCommand.FullCommand():
		commandAction(*pullTargetArg, func(uow *UnitOfWork) {
			uow.PullImage()
		}, false)

	case logsCommand.FullCommand():
		commandAction(*logsTargetArg, func(uow *UnitOfWork) {
			uow.Logs(*followFlag, *timestampsFlag, *tailFlag, *colorizeFlag, *sinceFlag)
		}, false)

	case generateCommand.FullCommand():
		if len(*templateFlag) == 0 {
			printErrorf("ERROR: No template specified. The flag `--template` is required.\n")
			return
		}
		commandAction(*generateTargetArg, func(uow *UnitOfWork) {
			uow.Generate(*templateFlag, *outputFlag)
		}, false)

	case syncStartCommand.FullCommand():
		cfg = NewConfig(*configFlag, *prefixFlag, *tagFlag)
		sync := cfg.MacSync(*syncStartVolumeArg)
		if sync == nil {
			printErrorf("ERROR: No such sync configured: %s.", *syncStartVolumeArg)
			return
		}
		sync.Start()

	case syncStopCommand.FullCommand():
		cfg = NewConfig(*configFlag, *prefixFlag, *tagFlag)
		sync := cfg.MacSync(*syncStopVolumeArg)
		if sync == nil {
			printErrorf("ERROR: No such sync configured: %s.", *syncStartVolumeArg)
			return
		}
		sync.Stop()

	case syncStatusCommand.FullCommand():
		cfg = NewConfig(*configFlag, *prefixFlag, *tagFlag)
		w := new(tabwriter.Writer)
		w.Init(os.Stdout, 0, 8, 1, '\t', 0)
		fmt.Fprintln(w, "VOLUME\tCONTAINER\tSTATUS")
		for _, name := range cfg.MacSyncNames() {
			s := cfg.MacSync(name)
			status := "-"
			if s.Exists() {
				status = "stopped"
				if s.Running() {
					status = "running"
				}
			}
			fmt.Fprintf(w, "%s\n", s.Volume()+"\t"+s.ContainerName()+"\t"+status)
		}
		w.Flush()
	}
}
Пример #17
0
func handleCmd() {
	switch kingpin.MustParse(app.Parse(os.Args[1:])) {

	case liftCommand.FullCommand():
		commandAction(*liftTargetArg, func(uow *UnitOfWork) {
			uow.Lift(*liftCmdArg, excluded, *liftNoCacheFlag)
		}, true)

	case versionCommand.FullCommand():
		fmt.Println("v2.1.0")

	case graphCommand.FullCommand():
		commandAction(*graphTargetArg, func(uow *UnitOfWork) {
			cfg.DependencyGraph(excluded).DOT(os.Stdout, uow.Targeted().Reversed())
		}, false)

	case statsCommand.FullCommand():
		commandAction(*statsTargetArg, func(uow *UnitOfWork) {
			uow.Stats()
		}, false)

	case statusCommand.FullCommand():
		commandAction(*statusTargetArg, func(uow *UnitOfWork) {
			uow.Status(*noTruncFlag)
		}, false)

	case pushCommand.FullCommand():
		commandAction(*pushTargetArg, func(uow *UnitOfWork) {
			uow.Push()
		}, false)

	case unpauseCommand.FullCommand():
		commandAction(*unpauseTargetArg, func(uow *UnitOfWork) {
			uow.Unpause()
		}, false)

	case pauseCommand.FullCommand():
		commandAction(*pauseTargetArg, func(uow *UnitOfWork) {
			uow.Pause()
		}, false)

	case startCommand.FullCommand():
		commandAction(*startTargetArg, func(uow *UnitOfWork) {
			uow.Start()
		}, true)

	case stopCommand.FullCommand():
		commandAction(*stopTargetArg, func(uow *UnitOfWork) {
			uow.Stop()
		}, false)

	case killCommand.FullCommand():
		commandAction(*killTargetArg, func(uow *UnitOfWork) {
			uow.Kill()
		}, false)

	case execCommand.FullCommand():
		commandAction(*execTargetArg, func(uow *UnitOfWork) {
			uow.Exec(*execCmdArg)
		}, false)

	case rmCommand.FullCommand():
		commandAction(*rmTargetArg, func(uow *UnitOfWork) {
			uow.Rm(*forceRmFlag)
		}, false)

	case runCommand.FullCommand():
		commandAction(*runTargetArg, func(uow *UnitOfWork) {
			uow.Run(*runCmdArg, excluded)
		}, true)

	case createCommand.FullCommand():
		commandAction(*createTargetArg, func(uow *UnitOfWork) {
			uow.Create(*createCmdArg, excluded)
		}, true)

	case provisionCommand.FullCommand():
		commandAction(*provisionTargetArg, func(uow *UnitOfWork) {
			uow.Provision(*provisionNoCacheFlag)
		}, false)

	case pullCommand.FullCommand():
		commandAction(*pullTargetArg, func(uow *UnitOfWork) {
			uow.PullImage()
		}, false)

	case logsCommand.FullCommand():
		commandAction(*logsTargetArg, func(uow *UnitOfWork) {
			uow.Logs(*followFlag, *timestampsFlag, *tailFlag, *colorizeFlag, *sinceFlag)
		}, false)
	}
}
Пример #18
0
func main() {
	command := kingpin.MustParse(app.Parse(os.Args[1:]))
	runtime.GOMAXPROCS(*ncpu)

	switch command {
	case filterApp.FullCommand():
		filtercmd := cmdFilter{
			featureDB:   *filterFeatureDB,
			bamFile:     *filterBam,
			outFile:     *filterOut,
			maxDistance: *filterMaxDist,
			mapQ:        *filterMapQ,
		}
		filtercmd.run()
	case featApp.FullCommand():
		featcmd := cmdFeat{
			out: *featOut,
			dir: *featDir,
		}
		featcmd.run()
		break
	case readApp.FullCommand():
		readcmd := cmdRead{
			pileupFile: *pileupFile,
			dbfile:     *readOut,
			minCover:   *readMinCover,
			minDepth:   *readMinDepth,
			featureDB:  *readFeature,
		}
		readcmd.run()
		break
	case reportApp.FullCommand():
		var sizeDB int64 = 1 << 30
		numDB := 10
		featureDB, err := createNoLockEnv(*reportFeatureDB, numDB, sizeDB)
		for lmdb.IsMapFull(err) {
			sizeDB *= 2
			featureDB, err = createNoLockEnv(*reportFeatureDB, numDB, sizeDB)
		}
		raiseError(err)
		defer featureDB.Close()

		sizeDB = 1 << 30
		resultsDB, err := createNoLockEnv(*reportResultsDB, numDB, sizeDB)
		for lmdb.IsMapFull(err) {
			sizeDB *= 2
			resultsDB, err = createNoLockEnv(*reportResultsDB, numDB, sizeDB)
		}
		raiseError(err)
		defer resultsDB.Close()
		reportcmd := cmdReport{
			featureDB: featureDB,
			resultsDB: resultsDB,
			prefix:    *reportPrefix,
			maxl:      *reportMaxl,
		}
		reportcmd.run()
		break
	// case report2App.FullCommand():
	// 	featureDB := createNoLockEnv(*report2FeatureDB, 10, 0)
	// 	defer featureDB.Close()
	// 	resultsDB := createReadOnlyEnv(*report2ResultsDB, 10, 0)
	// 	defer resultsDB.Close()
	// 	reportcmd2 := cmdReport2{
	// 		featureDB: featureDB,
	// 		resultsDB: resultsDB,
	// 		prefix:    *report2Prefix,
	// 	}
	// 	reportcmd2.run()
	// 	break
	case covApp.FullCommand():
		crcmd := cmdCr{
			dbfile:        *covResultsDb,
			codonID:       *covGC,
			featureDbPath: *covFeatureDb,
			minDepth:      *covMinDepth,
		}
		crcmd.run()
		break
	case mergeApp.FullCommand():
		mergecmd := cmdMerge{
			sampleFile: *mergeSampleFile,
			dbiName:    *mergeDbiName,
			dbOut:      *mergeOutDb,
		}
		mergecmd.run()
		break
	}
}
Пример #19
0
Файл: cli.go Проект: bivas/crane
func runCli() {
	switch kingpin.MustParse(app.Parse(os.Args[1:])) {

	case liftCommand.FullCommand():
		commandAction(*liftTargetArg, func(uow *UnitOfWork) {
			uow.Lift(*liftCmdArg, *liftNoCacheFlag, *liftParallelFlag)
		}, true)

	case versionCommand.FullCommand():
		fmt.Println("v2.8.0")

	case statsCommand.FullCommand():
		commandAction(*statsTargetArg, func(uow *UnitOfWork) {
			uow.Stats()
		}, false)

	case statusCommand.FullCommand():
		commandAction(*statusTargetArg, func(uow *UnitOfWork) {
			uow.Status(*noTruncFlag)
		}, false)

	case pushCommand.FullCommand():
		commandAction(*pushTargetArg, func(uow *UnitOfWork) {
			uow.Push()
		}, false)

	case unpauseCommand.FullCommand():
		commandAction(*unpauseTargetArg, func(uow *UnitOfWork) {
			uow.Unpause()
		}, false)

	case pauseCommand.FullCommand():
		commandAction(*pauseTargetArg, func(uow *UnitOfWork) {
			uow.Pause()
		}, false)

	case startCommand.FullCommand():
		commandAction(*startTargetArg, func(uow *UnitOfWork) {
			uow.Start()
		}, true)

	case stopCommand.FullCommand():
		commandAction(*stopTargetArg, func(uow *UnitOfWork) {
			uow.Stop()
		}, false)

	case killCommand.FullCommand():
		commandAction(*killTargetArg, func(uow *UnitOfWork) {
			uow.Kill()
		}, false)

	case execCommand.FullCommand():
		commandAction(*execTargetArg, func(uow *UnitOfWork) {
			uow.Exec(*execCmdArg)
		}, false)

	case rmCommand.FullCommand():
		commandAction(*rmTargetArg, func(uow *UnitOfWork) {
			uow.Rm(*forceRmFlag)
		}, false)

	case runCommand.FullCommand():
		commandAction(*runTargetArg, func(uow *UnitOfWork) {
			uow.Run(*runCmdArg)
		}, true)

	case createCommand.FullCommand():
		commandAction(*createTargetArg, func(uow *UnitOfWork) {
			uow.Create(*createCmdArg)
		}, true)

	case provisionCommand.FullCommand():
		commandAction(*provisionTargetArg, func(uow *UnitOfWork) {
			uow.Provision(*provisionNoCacheFlag, *provisionParallelFlag)
		}, false)

	case pullCommand.FullCommand():
		commandAction(*pullTargetArg, func(uow *UnitOfWork) {
			uow.PullImage()
		}, false)

	case logsCommand.FullCommand():
		commandAction(*logsTargetArg, func(uow *UnitOfWork) {
			uow.Logs(*followFlag, *timestampsFlag, *tailFlag, *colorizeFlag, *sinceFlag)
		}, false)

	case generateCommand.FullCommand():
		if len(*templateFlag) == 0 {
			printErrorf("ERROR: No template specified. The flag `--template` is required.\n")
			return
		}
		commandAction(*generateTargetArg, func(uow *UnitOfWork) {
			uow.Generate(*templateFlag, *outputFlag)
		}, false)
	}
}
Пример #20
0
func main() {
	app.Writer(os.Stdout)
	app.Version(VV)
	app.HelpFlag.Short('h')
	app.VersionFlag.Short('v')
	command := kingpin.MustParse(app.Parse(os.Args[1:]))

	err := ReadConfig(*configFile, *account)
	if !strings.HasPrefix(command, "config") && !strings.HasPrefix(command, "update") {
		// Makes sure the config file structure is valid
		if err != nil {
			fatalError("%s: Error reading config file: %s\n", filepath.Base(os.Args[0]), err.Error())
		}

		// Make sure the config file auth token is valid. Check now so we don't have to
		// keep rechecking in code.
		_, err := Config.Account.Client15()
		if err != nil {
			fatalError("Authentication error: %s", err.Error())
		}
	}

	// Handle logging
	logLevel := log15.LvlInfo

	if *debug {
		log.Logger.SetHandler(
			log15.LvlFilterHandler(
				log15.LvlDebug,
				log15.StderrHandler))
		httpclient.DumpFormat = httpclient.Debug
		logLevel = log15.LvlDebug
	}
	handler := log15.LvlFilterHandler(logLevel, log15.StreamHandler(colorable.NewColorableStdout(), log15.TerminalFormat()))
	log15.Root().SetHandler(handler)

	if Config.GetBool("update.check") && !strings.HasPrefix(command, "update") {
		defer UpdateCheck(VV, os.Stderr)
	}

	switch command {
	case stShowCmd.FullCommand():
		href, err := paramToHref("server_templates", *stShowNameOrHref, 0)
		if err != nil {
			fatalError("%s", err.Error())
		}
		stShow(href)
	case stUploadCmd.FullCommand():
		files, err := walkPaths(*stUploadPaths)
		if err != nil {
			fatalError("%s\n", err.Error())
		}
		stUpload(files, *stUploadPrefix)
	case stDeleteCmd.FullCommand():
		files, err := walkPaths(*stDeletePaths)
		if err != nil {
			fatalError("%s\n", err.Error())
		}
		stDelete(files, *stDeletePrefix)
	case stDownloadCmd.FullCommand():
		href, err := paramToHref("server_templates", *stDownloadNameOrHref, 0)
		if err != nil {
			fatalError("%s", err.Error())
		}
		stDownload(href, *stDownloadTo, *stDownloadPublished, *stDownloadMciSettings, *stDownloadScriptPath)
	case stValidateCmd.FullCommand():
		files, err := walkPaths(*stValidatePaths)
		if err != nil {
			fatalError("%s\n", err.Error())
		}
		stValidate(files)
	case rightScriptShowCmd.FullCommand():
		href, err := paramToHref("right_scripts", *rightScriptShowNameOrHref, 0)
		if err != nil {
			fatalError("%s", err.Error())
		}
		rightScriptShow(href)
	case rightScriptUploadCmd.FullCommand():
		files, err := walkPaths(*rightScriptUploadPaths)
		if err != nil {
			fatalError("%s\n", err.Error())
		}
		rightScriptUpload(files, *rightScriptUploadForce, *rightScriptUploadPrefix)
	case rightScriptDeleteCmd.FullCommand():
		files, err := walkPaths(*rightScriptDeletePaths)
		if err != nil {
			fatalError("%s\n", err.Error())
		}
		rightScriptDelete(files, *rightScriptDeletePrefix)
	case rightScriptDownloadCmd.FullCommand():
		href, err := paramToHref("right_scripts", *rightScriptDownloadNameOrHref, 0)
		if err != nil {
			fatalError("%s", err.Error())
		}
		rightScriptDownload(href, *rightScriptDownloadTo)
	case rightScriptScaffoldCmd.FullCommand():
		files, err := walkPaths(*rightScriptScaffoldPaths)
		if err != nil {
			fatalError("%s\n", err.Error())
		}
		rightScriptScaffold(files, !*rightScriptScaffoldNoBackup, *rightScriptScaffoldForce)
	case rightScriptValidateCmd.FullCommand():
		files, err := walkPaths(*rightScriptValidatePaths)
		if err != nil {
			fatalError("%s\n", err.Error())
		}
		rightScriptValidate(files)
	case configAccountCmd.FullCommand():
		err := Config.SetAccount(*configAccountName, *configAccountDefault, os.Stdin, os.Stdout)
		if err != nil {
			fatalError("%s\n", err.Error())
		}
	case configShowCmd.FullCommand():
		err := Config.ShowConfiguration(os.Stdout)
		if err != nil {
			fatalError("%s\n", err.Error())
		}
	case updateListCmd.FullCommand():
		err := UpdateList(VV, os.Stdout)
		if err != nil {
			fatalError("%s\n", err.Error())
		}
	case updateApplyCmd.FullCommand():
		err := UpdateApply(VV, os.Stdout, *updateApplyMajorVersion, "")
		if err != nil {
			fatalError("%s\n", err.Error())
		}
	}
}
Пример #21
0
func main() {
	// Define the command-line structure using Kingpin
	var versionString = fmt.Sprintf("ceftools v%v.%v (C) 2015 Sten Linnarsson <http://linnarssonlab.org/>", ceftools.MajorVersion, ceftools.MinorVersion)

	var app = kingpin.New("cef", versionString)
	var app_bycol = app.Flag("bycol", "Apply command by columns instead of by rows").Short('c').Bool()
	var app_profile = app.Flag("profile", "Run with CPU profiling, output to the given file").String()

	var info = app.Command("info", "Show a summary of the file contents")
	var test = app.Command("test", "Perform an internal test")
	var transpose = app.Command("transpose", "Transpose rows and columns")
	var cmdimport = app.Command("import", "Import from a legacy format")
	var import_format = cmdimport.Flag("format", "The file format to expect ('strt')").Required().Short('f').String()

	var rename = app.Command("rename", "Rename attribute")
	var rename_attr = rename.Flag("attr", "The attribute to rename ('old=new')").Required().Short('c').String()

	var drop = app.Command("drop", "Remove attributes")
	var drop_attrs = drop.Flag("attrs", "Row attribute(s) to remove (case-sensitive, comma-separated)").Short('a').String()
	var drop_headers = drop.Flag("headers", "Headers to remove (case-sensitive, comma-separated)").Short('h').String()
	var drop_except = drop.Flag("except", "Keep the given attributes instead of dropping them ").Bool()

	var add = app.Command("add", "Add header or row attribute")
	var add_header = add.Flag("header", "Header to add, in the form 'name=value'").Short('h').String()
	var add_attr = add.Flag("attr", "Attribute to add, in the form 'name=value' (value can be '(row)')").Short('a').String()

	var cmdselect = app.Command("select", "Select rows that match criteria (and drop the rest)")
	var select_range = cmdselect.Flag("range", "Select a range of rows (like '10:90')").String()
	var select_where = cmdselect.Flag("where", "Select rows with specific value for attribute ('attr=value')").String()
	var select_except = cmdselect.Flag("except", "Invert selection").Bool()

	var rescale = app.Command("rescale", "Rescale values by rows")
	var rescale_method = rescale.Flag("method", "Method to use (log, tpm or rpkm)").Short('m').Required().Enum("log", "tpm", "rpkm")
	var rescale_length = rescale.Flag("length", "Indicate the name of the attribute that gives gene length (for RPKM)").String()

	var join = app.Command("join", "Join two files based on given attributes")
	var join_other = join.Flag("with", "The file to which the input should be joined").Required().String()
	var join_on = join.Flag("on", "The attributes on which to join, of form 'attr1=attr2'").Required().String()

	var sort = app.Command("sort", "Sort by row attribute or by specific column")
	var sort_by = sort.Flag("by", "The attribute or column ('column=value') to sort by").String()
	var sort_reverse = sort.Flag("reverse", "Sort in reverse order").Short('r').Bool()
	var sort_numerical = sort.Flag("numerical", "Numerical sort (default: alphabetical)").Short('n').Bool()
	var sort_spin = sort.Flag("spin", "Sort by SPIN").Bool()
	var sort_corrfile = sort.Flag("corrfile", "Optional filename where to write the sorted correlation matrix").String()

	var aggregate = app.Command("aggregate", "Calculate aggregate statistics per row")
	var aggregate_cv = aggregate.Flag("cv", "Calculate coefficient of variation (CV)").Bool()
	var aggregate_mean = aggregate.Flag("mean", "Calculate mean").Bool()
	var aggregate_stdev = aggregate.Flag("stdev", "Calculate standard deviation").Bool()
	var aggregate_max = aggregate.Flag("max", "Calculate max value").Bool()
	var aggregate_min = aggregate.Flag("min", "Calculate min value").Bool()
	var aggregate_noise = aggregate.Flag("noise", "Calculate noise (CV-vs-mean offset)").Required().Enum("std", "bands")

	var view = app.Command("view", "View the file content interactively")

	// Parse the command line
	var parsed, err = app.Parse(os.Args[1:])
	if err != nil {
		app.Usage(os.Stderr)
		return
	}

	if *app_profile != "" {
		f, err := os.Create(*app_profile)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()

	}

	// Handle the sub-commands
	switch kingpin.MustParse(parsed, nil) {
	case view.FullCommand():
		if err = ceftools.Viewer(*app_bycol); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return
	case aggregate.FullCommand():
		if err = ceftools.CmdAggregate(*aggregate_mean, *aggregate_cv, *aggregate_stdev, *aggregate_max, *aggregate_min, *aggregate_noise, *app_bycol); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return
	case rename.FullCommand():
		if err = ceftools.CmdRename(*rename_attr, *app_bycol); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return
	case add.FullCommand():
		if err = ceftools.CmdAdd(*add_attr, *add_header, *app_bycol); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return
	case sort.FullCommand():
		if *sort_spin {
			if err = ceftools.CmdSPIN(*sort_corrfile, *app_bycol); err != nil {
				fmt.Fprintln(os.Stderr, err)
			}
		} else {
			if err = ceftools.CmdSort(*sort_by, *sort_numerical, *sort_reverse, *app_bycol); err != nil {
				fmt.Fprintln(os.Stderr, err)
			}
		}
		return
	case join.FullCommand():
		if err = ceftools.CmdJoin(*join_other, *join_on, *app_bycol); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return
	case cmdimport.FullCommand():
		if *import_format == "strt" {
			if err = ceftools.CmdImportStrt(); err != nil {
				fmt.Fprintln(os.Stderr, err)
			}
		} else {
			fmt.Fprintln(os.Stderr, "Unknown format (only valid format is 'strt')")
		}
		return
	case cmdselect.FullCommand():
		if *select_range != "" {
			if *select_where != "" {
				fmt.Fprintln(os.Stderr, "Cannot select using --range and --where simultaneously (use a pipe)")
				return
			}
			temp := strings.Split(*select_range, ":")
			if len(temp) != 2 {
				fmt.Fprintln(os.Stderr, "Invalid range specification (should be like '1:10', ':20', or '100:')")
				return
			}
			from := 1
			if temp[0] != "" {
				from, err = strconv.Atoi(temp[0])
				if err != nil {
					fmt.Fprintln(os.Stderr, "Invalid range specification (should be like '1:10', ':20', or '100:')")
					return
				}
			}
			to := -1
			if temp[1] != "" {
				to, err = strconv.Atoi(temp[1])
				if err != nil {
					fmt.Fprintln(os.Stderr, "Invalid range specification (should be like '1:10', ':20', or '100:')")
					return
				}
			}
			if err := ceftools.CmdSelectRange(from, to, *app_bycol, *select_except); err != nil {
				fmt.Fprintln(os.Stderr, err.Error())
			}
			return
		}
		if *select_where != "" {
			if err := ceftools.CmdSelect(*select_where, *app_bycol, *select_except); err != nil {
				fmt.Fprintln(os.Stderr, err.Error())
			}
			return
		}
	case transpose.FullCommand():
		// Read the input
		var cef, err = ceftools.Read(os.Stdin, true)
		if err != nil {
			fmt.Fprintln(os.Stderr, err.Error())
			return
		}
		// Write the CEF file
		if err := ceftools.Write(cef, os.Stdout, false); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return
	case drop.FullCommand():
		if err = ceftools.CmdDrop(*drop_attrs, *drop_headers, *drop_except, *app_bycol); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return
	case rescale.FullCommand():
		if err = ceftools.CmdRescale(*rescale_method, *rescale_length, *app_bycol); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return

	// Perform test
	case test.FullCommand():
		var cef = new(ceftools.Cef)
		cef.Columns = 5
		cef.Rows = 10
		cef.Headers = make([]ceftools.Header, 2)
		cef.Headers[0].Name = "Tissue"
		cef.Headers[0].Value = "Amygdala"
		cef.Headers[1].Name = "Species"
		cef.Headers[1].Value = "Mouse"
		cef.ColumnAttributes = make([]ceftools.Attribute, 2)
		cef.ColumnAttributes[0].Name = "CellID"
		cef.ColumnAttributes[0].Values = []string{"A", "B", "C", "D", "E"}
		cef.ColumnAttributes[1].Name = "Well"
		cef.ColumnAttributes[1].Values = []string{"A01", "B03", "C09", "D12", "E21"}
		cef.RowAttributes = make([]ceftools.Attribute, 3)
		cef.RowAttributes[0].Name = "Gene"
		cef.RowAttributes[0].Values = []string{"Actb", "Gapdh", "Synpr", "Pou3f2", "Bdnf", "Ngf", "Sox11", "Olig1", "Olig2", "Foxj1"}
		cef.RowAttributes[1].Name = "Chromosome"
		cef.RowAttributes[1].Values = []string{"Chr0", "Chr1", "Chr2", "Chr3", "Chr4", "Chr5", "Chr6", "Chr7", "Chr8", "Chr9"}
		cef.RowAttributes[2].Name = "Length"
		cef.RowAttributes[2].Values = []string{"1200", "1300", "1400", "1700", "1920", "130", "800", "7800", "1100", "200"}
		cef.Matrix = make([]float32, 10*5)
		cef.Set(0, 0, 0)
		cef.Set(1, 0, 1)
		cef.Set(2, 0, 2)
		cef.Set(3, 0, 3)
		cef.Set(4, 0, 4)
		cef.Set(5, 0, 5)
		cef.Set(6, 0, 6)
		cef.Set(7, 0, 7)
		cef.Set(8, 0, 8)
		cef.Set(9, 0, 9)
		ceftools.Permute(cef, []int{0, 4, 2, 3, 1, 5, 6, 7, 8, 9}, []int{4, 3, 0, 1, 2})
		if err := ceftools.Write(cef, os.Stdout, false); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return

	// Show info
	case info.FullCommand():
		var cef, err = ceftools.Read(os.Stdin, *app_bycol)
		if err != nil {
			fmt.Fprintln(os.Stderr, err.Error())
			return
		}
		fmt.Fprintf(os.Stderr, "          Columns: %v\n", cef.Columns)
		fmt.Fprintf(os.Stderr, "             Rows: %v\n", cef.Rows)
		fmt.Fprintf(os.Stderr, "            Flags: %v\n", cef.Flags)
		fmt.Fprintln(os.Stderr, "          Headers:")
		for i := 0; i < len(cef.Headers); i++ {
			fmt.Fprint(os.Stderr, "                   ")
			fmt.Fprint(os.Stderr, cef.Headers[i].Name)
			fmt.Fprint(os.Stderr, " = ")
			fmt.Fprintf(os.Stderr, cef.Headers[i].Value)
			fmt.Fprint(os.Stderr, "\n")
		}
		fmt.Fprint(os.Stderr, "\n")
		fmt.Fprint(os.Stderr, "Column attributes: ")
		for i := 0; i < len(cef.ColumnAttributes); i++ {
			fmt.Fprint(os.Stderr, cef.ColumnAttributes[i].Name)
			if i != (len(cef.ColumnAttributes) - 1) {
				fmt.Fprint(os.Stderr, ", ")
			}
		}
		fmt.Fprint(os.Stderr, "\n")
		fmt.Fprint(os.Stderr, "   Row attributes: ")
		for i := 0; i < len(cef.RowAttributes); i++ {
			fmt.Fprint(os.Stderr, cef.RowAttributes[i].Name)
			if i != (len(cef.RowAttributes) - 1) {
				fmt.Fprint(os.Stderr, ", ")
			}
		}
		fmt.Fprintln(os.Stderr, "")
		return
	default:
		kingpin.Usage()
	}
}
Пример #22
0
func main() {
	// Parse flags and arguments.
	command := kingpin.MustParse(app.Parse(os.Args[1:]))

	// Profile CPU usage.
	if *profile != "" {
		cpuprofile := *profile + ".cpu"
		heapprofile := *profile + ".heap"
		f1 := createFile(cpuprofile)
		defer f1.Close()
		f2 := createFile(heapprofile)
		defer f2.Close()
		if *debug {
			log.Printf("Created CPU profile file: %s\nand Heap profile: %s\n", cpuprofile, heapprofile)
		}
		pprof.StartCPUProfile(f1)
		pprof.WriteHeapProfile(f2)
		defer pprof.StopCPUProfile()
	}

	switch command {
	case pileupApp.FullCommand():
		pileupCmd := cmdPileup{
			minBQ:     *pileupMinBQ,
			minMQ:     *pileupMinMQ,
			outFile:   *pileupOutFile,
			fastaFile: *pileupFastaFile,
			bamFile:   *pileupBamFile,
		}
		pileupCmd.Run()
		break
	case piApp.FullCommand():
		piCmd := cmdPi{
			outFile:      *piOutFile,
			minBQ:        *piMinBQ,
			pileupFile:   *piPileupFile,
			debug:        *debug,
			minCoverage:  *piMinCoverage,
			pileupFormat: *piFormat,
		}
		piCmd.regionStart = *piRegionStart
		piCmd.regionEnd = *piRegionEnd
		piCmd.Run()
		break
	case ctApp.FullCommand():
		runtime.GOMAXPROCS(*ncpu)
		ctCmd := cmdCt{
			codonTableID: *ctCondonTableID,
			maxl:         *ctMaxL,
			pos:          *ctPos,
			minCoverage:  *ctMinCoverage,
			regionStart:  *ctRegionStart,
			regionEnd:    *ctRegionEnd,
			chunckSize:   *ctChunckSize,
			pileupFile:   *ctPileupFile,
			fastaFile:    *ctFastaFile,
			gffFile:      *ctGffFile,
			outFile:      *ctOutFile,
			debug:        *debug,
		}
		ctCmd.Run()
		break
	case crApp.FullCommand():
		crCmd := cmdCr{
			codonTableID: *crCondonTableID,
			maxl:         *crMaxL,
			pos:          *crPos,
			minCoverage:  *crMinCoverage,
			regionStart:  *crRegionStart,
			regionEnd:    *crRegionEnd,
			chunckSize:   *crChunckSize,
			genomeDir:    *crGenomeDir,
			prefix:       *crPrefix,
		}
		crCmd.Run()
		break
	}
}
Пример #23
0
func main() {
	// Load htraced configuration
	cnf := common.LoadApplicationConfig()

	// Parse argv
	app := kingpin.New(os.Args[0], USAGE)
	app.Flag("Dmy.key", "Set configuration key 'my.key' to 'my.value'.  Replace 'my.key' "+
		"with any key you want to set.").Default("my.value").String()
	addr := app.Flag("addr", "Server address.").String()
	verbose = app.Flag("verbose", "Verbose.").Default("false").Bool()
	version := app.Command("version", "Print the version of this program.")
	serverInfo := app.Command("serverInfo", "Print information retrieved from an htraced server.")
	serverStats := app.Command("serverStats", "Print statistics retrieved from the htraced server.")
	serverStatsJson := serverStats.Flag("json", "Display statistics as raw JSON.").Default("false").Bool()
	findSpan := app.Command("findSpan", "Print information about a trace span with a given ID.")
	findSpanId := findSpan.Arg("id", "Span ID to find. Example: be305e54-4534-2110-a0b2-e06b9effe112").Required().String()
	findChildren := app.Command("findChildren", "Print out the span IDs that are children of a given span ID.")
	parentSpanId := findChildren.Arg("id", "Span ID to print children for. Example: be305e54-4534-2110-a0b2-e06b9effe112").
		Required().String()
	childLim := findChildren.Flag("lim", "Maximum number of child IDs to print.").Default("20").Int()
	loadFile := app.Command("loadFile", "Write whitespace-separated JSON spans from a file to the server.")
	loadFilePath := loadFile.Arg("path",
		"A file containing whitespace-separated span JSON.").Required().String()
	loadJson := app.Command("load", "Write JSON spans from the command-line to the server.")
	loadJsonArg := loadJson.Arg("json", "A JSON span to write to the server.").Required().String()
	dumpAll := app.Command("dumpAll", "Dump all spans from the htraced daemon.")
	dumpAllOutPath := dumpAll.Arg("path", "The path to dump the trace spans to.").Default("-").String()
	dumpAllLim := dumpAll.Flag("lim", "The number of spans to transfer from the server at once.").
		Default("100").Int()
	graph := app.Command("graph", "Visualize span JSON as a graph.")
	graphJsonFile := graph.Arg("input", "The JSON file to load").Required().String()
	graphDotFile := graph.Flag("output",
		"The path to write a GraphViz dotfile to.  This file can be used as input to "+
			"GraphViz, in order to generate a pretty picture.  See graphviz.org for more "+
			"information about generating pictures of graphs.").Default("-").String()
	query := app.Command("query", "Send a query to htraced.")
	queryLim := query.Flag("lim", "Maximum number of spans to retrieve.").Default("20").Int()
	queryArg := query.Arg("query", "The query string to send.  Query strings have the format "+
		"[TYPE] [OPERATOR] [CONST], joined by AND statements.").Required().String()
	rawQuery := app.Command("rawQuery", "Send a raw JSON query to htraced.")
	rawQueryArg := query.Arg("json", "The query JSON to send.").Required().String()
	cmd := kingpin.MustParse(app.Parse(os.Args[1:]))

	// Add the command-line settings into the configuration.
	if *addr != "" {
		cnf = cnf.Clone(conf.HTRACE_WEB_ADDRESS, *addr)
	}

	// Handle commands that don't require an HTrace client.
	switch cmd {
	case version.FullCommand():
		os.Exit(printVersion())
	case graph.FullCommand():
		err := jsonSpanFileToDotFile(*graphJsonFile, *graphDotFile)
		if err != nil {
			fmt.Printf("graphing error: %s\n", err.Error())
			os.Exit(EXIT_FAILURE)
		}
		os.Exit(EXIT_SUCCESS)
	}

	// Create HTrace client
	hcl, err := htrace.NewClient(cnf)
	if err != nil {
		fmt.Printf("Failed to create HTrace client: %s\n", err.Error())
		os.Exit(EXIT_FAILURE)
	}

	// Handle commands that require an HTrace client.
	switch cmd {
	case version.FullCommand():
		os.Exit(printVersion())
	case serverInfo.FullCommand():
		os.Exit(printServerInfo(hcl))
	case serverStats.FullCommand():
		if *serverStatsJson {
			os.Exit(printServerStatsJson(hcl))
		} else {
			os.Exit(printServerStats(hcl))
		}
	case findSpan.FullCommand():
		var id *common.SpanId
		id.FromString(*findSpanId)
		os.Exit(doFindSpan(hcl, *id))
	case findChildren.FullCommand():
		var id *common.SpanId
		id.FromString(*parentSpanId)
		os.Exit(doFindChildren(hcl, *id, *childLim))
	case loadJson.FullCommand():
		os.Exit(doLoadSpanJson(hcl, *loadJsonArg))
	case loadFile.FullCommand():
		os.Exit(doLoadSpanJsonFile(hcl, *loadFilePath))
	case dumpAll.FullCommand():
		err := doDumpAll(hcl, *dumpAllOutPath, *dumpAllLim)
		if err != nil {
			fmt.Printf("dumpAll error: %s\n", err.Error())
			os.Exit(EXIT_FAILURE)
		}
		os.Exit(EXIT_SUCCESS)
	case query.FullCommand():
		err := doQueryFromString(hcl, *queryArg, *queryLim)
		if err != nil {
			fmt.Printf("query error: %s\n", err.Error())
			os.Exit(EXIT_FAILURE)
		}
		os.Exit(EXIT_SUCCESS)
	case rawQuery.FullCommand():
		err := doRawQuery(hcl, *rawQueryArg)
		if err != nil {
			fmt.Printf("raw query error: %s\n", err.Error())
			os.Exit(EXIT_FAILURE)
		}
		os.Exit(EXIT_SUCCESS)
	}

	app.UsageErrorf(os.Stderr, "You must supply a command to run.")
}
Пример #24
0
func main() {
	app := kingpin.New("modular", "My modular application.")
	configureLsCommand(app)
	kingpin.MustParse(app.Parse(os.Args[1:]))
}
Пример #25
0
func main() {
	// Load the htraced configuration.
	// This also parses the -Dfoo=bar command line arguments and removes them
	// from os.Argv.
	cnf, cnfLog := conf.LoadApplicationConfig("htraced.")

	// Parse the remaining command-line arguments.
	app := kingpin.New(os.Args[0], USAGE)
	version := app.Command("version", "Print server version and exit.")
	cmd := kingpin.MustParse(app.Parse(os.Args[1:]))

	// Handle the "version" command-line argument.
	if cmd == version.FullCommand() {
		fmt.Printf("Running htraced %s [%s].\n", RELEASE_VERSION, GIT_VERSION)
		os.Exit(0)
	}

	// Open the HTTP port.
	// We want to do this first, before initializing the datastore or setting up
	// logging.  That way, if someone accidentally starts two daemons with the
	// same config file, the second invocation will exit with a "port in use"
	// error rather than potentially disrupting the first invocation.
	rstListener, listenErr := net.Listen("tcp", cnf.Get(conf.HTRACE_WEB_ADDRESS))
	if listenErr != nil {
		fmt.Fprintf(os.Stderr, "Error opening HTTP port: %s\n",
			listenErr.Error())
		os.Exit(1)
	}

	// Print out the startup banner and information about the daemon
	// configuration.
	lg := common.NewLogger("main", cnf)
	defer lg.Close()
	lg.Infof("*** Starting htraced %s [%s]***\n", RELEASE_VERSION, GIT_VERSION)
	scanner := bufio.NewScanner(cnfLog)
	for scanner.Scan() {
		lg.Infof(scanner.Text() + "\n")
	}
	common.InstallSignalHandlers(cnf)
	if runtime.GOMAXPROCS(0) == 1 {
		ncpu := runtime.NumCPU()
		runtime.GOMAXPROCS(ncpu)
		lg.Infof("setting GOMAXPROCS=%d\n", ncpu)
	} else {
		lg.Infof("GOMAXPROCS=%d\n", runtime.GOMAXPROCS(0))
	}
	lg.Infof("leveldb version=%d.%d\n",
		levigo.GetLevelDBMajorVersion(), levigo.GetLevelDBMinorVersion())

	// Initialize the datastore.
	store, err := CreateDataStore(cnf, nil)
	if err != nil {
		lg.Errorf("Error creating datastore: %s\n", err.Error())
		os.Exit(1)
	}
	var rsv *RestServer
	rsv, err = CreateRestServer(cnf, store, rstListener)
	if err != nil {
		lg.Errorf("Error creating REST server: %s\n", err.Error())
		os.Exit(1)
	}
	var hsv *HrpcServer
	if cnf.Get(conf.HTRACE_HRPC_ADDRESS) != "" {
		hsv, err = CreateHrpcServer(cnf, store, nil)
		if err != nil {
			lg.Errorf("Error creating HRPC server: %s\n", err.Error())
			os.Exit(1)
		}
	} else {
		lg.Infof("Not starting HRPC server because no value was given for %s.\n",
			conf.HTRACE_HRPC_ADDRESS)
	}
	naddr := cnf.Get(conf.HTRACE_STARTUP_NOTIFICATION_ADDRESS)
	if naddr != "" {
		notif := StartupNotification{
			HttpAddr:  rsv.Addr().String(),
			ProcessId: os.Getpid(),
		}
		if hsv != nil {
			notif.HrpcAddr = hsv.Addr().String()
		}
		err = sendStartupNotification(naddr, &notif)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to send startup notification: "+
				"%s\n", err.Error())
			os.Exit(1)
		}
	}
	for {
		time.Sleep(time.Duration(10) * time.Hour)
	}
}
Пример #26
0
func main() {
	var configFile, dataPath, assets, netHostname string
	var httpPort, netPort int

	var alias, repo, random, hash, node string

	app := kingpin.New("gitchain", "Gitchain daemon and command line interface")
	app.Flag("config", "configuration file").Short('c').ExistingFileVar(&configFile)
	app.Flag("data-path", "path to the data directory").Short('d').StringVar(&dataPath)
	app.Flag("development-mode-assets", "path to the assets (ui) directory, only for developmenty").ExistingDirVar(&assets)
	app.Flag("net-hostname", "Gitchain network hostname").StringVar(&netHostname)
	app.Flag("http-port", "HTTTP port to connect to or listen on").IntVar(&httpPort)
	app.Flag("net-port", "Network port to listen").IntVar(&netPort)

	keypairGenerate := app.Command("keypair-generate", "Generates a new keypair")
	keypairGenerate.Arg("alias", "Keypair name to save it under").Required().StringVar(&alias)

	keypairPrimary := app.Command("keypair-primary", "Sets or gets primary keypair")
	keypairPrimary.Arg("alias", "Keypair name to save it under").StringVar(&alias)

	app.Command("keypair-list", "Lists all keypairs")

	nameReservation := app.Command("name-reservation", "Submits a Name Reservation Transaction")
	nameReservation.Arg("alias", "Keypair name to save it under").Required().StringVar(&alias)
	nameReservation.Arg("name", "Repository name to reserve").Required().StringVar(&repo)

	nameAllocation := app.Command("name-allocation", "Submits a Name Allocation Transaction")
	nameAllocation.Arg("alias", "Keypair name to save it under").Required().StringVar(&alias)
	nameAllocation.Arg("name", "Repository name to allocate").Required().StringVar(&repo)
	nameAllocation.Arg("random", "Random number returned by the name-reservation command").Required().StringVar(&random)

	app.Command("repo-list", "Lists all repositories")

	block := app.Command("block", "Renders a block")
	block.Arg("block", "Block hash").Required().StringVar(&hash)

	app.Command("block-last", "Returns last block hash")

	transactions := app.Command("transactions", "Returns a list of transactions in a block")
	transactions.Arg("block", "Block hash").Required().StringVar(&hash)

	transaction := app.Command("transaction", "Renders a transaction")
	transaction.Arg("txn", "Transaction hash").Required().StringVar(&hash)

	app.Command("info", "Returns gitchain node information")

	join := app.Command("node-join", "Connect to another node")
	join.Arg("node", "Node address <host:port>").Required().StringVar(&node)

	command := kingpin.MustParse(app.Parse(os.Args[1:]))

	var cfg *config.T
	var err error

	cfg = config.Default()

	cfg.General.DataPath = dataPath
	if httpPort != 0 {
		cfg.API.HttpPort = httpPort
	}
	cfg.API.DevelopmentModeAssets = assets
	cfg.Network.Hostname = netHostname
	if netPort != 0 {
		cfg.Network.Port = netPort
	}

	if len(configFile) > 0 {
		err = config.ReadFile(configFile, cfg)
		if err != nil {
			log.Printf("Error read config file %s: %v", configFile, err) // don't use log15 here
			os.Exit(1)
		}
	}

	switch command {
	case "keypair-generate":
		var resp api.GeneratePrivateKeyReply
		err := jsonrpc(cfg, "KeyService.GeneratePrivateKey", &api.GeneratePrivateKeyArgs{Alias: alias}, &resp)
		if err != nil {
			fmt.Printf("Can't generate private key because of %v\n", err)
			os.Exit(1)
		}
		if resp.Success {
			fmt.Printf("Private key has been successfully generated with an alias of %s, the public address is %s\n", alias, resp.PublicKey)
		} else {
			fmt.Printf("Server can't generate the private key\n")
			os.Exit(1)
		}
	case "keypair-primary":
		if alias != "" {
			var resp api.SetMainKeyReply
			err := jsonrpc(cfg, "KeyService.SetMainKey", &api.SetMainKeyArgs{Alias: alias}, &resp)
			if err != nil {
				fmt.Printf("Can't set main private key to %s because of %v\n", alias, err)
				os.Exit(1)
			}
			if !resp.Success {
				fmt.Printf("Can't set main private key to %s (doesn't exist?)\n", alias)
				os.Exit(1)
			}
			fmt.Printf("Successfully set main private key to %s\n", alias)
		} else {
			var mainKeyResp api.GetMainKeyReply
			err = jsonrpc(cfg, "KeyService.GetMainKey", &api.GetMainKeyArgs{}, &mainKeyResp)
			if err != nil {
				fmt.Printf("Can't discover main private key because of %v\n", err)
				os.Exit(1)
			}
			fmt.Println(mainKeyResp.Alias)
		}
	case "keypair-list":
		var resp api.ListPrivateKeysReply
		err := jsonrpc(cfg, "KeyService.ListPrivateKeys", &api.ListPrivateKeysArgs{}, &resp)
		if err != nil {
			fmt.Printf("Can't list private keys because of %v\n", err)
			os.Exit(1)
		}
		var mainKeyResp api.GetMainKeyReply
		err = jsonrpc(cfg, "KeyService.GetMainKey", &api.GetMainKeyArgs{}, &mainKeyResp)
		if err != nil {
			fmt.Printf("Can't discover main private key because of %v\n", err)
			os.Exit(1)
		}
		for i := range resp.Aliases {
			fmt.Printf("%s %s\n", func() string {
				if resp.Aliases[i] == mainKeyResp.Alias {
					return "*"
				} else {
					return " "
				}
			}(), resp.Aliases[i])
		}
	case "name-reservation":
		var resp api.NameReservationReply
		err := jsonrpc(cfg, "NameService.NameReservation", &api.NameReservationArgs{Alias: alias, Name: repo}, &resp)
		if err != nil {
			fmt.Printf("Can't make a name reservation because of %v\n", err)
			os.Exit(1)
		}
		fmt.Printf("Name reservation for %s has been submitted (%s)\nRecord the above transaction hash and following random number for use during allocation: %s\n", repo, resp.Id, resp.Random)
	case "name-allocation":
		var resp api.NameAllocationReply
		err := jsonrpc(cfg, "NameService.NameAllocation", &api.NameAllocationArgs{Alias: alias, Name: repo, Random: random}, &resp)
		if err != nil {
			fmt.Printf("Can't make a name allocation because of %v\n", err)
			os.Exit(1)
		}
		fmt.Printf("Name allocation for %s has been submitted (%s)\n", repo, resp.Id)
	case "repo-list":
		var resp api.ListRepositoriesReply
		err := jsonrpc(cfg, "RepositoryService.ListRepositories", &api.ListRepositoriesArgs{}, &resp)
		if err != nil {
			fmt.Printf("Can't list repositories because of %v\n", err)
			os.Exit(1)
		}
		for i := range resp.Repositories {
			fmt.Printf("%s %s %s\n", resp.Repositories[i].Name, resp.Repositories[i].Status, resp.Repositories[i].NameAllocationTx)
		}
	case "block-last":
		var resp api.GetLastBlockReply
		err := jsonrpc(cfg, "BlockService.GetLastBlock", &api.GetLastBlockArgs{}, &resp)
		if err != nil {
			fmt.Printf("Can't get a block because of %v\n", err)
			os.Exit(1)
		}
		fmt.Printf("%s\n", resp.Hash)
	case "block":
		var resp api.GetBlockReply
		err := jsonrpc(cfg, "BlockService.GetBlock", &api.GetBlockArgs{Hash: hash}, &resp)
		if err != nil {
			fmt.Printf("Can't get a block because of %v\n", err)
			os.Exit(1)
		}
		fmt.Printf("Previous block hash: %v\nNext block hash: %v\nMerkle root hash: %v\nTimestamp: %v\nBits: %#x\nNonce: %v\nTransactions: %d\n",
			resp.PreviousBlockHash, resp.NextBlockHash, resp.MerkleRootHash,
			time.Unix(resp.Timestamp, 0).String(), resp.Bits, resp.Nonce, resp.NumTransactions)
	case "transactions":
		var resp api.BlockTransactionsReply
		err := jsonrpc(cfg, "BlockService.BlockTransactions", &api.BlockTransactionsArgs{Hash: hash}, &resp)
		if err != nil {
			fmt.Printf("Can't get a list of block transactions because of %v\n", err)
			os.Exit(1)
		}
		for i := range resp.Transactions {
			fmt.Println(resp.Transactions[i])
		}
	case "transaction":
		var resp api.GetTransactionReply
		err := jsonrpc(cfg, "TransactionService.GetTransaction", &api.GetTransactionArgs{Hash: hash}, &resp)
		if err != nil {
			fmt.Printf("Can't get a transaction because of %v\n", err)
			os.Exit(1)
		}
		fmt.Printf("Previous transaction hash: %v\nPublic key: %v\nNext public key: %v\nValid: %v\n%+v\n",
			resp.PreviousTransactionHash, resp.PublicKey, resp.NextPublicKey, resp.Valid,
			resp.Content)
	case "info":
		resp, err := http.Get(fmt.Sprintf("http://localhost:%d/info", cfg.API.HttpPort))
		if err != nil {
			fmt.Printf("Can't retrieve info because of %v\n", err)
			os.Exit(1)
		}
		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			fmt.Printf("Can't retrieve info because of %v\n", err)
			os.Exit(1)
		}
		fmt.Println(string(body))
	case "join":
		var resp api.JoinReply
		err := jsonrpc(cfg, "NetService.Join", &api.JoinArgs{Host: node}, &resp)
		if err != nil {
			fmt.Printf("Can't join because of %v\n", err)
			os.Exit(1)
		}
	default:
		srv := &context.T{Config: cfg}
		err := srv.Init()
		if err != nil {
			log.Printf("Error during server initialization: %v", err) // don't use log15 here
			os.Exit(1)
		}
		go netserver.Server(srv)
		go server.NameRegistrar(srv)
		go server.RepositoryServer(srv)
		go server.MiningFactory(srv)
		go server.TransactionListener(srv)
		httpserver.Server(srv)
	}
}