Ejemplo n.º 1
0
func main() {
	mrand.Seed(time.Now().UnixNano())
	errors := []error{
		flag.Set("logtostderr", "true"),
		flag.Set("logcolor", "true"),
	}
	for _, err := range errors {
		if err != nil {
			panic(err)
		}
	}
	lg.SetSrcHighlight("alkasir/cmd", "alkasir/pkg")
	lg.CopyStandardLogTo("info")
	flag.Parse()
	flagenv.Prefix = "ALKASIR_"
	flagenv.Parse()
	err := commandHandler(flag.Args())
	if err != nil {
		if err == errCommandNotFound {
			fmt.Println("")
			fmt.Println("Command index:")
			fmt.Println("")
			rootCommand.PrintHelp("alkasir-admin", 0)
			fmt.Println("")
			os.Exit(1)
		}
		lg.Fatal(err)
		os.Exit(1)
	}

}
Ejemplo n.º 2
0
func main() {
	// Parse flags from command-line
	flag.Parse()

	// Parser flags from config
	flagcfg.AddDefaults()
	flagcfg.Parse()

	// Parse flags from environment (using github.com/facebookgo/flagenv)
	flagenv.Prefix = "RANDFILES_"
	flagenv.Parse()

	if help {
		showHelp()
		return
	}

	// setup number of CPUs
	runtime.GOMAXPROCS(cpus)

	name, _ := os.Hostname()

	http.Handle("/", http.HandlerFunc(kubismus.ServeHTTP))

	kubismus.Setup("randfiles", "")
	kubismus.Note("Host Name", name)
	kubismus.Note("CPUs", fmt.Sprintf("%d of %d", runtime.GOMAXPROCS(0), runtime.NumCPU()))
	kubismus.Note("Delay", delay.String())
	kubismus.Note("Writer threads", fmt.Sprintf("%d", threads))
	kubismus.Note("File size", fmt.Sprintf("%d to %d bytes", minSize, maxSize))
	kubismus.Note("File extension", ext)
	kubismus.Define("Data", kubismus.COUNT, "Files/second")
	kubismus.Define("Data", kubismus.SUM, "Bytes/second")

	// switch to working dir
	if workingDir != "" {
		err := os.Chdir(workingDir)
		if err != nil {
			log.Fatal(err)
		}
	}
	wd, err := os.Getwd()
	if err == nil {
		kubismus.Note("Working Directory", wd)
	}

	rand.Seed(time.Now().UnixNano())
	for i := 0; i < threads; i++ {
		go writeFiles(minSize, maxSize, delay, ext)
	}
	go calcMetrics()

	log.Fatal(http.ListenAndServe(addr, nil))
}
Ejemplo n.º 3
0
func ExampleParse() {
	var raz string
	flag.StringVar(&raz, "raz-value", "bar", "set the raz")

	// override default flag value with value found in MY_RAZ_VALUE
	flagenv.Prefix = "my_"
	flagenv.Parse()

	// override value found in MY_RAZ_VALUE with command line flag value -raz-value=foo
	flag.Parse()
}
Ejemplo n.º 4
0
func main() {
	rand.Seed(time.Now().UnixNano())
	flag.Parse()
	flagenv.Prefix = "ALKASIR_"
	flagenv.Parse()
	err := central.Init()
	if err == nil {
		central.Run()
	}

}
Ejemplo n.º 5
0
func main() {
	var err error

	// flag vars
	var port int
	var mysqlHost, mysqlPort, mysqlUser, mysqlPass, mysqlDBname string
	var start, end string

	// defaults for start and end vars
	startDefault := fmt.Sprintf("%d-11-01", time.Now().Year())
	endDefault := fmt.Sprintf("%d-11-31", time.Now().Year())

	// get flags
	flag.IntVar(&port, "port", 9126, "port to run site")
	flag.StringVar(&start, "start-date", startDefault, "the start date to when querying the db")
	flag.StringVar(&end, "end-date", endDefault, "the end date to when querying the db")
	flag.StringVar(&mysqlHost, "mysql-host", "localhost", "mysql host")
	flag.StringVar(&mysqlPort, "mysql-port", "3306", "mysql port")
	flag.StringVar(&mysqlUser, "mysql-user", "root", "mysql root")
	flag.StringVar(&mysqlPass, "mysql-pass", "", "mysql pass")
	flag.StringVar(&mysqlDBname, "mysql-dbname", "countmyreps", "mysql dbname")
	flag.BoolVar(&Debug, "debug", false, "set flag for verbose logging")

	flagenv.Parse()
	flag.Parse()

	// validate flags
	StartDate, err = time.Parse("2006-01-02", start)
	if err != nil {
		log.Fatal(err)
	}
	EndDate, err = time.Parse("2006-01-02", end)
	if err != nil {
		log.Fatal(err)
	}

	db := SetupDB(mysqlUser, mysqlPass, mysqlHost, mysqlPort, mysqlDBname)

	log.Printf("starting on :%d", port)
	s := NewServer(db, port, SendGridEmailer{})

	if err := s.Serve(); err != nil {
		log.Println("Unexpected error serving: ", err.Error())
	}
}
Ejemplo n.º 6
0
func main() {
	var bindaddr = flag.String("bindaddr", "0.0.0.0:7245", "bind address")
	rand.Seed(time.Now().UnixNano())
	flag.Parse()
	flagenv.Prefix = "ALKASIR_WANIP_SERVER_"
	flagenv.Parse()
	lg.CopyStandardLogTo("INFO")
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		ipAddress, _, _ := net.SplitHostPort(r.RemoteAddr)
		fmt.Fprintf(w, "%s", ipAddress)
		if lg.V(5) {
			lg.Infof("returning %s", ipAddress)
		}
	})
	lg.Infof("Listening to http://%s", *bindaddr)
	err := http.ListenAndServe(*bindaddr, nil)
	if err != nil {
		lg.Fatal(err)
	}
}
Ejemplo n.º 7
0
func TestMain(m *testing.M) {
	// flag vars
	var mysqlHost, mysqlPort, mysqlUser, mysqlPass, mysqlDBname string
	var start, end string
	var overwriteDB, noTearDown bool

	// defaults for start and end vars
	monthStart := "2016-11-01"
	monthEnd := "2016-11-30"
	today := "2016-11-15"

	flag.IntVar(&Port, "port", 9126, "port of the running countmyreps instance")
	flag.StringVar(&start, "start-date", monthStart, "the start date to when querying the db")
	flag.StringVar(&end, "end-date", monthEnd, "the end date to when querying the db")
	flag.StringVar(&today, "today-date", today, "the date that we set the world to be for the tests")
	flag.StringVar(&mysqlHost, "mysql-host", "localhost", "mysql host")
	flag.StringVar(&mysqlPort, "mysql-port", "3306", "mysql port")
	flag.StringVar(&mysqlUser, "mysql-user", "root", "mysql root")
	flag.StringVar(&mysqlPass, "mysql-pass", "", "mysql pass")
	flag.StringVar(&mysqlDBname, "mysql-dbname", "countmyreps_test", "mysql dbname")
	flag.BoolVar(&overwriteDB, "overwrite-database", false, "allow overwriting database")
	flag.BoolVar(&noTearDown, "no-tear-down", false, "set to keep the data after the test run")
	flag.BoolVar(&Debug, "verbose", false, "Set flag to show debug logs")

	flagenv.Parse()
	flag.Parse()

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/", mysqlUser, mysqlPass, mysqlHost, mysqlPort)

	db := SetupDB(dsn, mysqlDBname, overwriteDB)
	err := Seed(db, monthStart, monthEnd, today)
	if err != nil {
		log.Fatalf("error seeding data: %v", err)
	}
	if !noTearDown {
		defer TearDownDB(db, mysqlDBname)
	}
	// TODO - start countmyreps
	os.Exit(m.Run())
}
Ejemplo n.º 8
0
func main() {
	rand.Seed(time.Now().UnixNano())

	var errors []error
	errors = append(errors,
		flag.Set("logtomemory", "true"),
	)

	// set more flag defaults if debug is not enabled
	if os.Getenv("ALKASIR_DEBUG") == "" {
		errors = append(errors,
			flag.Set("logtofile", "false"),
			flag.Set("v", "19"),
		)
	}
	for _, err := range errors {
		if err != nil {
			panic(err)
		}
	}

	flag.Parse()
	flagenv.Prefix = "ALKASIR_"
	flagenv.Parse()

	server.AddChecker(torpt.Check)
	server.AddChecker(shadowsocks.Check)

	if server.CheckServiceEnv() {
		torpt.SetConfigDir(client.ConfigPath("torpt"))
		server.RunService()
	} else if obfs4proxy.Check() {
		obfs4proxy.Run(obfs4proxy.Config{})
	} else {
		ui.Set(wm.New())
		client.SetUpgradeArtifact("alkasir-gui")
		client.Run()
	}
}
Ejemplo n.º 9
0
func main() {
	// Parse flags from command-line
	flag.Parse()

	// Parser flags from config
	flagcfg.AddDefaults()
	flagcfg.Parse()

	// Parse flags from environment (using github.com/facebookgo/flagenv)
	flagenv.Prefix = "WEBNULL_"
	flagenv.Parse()

	if help {
		showHelp()
		return
	}

	// setup number of CPUs
	runtime.GOMAXPROCS(cpus)

	name, _ := os.Hostname()

	http.Handle("/status/", http.StripPrefix("/status", http.HandlerFunc(kubismus.ServeHTTP)))
	http.Handle("/", kubismus.HttpRequestMetric("Requests", handleRequest()))
	http.HandleFunc("/media/", ServeHTTP)

	kubismus.Setup("/web/null", "/media/null.png")
	kubismus.Note("Host Name", name)
	kubismus.Note("CPUs", fmt.Sprintf("%d of %d", runtime.GOMAXPROCS(0), runtime.NumCPU()))
	kubismus.Define("Requests", kubismus.COUNT, "Requests/second")
	kubismus.Define("Requests", kubismus.SUM, "Bytes/second")

	go calcMetrics()

	log.Fatal(http.ListenAndServe(addr, nil))
}
Ejemplo n.º 10
0
func main() {
	// Parse flags from command-line
	flag.Parse()

	// Parser flags from config
	flagcfg.AddDefaults()
	flagcfg.Parse()

	// Parse flags from environment (using github.com/facebookgo/flagenv)
	flagenv.Prefix = "HURL_"
	flagenv.Parse()

	if help {
		showHelp()
		return
	}

	if version {
		showVersion()
		return
	}

	if flag.NArg() < 1 {
		fmt.Fprintf(os.Stderr, "Please provide a URL to fetch.\n")
		return
	}

	err := parseHeaders()
	if err != nil {
		log.Fatal(err)
	}
	// log.Printf("%#v", headers)

	// setup number of CPUs
	runtime.GOMAXPROCS(cpus)

	// setup cpu profiling if desired
	if cpuProfile != "" {
		f, err := os.Create(cpuProfile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer func() {
			log.Print("Writing CPU profile to ", cpuProfile)
			pprof.StopCPUProfile()
			f.Close()
		}()
	}

	// create HTTP transport and client
	transport = &http.Transport{DisableKeepAlives: noKeepAlive, MaxIdleConnsPerHost: conns, DisableCompression: noCompress, ResponseHeaderTimeout: timeout}
	client = &http.Client{Transport: transport, Timeout: timeout}

	// setup Kubismus
	kubismus.Setup("hURL", "/media/logo36.png")
	kubismus.Define("Sent", kubismus.COUNT, "HTTP Posts")
	kubismus.Define("Sent", kubismus.SUM, "Bytes Sent")
	kubismus.Define("Received", kubismus.SUM, "Bytes Received")
	kubismus.Define("Received100", kubismus.COUNT, "1xx Responses")
	kubismus.Define("Received200", kubismus.COUNT, "2xx Responses")
	kubismus.Define("Received300", kubismus.COUNT, "3xx Responses")
	kubismus.Define("Received400", kubismus.COUNT, "4xx Responses")
	kubismus.Define("Received500", kubismus.COUNT, "5xx Responses")
	kubismus.Define("Error", kubismus.COUNT, "Communication Errors")
	kubismus.Define("ResponseTime", kubismus.AVERAGE, "Average Time (s)")
	kubismus.Note("Concurrent Connections", strconv.Itoa(conns))
	kubismus.Note("HTTP Method", method)
	kubismus.Note("Timeout", timeout.String())
	kubismus.Note("Processors", fmt.Sprintf("%d of %d", runtime.GOMAXPROCS(0), runtime.NumCPU()))
	kubismus.Note("Data files", strings.Join(strings.Split(filesPat, ","), "\n"))
	kubismus.Note("URLs", strings.Join(flag.Args(), "\n"))
	kubismus.Note("Discard files", strconv.FormatBool(discard))
	http.Handle("/", http.HandlerFunc(kubismus.ServeHTTP))
	http.HandleFunc("/media/", ServeHTTP)

	// switch to working dir
	if workingDir != "" {
		err := os.Chdir(workingDir)
		if err != nil {
			log.Fatal(err)
		}
	}
	wd, err := os.Getwd()
	if err == nil {
		kubismus.Note("Working Directory", wd)
	}

	// setup the thread context
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// spawn a function that updates the number of goroutines shown in the status page
	go func() {
		done := ctx.Done()
		t := time.NewTicker(5 * time.Second)
		defer t.Stop()
		for {
			select {
			case <-done:
				return
			case <-t.C:
				kubismus.Note("Goroutines", fmt.Sprintf("%d", runtime.NumGoroutine()))
			}
		}
	}()

	// spawn the status web site
	go func() {
		log.Fatal(http.ListenAndServe(addr, nil))
	}()

	// handle kill signals
	go func() {
		// Set up channel on which to send signal notifications.
		// We must use a buffered channel or risk missing the signal
		// if we're not ready to receive when the signal is sent.
		c := make(chan os.Signal, 1)
		signal.Notify(c, os.Interrupt, os.Kill)

		// Block until a signal is received.
		s := <-c
		log.Print("Got signal ", s, ", canceling work")
		cancel()
	}()

	// Build pipeline
	var patList []string
	if filesPat != "" {
		patList = strings.Split(filesPat, ",")
	}
	ch1 := loopCount(ctx, loop)
	ch2 := loopUrls(ctx, method, flag.Args(), ch1)
	ch3 := loopFiles(ctx, patList, ch2)
	doHttp(ctx, conns, ch3)

	// write memory profile if configured
	if memProfile != "" {
		f, err := os.Create(memProfile)
		if err != nil {
			log.Print(err)
		} else {
			log.Print("Writing memory profile to ", memProfile)
			pprof.WriteHeapProfile(f)
			f.Close()
		}
	}
}
Ejemplo n.º 11
0
func main() {
	// Parse flags from command-line
	flag.Parse()

	// Parser flags from config
	flagcfg.AddDefaults()
	flagcfg.Parse()

	// Parse flags from environment (using github.com/facebookgo/flagenv)
	flagenv.Prefix = "AUTOHURL_"
	flagenv.Parse()

	if help {
		showHelp()
		return
	}

	if version {
		showVersion()
		return
	}

	// parse default headers - make sure they work
	var err error
	err = defaultCfg.ParseHeaders()
	if err != nil {
		log.Fatal(err)
	}
	// log.Printf("%#v", headers)

	// setup number of CPUs
	runtime.GOMAXPROCS(cpus)

	// setup cpu profiling if desired
	if cpuProfile != "" {
		f, err := os.Create(cpuProfile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer func() {
			log.Print("Writing CPU profile to ", cpuProfile)
			pprof.StopCPUProfile()
			f.Close()
		}()
	}

	// setup Kubismus
	kubismus.Setup("autohURL", "/media/logo36.png")
	kubismus.Note("Processors", fmt.Sprintf("%d of %d", runtime.GOMAXPROCS(0), runtime.NumCPU()))
	http.Handle("/", http.HandlerFunc(kubismus.ServeHTTP))
	http.HandleFunc("/media/", ServeHTTP)

	// switch to working dir
	if workingDir != "" {
		err := os.Chdir(workingDir)
		if err != nil {
			log.Fatal(err)
		}
	}
	wd, err := os.Getwd()
	if err == nil {
		kubismus.Note("Working Directory", wd)
	}

	// Print settings
	fmt.Printf("addr = \"%s\"\n", addr)
	fmt.Printf("cpu = %d\n", cpus)
	fmt.Printf("wd = \"%s\"\n", workingDir)
	fmt.Printf("cpuprofile = \"%s\"\n", cpuProfile)
	fmt.Printf("memprofile = \"%s\"\n", memProfile)
	fmt.Println()

	// Print default folder settings
	fmt.Printf("[folders.*]\n%s\n", defaultCfg.String())

	// read folders
	var cfg map[string]*FolderCfg
	cfg, err = readConfig(flagcfg.Filename())
	if err != nil {
		log.Fatal(err)
	}
	if len(cfg) == 0 {
		log.Fatal("No folders configured to watch")
	}
	// set up default settings
	for i, _ := range cfg {
		cfg[i].SetDefaults(&defaultCfg)
		err = cfg[i].ParseHeaders()
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("[folders.%s]\n%s\n", i, cfg[i].String())
		kubismus.Note("folders."+i, cfg[i].String())
		kubismus.Define(i+"_Errors", kubismus.COUNT, i+": Errors")
		kubismus.Define(i+"_Sent", kubismus.COUNT, i+": HTTP Posts")
		kubismus.Define(i+"_Sent", kubismus.SUM, i+": Bytes Sent")
		kubismus.Define(i+"_Received", kubismus.SUM, i+": Bytes Received")
		kubismus.Define(i+"_ResponseTime", kubismus.AVERAGE, i+": Average Time (s)")
	}

	// setup the thread context
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// spawn a function that updates the number of goroutines shown in the status page
	go func() {
		done := ctx.Done()
		t := time.NewTicker(5 * time.Second)
		defer t.Stop()
		for {
			select {
			case <-done:
				return
			case <-t.C:
				kubismus.Note("Goroutines", fmt.Sprintf("%d", runtime.NumGoroutine()))
			}
		}
	}()

	// handle kill signals
	go func() {
		// Set up channel on which to send signal notifications.
		// We must use a buffered channel or risk missing the signal
		// if we're not ready to receive when the signal is sent.
		c := make(chan os.Signal, 1)
		signal.Notify(c, os.Interrupt, os.Kill)

		// Block until a signal is received.
		s := <-c
		log.Print("Got signal ", s, ", canceling work")
		cancel()
	}()

	// Build pipeline
	for name, fldr := range cfg {
		ch1 := readDir(ctx, name, fldr)
		go doHttp(ctx, name, fldr, ch1)
	}

	// write memory profile if configured
	if memProfile != "" {
		defer func() {
			f, err := os.Create(memProfile)
			if err != nil {
				log.Print(err)
			} else {
				log.Print("Writing memory profile to ", memProfile)
				pprof.WriteHeapProfile(f)
				f.Close()
			}
		}()
	}

	// status web site
	log.Fatal(http.ListenAndServe(addr, nil))
}
Ejemplo n.º 12
0
func main() {
	configLocation := flag.String("config", "/etc/pmdns/config.toml", "config location (S3 location is acceptable)")
	httpAddr := flag.String("debug.http.addr", ":9191", "debug http server bind address")
	log.Printf("ignoring config location: %v", *configLocation)

	flagenv.Prefix = "PMDNS_"
	flagenv.Parse()

	statsLock := &sync.RWMutex{}
	stats := &DynamicIPStats{}
	expfn := expvar.Func(func() interface{} {
		statsLock.RLock()
		defer statsLock.RUnlock()
		_stats := *stats
		return &_stats
	})
	expvar.Publish("DynamicIPStats", expfn)

	if *httpAddr != "" {
		go http.ListenAndServe(*httpAddr, nil)
	}

	disco := &ifconfigme.Service{
		HTTPClient: &http.Client{
			Transport: &http.Transport{
				Dial: (&net.Dialer{
					Timeout: 5 * time.Second,
				}).Dial,
			},
			Timeout: 10 * time.Second,
		},
	}
	registry := &dreamhostregistry.Registry{
		APIKey:      os.Getenv("DREAMHOST_API_KEY"),
		APIEndpoint: os.Getenv("DREAMHOST_API_ENDPOINT"),
		RecordName:  os.Getenv("DREAMHOST_RECORD_NAME"),
		HTTPClient: &http.Client{
			Transport: &http.Transport{
				Dial: (&net.Dialer{
					Timeout: 5 * time.Second,
				}).Dial,
			},
			Timeout: 10 * time.Second,
		},
	}

	sig := make(chan os.Signal, 1)
	signal.Notify(sig, os.Interrupt, syscall.SIGTERM)

	ctxRoot := context.Background()
	ctxRoot, killAll := context.WithCancel(ctxRoot)
	defer killAll()

	opt := NewDynamicIPOptions()
	opt.Context = ctxRoot
	opt.PollInterval = 30 * time.Second
	m := NewDynamicIPManager(disco, registry, opt)

	go func() {
		tick := time.NewTicker(731 * time.Millisecond)
		for {
			select {
			case <-ctxRoot.Done():
				tick.Stop()
				return
			case <-tick.C:
				_stats := m.Stats()
				statsLock.Lock()
				stats = _stats
				statsLock.Unlock()
			}
		}
	}()

	terminating := false
	for {
		select {
		case <-m.Wait():
			log.Panicf("pipeline terminated normally -- show me the stacks")
		case s := <-sig:
			if s == syscall.SIGTERM {
				log.Panicf("%s signal received", s)
			}
			if terminating {
				log.Panicf("%s signal received -- forcefully shutting down", s)
			}
			log.Printf("%s signal received -- attempting graceful shut down", s)
			terminating = true
			go killAll()
		}
	}
}
Ejemplo n.º 13
0
func TestGlobalParse(t *testing.T) {
	flagenv.Parse()
}
Ejemplo n.º 14
0
// program start
func main() {
	var err error

	sconf := service.Config{
		Name:        "BabelPoxy",
		DisplayName: "Babel Proxy",
		Description: "babelproxy converts RESTful calls into Babel calls.",
	}

	// Parse flags from command-line
	flag.Parse()

	// Parser flags from config
	flagcfg.AddDefaults()
	flagcfg.Parse()

	// Parse flags from environment (using github.com/facebookgo/flagenv)
	flagenv.Prefix = "BABELPROXY_"
	flagenv.Parse()

	// show help if asked
	if help {
		fmt.Fprintln(os.Stderr, `Usage of babelproxy:
  babelproxy [options] <filepatterns>

"For the faasti RESTafarians! (Feel no way, we maas.)"

Example:
  babelproxy *.babel

Options include:`)
		flag.PrintDefaults()
		fmt.Fprintln(os.Stderr, `
All of the options can be overridden in the configuration file. To override
the location of the configuration file, set the BABELPROXY_CONFIG environment
variable. When running as a service, all options must be specified in the
configuration file or environment variables.`)
		return
	}

	// show version if asked
	if ver {
		fmt.Printf("babelproxy Version %s\n", BABELPROXY_VERSION)
		return
	}

	// default the pubaddr
	if strings.TrimSpace(conf.PubAddr) == "" {
		conf.PubAddr = conf.RestAddr
	}

	// handle kill signals
	go func() {
		// setup cpu profiling if desired
		var f io.WriteCloser
		var err error
		if conf.CpuProfile != "" {
			f, err = os.Create(conf.CpuProfile)
			if err != nil {
				log.Fatal(err)
			}
			pprof.StartCPUProfile(f)
		}

		// Set up channel on which to send signal notifications.
		// We must use a buffered channel or risk missing the signal
		// if we're not ready to receive when the signal is sent.
		c := make(chan os.Signal, 1)
		signal.Notify(c, os.Interrupt, os.Kill)

		// Block until a signal is received.
		s := <-c
		log.Print("Got signal ", s, ", canceling work")

		if conf.CpuProfile != "" {
			log.Print("Writing CPU profile to ", conf.CpuProfile)
			pprof.StopCPUProfile()
			f.Close()
		}

		// write memory profile if configured
		if conf.MemProfile != "" {
			f, err := os.Create(conf.MemProfile)
			if err != nil {
				log.Print(err)
			} else {
				log.Print("Writing memory profile to ", conf.MemProfile)
				pprof.WriteHeapProfile(f)
				f.Close()
			}
		}
		os.Exit(0)
	}()

	// setup number of CPUs
	runtime.GOMAXPROCS(conf.Cpus)

	// set working directory
	if conf.WorkingDir != "" {
		err = os.Chdir(conf.WorkingDir)
		if err != nil {
			log.Fatal(err)
		}
	}

	// override configured arguments (file list) with command line
	if flag.NArg() > 0 {
		conf.Args = flag.Args()
	}

	var i svcImpl
	svcBroxy, err = service.New(&i, &sconf)
	if err != nil {
		log.Fatal(err)
	}
	/*
		svcLogger, err = svcBroxy.Logger(nil)
		if err != nil {
			log.Fatal(err)
		}
	*/
	if control != "" {
		err = service.Control(svcBroxy, control)
		if err != nil {
			log.Fatal(err)
		}
		return
	}

	if service.Interactive() {
		i.doWork()
	} else {
		err = svcBroxy.Run()
		if err != nil {
			//svcLogger.Error(err.Error())
			log.Println(err)
		}
	}
}
Ejemplo n.º 15
0
func init() {
	const (
		name        = "HashSrv"
		displayName = "HashSrv"
		desc        = "HashSrv is a service for hashing, compressing, encrypting, and encoding things."
	)

	var help bool
	var ver bool
	var noisy bool
	var svcInstall bool
	var svcRemove bool
	var svcStart bool
	var svcStop bool

	flag.BoolVar(&noisy, "noisy", false, "Enable logging")
	flag.BoolVar(&help, "help", false, "Show command help")
	flag.BoolVar(&ver, "version", false, "Show version")
	flag.StringVar(&cpuprofile, "cpuprofile", "", "Write CPU profile to file")
	flag.StringVar(&memprofile, "memprofile", "", "Write memory profile to file")
	flag.BoolVar(&svcInstall, "install", false, "Install HashSrv as a service")
	flag.BoolVar(&svcRemove, "remove", false, "Remove the HashSrv service")
	flag.BoolVar(&svcRun, "run", false, "Run HashSrv standalone (not as a service)")
	flag.BoolVar(&svcStart, "start", false, "Start the HashSrv service")
	flag.BoolVar(&svcStop, "stop", false, "Stop the HashSrv service")
	flag.StringVar(&hostAddr, "addr", ":9009", "Address to host the service on")
	flag.Parse()
	flagcfg.AddDefaults()
	flagcfg.Parse()
	flagenv.Prefix = "HASHSRV_"
	flagenv.Parse()

	if help {
		usage()
		os.Exit(0)
	}

	if ver {
		fmt.Printf("HashSrv Version %s\n", HASHSRV_VERSION)
		os.Exit(0)
	}

	var err error
	var i impl
	wsHashSrv, err = service.New(i, &service.Config{Name: name, DisplayName: displayName, Description: desc})
	if err != nil {
		log.Fatal(err)
	}
	wsLogger, err = wsHashSrv.Logger(nil)
	if err != nil {
		log.Fatal(err)
	}

	if svcInstall == true && svcRemove == true {
		log.Fatalln("Options -install and -remove cannot be used together.")
	} else if svcInstall == true {
		err = wsHashSrv.Install()
		if err != nil {
			log.Fatal(err)
		}
		log.Printf("Service \"%s\" installed.\n", displayName)
		os.Exit(0)
	} else if svcRemove == true {
		err = wsHashSrv.Uninstall()
		if err != nil {
			log.Fatal(err)
		}
		log.Printf("Service \"%s\" removed.\n", displayName)
		os.Exit(0)
	} else if svcStart == true {
		err = wsHashSrv.Start()
		if err != nil {
			log.Fatal(err)
		}
		log.Printf("Service \"%s\" started.\n", displayName)
		os.Exit(0)
	} else if svcStop == true {
		err = wsHashSrv.Stop()
		if err != nil {
			log.Fatal(err)
		}
		log.Printf("Service \"%s\" stopped.\n", displayName)
		os.Exit(0)
	}

	if noisy == false {
		log.SetOutput(ioutil.Discard)
	}
}