func main() {
	upgradelater := flag.Bool("upgradelater", false, "Upgrade later")

	flag.Parse()

	had_upgrade := false
	if !*upgradelater && os.Getenv("GOAGAIN_PPID") == "" { // not after gone again
		log.Println("Initial check for upgrades; run with -ugradelater to disable")
		had_upgrade = upgrade_once(false)
	}

	if !had_upgrade { // start the background routine unless just had an upgrade and gonna relaunch anyway
		go ostent.Loop()
		// go ostent.CollectdLoop()
	}

	listen, err := goagain.Listener()
	if err != nil {
		listen, err = net.Listen("tcp", ostent.OstentBindFlag.String())
		if err != nil {
			log.Fatalln(err)
		}

		if had_upgrade { // goagain
			go func() {
				time.Sleep(time.Second) // not before goagain.Wait
				syscall.Kill(os.Getpid(), syscall.SIGUSR2)
				// goagain.ForkExec(listen)
			}()
		} else {
			go upgrade_loop()
			go ostent.Serve(listen, true, nil)
		}

	} else {
		go upgrade_loop()
		go ostent.Serve(listen, true, nil)

		if err := goagain.Kill(); err != nil {
			log.Fatalln(err)
		}
	}

	if _, err := goagain.Wait(listen); err != nil { // signals before won't be catched
		log.Fatalln(err)
	}

	// shutting down

	if ostent.Connections.Reload() {
		time.Sleep(time.Second)
	} // */

	if err := listen.Close(); err != nil {
		log.Fatalln(err)
	}
	time.Sleep(time.Second)
}
Пример #2
0
Файл: main.go Проект: rmg/tyk
func main() {
	displayConfig()

	if doMemoryProfile {
		log.Info("Memory profiling active")
		profileFile, _ = os.Create("tyk.mprof")
		defer profileFile.Close()
	}

	targetPort := fmt.Sprintf(":%d", config.ListenPort)
	loadAPIEndpoints(http.DefaultServeMux)

	// Handle reload when SIGUSR2 is received
	l, err := goagain.Listener()
	if nil != err {

		// Listen on a TCP or a UNIX domain socket (TCP here).
		l, err = net.Listen("tcp", targetPort)
		if nil != err {
			log.Fatalln(err)
		}
		log.Println("Listening on", l.Addr())

		// Accept connections in a new goroutine.
		specs := getAPISpecs()
		loadApps(specs, http.DefaultServeMux)
		go http.Serve(l, nil)

	} else {

		// Resume accepting connections in a new goroutine.
		log.Println("Resuming listening on", l.Addr())
		specs := getAPISpecs()
		loadApps(specs, http.DefaultServeMux)
		go http.Serve(l, nil)

		// Kill the parent, now that the child has started successfully.
		if err := goagain.Kill(); nil != err {
			log.Fatalln(err)
		}

	}

	// Block the main goroutine awaiting signals.
	if _, err := goagain.Wait(l); nil != err {
		log.Fatalln(err)
	}

	// Do whatever's necessary to ensure a graceful exit like waiting for
	// goroutines to terminate or a channel to become closed.
	//
	// In this case, we'll simply stop listening and wait one second.
	if err := l.Close(); nil != err {
		log.Fatalln(err)
	}
	time.Sleep(1e9)
}
Пример #3
0
func main() {

	// Inherit a net.Listener from our parent process or listen anew.
	ch := make(chan struct{})
	wg := &sync.WaitGroup{}
	wg.Add(1)
	l, err := goagain.Listener()
	if nil != err {

		// Listen on a TCP or a UNIX domain socket (TCP here).
		l, err = net.Listen("tcp", "127.0.0.1:48879")
		if nil != err {
			log.Fatalln(err)
		}
		log.Println("listening on", l.Addr())

		// Accept connections in a new goroutine.
		go serve(l, ch, wg)

	} else {

		// Resume listening and accepting connections in a new goroutine.
		log.Println("resuming listening on", l.Addr())
		go serve(l, ch, wg)

		// If this is the child, send the parent SIGUSR2.  If this is the
		// parent, send the child SIGQUIT.
		if err := goagain.Kill(); nil != err {
			log.Fatalln(err)
		}

	}

	// Block the main goroutine awaiting signals.
	sig, err := goagain.Wait(l)
	if nil != err {
		log.Fatalln(err)
	}

	// Do whatever's necessary to ensure a graceful exit like waiting for
	// goroutines to terminate or a channel to become closed.
	//
	// In this case, we'll close the channel to signal the goroutine to stop
	// accepting connections and wait for the goroutine to exit.
	close(ch)
	wg.Wait()

	// If we received SIGUSR2, re-exec the parent process.
	if goagain.SIGUSR2 == sig {
		if err := goagain.Exec(l); nil != err {
			log.Fatalln(err)
		}
	}

}
Пример #4
0
func doLoadWithBackup(specs *[]*APISpec) {

	log.Warning("[RPC Backup] --> Load Policies too!")

	if len(*specs) == 0 {
		log.WithFields(logrus.Fields{
			"prefix": "main",
		}).Warning("No API Definitions found, not loading backup")
		return
	}

	// Reset the JSVM
	GlobalEventsJSVM.Init(config.TykJSPath)
	log.Warning("[RPC Backup] --> Initialised JSVM")

	newRouter := mux.NewRouter()
	mainRouter = newRouter

	var newMuxes *mux.Router
	if getHostName() != "" {
		newMuxes = newRouter.Host(getHostName()).Subrouter()
	} else {
		newMuxes = newRouter
	}

	log.Warning("[RPC Backup] --> Set up routers")
	log.Warning("[RPC Backup] --> Loading endpoints")

	loadAPIEndpoints(newMuxes)

	log.Warning("[RPC Backup] --> Loading APIs")
	loadApps(specs, newMuxes)
	log.Warning("[RPC Backup] --> API Load Done")

	newServeMux := http.NewServeMux()
	newServeMux.Handle("/", mainRouter)

	http.DefaultServeMux = newServeMux
	log.Warning("[RPC Backup] --> Replaced muxer")

	log.WithFields(logrus.Fields{
		"prefix": "main",
	}).Info("API backup load complete")

	log.Warning("[RPC Backup] --> Ready to listen")
	RPC_EmergencyModeLoaded = true

	l, goAgainErr := goagain.Listener()
	var err error
	if l, err = generateListener(l); err != nil {
		log.Info("Failed to generate listener!")
	}

	listen(l, goAgainErr)
}
func main() {
	updatelater := flag.Bool("updatelater", false, "Update later")
	flag.Parse()

	had_update := false
	if !*updatelater && os.Getenv("GOAGAIN_PPID") == "" { // not after gone again
		log.Println("Initial check for updates; run with -updatelater to disable")
		had_update = update_once(false)
	}

	martini.Env = martini.Prod
	listen, err := goagain.Listener()
	if err != nil {
		listen, err = ostential.Listen()
		if err != nil {
			if _, ok := err.(ostential.FlagError); ok {
				flag.Usage()
				os.Exit(2)
				return
			}
			log.Fatalln(err)
		}

		if had_update { // goagain
			go func() {
				time.Sleep(time.Second) // not before goagain.Wait
				syscall.Kill(os.Getpid(), syscall.SIGUSR2)
				// goagain.ForkExec(listen)
			}()
		} else {
			go update_loop()
			go ostential.Serve(listen, ostential.LogOne, nil)
		}

	} else {
		go update_loop()
		go ostential.Serve(listen, ostential.LogOne, nil)

		if err := goagain.Kill(); err != nil {
			log.Fatalln(err)
		}
	}

	if _, err := goagain.Wait(listen); err != nil { // signals before won't be catched
		log.Fatalln(err)
	}
	if err := listen.Close(); err != nil {
		log.Fatalln(err)
	}
	time.Sleep(time.Second)
}
Пример #6
0
func main() {

	// Inherit a net.Listener from our parent process or listen anew.
	l, err := goagain.Listener()
	if nil != err {

		// Listen on a TCP or a UNIX domain socket (TCP here).
		l, err = net.Listen("tcp", "127.0.0.1:48879")
		if nil != err {
			log.Fatalln(err)
		}
		log.Println("listening on", l.Addr())

		// Accept connections in a new goroutine.
		go serve(l)

	} else {

		// Resume accepting connections in a new goroutine.
		log.Println("resuming listening on", l.Addr())
		go serve(l)

		// Kill the parent, now that the child has started successfully.
		if err := goagain.Kill(); nil != err {
			log.Fatalln(err)
		}

	}

	// Block the main goroutine awaiting signals.
	if _, err := goagain.Wait(l); nil != err {
		log.Fatalln(err)
	}

	// Do whatever's necessary to ensure a graceful exit like waiting for
	// goroutines to terminate or a channel to become closed.
	//
	// In this case, we'll simply stop listening and wait one second.
	if err := l.Close(); nil != err {
		log.Fatalln(err)
	}
	time.Sleep(1e9)

}
Пример #7
0
func startServer() syscall.Signal {
	listener, err := again.Listener()
	if err != nil {
		port := config.Get("port").(string)
		listener, err = net.Listen("tcp4", "127.0.0.1:"+port)
		if err != nil {
			panic(err)
		}
		logger.Infof("listening on %s", listener.Addr())

		go serve(listener)
	} else {
		go serve(listener)

		err := again.Kill()
		if err != nil {
			panic(err)
		}
	}

	logPid()

	//block
	signal, err := again.Wait(listener)
	if err != nil {
		logger.Errorf(err.Error())
		panic(err)
	}
	err = listener.Close()
	if err != nil {
		logger.Errorf(err.Error())
		panic(err)
	}

	return signal
}
Пример #8
0
/**
 * 运行一个可以平滑重启的服务器
 */
func RunZeroDowntimeRestartServer(address string, serve ServerStarter, exiter ServerExiter) {
	l, err := goagain.Listener()

	if nil != err {
		l, err = net.Listen("tcp", address)
		if nil != err {
			log.Fatalln(err)
		}
		log.Println("listening on", l.Addr())
		go serve(l)
	} else {
		log.Println("resuming listening on", l.Addr())
		go serve(l)
		if err := goagain.Kill(); nil != err {
			log.Fatalln(err)
		}
	}

	sig, err := goagain.Wait(l)
	if nil != err {
		log.Println(sig, err)
	}
	exiter(l, sig)
}
Пример #9
0
func main() {
	displayConfig()

	ReadTimeout := 120
	WriteTimeout := 120
	if config.HttpServerOptions.ReadTimeout > 0 {
		ReadTimeout = config.HttpServerOptions.ReadTimeout
	}

	if config.HttpServerOptions.WriteTimeout > 0 {
		WriteTimeout = config.HttpServerOptions.WriteTimeout
	}

	if doMemoryProfile {
		log.Debug("Memory profiling active")
		profileFile, _ = os.Create("tyk.mprof")
		defer profileFile.Close()
	}

	targetPort := fmt.Sprintf(":%d", config.ListenPort)

	// Set up a default org manager so we can traverse non-live paths
	if !config.SupressDefaultOrgStore {
		log.Debug("Initialising default org store")
		//DefaultOrgStore.Init(&RedisStorageManager{KeyPrefix: "orgkey."})
		DefaultOrgStore.Init(GetGlobalStorageHandler("orgkey.", false))
		//DefaultQuotaStore.Init(GetGlobalStorageHandler(CloudHandler, "orgkey.", false))
		DefaultQuotaStore.Init(GetGlobalStorageHandler("orgkey.", false))
	}

	loadAPIEndpoints(http.DefaultServeMux)

	// Start listening for reload messages
	if !config.SuppressRedisSignalReload {
		go StartPubSubLoop()
	}

	if config.SlaveOptions.UseRPC {
		log.Warning("Strting RPC reload listener!")
		RPCListener := RPCStorageHandler{KeyPrefix: "rpc.listener.", UserKey: config.SlaveOptions.APIKey, Address: config.SlaveOptions.ConnectionString}
		RPCListener.Connect()
		go RPCListener.CheckForReload(config.SlaveOptions.RPCKey)
	}

	// Handle reload when SIGUSR2 is received
	l, err := goagain.Listener()
	if nil != err {

		// Listen on a TCP or a UNIX domain socket (TCP here).
		l, err = net.Listen("tcp", targetPort)
		if nil != err {
			log.Fatalln(err)
		}
		//log.Println("Listening on", l.Addr())

		// Accept connections in a new goroutine.
		specs := getAPISpecs()
		loadApps(specs, http.DefaultServeMux)
		getPolicies()

		// Use a custom server so we can control keepalives
		if config.HttpServerOptions.OverrideDefaults {
			log.Info("Custom Server started")
			log.Warning("HTTP Server Overrides detected, this could destabilise long-running http-requests")
			s := &http.Server{
				Addr:         ":" + targetPort,
				ReadTimeout:  time.Duration(ReadTimeout) * time.Second,
				WriteTimeout: time.Duration(WriteTimeout) * time.Second,
				Handler:      http.DefaultServeMux,
			}

			go s.Serve(l)
		} else {
			log.Printf("Server started (%v)", VERSION)
			go http.Serve(l, nil)
		}

	} else {

		// Resume accepting connections in a new goroutine.
		log.Info("Resuming listening on", l.Addr())
		specs := getAPISpecs()
		loadApps(specs, http.DefaultServeMux)
		getPolicies()

		if config.HttpServerOptions.OverrideDefaults {
			log.Warning("HTTP Server Overrides detected, this could destabilise long-running http-requests")
			s := &http.Server{
				Addr:         ":" + targetPort,
				ReadTimeout:  time.Duration(ReadTimeout) * time.Second,
				WriteTimeout: time.Duration(WriteTimeout) * time.Second,
				Handler:      http.DefaultServeMux,
			}

			log.Info("Custom server started")
			go s.Serve(l)
		} else {
			log.Printf("Server started (%v)", VERSION)
			http.Serve(l, nil)
		}

		// Kill the parent, now that the child has started successfully.
		if err := goagain.Kill(); nil != err {
			log.Fatalln(err)
		}

	}

	// Block the main goroutine awaiting signals.
	if _, err := goagain.Wait(l); nil != err {
		log.Fatalln(err)
	}

	// Do whatever's necessary to ensure a graceful exit like waiting for
	// goroutines to terminate or a channel to become closed.
	//
	// In this case, we'll simply stop listening and wait one second.
	if err := l.Close(); nil != err {
		log.Fatalln(err)
	}
	//time.Sleep(1e9)
}
Пример #10
0
func main() {
	ReadTimeout := 120
	WriteTimeout := 120
	if config.HttpServerOptions.ReadTimeout > 0 {
		ReadTimeout = config.HttpServerOptions.ReadTimeout
	}

	if config.HttpServerOptions.WriteTimeout > 0 {
		WriteTimeout = config.HttpServerOptions.WriteTimeout
	}

	if doMemoryProfile {
		log.Debug("Memory profiling active")
		profileFile, _ = os.Create("tyk.mprof")
		defer profileFile.Close()
	}

	targetPort := fmt.Sprintf(":%d", config.ListenPort)

	// Set up a default org manager so we can traverse non-live paths
	if !config.SupressDefaultOrgStore {
		log.Debug("Initialising default org store")
		//DefaultOrgStore.Init(&RedisClusterStorageManager{KeyPrefix: "orgkey."})
		DefaultOrgStore.Init(GetGlobalStorageHandler("orgkey.", false))
		//DefaultQuotaStore.Init(GetGlobalStorageHandler(CloudHandler, "orgkey.", false))
		DefaultQuotaStore.Init(GetGlobalStorageHandler("orgkey.", false))
	}

	loadAPIEndpoints(http.DefaultServeMux)

	// Start listening for reload messages
	if !config.SuppressRedisSignalReload {
		go StartPubSubLoop()
	}

	if config.SlaveOptions.UseRPC {
		log.Debug("Starting RPC reload listener")
		RPCListener = RPCStorageHandler{
			KeyPrefix:        "rpc.listener.",
			UserKey:          config.SlaveOptions.APIKey,
			Address:          config.SlaveOptions.ConnectionString,
			SuppressRegister: true,
		}
		RPCListener.Connect()
		go RPCReloadLoop(config.SlaveOptions.RPCKey)
		go RPCListener.StartRPCLoopCheck(config.SlaveOptions.RPCKey)
	}

	// Handle reload when SIGUSR2 is received
	l, err := goagain.Listener()
	if nil != err {

		// Listen on a TCP or a UNIX domain socket (TCP here).
		log.Info("Setting up Server")
		if config.HttpServerOptions.UseSSL {
			log.Warning("--> Using SSL (https)")
			certs := make([]tls.Certificate, len(config.HttpServerOptions.Certificates))
			certNameMap := make(map[string]*tls.Certificate)
			for i, certData := range config.HttpServerOptions.Certificates {
				cert, err := tls.LoadX509KeyPair(certData.CertFile, certData.KeyFile)
				if err != nil {
					log.Fatalf("Server error: loadkeys: %s", err)
				}
				certs[i] = cert
				certNameMap[certData.Name] = &certs[i]
			}

			config := tls.Config{
				Certificates:      certs,
				NameToCertificate: certNameMap,
				ServerName:        config.HttpServerOptions.ServerName,
				MinVersion:        config.HttpServerOptions.MinVersion,
			}
			l, err = tls.Listen("tcp", targetPort, &config)
		} else {
			log.Warning("--> Standard listener (http)")
			l, err = net.Listen("tcp", targetPort)
		}

		// Accept connections in a new goroutine.
		specs := getAPISpecs()
		loadApps(specs, http.DefaultServeMux)
		getPolicies()

		// Use a custom server so we can control keepalives
		if config.HttpServerOptions.OverrideDefaults {
			log.Info("Custom gateway started")
			log.Warning("HTTP Server Overrides detected, this could destabilise long-running http-requests")
			s := &http.Server{
				Addr:         ":" + targetPort,
				ReadTimeout:  time.Duration(ReadTimeout) * time.Second,
				WriteTimeout: time.Duration(WriteTimeout) * time.Second,
				Handler:      http.DefaultServeMux,
			}

			go s.Serve(l)
			displayConfig()
		} else {
			log.Printf("Gateway started (%v)", VERSION)
			go http.Serve(l, nil)
			displayConfig()
		}

	} else {

		// Resume accepting connections in a new goroutine.
		log.Info("Resuming listening on", l.Addr())
		specs := getAPISpecs()
		loadApps(specs, http.DefaultServeMux)
		getPolicies()

		if config.HttpServerOptions.OverrideDefaults {
			log.Warning("HTTP Server Overrides detected, this could destabilise long-running http-requests")
			s := &http.Server{
				Addr:         ":" + targetPort,
				ReadTimeout:  time.Duration(ReadTimeout) * time.Second,
				WriteTimeout: time.Duration(WriteTimeout) * time.Second,
				Handler:      http.DefaultServeMux,
			}

			log.Info("Custom gateway started")
			go s.Serve(l)
			displayConfig()
		} else {
			log.Printf("Gateway started (%v)", VERSION)
			displayConfig()
			http.Serve(l, nil)
		}

		// Kill the parent, now that the child has started successfully.
		if err := goagain.Kill(); nil != err {
			log.Fatalln(err)
		}

	}

	// Block the main goroutine awaiting signals.
	if _, err := goagain.Wait(l); nil != err {
		log.Fatalln(err)
	}

	// Do whatever's necessary to ensure a graceful exit like waiting for
	// goroutines to terminate or a channel to become closed.
	//
	// In this case, we'll simply stop listening and wait one second.
	if err := l.Close(); nil != err {
		log.Fatalln(err)
	}
	//time.Sleep(1e9)
}
Пример #11
0
func main() {

	runtime.GOMAXPROCS(runtime.NumCPU())

	flag.Parse()
	log.SetFlags(log.Lmicroseconds | log.Lshortfile)
	log.SetPrefix(fmt.Sprintf("pid:%d ", syscall.Getpid()))

	if err := readConfig(configFileName); err != nil {
		log.Fatalf("error reading config %s: %s", *configFileName, err)
	}
	logFile, err := os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		log.Fatalf("error opening log file %s: %s", logFileName, err)
	}
	defer logFile.Close()
	log.SetOutput(logFile)

	err = ioutil.WriteFile(pidFileName, []byte(fmt.Sprint(syscall.Getpid())), 0644)
	if err != nil {
		log.Fatalf("error writing pid file %s: %s", pidFileName, err)
	}

	retentionConfigFile, err := os.Open(retentionConfigFileName)
	if err != nil {
		log.Fatalf("error open retentions file %s: %s", pidFileName, err)
	}

	filter.InitGraphiteMetrics()

	db = filter.NewDbConnector(newRedisPool(redisURI))
	patterns = filter.NewPatternStorage()
	cache, err = filter.NewCacheStorage(retentionConfigFile)
	if err != nil {
		log.Fatalf("failed to initialize cache with config %s: %s", retentionConfigFileName, err.Error())
	}

	go patterns.Refresh(db)

	if graphiteURI != "" {
		graphiteAddr, _ := net.ResolveTCPAddr("tcp", graphiteURI)
		go graphite.Graphite(metrics.DefaultRegistry, time.Duration(graphiteInterval)*time.Second, fmt.Sprintf("%s.cache", graphitePrefix), graphiteAddr)
	}

	l, err := goagain.Listener()
	if err != nil {
		l, err = net.Listen("tcp", listen)
		if err != nil {
			log.Fatalf("failed to listen on %s: %s", listen, err.Error())
		}
		log.Printf("listening on %s", listen)

		go serve(l)

	} else {
		log.Printf("resuming listening on %s", listen)

		go serve(l)

		if err := goagain.Kill(); err != nil {
			log.Fatalf("failed to kill parent process: %s", err.Error())
		}
	}

	if _, err := goagain.Wait(l); err != nil {
		log.Fatalf("failed to block main goroutine: %s", err.Error())
	}

	log.Printf("shutting down")
	if err := l.Close(); err != nil {
		log.Fatalf("failed to stop listening: %s", err.Error())
	}
	time.Sleep(time.Second)
	log.Printf("shutdown complete")
}