Beispiel #1
0
func main() {
	var err error
	flags.Parse(os.Args[1:])

	conf, err := server.NewConfigFromFile(*confFile, os.Getenv("CONFIG"))
	if err != nil {
		log.Fatal(err)
	}

	srv := server.New(conf)
	if err := srv.Configure(); err != nil {
		log.Fatal(err)
	}

	lg.Infof("** Imgry Server v%s at %s **", imgry.VERSION, srv.Config.Bind)
	lg.Infof("** Engine: %s", srv.ImageEngine.Version())

	graceful.AddSignal(syscall.SIGINT, syscall.SIGTERM)
	graceful.Timeout(30 * time.Second)
	graceful.PreHook(srv.Close)
	graceful.PostHook(srv.Shutdown)

	err = graceful.ListenAndServe(srv.Config.Bind, srv.NewRouter())
	if err != nil {
		lg.Fatal(err.Error())
	}
	graceful.Wait()
}
Beispiel #2
0
// Serve starts the go-horizon system, binding it to a socket, setting up
// the shutdown signals and starting the appropriate db-streaming pumps.
func (a *App) Serve() {

	a.web.router.Compile()
	http.Handle("/", a.web.router)

	listenStr := fmt.Sprintf(":%d", a.config.Port)
	listener := bind.Socket(listenStr)
	log.Infof(a.ctx, "Starting horizon on %s", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()
	graceful.PreHook(func() {
		log.Info(a.ctx, "received signal, gracefully stopping")
		a.Cancel()
	})
	graceful.PostHook(func() {
		log.Info(a.ctx, "stopped")
	})

	if a.config.Autopump {
		sse.SetPump(a.ctx, sse.AutoPump)
	} else {
		sse.SetPump(a.ctx, db.NewLedgerClosePump(a.ctx, a.historyDb))
	}

	err := graceful.Serve(listener, http.DefaultServeMux)

	if err != nil {
		log.Panic(a.ctx, err)
	}

	graceful.Wait()
}
Beispiel #3
0
// Serve starts the horizon system, binding it to a socket, setting up
// the shutdown signals and starting the appropriate db-streaming pumps.
func (a *App) Serve() {

	a.web.router.Compile()
	http.Handle("/", a.web.router)

	listenStr := fmt.Sprintf(":%d", a.config.Port)
	listener := bind.Socket(listenStr)
	log.Infof("Starting horizon on %s", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()
	graceful.PreHook(func() {
		log.Info("received signal, gracefully stopping")
		a.Close()
	})
	graceful.PostHook(func() {
		log.Info("stopped")
	})

	sse.SetPump(a.pump.Subscribe())

	err := graceful.Serve(listener, http.DefaultServeMux)

	if err != nil {
		log.Panic(err)
	}

	graceful.Wait()
}
Beispiel #4
0
func main() {
	flags.Parse(os.Args[1:])

	// Override config file by the CONFIG env var, if specified.
	if os.Getenv("CONFIG") != "" {
		*confFile = os.Getenv("CONFIG")
	}

	// Read Config.
	conf, err := config.New(*confFile)
	if err != nil {
		log.Fatal(err)
	}

	// Run QMD.
	app, err := qmd.New(conf)
	if err != nil {
		log.Fatal(err)
	}
	go app.WatchScripts()
	go app.StartWorkers()
	go app.ListenQueue()

	graceful.AddSignal(syscall.SIGINT, syscall.SIGTERM)
	graceful.PreHook(app.Close)

	// Start the API server.
	log.Printf("Starting QMD API at %s\n", conf.Bind)
	err = graceful.ListenAndServe(conf.Bind, rest.Routes(app))
	if err != nil {
		log.Fatal(err)
	}
	graceful.Wait()
}
Beispiel #5
0
// Serve starts kami with reasonable defaults.
// It works (exactly) like Goji, looking for Einhorn, the bind flag, GOJI_BIND...
func Serve() {
	if !flag.Parsed() {
		flag.Parse()
	}

	// Install our handler at the root of the standard net/http default mux.
	// This allows packages like expvar to continue working as expected.
	http.Handle("/", Handler())

	listener := bind.Default()
	log.Println("Starting kami on", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()
	graceful.PreHook(func() { log.Printf("kami received signal, gracefully stopping") })
	graceful.PostHook(func() { log.Printf("kami stopped") })

	err := graceful.Serve(listener, http.DefaultServeMux)

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

	graceful.Wait()
}
Beispiel #6
0
func main() {
	var err error
	flags.Parse(os.Args[1:])

	conf, err := server.NewConfigFromFile(*confFile, os.Getenv("CONFIG"))
	if err != nil {
		log.Fatal(err)
	}

	srv := server.New(conf)

	graceful.AddSignal(syscall.SIGINT, syscall.SIGTERM)
	graceful.PreHook(func() { srv.Close() })

	if err := srv.Configure(); err != nil {
		log.Fatal(err)
	}

	lg.Infof("** Imgry Server v%s at %s **\n", imgry.VERSION, srv.Config.Server.Addr)
	lg.Infof("** Engine: %s", imagick.Engine{}.Version())

	err = graceful.ListenAndServe(srv.Config.Server.Addr, srv.NewRouter())
	if err != nil {
		lg.Fatal(err.Error())
	}
	graceful.Wait()
}
Beispiel #7
0
func main() {
	start := time.Now()
	defer func() {
		end := time.Now()
		fmt.Printf("The call took %v to run.\n", end.Sub(start))
	}()
	if len(os.Args) == 1 {
		help("unkown")
		return
	}
	switch cmd := os.Args[1]; {
	case cmd == "server" || cmd == "s":
		startServer()
		defer graceful.Wait()
	case cmd == "generate" || cmd == "g":
		generate()
	case cmd == "init" || cmd == "i":
		workspace()
	case cmd == "new" || cmd == "n":
		article(os.Args[2:])
	case cmd == "help" || cmd == "h":
		if len(os.Args) > 2 {
			help(os.Args[2])
		}
	case cmd == "deploy" || cmd == "d":
		server.Deploy()
	default:
		help("unkown")
	}
}
// Serve starts Goji using reasonable defaults.
func Serve() {
	if !flag.Parsed() {
		flag.Parse()
	}

	log.SetFlags(log.Flags() | log.Lmicroseconds)

	// Install our handler at the root of the standard net/http default mux.
	// This allows packages like expvar to continue working as expected.
	http.Handle("/", DefaultMux)

	listener := bind.Default()
	log.Println("Starting Goji on", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()

	err := graceful.Serve(listener, http.DefaultServeMux)

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

	graceful.Wait()
}
Beispiel #9
0
func serve() {
	goji.DefaultMux.Compile()
	// Install our handler at the root of the standard net/http default mux.
	// This allows packages like expvar to continue working as expected.
	http.Handle("/", goji.DefaultMux)

	listener := bind.Socket(bind.Sniff())
	log.Println("Starting Goji on", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()
	graceful.PreHook(func() { log.Printf("Goji received signal, gracefully stopping") })
	graceful.PostHook(func() {
		log.Printf("Goji stopped")
		log.Printf("Shutting down the server")
		handler.DB.Close()
		log.Printf("Database shut down. Terminating the process.")
	})

	err := graceful.Serve(listener, http.DefaultServeMux)

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

	graceful.Wait()
}
Beispiel #10
0
func Run() {
	http.Handle("/", DefaultServerMux)
	listener, err := net.Listen("tcp", Config.App.Bind)
	if err != nil {
		panic(err)
	}
	err = graceful.Serve(listener, DefaultServerMux)
	if err != nil {
		panic(err)
	}
	graceful.Wait()
}
Beispiel #11
0
func (s *Server) HTTPServe() {
	httpSocket := bind.Socket(s.HTTPAddr)
	graceful.Timeout(10 * time.Second)
	graceful.PreHook(func() {
		s.logger.Info("Terminating HTTP listener")
	})
	graceful.HandleSignals()
	s.logger.WithField("address", s.HTTPAddr).Info("HTTP server listening")
	bind.Ready()

	if err := graceful.Serve(httpSocket, s.Handler()); err != nil {
		s.logger.WithError(err).Error("HTTP server shut down due to error")
	}
	graceful.Wait()
}
func main() {
	// sets the maximum number of CPUs that can be executing simultaneously
	runtime.GOMAXPROCS(runtime.NumCPU())

	// override defaults via env vars
	if os.Getenv("ES_HOST") != "" {
		esHost = os.Getenv("ES_HOST")
	}
	if os.Getenv("ES_PORT") != "" {
		esPort = os.Getenv("ES_PORT")
	}
	if os.Getenv("REDIS_HOST") != "" {
		redisHost = os.Getenv("REDIS_HOST")
	}
	if os.Getenv("REDIS_PORT") != "" {
		redisPort = os.Getenv("REDIS_PORT")
	}
	if os.Getenv("PUBLIC_DIR") != "" {
		publicDir = os.Getenv("PUBLIC_DIR")
	}

	// log endpoints
	log.Infof("Redis endpoint set to %s:%s", redisHost, redisPort)
	log.Infof("Elasticsearch endpoint set to %s:%s", esHost, esPort)

	// register available tiling types
	tile.Register("heatmap", elastic.NewHeatmapTile(esHost, esPort))
	tile.Register("topic_count", elastic.NewTopCountTile(esHost, esPort))
	// register available meta data types
	meta.Register("default", elastic.NewDefaultMeta(esHost, esPort))
	// register available store types
	store.Register("redis", redis.NewConnection(redisHost, redisPort))

	// create server
	app := api.New(publicDir)

	// catch kill signals for graceful shutdown
	graceful.AddSignal(syscall.SIGINT, syscall.SIGTERM)
	// start server
	log.Infof("Prism server listening on port %s", port)
	err := graceful.ListenAndServe(":"+port, app)
	if err != nil {
		log.Error(err)
	}
	// wait until server gracefully exits
	graceful.Wait()
}
Beispiel #13
0
func serve(mux *web.Mux, bindProtocol, bindPort string) {
	// For now, this is completely lifted from goji's default handler.
	http.Handle("/", mux)
	log.Printf("Starting on %v/%v", bindProtocol, bindPort)
	graceful.HandleSignals()
	listener, err := net.Listen(bindProtocol, bindPort)
	if err != nil {
		log.Fatalf("Couldn't open socket on %v/%v: %v", bindProtocol, bindPort, err)
	}
	graceful.PreHook(func() { log.Info("Received signal, gracefully stopping.") })
	graceful.PostHook(func() { log.Info("Stopped.") })
	err = graceful.Serve(listener, http.DefaultServeMux)
	if err != nil {
		log.Fatalf("Couldn't serve on %v/%v: %v", bindProtocol, bindPort, err)
	}
	graceful.Wait()
}
Beispiel #14
0
// SetupMainServer allocates a listener socket and starts a web server with graceful restart
// on the specified IP address and port. The ipPort has the format "ip_address:port" or
// ":port" for 0.0.0.0/port.
func SetupMainServer(ipPort string, mux *web.Mux) {
	listener, err := net.Listen("tcp4", ipPort)
	if err != nil {
		FatalError(err.Error())
	}

	// Install our handler at the root of the standard net/http default mux.
	// This allows packages like expvar to continue working as expected.
	mux.Compile()
	http.Handle("/", mux)

	graceful.HandleSignals()
	graceful.PreHook(func() { log15.Warn("Gracefully stopping on signal") })
	graceful.PostHook(func() { log.Printf("Gracefully stopped") })

	err = graceful.Serve(listener, http.DefaultServeMux)
	if err != nil {
		FatalError(err.Error())
	}

	graceful.Wait()
}
Beispiel #15
0
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	// Parse the flags and store them as a conf struct
	flag.Parse()
	conf := skeletor.Conf{
		Prod:    *prod,
		Version: version,
	}
	skeletor.SaveConf(&conf)

	// Start the web server
	graceful.AddSignal(syscall.SIGINT, syscall.SIGTERM)
	app := api.New()
	log.Println("Skeletor server listening on", *bind)
	err := graceful.ListenAndServe(*bind, app)
	if err != nil {
		log.Fatal(err)
	}

	graceful.Wait()
}
Beispiel #16
0
/**
*There was no support of TLS in kami
*Copy-paste from Goji
**/
func ServeTLS(config *tls.Config) {
	if !flag.Parsed() {
		flag.Parse()
	}

	http.Handle("/", kami.Handler())

	listener := tls.NewListener(bind.Default(), config)
	log.Println("Starting kami on", listener.Addr())

	graceful.HandleSignals()
	bind.Ready()
	graceful.PreHook(func() { log.Printf("kami received signal, gracefully stopping") })
	graceful.PostHook(func() { log.Printf("kami stopped") })

	err := graceful.Serve(listener, http.DefaultServeMux)

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

	graceful.Wait()
}
Beispiel #17
0
func main() {
	// Create a DB with the test table and seed data
	db, _ := gorm.Open("sqlite3", "./grapi-example.db")
	seedDb(&db)

	// Create an API server. We need to supply JwtKey if we're doing authentication.
	// We pass db.Debug() instead of &db so you can see the sql queries in the log.
	a := grapi.New(grapi.Options{Db: db.Debug(), JwtKey: "SomethingLongAndDifficultToGuess"})
	http.Handle("/api/", a)
	http.HandleFunc("/", indexHandler)

	// Allow logging in with the User model at /api/login. Details will be checked by User.CheckLoginDetails()
	a.SetAuth(&User{}, "login")

	// Setup some useful RouteOptions that we will use for adding authenticated routs.

	// This one allows only authenticated users (ie. they've logged in at "/login" above).
	onlyAuthenticated := grapi.RouteOptions{UseDefaultAuth: true}

	// Only Allow Admin
	onlyAdmin := grapi.RouteOptions{
		UseDefaultAuth: true,
		// Add an authorize callback. This is a Martini handler, and can access the LoginModel
		// used for authentication. As we called API.SetAuth with &User{} this is guaranteed to
		// be a *User, so we can do a type assertion.
		Authorize: func(req grapi.ReqToAuthorize) bool {
			user := req.GetLoginObject().(*User)
			if !user.Admin {
				http.Error(req.GetResponseWriter(), `{"error":"You need to be admin to do that"}`, 403)
				return false
			}
			return true
		}}

	// This RouteOptions can be used for any table with a user_id field. If logged in as admin
	// it allows anything. If logged in as user it limits GETs to those of own user_id, and
	// delete to own user_id. It also prevents changing user ownership.
	onlyOwnUnlessAdmin := grapi.RouteOptions{
		UseDefaultAuth: true,
		Query: func(req grapi.ReqToLimit) bool {
			user := req.GetLoginObject().(*User)
			// Scope the requests database to only contain owned items. This prevents unauthorized
			// GET, DELETE, and PATCH requests, and limits the index to own items.
			if !user.Admin {
				req.SetDB(req.GetDB().Where("user_id = ?", user.ID))
			}
			return true
		},
		CheckUpload: func(req grapi.ReqULToCheck) bool {
			user := req.GetLoginObject().(*User)
			uploaded := req.GetUpload().(BelongsToUser)
			// For PATCH and POST routes we also need to check that the uploaded object has the correct user_id
			if !user.Admin && user.ID != uploaded.UserId() {
				http.Error(req.GetResponseWriter(), `{"error":"Only admin can change a user_id"}`, 403)
				return false
			}
			return true
		}}

	// Add the Default REST routes for User.
	// If two RouteOptions structures are provided the first is used for Read routes,
	// and the second for Write routes. If three are given then the third is used for
	// DELETE requests.
	a.AddDefaultRoutes(&User{}, onlyAuthenticated, onlyAdmin)

	// We want people to only see their own widgets, unless they are admin.
	a.AddDefaultRoutes(&PrivateWidget{}, onlyOwnUnlessAdmin)

	// We are going to make the widget list available to view by user at
	// /api/user/:user_id/private_widgets
	a.AddIndexRoute(&PrivateWidget{},
		&grapi.RouteOptions{
			Prefix: "/user/:user_id",
			Query: func(req grapi.ReqToLimit) bool {
				req.SetDB(req.GetDB().Where("user_id = ?", req.Param("user_id")))
				return true
			}})

	// Run the server.
	listener, err := net.Listen("tcp", "127.0.0.1:3000")
	if err != nil {
		panic(err.Error())
	}
	err = graceful.Serve(listener, http.DefaultServeMux)
	if err != nil {
		panic(err.Error())
	}

	graceful.Wait()
}
Beispiel #18
0
func main() {
	// Parse the flags
	flag.Parse()

	logrus.Infoln("**********************************************************")
	logrus.Infoln("goproject server starting ...")
	logrus.Infof("Version : %s (%s-%s)", version.Version, version.Revision, version.Branch)

	// Set localtime to UTC
	time.Local = time.UTC

	// Put config into the environment package
	shared.Config = &shared.Flags{
		BindAddress:      *bindAddress,
		LogFormatterType: *logFormatterType,
		ForceColors:      *forceColors,
		RavenDSN:         *ravenDSN,

		DatabaseDriver:    *databaseDriver,
		DatabaseHost:      *databaseHost,
		DatabaseNamespace: *databaseNamespace,
		DatabaseUser:      *databaseUser,
		DatabasePassword:  *databasePassword,

		MemcachedHosts: *memcachedHosts,
		RedisHost:      *redisHost,
	}

	// Generate a mux
	mux := system.Setup(shared.Config)

	// Make the mux handle every request
	http.Handle("/", mux)

	// Log that we're starting the server
	shared.Log.WithFields(logrus.Fields{
		"address": shared.Config.BindAddress,
	}).Info("Starting the HTTP server")

	// Initialize the goroutine listening to signals passed to the app
	graceful.HandleSignals()

	// Pre-graceful shutdown event
	graceful.PreHook(func() {
		shared.Log.Info("Received a signal, stopping the application")
	})

	// Post-shutdown event
	graceful.PostHook(func() {
		shared.Log.Info("Stopped the application")
	})

	// Listen to the passed address
	listener, err := net.Listen("tcp", shared.Config.BindAddress)
	if err != nil {
		shared.Log.WithFields(logrus.Fields{
			"error":   err,
			"address": *bindAddress,
		}).Fatal("Cannot set up a TCP listener")
	}

	// Start the listening
	err = graceful.Serve(listener, http.DefaultServeMux)
	if err != nil {
		// Don't use .Fatal! We need the code to shut down properly.
		shared.Log.Error(err)
	}

	// If code reaches this place, it means that it was forcefully closed.

	// Wait until open connections close.
	graceful.Wait()
}
Beispiel #19
0
func main() {
	// Parse the flags
	flag.Parse()

	// Put config into the environment package
	env.Config = &env.Flags{
		BindAddress:      *bindAddress,
		APIVersion:       *apiVersion,
		LogFormatterType: *logFormatterType,
		ForceColors:      *forceColors,
		EmailDomain:      *emailDomain,

		SessionDuration: *sessionDuration,

		RedisAddress:  *redisAddress,
		RedisDatabase: *redisDatabase,
		RedisPassword: *redisPassword,

		RethinkDBAddress:  *rethinkdbAddress,
		RethinkDBKey:      *rethinkdbKey,
		RethinkDBDatabase: *rethinkdbDatabase,

		NSQdAddress:    *nsqdAddress,
		LookupdAddress: *lookupdAddress,

		YubiCloudID:  *yubiCloudID,
		YubiCloudKey: *yubiCloudKey,

		SlackURL:      *slackURL,
		SlackLevels:   *slackLevels,
		SlackChannel:  *slackChannel,
		SlackIcon:     *slackIcon,
		SlackUsername: *slackUsername,

		BloomFilter: *bloomFilter,
		BloomCount:  *bloomCount,

		RavenDSN: *ravenDSN,
	}

	// Generate a mux
	mux := setup.PrepareMux(env.Config)

	// Make the mux handle every request
	http.Handle("/", mux)

	// Log that we're starting the server
	env.Log.WithFields(logrus.Fields{
		"address": env.Config.BindAddress,
	}).Info("Starting the HTTP server")

	// Initialize the goroutine listening to signals passed to the app
	graceful.HandleSignals()

	// Pre-graceful shutdown event
	graceful.PreHook(func() {
		env.Log.Info("Received a singnal, stopping the application")
	})

	// Post-shutdown event
	graceful.PostHook(func() {
		env.Log.Info("Stopped the application")
	})

	// Listen to the passed address
	listener, err := net.Listen("tcp", env.Config.BindAddress)
	if err != nil {
		env.Log.WithFields(logrus.Fields{
			"error":   err,
			"address": *bindAddress,
		}).Fatal("Cannot set up a TCP listener")
	}

	// Start the listening
	err = graceful.Serve(listener, http.DefaultServeMux)
	if err != nil {
		// Don't use .Fatal! We need the code to shut down properly.
		env.Log.Error(err)
	}

	// If code reaches this place, it means that it was forcefully closed.

	// Wait until open connections close.
	graceful.Wait()
}