Ejemplo n.º 1
0
func main() {
	controlFlag := flag.String("control", "", "{install|uninstall|start|stop}")
	flag.Parse()
	conf := &service.Config{
		Name:        "shuthelper_server",
		DisplayName: "shuthelper server service",
		Description: "remote host shutdown helper service ...",
	}

	p := &program{}

	s, err := service.New(p, conf)
	if err != nil {
		panic(err)
	}

	logger, err = s.Logger(nil)
	if err != nil {
		panic(err)
	}

	if !strings.EqualFold(*controlFlag, "") {
		err = service.Control(s, *controlFlag)
		if err != nil {
			panic(err)
		}
		return
	}

	s.Run()
}
Ejemplo n.º 2
0
func main() {
	svcConfig := &service.Config{
		Name:        "GoServiceExampleStopPause",
		DisplayName: "Go Service Example: Stop Pause",
		Description: "This is an example Go service that pauses on stop.",
	}

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}
	if len(os.Args) > 1 {
		err = service.Control(s, os.Args[1])
		if err != nil {
			log.Fatal(err)
		}
		return
	}

	logger, err = s.Logger(nil)
	if err != nil {
		log.Fatal(err)
	}
	err = s.Run()
	if err != nil {
		logger.Error(err)
	}
}
Ejemplo n.º 3
0
func main() {
	svcConfig := &service.Config{
		Name:        "KnowledgeDB",
		DisplayName: "Knowledge DB",
		Description: "Knowledge DB - Webserver",
	}

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}

	logger, err := s.Logger(nil)
	if err != nil {
		log.Fatal(err)
	}
	log.SetServiceLogger(logger)

	if len(os.Args) == 2 {
		command := os.Args[1]
		err := service.Control(s, command)
		if err != nil {
			log.Fatalf("%v\n\nValidOperations: %v", err, service.ControlAction)
		}
		return
	}
	err = s.Run()
	if err != nil {
		log.Error(err)
	}
}
Ejemplo n.º 4
0
func main() {
	svcConfig := &service.Config{
		Name:        "ArduinoCreateBridge",
		DisplayName: "Arduino Create Bridge",
		Description: "A bridge that allows Arduino Create to operate on the boards connected to the computer",
	}

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}
	if len(os.Args) > 1 {
		err = service.Control(s, os.Args[1])
		if err != nil {
			log.Fatal(err)
		}
		return
	}

	logger, err = s.Logger(nil)
	if err != nil {
		log.Fatal(err)
	}

	err = s.Install()
	if err != nil {
		logger.Error(err)
	}

	err = s.Run()
	if err != nil {
		logger.Error(err)
	}
}
Ejemplo n.º 5
0
func main() {
	settings.Init()
	flag.Parse()

	if len(os.Args) == 1 {
		flag.Usage()
		return
	}

	if flag.Lookup("run") == nil && flag.Lookup("svcctl") == nil && flag.Lookup("help") == nil && flag.Lookup("console") == nil {
		flag.Usage()
		return
	}

	if *help {
		flag.Usage()
		return
	}

	LogFile, err := os.OpenFile(settings.Log.File, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0777)
	if err != nil {
		fmt.Println(err)
		return
	}

	p := &Program{
		Logger: log.New(LogFile, "[filesync]", log.Ldefault|log.Lmicroseconds),
	}

	s, err := svc.New(p, &svc.Config{
		Name:        "Filesync",
		DisplayName: "FileSync Service",
		Description: "Filesync is a simple tool to sync files between multiple directory pairs.",
		Arguments:   []string{"-run"},
	})

	if err != nil {
		fmt.Println(err.Error())
		return
	}

	if *run {
		if *console {
			p.Logger = log.New(os.Stdout, "[filesync]", log.Ldefault|log.Lmicroseconds)
			p.run()
			return
		}
		err := s.Run()
		fmt.Println("run with error: ", err)
		return
	}

	Actions := strings.Split(*controls, ",")
	for _, action := range Actions {
		err := svc.Control(s, action)
		fmt.Println(err)
	}

}
Ejemplo n.º 6
0
func main() {
	svcFlag := flag.String("service", "", "Control the system service.")
	flag.Parse()

	configPath, err := getConfigPath()
	if err != nil {
		log.Fatal(err)
	}
	config, err := getConfig(configPath)
	if err != nil {
		log.Fatal(err)
	}

	svcConfig := &service.Config{
		Name:        config.Name,
		DisplayName: config.DisplayName,
		Description: config.Description,
	}

	prg := &program{
		exit: make(chan struct{}),

		Config: config,
	}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}
	prg.service = s

	errs := make(chan error, 5)
	logger, err = s.Logger(errs)
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		for {
			err := <-errs
			if err != nil {
				log.Print(err)
			}
		}
	}()

	if len(*svcFlag) != 0 {
		err := service.Control(s, *svcFlag)
		if err != nil {
			log.Printf("Valid actions: %q\n", service.ControlAction)
			log.Fatal(err)
		}
		return
	}
	err = s.Run()
	if err != nil {
		logger.Error(err)
	}
}
Ejemplo n.º 7
0
Archivo: main.go Proyecto: vsdutka/ipdf
// Service setup.
//   Define service config.
//   Create the service.
//   Setup the logger.
//   Handle service controls (optional).
//   Run the service.
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	flag.Usage = usage
	svcFlag = flag.String("service", "", fmt.Sprintf("Control the system service. Valid actions: %q\n", service.ControlAction))
	portFlag = flag.Int("port", 17000, "    Port number")
	flag.Parse()

	if *portFlag == 0 {
		usage()
		os.Exit(2)
	}

	svcConfig := &service.Config{
		Name:        serviceName(),
		DisplayName: serviceDisplayName(),
		Description: serviceDisplayName(),
		Arguments:   []string{fmt.Sprintf("-port=%d", *portFlag)},
	}

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}
	errs := make(chan error, 5)
	func() {
		loggerLock.Lock()
		defer loggerLock.Unlock()
		logger, err = s.Logger(errs)
		if err != nil {
			log.Fatal(err)
		}
	}()

	go func() {
		for {
			err := <-errs
			if err != nil {
				log.Print(err)
			}
		}
	}()

	if len(*svcFlag) != 0 {
		err := service.Control(s, *svcFlag)
		if err != nil {
			log.Printf("Valid actions: %q\n", service.ControlAction)
			log.Fatal(err)
		}
		return
	}
	err = s.Run()
	if err != nil {
		logError(err)
	}
}
Ejemplo n.º 8
0
// Service setup.
//   Define service config.
//   Create the service.
//   Setup the logger.
//   Handle service controls (optional).
//   Run the service.
func main() {

	svcFlag := flag.String("service", "", "Control the system service.")
	flag.Parse()

	if !service.Interactive() {
		root, _ := osext.ExecutableFolder()

		f, err := os.OpenFile(root+"/output.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			log.Fatal(err)
		}
		defer f.Close()
		log.SetOutput(f)
	}

	svcConfig := &service.Config{
		Name:        "FPL Checker",
		DisplayName: "FPL Checker",
		Description: "Free Post Code Lottery daily winner checker",
	}

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}
	errs := make(chan error, 5)
	logger, err = s.Logger(errs)
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		for {
			err := <-errs
			if err != nil {
				log.Print(err)
			}
		}
	}()

	if len(*svcFlag) != 0 {
		err := service.Control(s, *svcFlag)
		if err != nil {
			log.Printf("Valid actions: %q\n", service.ControlAction)
			log.Fatal(err)
		}
		return
	}
	err = s.Run()
	if err != nil {
		logger.Error(err)
	}
}
Ejemplo n.º 9
0
func main() {
	usageHelpMessage := `You must set the config, e.g. BarcodeQueryTool.exe -config="config.json"`

	// Get flags
	svcFlag := flag.String("service", "", "Control the system service.")
	mainconfig := flag.String("config", "", usageHelpMessage)
	flag.Parse()

	svcConfig := &service.Config{
		Name:        "Barcode Query Tool",
		DisplayName: "BarcodeQueryTool",
		Description: "Back-end for BarcodeQueryTool in Siemens WinCC",
		Arguments:   []string{"-config=" + *mainconfig},
	}
	newApp := &app{}
	s, err := service.New(newApp, svcConfig)
	if err != nil {
		log.Fatal(err)
	}

	if *svcFlag != "" {
		err = service.Control(s, *svcFlag)
		if err != nil {
			log.Printf("Valid actions: %q\n", service.ControlAction)
			log.Fatal(err)
		}
		return
	}

	newApp.execPath, err = osext.ExecutableFolder()
	if err != nil {
		log.Fatalf("Error finding program executable path: %v", err)
	}

	// Load config
	if *mainconfig == "" {
		log.Fatal(usageHelpMessage)
	}
	newApp.conf = &api.AppConfig{}
	err = newApp.conf.LoadFromFile(newApp.execPath + "\\" + *mainconfig)
	if err != nil {
		log.Fatalf("Error loading %v: %v", *mainconfig, err)
	}

	err = s.Run()
	if err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 10
0
func main() {
	if commandLineSetup() {
		return
	}

	// setup system service
	serviceConfig := &service.Config{
		Name:        daemon.Daemon.Name,
		DisplayName: daemon.Daemon.DisplayName,
		Description: daemon.Daemon.Description,
	}

	supervisor := daemon.Daemon.NewSupervisor()
	s, err := service.New(supervisor, serviceConfig)
	if err != nil {
		log.Fatalf("Operating system is not supported: %s", err)
	}
	supervisor.BindToService(s)

	if len(*serviceParam) != 0 {
		err := service.Control(s, *serviceParam)
		if err != nil {
			log.Info("Valid service actions:\n", service.ControlAction)
			log.Fatal(err)
		}
		return
	}

	// initialize application context
	context := context.NewContext()
	err = context.LoadConfig(configurationFile)
	if err != nil {
		log.Fatal("Loading configuration file failed.")
	}
	if cfgfile.ValidateConfig() {
		log.Info("Config OK")
		return
	}

	backendSetup(context)

	// start main loop
	services.StartPeriodicals(context)
	err = s.Run()
	if err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 11
0
func main() {
	svcFlag := flag.String("service", "", "Control the system service.")
	flag.Parse()

	svcConfig := &service.Config{
		Name:        "GoPrintServer",
		DisplayName: "Go Print Server",
		Description: "Expose printer control as WebSocket server.",
	}

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}
	logger, err = s.Logger(nil)
	if err != nil {
		log.Fatal(err)
	}
	errs := make(chan error, 5)
	logger, err = s.Logger(errs)
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		for {
			err := <-errs
			if err != nil {
				log.Print(err)
			}
		}
	}()

	if len(*svcFlag) != 0 {
		err := service.Control(s, *svcFlag)
		if err != nil {
			log.Printf("Valid actions: %q\n", service.ControlAction)
			log.Fatal(err)
		}
		return
	}
	err = s.Run()
	if err != nil {
		logger.Error(err)
	}
}
Ejemplo n.º 12
0
// Service setup.
//   Define service config.
//   Create the service.
//   Setup the logger.
//   Handle service controls (optional).
//   Run the service.
func main() {
	svcFlag := flag.String("service", "", "Control the system service.")
	flag.Parse()

	svcConfig := &service.Config{
		Name:        "gtdworker",
		DisplayName: "Getting Things Done",
		Description: "Worker Service to get things done.",
	}

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}
	errs := make(chan error, 5)
	logger, err = s.Logger(errs)
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		for {
			err := <-errs
			if err != nil {
				log.Print(err)
			}
		}
	}()

	if len(*svcFlag) != 0 {
		err := service.Control(s, *svcFlag)
		if err != nil {
			log.Printf("Valid actions: %q\n", service.ControlAction)
			log.Fatal(err)
		}
		return
	}

	err = s.Run()
	if err != nil {
		logger.Error(err)
	}
}
Ejemplo n.º 13
0
// Service setup.
//   Define service config.
//   Create the service.
//   Setup the logger.
//   Handle service controls (optional).
//   Run the service.
func main() {
	svcFlag := flag.String("service", "", "Control the system service.")
	flag.Parse()

	svcConfig := &service.Config{
		Name:        "GoServiceExampleLogging",
		DisplayName: "Go Service Example for Logging",
		Description: "This is an example Go service that outputs log messages.",
	}

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}
	errs := make(chan error, 5)
	logger, err = s.Logger(errs)
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		for {
			err := <-errs
			if err != nil {
				log.Print(err)
			}
		}
	}()

	if len(*svcFlag) != 0 {
		err := service.Control(s, *svcFlag)
		if err != nil {
			log.Printf("Valid actions: %q\n", service.ControlAction)
			log.Fatal(err)
		}
		return
	}
	err = s.Run()
	if err != nil {
		logger.Error(err)
	}
}
Ejemplo n.º 14
0
func main() {
	if runtime.GOOS == "windows" {
		svcConfig = &service.Config{
			Name:        "telegraf",
			DisplayName: "Telegraf Data Collector Service",
			Description: "Collects data using a series of plugins and publishes it to" +
				"another series of plugins.",
			Arguments: []string{"-config", "C:\\Program Files\\Telegraf\\telegraf.conf"},
		}

		prg := &program{}
		s, err := service.New(prg, svcConfig)
		if err != nil {
			log.Fatal(err)
		}
		logger, err = s.Logger(nil)
		if err != nil {
			log.Fatal(err)
		}
		// Handle the -service flag here to prevent any issues with tooling that may not have an interactive
		// session, e.g. installing from Ansible
		flag.Parse()
		if *fService != "" {
			if *fConfig != "" {
				(*svcConfig).Arguments = []string{"-config", *fConfig}
			}
			err := service.Control(s, *fService)
			if err != nil {
				log.Fatal(err)
			}
		} else {
			err = s.Run()
			if err != nil {
				logger.Error(err)
			}
		}
	} else {
		stop = make(chan struct{})
		reloadLoop(stop, nil)
	}
}
Ejemplo n.º 15
0
Archivo: main.go Proyecto: rdterner/tp
func main() {
	flag.Parse()

	hasFile, err := loadConfig()
	if hasFile == true && err != nil {
		fmt.Println("failed to read config file %q: %v", configFileName, err)
		os.Exit(1)
	}

	sc := &service.Config{
		Name: "tps",
	}
	a := &app{}
	s, err := service.New(a, sc)
	if err != nil {
		fmt.Println("failed to create service: %v", err)
		os.Exit(1)
	}

	log, err = s.Logger(nil)
	if err != nil {
		fmt.Println("error opening logger: %v", err)
		os.Exit(1)
	}
	if len(*action) > 0 {
		err = service.Control(s, *action)
		if err != nil {
			fmt.Printf("Control action %q failed: %v\n", *action, err)
			fmt.Printf("available actions: %q\n", service.ControlAction)
			flag.PrintDefaults()
			os.Exit(2)
		}
		return
	}
	err = s.Run()
	if err != nil {
		log.Errorf("runtime error: %v", err)
	}
}
Ejemplo n.º 16
0
func initService() service.Service {
	svcFlag := flag.String("service", "", "Control the system service.")
	flag.Parse()

	svcConfig := &service.Config{
		Name:        "ipsecdiagtool",
		DisplayName: "A service for IPSecDiagTool",
		Description: "Detects packet loss & periodically reports the MTU for all configured tunnels.",
	}

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}
	errs := make(chan error, 5)
	//logger, err = s.Logger(errs)
	if err != nil {
		log.Fatal(err)
	}

	go func() {
		for {
			err := <-errs
			check(err)
		}
	}()

	if len(*svcFlag) != 0 {
		err := service.Control(s, *svcFlag)
		if err != nil {
			log.Printf("Valid actions: %q\n", service.ControlAction)
			log.Fatal(err)
		}
		os.Exit(0)
	}
	return s
}
Ejemplo n.º 17
0
func main() {
	cfg := config.GetConfig()

	svcConfig := &service.Config{
		Name:        "GoWebService",
		DisplayName: "Go Web Service Example",
		Description: "This is an example Go Web service.",
	}

	s, err := gowebservice.DoInit(cfg, svcConfig, routing.MiddlewaresFactory, routing.GetRoutesFactory())
	if err != nil {
		return
	}

	if len(os.Args) > 1 {
		if err := service.Control(s, os.Args[1]); err != nil {
			log.Fatal(err)
		}
	} else {
		if err := s.Run(); err != nil {
			log.Fatal(err)
		}
	}
}
Ejemplo n.º 18
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.º 19
0
// Service setup.
//   Define service config.
//   Create the service.
//   Setup the logger.
//   Handle service controls (optional).
//   Run the service.
func ServiceMain(startfunc, runfunc, stopfunc func()) {
	log.Println("ServiceMain")
	svcFlag := flag.String("service", "", "Control the system service.")
	cfg := Cfg().Get("service")
	flag.Parse()
	svcConfig := &service.Config{
		Name:        cfg.Get("name").String(),
		DisplayName: cfg.Get("display").String(),
		Description: cfg.Get("desc").String(),
	}
	if len(svcConfig.Name) <= 0 || svcConfig.Name == "null" {
		cfg := Cfg()
		svcConfig.Name = cfg.Get("name").String()
		svcConfig.DisplayName = svcConfig.Name + " go service"
		svcConfig.Description = "<missing description>"
	}

	prg := &program{}
	svcprog = prg
	prg.startfunc = startfunc
	prg.runfunc = runfunc
	prg.stopfunc = stopfunc
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Println(err)
		logCoolDown()
		return
	}
	errs := make(chan error, 5)
	logger, err = s.Logger(errs)
	if err != nil {
		log.Println(err)
		logCoolDown()
		return
	}

	go func() {
		for {
			err := <-errs
			if err != nil {
				log.Print(err)
			}
		}
	}()

	if len(*svcFlag) != 0 {
		err := service.Control(s, *svcFlag)
		if err != nil {
			log.Printf("Valid actions: %q\n", service.ControlAction)
			log.Println(err)
		}
		logCoolDown()
		return
	}

	err = s.Run()
	if err != nil {
		logger.Error(err)
	}
	logCoolDown()
	return
}
Ejemplo n.º 20
0
func reloadLoop(stop chan struct{}, s service.Service) {
	defer func() {
		if service.Interactive() {
			os.Exit(0)
		}
		return
	}()
	reload := make(chan bool, 1)
	reload <- true
	for <-reload {
		reload <- false
		flag.Usage = func() { usageExit(0) }
		flag.Parse()
		args := flag.Args()

		var inputFilters []string
		if *fInputFilters != "" {
			inputFilter := strings.TrimSpace(*fInputFilters)
			inputFilters = strings.Split(":"+inputFilter+":", ":")
		}
		var outputFilters []string
		if *fOutputFilters != "" {
			outputFilter := strings.TrimSpace(*fOutputFilters)
			outputFilters = strings.Split(":"+outputFilter+":", ":")
		}

		if len(args) > 0 {
			switch args[0] {
			case "version":
				v := fmt.Sprintf("Telegraf - version %s", version)
				fmt.Println(v)
				return
			case "config":
				config.PrintSampleConfig(inputFilters, outputFilters)
				return
			}
		}

		// switch for flags which just do something and exit immediately
		switch {
		case *fOutputList:
			fmt.Println("Available Output Plugins:")
			for k, _ := range outputs.Outputs {
				fmt.Printf("  %s\n", k)
			}
			return
		case *fInputList:
			fmt.Println("Available Input Plugins:")
			for k, _ := range inputs.Inputs {
				fmt.Printf("  %s\n", k)
			}
			return
		case *fVersion:
			v := fmt.Sprintf("Telegraf - version %s", version)
			fmt.Println(v)
			return
		case *fSampleConfig:
			config.PrintSampleConfig(inputFilters, outputFilters)
			return
		case *fUsage != "":
			if err := config.PrintInputConfig(*fUsage); err != nil {
				if err2 := config.PrintOutputConfig(*fUsage); err2 != nil {
					log.Fatalf("%s and %s", err, err2)
				}
			}
			return
		case *fService != "" && runtime.GOOS == "windows":
			if *fConfig != "" {
				(*svcConfig).Arguments = []string{"-config", *fConfig}
			}
			err := service.Control(s, *fService)
			if err != nil {
				log.Fatal(err)
			}
			return
		}

		// If no other options are specified, load the config file and run.
		c := config.NewConfig()
		c.OutputFilters = outputFilters
		c.InputFilters = inputFilters
		err := c.LoadConfig(*fConfig)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		if *fConfigDirectory != "" {
			err = c.LoadDirectory(*fConfigDirectory)
			if err != nil {
				log.Fatal(err)
			}
		}
		if len(c.Outputs) == 0 {
			log.Fatalf("Error: no outputs found, did you provide a valid config file?")
		}
		if len(c.Inputs) == 0 {
			log.Fatalf("Error: no inputs found, did you provide a valid config file?")
		}

		ag, err := agent.NewAgent(c)
		if err != nil {
			log.Fatal(err)
		}

		if *fDebug {
			ag.Config.Agent.Debug = true
		}

		if *fQuiet {
			ag.Config.Agent.Quiet = true
		}

		if *fTest {
			err = ag.Test()
			if err != nil {
				log.Fatal(err)
			}
			return
		}

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

		shutdown := make(chan struct{})
		signals := make(chan os.Signal)
		signal.Notify(signals, os.Interrupt, syscall.SIGHUP)
		go func() {
			select {
			case sig := <-signals:
				if sig == os.Interrupt {
					close(shutdown)
				}
				if sig == syscall.SIGHUP {
					log.Printf("Reloading Telegraf config\n")
					<-reload
					reload <- true
					close(shutdown)
				}
			case <-stop:
				close(shutdown)
			}
		}()

		log.Printf("Starting Telegraf (version %s)\n", version)
		log.Printf("Loaded outputs: %s", strings.Join(c.OutputNames(), " "))
		log.Printf("Loaded inputs: %s", strings.Join(c.InputNames(), " "))
		log.Printf("Tags enabled: %s", c.ListTags())

		if *fPidfile != "" {
			f, err := os.Create(*fPidfile)
			if err != nil {
				log.Fatalf("Unable to create pidfile: %s", err)
			}

			fmt.Fprintf(f, "%d\n", os.Getpid())

			f.Close()
		}

		ag.Run(shutdown)
	}
}
Ejemplo n.º 21
0
func main() {

	// Parse config (we don't action any errors quite yet)
	var err error
	config, err = LoadConfig()
	if err != nil {
		fmt.Fprintf(os.Stderr, "ERROR: Invalid config - %v\n", err)
		os.Exit(1)
	}

	normalizeArgs()

	// Check args
	if !validateArgs() {
		fmt.Printf("%s (%s)\n", config.ServiceDescription.DisplayName,
			serviceName())
		fmt.Printf("%s\n\n", config.ServiceDescription.Description)
		fmt.Printf("Usage:\n")
		fmt.Printf("%s [install|uninstall|start|stop|command|validate|run|help] [command-name]\n", exeName())
		fmt.Printf("  install   - Install the service.\n")
		fmt.Printf("  uninstall    - Remove/uninstall the service.\n")
		fmt.Printf("  start     - Start an installed service.\n")
		fmt.Printf("  stop      - Stop an installed service.\n")
		fmt.Printf("  validate  - Test the configuration file.\n")
		fmt.Printf("  run       - Run service on in command-line mode.\n")
		fmt.Printf("  command   - Run a command [command-name].\n")
		fmt.Printf("  help      - This usage message.\n")
		os.Exit(1)
	}

	if err := os.Chdir(exeFolder()); err != nil {
		fmt.Fprintf(os.Stderr, "ERROR: Unable to set working directory - %v\n", err)
		os.Exit(1)
	}

	// Run command if requested
	if len(os.Args) > 1 && (os.Args[1] == "command" || os.Args[1] == "validate") {
		if os.Args[1] == "command" {
			execCommand()
		} else {
			fmt.Println("Config is valid")
			os.Exit(0)
		}
		return
	}

	// Setup log file out
	logFile := config.ServiceConfig.LogFile
	maxSize := int64(config.ServiceConfig.LogFileMaxSizeMb) * 1024 * 1024
	if logFile == "" {
		logFile = serviceName() + ".log"
	}
	logger = logging.NewFileLoggerWithMaxSize(logFile, maxSize)

	// Setup service
	svcConfig := &service.Config{
		Name:        serviceName(),
		DisplayName: config.ServiceDescription.DisplayName,
		Description: config.ServiceDescription.Description,
	}

	prog := &program{}
	svc, err := service.New(prog, svcConfig)
	if err != nil {
		fmt.Println("ERROR: Invalid service config: %s", err)
		os.Exit(1)
	}

	if len(os.Args) > 1 && os.Args[1] != "run" {
		err = service.Control(svc, os.Args[1])
		if err != nil {
			fmt.Println("ERROR: Invalid service command: %v", err)
			os.Exit(1)
		}
		os.Exit(0)
	}

	err = svc.Run()
	if err != nil {
		fmt.Println("ERROR: %s", err)
		os.Exit(1)
	}

	pidFile := config.ServiceConfig.PidFile
	if pidFile != "" {
		ioutil.WriteFile(pidFile, []byte(fmt.Sprintf("%d\n", os.Getpid())), 0644)
	}
}
Ejemplo n.º 22
0
func main() {
	//flag.Parse()
	iniflags.Parse()

	svcConfig := &service.Config{
		Name:        "proxy3",
		DisplayName: "Sliq Proxy3 Service",
		Description: "Proxy cache server for Live HLS streams",
		Arguments:   []string{},
	}
	for _, arg := range os.Args[1:] {
		if !strings.HasPrefix(arg, "-service=") {
			svcConfig.Arguments = append(svcConfig.Arguments, arg)
		}
	}
	/*fmt.Println(svcConfig.Arguments)
	return*/

	// intiailze the generic log file
	if Settings.LogSetting.Filename != "" {
		log.SetOutput(&lumberjack.Logger{
			Filename:   Settings.LogSetting.Filename,
			MaxSize:    Settings.LogSetting.MaxSize,
			MaxBackups: Settings.LogSetting.MaxBackups,
			MaxAge:     Settings.LogSetting.MaxAge,
			LocalTime:  Settings.LogSetting.LocalTime,
		})
	}

	// initialize the access log file
	if true {
		accessLog = NewAccessLog(Settings.AccessLogSetting)
	}

	initUpstreamClients()
	for _, client := range upstreamClients {
		logMessage("upstreamClient \"%s\": \"%s\"", client.name, client.upstreamHost)
	}

	runtime.GOMAXPROCS(Settings.GoMaxProcs)

	//c := make(chan os.Signal, 1)
	//signal.Notify(c, os.Interrupt)
	//<-c
	//logMessage("ctrl-c is captured")

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		log.Fatal(err)
	}
	errs := make(chan error, 5)
	logger, err = s.Logger(errs)
	if err != nil {
		log.Fatal(err)
	}

	if len(*svcFlag) != 0 {
		err := service.Control(s, *svcFlag)
		if err != nil {
			log.Printf("Valid actions: %q\n", service.ControlAction)
			log.Fatal(err)
		}
		return
	}

	go func() {
		for {
			err := <-errs
			if err != nil {
				log.Print(err)
			}
		}
	}()

	if len(*svcFlag) != 0 {
		err := service.Control(s, *svcFlag)
		if err != nil {
			log.Printf("Valid actions: %q\n", service.ControlAction)
			log.Fatal(err)
		}
		return
	}
	err = s.Run()
	if err != nil {
		logger.Error(err)
	}
	//Start(nil)
}
Ejemplo n.º 23
0
func main() {
	configPath := ""
	flag.StringVar(&configPath, "c", "", "config json-file path")
	flag.Parse()

	if configPath == "" {
		c, err := getConfigPath()
		if err != nil {
			log.Fatal(err)
		}
		configPath = c
	}

	svcConfig := &service.Config{
		Name:        "supervisorgo",
		DisplayName: "SuperVisorGo",
		Description: "process bootstrap daemon",
		Option: service.KeyValue{
			"UserService": true,
			"RunAtLoad":   true,
		},
	}

	conf, err := getConfig(configPath)
	if err != nil {
		log.Fatal(err)
	}
	if conf.ControlUri == "" {
		conf.ControlUri = "unix:./supervisorgo.sock"
	}
	u, err := url.Parse(conf.ControlUri)
	if err != nil {
		log.Fatal(err)
	}
	m := supervisorgo.NewManager(conf)
	s, err := service.New(m, svcConfig)
	if err != nil {
		log.Fatal(err)
	}

	errs := make(chan error, 5)
	logger, err = s.Logger(errs)
	if err != nil {
		log.Fatal(err)
	}
	supervisorgo.SetLogger(logger)

	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		for err := range errs {
			if err != nil {
				log.Print(err)
			}
		}
	}()
	defer wg.Wait()
	defer close(errs)

	if len(flag.Args()) != 0 {
		if err := service.Control(s, flag.Arg(0)); err != nil {
			log.Printf("Valid actions: %q\n", service.ControlAction)
			log.Fatal(err)
		}
		log.Printf("%s succeeded", flag.Arg(0))
		return
	}

	os.Exit(run(s, m, u))
}