Example #1
1
File: validate.go Project: kego/ke
// ValidateMain is called by the generated validate command.
// ke: {"func": {"notest": true}}
func ValidateMain(path string) {

	// Using process.Flags as the options means that the non-specified options are read from the
	// command flags.
	update := false
	options := &process.Flags{
		Update: &update,
		Path:   &path,
	}

	ctx, cancel, err := process.Initialise(context.Background(), options)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

	// The log function outputs errors and messages to the console. We pass it in to permit testing.
	log := func(message string) {
		fmt.Println(message)
	}

	// The interrupt chanel signals that Ctrl+C or other OS interrupts have happened.
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, os.Interrupt)
	signal.Notify(interrupt, syscall.SIGTERM)

	exitStatus := validateMain(ctx, cancel, log, interrupt)

	wgctx.WaitAndExit(ctx, exitStatus)

}
Example #2
0
func main() {
	flag.Parse()
	if *host == "" || *topic == "" {
		fmt.Printf("pararm error,host=%s,topic=%s\n", *host, *topic)
		os.Exit(0)
	}

	hosts := strings.Split(*host, ",")
	//kafka
	kafkaClient := NewKafkaClient()
	err := kafkaClient.NewConsumer(hosts)
	if err != nil {
		os.Exit(-2)
	}
	defer kafkaClient.Close()
	kafkaClient.GetTopicMsg(*topic)

	// Trap SIGINT to trigger a shutdown.
	signals := make(chan os.Signal, 2)
	signal.Notify(signals, os.Interrupt)
	signal.Notify(signals, os.Kill)

ConsumerLoop:
	for {
		select {
		case msg := <-kafkaClient.Topicmap[*topic].Msgs:
			log.Println("get msg ", string(msg.Value))
		case <-signals:
			break ConsumerLoop
		}
	}

}
Example #3
0
func main() {

	sigchan := make(chan os.Signal, 1)
	signal.Notify(sigchan, os.Interrupt)
	signal.Notify(sigchan, syscall.SIGTERM)
	go func() {
		<-sigchan
		shutdownFlag = true
	}()

	rides = map[int64]*Ride{}
	rideUpdates = make(chan *Ride, 0)

	http.Handle("/live", websocket.Handler(livemap))
	http.HandleFunc("/location", locationHandler)

	// run main application in goroutine
	go http.ListenAndServe(":8080", nil)

	go updateClients()

	go rideCleanup()

	for !shutdownFlag {
		time.Sleep(1 * time.Second)
	}

	shutdown()

	os.Exit(1)
}
Example #4
0
//Called by main
//If main dies, we get missed signals -> kill the parent and return
func backup() {
	missed_signal := 0
	sigint := make(chan os.Signal, 1)
	sigquit := make(chan os.Signal, 1)
	sigusr := make(chan os.Signal, 1)
	signal.Notify(sigint, syscall.SIGINT)
	signal.Notify(sigquit, syscall.SIGQUIT)
	signal.Notify(sigusr, syscall.SIGUSR1)
	ppid := os.Getppid()
	log.Println("Backup started by pid: ", ppid)
	for {
		select {
		case <-sigusr:
			missed_signal = 0
			time.Sleep(200 * time.Millisecond)
		case <-sigint:
			log.Println("Backup caught SIGINT, ignore")
		case <-sigquit:
			log.Println("Received SIGQUIT. Shutting down backup")
			os.Exit(0)
		default:
			if missed_signal == 3 {
				killParent(ppid)
				return
			}
			missed_signal += 1
			time.Sleep(200 * time.Millisecond)
		}
	}
}
Example #5
0
func main() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	signal.Notify(c, syscall.SIGTERM)
	go func() {
		<-c
		cleanup()
		os.Exit(1)
	}()

	name := flag.String("name", "default", "vm name")
	flag.Parse()
	if *name == "" {
		os.Exit(10)
	}

	for {
		fp, err := os.OpenFile("/tmp/"+*name, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0600)
		if err != nil {
			panic(err)
		}

		fmt.Fprintf(fp, "%s:%d alive\n", *name, os.Getpid())
		fp.Close()

		time.Sleep(5 * time.Second)
	}
}
Example #6
0
// Start - Will loop throught each of servers and attempt to start them up.
// In case that channel receives single error it will kill function otherwise, will listen
// forever
func (m *Manager) Start() error {
	m.Info("Starting service management...")
	errors := make(chan error)

	signal.Notify(m.GetInterruptChan(), os.Interrupt)
	signal.Notify(m.GetInterruptChan(), syscall.SIGTERM)

	go m.HandleInterrupt()

	for _, serv := range m.Servers {
		go func(serv servers.Serverer) {
			if err := serv.Start(); err != nil {
				errors <- err
			}
		}(serv)
	}

	select {
	case err := <-errors:
		return err
	case <-m.GetInterruptChan():
		m.Warn("Service management interrupt signal caught. Giving it few seconds before we shut down permanently...")
		close(m.GetInterruptChan())

		time.Sleep(m.InterruptWaitTimeout)
		m.Info("All done :( We go underground now for good...")
		return nil
	}
}
Example #7
0
func main() {
	flag.Parse()
	if helpFlag {
		flag.Usage()
		os.Exit(0)
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGTERM)
	signal.Notify(c, os.Interrupt)
	s := daemon.NewServer()
	go func() {
		<-c
		if s != nil {
			s.Close()
		}
		os.Exit(1)
	}()
	if s == nil {
		util.Warn.Println("Failed to start Hover Server")
		os.Exit(1)
	}
	util.Info.Printf("Hover Server listening on %s\n", listenSocket)
	http.ListenAndServe(listenSocket, s.Handler())
}
Example #8
0
File: ldap.go Project: dogeerf/tool
func signalHandle() {
	c := make(chan os.Signal)
	signal.Notify(c)
	signal.Notify(c, syscall.SIGHUP)
	s := <-c
	fmt.Println("get signal:", s)
}
func (lc *LogCourier) registerSignals() {
	// *nix systems support SIGTERM so handle shutdown on that too
	signal.Notify(lc.shutdown_chan, os.Interrupt, syscall.SIGTERM)

	// *nix has SIGHUP for reload
	signal.Notify(lc.reload_chan, syscall.SIGHUP)
}
Example #10
0
func Launch(option *options.SysOption) {
	signalChannel := make(chan os.Signal, 1)
	signal.Notify(signalChannel, os.Interrupt)
	signal.Notify(signalChannel, syscall.SIGTERM)
	coremethods.Setup()
	mustExit := false
	stat := statistic.NewStatistic(*option)
	manager := coresupport.NewCoreWorkerManager(*option, stat)
	server := connectionserver.NewServer(*option, stat)
	server.Start(manager)
	manager.Start(server)
	// wait
	for !mustExit {
		select {
		case newSig := <-signalChannel:
			{
				if newSig != nil {
					rllogger.Output(rllogger.LogInfo, "Stoping service, now wait..")
					server.Stop()
					manager.Stop()
				}
			}
		case <-manager.OutSignalChannel:
			{
				rllogger.Output(rllogger.LogInfo, "Close manager.")
				mustExit = true
			}
		}
	}
	manager.Close()
	stat.Close()
	close(signalChannel)
}
Example #11
0
func watchSignals(ex chan struct{}, t chan Trigger) {
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh, os.Interrupt)
	signal.Notify(sigCh, syscall.SIGTERM)
	signal.Notify(sigCh, syscall.SIGHUP)

	// main control flow
	for {
		select {
		// when exit chan closes, return
		case <-ex:
			return
		// If a signal is caught, either shutdown or reload gracefully
		case sig := <-sigCh:
			switch sig {
			case os.Interrupt:
				fallthrough
			case syscall.SIGTERM:
				t <- TriggerStop
			case syscall.SIGHUP:
				t <- TriggerReload
			}
		}
	}

}
Example #12
0
File: main.go Project: robbrit/ridc
func main() {
	flag.Parse()

	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Printf("Could not open profile file: %s", err)
		} else {
			log.Printf("Logging CPU profile to %s", *cpuprofile)
			pprof.StartCPUProfile(f)
		}
	}

	database := ridc.CreateDatabase()

	go ridc.StartWebInterface(database)
	go ridc.StartSocketInterface(database, "3001")

	cleanup := func() {
		pprof.StopCPUProfile()
	}

	signalHandler := make(chan os.Signal, 1)
	signal.Notify(signalHandler, os.Interrupt)
	signal.Notify(signalHandler, syscall.SIGTERM)
	go func() {
		<-signalHandler
		log.Printf("Shutting down...")
		cleanup()
		os.Exit(1)
	}()

	select {}
}
Example #13
0
func sigHandleDemo() {
	sigRecv1 := make(chan os.Signal, 1)
	sigs1 := []os.Signal{syscall.SIGINT, syscall.SIGQUIT}
	fmt.Printf("Set notification for %s... [sigRecv1]\n", sigs1)
	signal.Notify(sigRecv1, sigs1...)
	sigRecv2 := make(chan os.Signal, 1)
	sigs2 := []os.Signal{syscall.SIGQUIT}
	fmt.Printf("Set notification for %s... [sigRecv2]\n", sigs2)
	signal.Notify(sigRecv2, sigs2...)

	var wg sync.WaitGroup
	wg.Add(2)
	go func() {
		for sig := range sigRecv1 {
			fmt.Printf("Received a signal from sigRecv1: %s\n", sig)
		}
		fmt.Printf("End. [sigRecv1]\n")
		wg.Done()
	}()
	go func() {
		for sig := range sigRecv2 {
			fmt.Printf("Received a signal from sigRecv2: %s\n", sig)
		}
		fmt.Printf("End. [sigRecv2]\n")
		wg.Done()
	}()

	fmt.Println("Wait for 2 seconds... ")
	time.Sleep(2 * time.Second)
	fmt.Printf("Stop notification...")
	signal.Stop(sigRecv1)
	close(sigRecv1)
	fmt.Printf("done. [sigRecv1]\n")
	wg.Wait()
}
Example #14
0
func run(context *cli.Context) {
	etcdURI, serverKey, uri := getOpts(context)

	control := make(chan bool)
	go loop(etcdURI, serverKey, uri, control)
	go iterate(control)

	sigTerm := make(chan os.Signal)
	signal.Notify(sigTerm, syscall.SIGTERM)

	sigHup := make(chan os.Signal)
	signal.Notify(sigHup, syscall.SIGHUP)

	go func() {
		for {
			<-sigHup
			fmt.Println("SIGHUP received, deregistering")
			control <- false
			onNotHealthy(etcdURI, serverKey)
			fmt.Println("deregistered, paused for 5 seconds")
			time.Sleep(5 * time.Second)
			go loop(etcdURI, serverKey, uri, control)
		}
	}()

	<-sigTerm
	fmt.Println("SIGTERM received, cleaning up")
	control <- false
	onNotHealthy(etcdURI, serverKey)
	os.Exit(0)
}
Example #15
0
// Run starts an elector loop.
func (e *Elector) Run() error {
	log.Println("Starting elector.")
	if e.updates != nil {
		return fmt.Errorf("Elector has already been initialized. Electors can be started once.")
	}

	// 0 so blocks on updates while error handler is executing
	e.updates = make(chan State)

	go e.reconcileStateLoop()
	go e.ElectionBackend.ElectionLoop(e.updates)

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	signal.Notify(c, syscall.SIGTERM)
	go func() {
		<-c
		e.updates <- StateNotLeader
		log.Println("Allowing 10s for StateNotLeader to process.")
		time.Sleep(10 * time.Second)
	}()

	group := sync.WaitGroup{}
	group.Add(2)
	defer group.Done()
	group.Wait()
	return nil
}
Example #16
0
// We need to be able to intercept execution so we can inject signal handling in
// a "child." To do this we ensure that we can fork/exec the built test
// executable and have it do the childs work for us.
func init() {
	if len(os.Args) != 2 {
		return
	} else if os.Args[1] != EXECUTION_TOKEN {
		return
	}

	usr1 := make(chan os.Signal, 100)
	usr2 := make(chan os.Signal, 100)
	signal.Notify(usr1, syscall.SIGUSR1)
	signal.Notify(usr2, syscall.SIGUSR2)

	// Send a ready message to the user.
	fmt.Fprintf(os.Stderr, "READY\n")
	os.Stderr.Close()

	for {
		select {
		case <-time.NewTimer(time.Second * 3).C:
			fmt.Println("TIMEOUT")
			os.Exit(1)
		case <-usr1:
			fmt.Println("SIGUSR1")
			os.Exit(0)
		case <-usr2:
			fmt.Println("SIGUSR2")
			os.Exit(0)
		}
	}
}
Example #17
0
func main() {
	path := flag.String("config", "/etc/pt-client.conf", "path to configuration file")
	debug := flag.Bool("v", false, "debug mode")
	flag.Parse()
	parsed := LoadConfig(path)
	if *debug {
		SetLogLevel(LOG_LEVEL_DEBUG)
	}
	if !parsed {
		os.Exit(1)
	}

	sig := make(chan os.Signal)
	signal.Notify(sig, syscall.SIGHUP)
	signal.Notify(sig, syscall.SIGINT)
	signal.Notify(sig, syscall.SIGTERM)

	ctrl := newController()
	ctrl.RunLoop()
	for {
		s := <-sig
		LogInfo("Got a signal: %d", s)
		if s != nil {
			if s == syscall.SIGHUP { // HUP
				LogLotate()
			} else {
				LogInfo("Finalizing controls...")
				ctrl.Stop()
				LogInfo("Bye.")
				break
			}
		}
	}
}
Example #18
0
// Golog function which starts local loggers
func Golog(windowLogGranularity int, keyLogGranularity int, standalone bool, serverAddr string) {
	// Setup our receiver
	receiver := &Receiver{
		ServerAddress: serverAddr,
	}

	// Setup our loggers
	l := &lgr{
		Receiver: receiver,
	}
	l.setupLoggers()

	// Trigger our updater in the background
	l.Updater(windowLogGranularity, keyLogGranularity)

	// Trap the exit signal
	exitChan := make(chan os.Signal, 1)
	signal.Notify(exitChan, os.Interrupt)
	signal.Notify(exitChan, syscall.SIGTERM)

	// And push remaining entries to the server
	go func() {
		// In cleanup, we need to
		<-exitChan
		l.SendLogs()
		os.Exit(0)
	}()

	// Every 10 seconds, send logs
	c := time.Tick(10 * time.Second)
	for _ = range c {
		l.SendLogs()
	}
}
Example #19
0
func HandleSignals(shutdownc <-chan io.Closer) {
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGHUP)
	signal.Notify(c, syscall.SIGINT)
	for {
		sig := <-c
		sysSig, ok := sig.(syscall.Signal)
		if !ok {
			glog.Fatal("Not a unix signal")
		}
		switch sysSig {
		case syscall.SIGHUP:
		case syscall.SIGINT:
			glog.Warningln("Got SIGTERM: shutting down")
			donec := make(chan bool)
			go func() {
				cl := <-shutdownc
				if err := cl.Close(); err != nil {
					exitf("Error shutting down: %v", err)
				}
				donec <- true
			}()
			select {
			case <-donec:
				glog.Infoln("Shut down completed.")
				os.Exit(0)
			case <-time.After(5 * time.Second):
				exitf("Timeout shutting down. Exiting uncleanly.")
			}
		default:
			glog.Fatal("Received another signal, should not happen.")
		}
	}
}
Example #20
0
func trapSignal() chan os.Signal {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	signal.Notify(c, syscall.SIGTERM)

	return c
}
Example #21
0
func main() {
	watchDir, targetDir := "tmp/source", "tmp/target"

	godotenv.Load(".env")

	fm, err := fm.NewFM("mms_prod")
	if err != nil {
		panic(err)
	}
	defer fm.Destroy()

	fm.Watch(watchDir, targetDir)

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	signal.Notify(c, syscall.SIGTERM)
	go func() {
		<-c
		fmt.Println("Bye Bye")
		fm.Destroy()
		os.Exit(0)
	}()

	quit := make(chan bool, 1)
	/*
		for {
			fmt.Println("sleeping...")
			time.Sleep(10 * time.Second) // or runtime.Gosched() or similar per @misterbee
		}
	*/
	<-quit
}
func main() {

	runtime.GOMAXPROCS(runtime.NumCPU())
	log.Println("Initializing Imagemagick")
	imagick.Initialize()

	http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
		log.Println("Hit the /test route")
		imagick.Terminate()
	})

	sigint := make(chan os.Signal, 1)
	signal.Notify(sigint, syscall.SIGINT)
	signal.Notify(sigint, syscall.SIGTERM)

	go func() {
		for {
			<-sigint
			log.Println("Caught SIGINT, shutting down imagick environment")
			imagick.Terminate()
			os.Exit(0)
		}

	}()
	http.ListenAndServe(":4000", nil)
}
Example #23
0
func main() {
	g.LoadConfig()
	g.InitialConn()
	g.InitTransfers()
	defer g.CloseConn()

	lenz.InitLenz()
	status.InitStatus()
	network.InitVlan()

	utils.WritePid(g.Config.PidFile)
	defer os.Remove(g.Config.PidFile)

	api.Serve()
	status.Load()
	status.StartMonitor()
	health.Check()
	app.Limit()

	var c = make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	signal.Notify(c, syscall.SIGTERM)
	signal.Notify(c, syscall.SIGHUP)
	signal.Notify(c, syscall.SIGKILL)
	signal.Notify(c, syscall.SIGQUIT)
	logs.Info("Eru Agent Catch", <-c)
}
Example #24
0
func HandleSignals() {
	sigs := make(chan os.Signal, 1)
	infosigs := make(chan os.Signal, 1)

	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
	signal.Notify(infosigs, syscall.SIGTSTP)

	go func() {

		quitInProgress := false

		for {

			<-sigs
			if quitInProgress == true {
				os.Exit(1)
			}
			go GracefullQuit()
			quitInProgress = true

		}

	}()
	go func() {

		for {

			<-infosigs
			DisplayInfo()

		}

	}()

}
Example #25
0
func main() {
	runtime, err := loadRuntime()
	if err != nil {
		panic(err)
	}
	if err := runtime.Cache.Load("cache.save"); err != nil {
		fmt.Println("failed to restore cache", err)
	}

	go garnish.Start(runtime)

	go func() {
		sigusr2 := make(chan os.Signal, 1)
		signal.Notify(sigusr2, syscall.SIGUSR2)
		for {
			<-sigusr2
			runtime, err := loadRuntime()
			if err != nil {
				fmt.Println("invalid configuration, did not reload.", err)
			} else {
				garnish.Reload(runtime)
				fmt.Println("reloaded")
			}
		}
	}()

	sigquit := make(chan os.Signal, 1)
	signal.Notify(sigquit, syscall.SIGQUIT)
	<-sigquit
	if err := runtime.Cache.Save("cache.save", 5000, time.Second*10); err != nil {
		fmt.Println("failed to save cache", err)
	}
}
Example #26
0
// setupStopSignals sets up UNIX-specific signals for terminating
// the program
func setupStopSignals(signalChannel chan os.Signal) {
	// TODO: not sure whether SIGHUP should be used here, only if not in
	// daemon mode
	signal.Notify(signalChannel, syscall.SIGHUP)

	signal.Notify(signalChannel, syscall.SIGTERM)
}
Example #27
0
// runStart starts the cockroach node using --stores as the list of
// storage devices ("stores") on this machine and --gossip as the list
// of "well-known" hosts used to join this node to the cockroach
// cluster via the gossip network.
func runStart(cmd *cobra.Command, args []string) {
	info := util.GetBuildInfo()
	log.Infof("build Vers: %s", info.Vers)
	log.Infof("build Tag:  %s", info.Tag)
	log.Infof("build Time: %s", info.Time)
	log.Infof("build Deps: %s", info.Deps)

	// Default user for servers.
	Context.User = security.NodeUser
	// First initialize the Context as it is used in other places.
	err := Context.Init("start")
	if err != nil {
		log.Errorf("failed to initialize context: %s", err)
		return
	}

	log.Info("starting cockroach cluster")
	stopper := util.NewStopper()
	stopper.AddWorker()
	s, err := server.NewServer(Context, stopper)
	if err != nil {
		log.Errorf("failed to start Cockroach server: %s", err)
		return
	}

	err = s.Start(false)
	if err != nil {
		log.Errorf("cockroach server exited with error: %s", err)
		return
	}

	signalCh := make(chan os.Signal, 1)
	signal.Notify(signalCh, os.Interrupt, os.Kill)
	// TODO(spencer): move this behind a build tag.
	signal.Notify(signalCh, syscall.SIGTERM)

	// Block until one of the signals above is received or the stopper
	// is stopped externally (for example, via the quit endpoint).
	select {
	case <-stopper.ShouldStop():
		stopper.SetStopped()
	case <-signalCh:
		log.Infof("initiating graceful shutdown of server")
		stopper.SetStopped()
		go func() {
			s.Stop()
		}()
	}

	select {
	case <-signalCh:
		log.Warningf("second signal received, initiating hard shutdown")
	case <-time.After(time.Minute):
		log.Warningf("time limit reached, initiating hard shutdown")
		return
	case <-stopper.IsStopped():
		log.Infof("server drained and shutdown completed")
	}
	log.Flush()
}
Example #28
0
// Prepares the signal handlers so that we handle interrupts properly.
// The signal handler exists in a goroutine.
func setupSignalHandlers() {
	ch := make(chan os.Signal, 1)
	signal.Notify(ch, os.Interrupt)
	signal.Notify(ch, syscall.SIGTERM)

	go func() {
		// First interrupt. We mostly ignore this because it allows the
		// plugins time to cleanup.
		<-ch
		log.Println("First interrupt. Ignoring to allow plugins to clean up.")

		//ui.Error("Interrupt signal received. Cleaning up...")

		// Second interrupt. Go down hard.
		<-ch
		log.Println("Second interrupt. Exiting now.")

		//ui.Error("Interrupt signal received twice. Forcefully exiting now.")

		// Force kill all the plugins, but mark that we're killing them
		// first so that we don't get panics everywhere.
		//plugin.CleanupClients()
		os.Exit(1)
	}()
}
Example #29
0
// Set up signal handlers.  Go sends signal notifications to a "signal
// channel".
func setupSignals(cmd *exec.Cmd) chan os.Signal {
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGTERM)
	signal.Notify(sigChan, syscall.SIGINT)
	signal.Notify(sigChan, syscall.SIGQUIT)
	return sigChan
}
Example #30
0
func Init(service_interface IServiceInterface, port string) bool {
	sigs := make(chan os.Signal)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGABRT, syscall.SIGTERM)

	sigs_hub := make(chan os.Signal)
	signal.Notify(sigs_hub, syscall.SIGHUP)

	go func() {
		for {
			select {
			case <-sigs:
				{
					fmt.Println("Terminate")
					service_interface.Terminate()
					break
				}
			case <-sigs_hub:
				{
					fmt.Println("reloadConfig")
					service_interface.ReloadConfig()
				}

			}

		}
	}()

	rand.New(rand.NewSource(time.Now().Unix()))
	return service_interface.Init(port)
}