Ejemplo n.º 1
1
func configureNewRelic() {
	agent := gorelic.NewAgent()
	agent.Verbose = true
	agent.NewrelicLicense = os.Getenv("NEW_RELIC_LICENSE_KEY")
	agent.NewrelicName = "Go sendgrid events handler"
	agent.Run()
}
Ejemplo n.º 2
1
// InitNewRelicAgent initializes a new gorelic agent for usage in Handler
func InitNewRelicAgent(license string, appname string, verbose bool) (*gorelic.Agent, error) {
	if license == "" {
		return gorelic.NewAgent(), fmt.Errorf("Please specify a NewRelic license")
	}
	agent = gorelic.NewAgent()

	agent.NewrelicLicense = license
	agent.NewrelicName = appname
	agent.HTTPTimer = metrics.NewTimer()
	agent.CollectHTTPStat = true
	agent.Verbose = verbose

	agent.Run()

	return agent, nil
}
Ejemplo n.º 3
0
// NewrelicAgentMiddleware inits gorelic's NewRelic object and returns handler function
func NewrelicAgentMiddleware(license string, appname string, verbose bool) gin.HandlerFunc {
	var agent *gorelic.Agent

	if license == "" {
		return nil
	}

	agent = gorelic.NewAgent()
	agent.NewrelicLicense = license

	agent.HTTPTimer = metrics.NewTimer()
	agent.CollectHTTPStat = true
	agent.Verbose = verbose

	agent.NewrelicName = appname
	agent.Run()

	return func(c *gin.Context) {
		startTime := time.Now()
		c.Next()

		if agent != nil {
			agent.HTTPTimer.UpdateSince(startTime)
		}
	}
}
Ejemplo n.º 4
0
func configureReporting(app *handlers.App) http.Handler {
	var handler http.Handler = app

	if app.Config.Reporting.Bugsnag.APIKey != "" {
		bugsnagConfig := bugsnag.Configuration{
			APIKey: app.Config.Reporting.Bugsnag.APIKey,
			// TODO(brianbland): provide the registry version here
			// AppVersion: "2.0",
		}
		if app.Config.Reporting.Bugsnag.ReleaseStage != "" {
			bugsnagConfig.ReleaseStage = app.Config.Reporting.Bugsnag.ReleaseStage
		}
		if app.Config.Reporting.Bugsnag.Endpoint != "" {
			bugsnagConfig.Endpoint = app.Config.Reporting.Bugsnag.Endpoint
		}
		bugsnag.Configure(bugsnagConfig)

		handler = bugsnag.Handler(handler)
	}

	if app.Config.Reporting.NewRelic.LicenseKey != "" {
		agent := gorelic.NewAgent()
		agent.NewrelicLicense = app.Config.Reporting.NewRelic.LicenseKey
		if app.Config.Reporting.NewRelic.Name != "" {
			agent.NewrelicName = app.Config.Reporting.NewRelic.Name
		}
		agent.CollectHTTPStat = true
		agent.Verbose = app.Config.Reporting.NewRelic.Verbose
		agent.Run()

		handler = agent.WrapHTTPHandler(handler)
	}

	return handler
}
Ejemplo n.º 5
0
func runLogProcesses() {
	fmt.Println("Initialize relic ")
	agent := gorelic.NewAgent()
	agent.Verbose = true
	agent.NewrelicLicense = os.Getenv("GRANTHCO_LOG_CREDENTIALS")
	agent.Run()

}
Ejemplo n.º 6
0
func startNewRelic() {
	key := os.Getenv("NEW_RELIC_LICENSE_KEY")
	agent := gorelic.NewAgent()
	agent.Verbose = true
	agent.NewrelicLicense = key

	fmt.Println("Starting NewRelic for " + key)
	agent.Run()
}
Ejemplo n.º 7
0
func startNewrelic() {
	if cfg.NewrelicEnabled {
		nr := gorelic.NewAgent()
		nr.Verbose = cfg.NewrelicVerbose
		nr.NewrelicLicense = cfg.NewrelicKey
		nr.NewrelicName = cfg.NewrelicName
		nr.Run()
	}
}
Ejemplo n.º 8
0
func startMonitoring(license string) {
	agent := gorelic.NewAgent()
	agent.Verbose = true
	agent.CollectHTTPStat = true
	agent.NewrelicLicense = license
	agent.NewrelicName = "Cloudgov Deck"
	if err := agent.Run(); err != nil {
		fmt.Println(err.Error())
	}
}
Ejemplo n.º 9
0
func main() {
	var (
		newrelicLicense = os.Getenv("NEWRELIC_LICENSE")
		newrelicName    = os.Getenv("NEWRELIC_NAME")
	)
	if newrelicLicense != "" && newrelicName != "" {
		agent := gorelic.NewAgent()
		agent.Verbose = true
		agent.NewrelicLicense = os.Getenv("NEWRELIC_LICENSE")
		agent.NewrelicName = os.Getenv("NEWRELIC_NAME")
		agent.Run()
	}

	m := martini.Classic()
	m.Get("/", func() string {
		return "Hello world!"
	})

	var logger *log.Logger
	logger = m.Injector.Get(reflect.TypeOf(logger)).Interface().(*log.Logger)

	m.Post("**", func(res http.ResponseWriter, req *http.Request) (int, string) {
		var (
			contentTypeHeader []string
			contentType       string
		)
		contentTypeHeader = req.Header["Content-Type"]
		if len(contentTypeHeader) > 0 {
			contentType = contentTypeHeader[0]
		} else {
			return 400, "Content-Type header is mandatory"
		}
		body, err := ioutil.ReadAll(req.Body)
		if err != nil {
			return 400, "Invalid request body"
		}
		if contentType == "application/x-php" {
			qsa := toMapStringString(req.URL.Query())
			return checkPhp(res, string(body[:]), qsa)
		}
		return 415, "Content-Type not currently supported"
	})

	var corsOrigins = os.Getenv("CORS_ORIGINS")
	if corsOrigins != "" {
		logger.Println("activating CORS: " + corsOrigins)
		m.Use(cors.Allow(&cors.Options{
			AllowOrigins: strings.Split(corsOrigins, ","),
			AllowMethods: []string{"GET", "POST"},
			AllowHeaders: []string{"Origin", "Content-Type"},
		}))
	}

	m.Run()
}
Ejemplo n.º 10
0
func registerNewRelic() {
	agent := gorelic.NewAgent()
	agent.Verbose = true
	agent.NewrelicLicense = os.Getenv("NEWRELIC_LICENSE")
	log.Printf("NRL %s", agent.NewrelicLicense)
	agent.NewrelicName = "Gaia"
	agent.CollectHTTPStat = true
	agent.Verbose = true

	agent.Run()
}
Ejemplo n.º 11
0
func startMetrics() {
	newRelicAPIKey := os.Getenv("NEW_RELIC_KEY")

	if newRelicAPIKey == "" {
		return
	}

	agent := gorelic.NewAgent()
	agent.Verbose = false
	agent.NewrelicLicense = newRelicAPIKey
	agent.Run()
}
Ejemplo n.º 12
0
func gorelicMonitor() {

	if envIsStaging() || envIsProduction() {
		if key := os.Getenv("NEW_RELIC_LICENSE_KEY"); key != "" {
			agent := gorelic.NewAgent()
			agent.NewrelicName = "emojitrack-gostreamer"
			agent.NewrelicLicense = key
			agent.Verbose = false
			agent.Run()
		}
	}

}
Ejemplo n.º 13
0
func initGorelic() {
	if !conf.IsDev() {
		return
	}

	agent = gorelic.NewAgent()
	agent.NewrelicName = "go-gamereviews"
	agent.Verbose = true
	agent.NewrelicLicense = conf.Config.NewrelicLicense
	agent.CollectHTTPStat = true
	agent.HTTPTimer = metrics.NewTimer()
	agent.Run()
}
Ejemplo n.º 14
0
func main() {

	flag.Parse()
	if *newrelicLicense == "" {
		log.Fatalf("Please, pass a valid newrelic license key.\n Use --help to get more information about available options\n")
	}
	agent := gorelic.NewAgent()
	agent.Verbose = true
	agent.NewrelicLicense = *newrelicLicense
	agent.Run()

	doSomeJob(100)
}
Ejemplo n.º 15
0
func main() {
	flag.Parse()
	if *newrelicLicense == "" {
		log.Fatalf("Please, pass a valid newrelic license key.\n Use --help to get more information about available options\n")
	}
	agent := gorelic.NewAgent()
	agent.Verbose = true
	agent.CollectHTTPStat = true
	agent.NewrelicLicense = *newrelicLicense
	agent.Run()

	http.HandleFunc("/", agent.WrapHTTPHandlerFunc(helloServer))
	http.ListenAndServe(":8080", nil)

}
Ejemplo n.º 16
0
func NewContext(c *config.Config) *Context {
	var agent *gorelic.Agent = nil

	if c.NewRelic != nil && len(c.NewRelic.Key) > 0 && len(c.NewRelic.Name) > 0 {
		agent = gorelic.NewAgent()
		agent.NewrelicLicense = c.NewRelic.Key
		agent.NewrelicName = c.NewRelic.Name
		agent.Run()
	}

	return &Context{
		HeimdallOptions: c.HeimdallOptions,
		NewRelic:        agent,
	}
}
Ejemplo n.º 17
0
func New(license string, appname string, verbose bool) *Gorelic {
	if license == "" {
		panic("Please specify NewRelic license")
	}

	agent := gorelic.NewAgent()
	agent.NewrelicLicense = license
	agent.HTTPTimer = metrics.NewTimer()
	agent.CollectHTTPStat = true
	agent.Verbose = verbose

	agent.NewrelicName = appname
	agent.Run()

	return &Gorelic{agent}
}
Ejemplo n.º 18
0
func main() {
	agent := gorelic.NewAgent()
	agent.NewrelicLicense = os.Getenv("NEW_RELIC_LICENSE_KEY")
	agent.Run()

	handler := routes.Handler()
	port := ":" + os.Getenv("PORT")
	http.Handle("/", handler)

	log.Println("Listening in", port)
	err := http.ListenAndServe(port, nil)

	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
Ejemplo n.º 19
0
func NewRelic(license string, appname string, verbose bool) gin.HandlerFunc {
	agent = gorelic.NewAgent()
	agent.NewrelicLicense = license

	agent.HTTPTimer = metrics.NewTimer()
	agent.CollectHTTPStat = true
	agent.Verbose = verbose

	agent.NewrelicName = appname
	agent.Run()

	return func(c *gin.Context) {
		startTime := time.Now()
		c.Next()
		agent.HTTPTimer.UpdateSince(startTime)
	}
}
Ejemplo n.º 20
0
// InitNewrelicAgent creates the new relic agent
func InitNewrelicAgent(license string, appname string, verbose bool, customMetrics []Metric) (gin.HandlerFunc, error) {
	if license == "" {
		return nil, fmt.Errorf("Please specify a NewRelic license")
	}

	agent = gorelic.NewAgent()
	agent.NewrelicLicense = license
	agent.HTTPTimer = metrics.NewTimer()
	agent.CollectHTTPStat = true
	agent.Verbose = verbose
	agent.NewrelicName = appname

	if customMetrics != nil {
		addCustomMetrics(customMetrics)
	}

	return Handler, agent.Run()
}
Ejemplo n.º 21
0
func (mw *NewRelicMiddleware) MiddlewareFunc(handler rest.HandlerFunc) rest.HandlerFunc {

	mw.agent = gorelic.NewAgent()
	mw.agent.NewrelicLicense = mw.License
	mw.agent.HTTPTimer = metrics.NewTimer()
	mw.agent.Verbose = mw.Verbose
	mw.agent.NewrelicName = mw.Name
	mw.agent.CollectHTTPStat = true
	mw.agent.Run()

	return func(writer rest.ResponseWriter, request *rest.Request) {

		handler(writer, request)

		// the timer middleware keeps track of the time
		startTime := request.Env["START_TIME"].(*time.Time)
		mw.agent.HTTPTimer.UpdateSince(*startTime)
	}
}
Ejemplo n.º 22
0
func NewContext(c *config.Config) *Context {
	var agent *gorelic.Agent = nil

	if c.NewRelic != nil && len(c.NewRelic.Key) > 0 && len(c.NewRelic.Name) > 0 {
		agent = gorelic.NewAgent()
		agent.NewrelicLicense = c.NewRelic.Key
		agent.NewrelicName = c.NewRelic.Name
		agent.Run()
	}

	c.Services.SetNextEndpoint(c.NextEndpoint)

	return &Context{
		BaseUrl:  c.BaseUrl,
		SignKey:  c.SignKey,
		Services: c.Services,
		Facebook: c.Facebook,
		NewRelic: agent,
	}
}
Ejemplo n.º 23
0
//NewImageServerWithNewRelic will return an image server with newrelic monitoring
//licenseKey must be your newrelic license key
func NewImageServerWithNewRelic(config *Config, storage Storage, licenseKey string) Server {
	var handler http.Handler
	// in order to simple configure the image server in the proxy configuration of nginx
	// we will be getting every database variable from the request
	serverRoute := "/{database}/{filename}"

	r := mux.NewRouter()
	r.HandleFunc("/", welcomeHandler)
	//TODO refactor depedency mess
	r.Handle(serverRoute, func(storage Storage, z *Config) http.HandlerFunc {
		return func(w http.ResponseWriter, r *http.Request) {
			vars := mux.Vars(r)

			requestConfig, validateError := CreateConfigurationFromVars(r, vars)

			if validateError != nil {
				log.Printf("%d invalid request parameters given.\n", http.StatusNotFound)
				w.WriteHeader(http.StatusNotFound)
				return
			}

			imageHandler(w, r, requestConfig, storage, z)
		}
	}(storage, config))
	http.Handle("/", r)

	handler = http.DefaultServeMux

	if licenseKey != "" {
		agent := gorelic.NewAgent()
		agent.NewrelicLicense = licenseKey
		agent.NewrelicName = "Go image server"
		agent.CollectHTTPStat = true
		agent.Run()
		handler = agent.WrapHTTPHandler(handler)
	}

	handlerMux := context.ClearHandler(handler)
	return &imageServer{imageConfiguration: config, handlerMux: handlerMux}
}
Ejemplo n.º 24
0
// InitNewrelicAgent creates the new relic agent
func InitNewrelicAgent(license string, appname string, verbose bool, customCounters map[string]string) error {

	if license == "" {
		return fmt.Errorf("Please specify NewRelic license")
	}

	agent = gorelic.NewAgent()
	agent.NewrelicLicense = license

	agent.HTTPTimer = metrics.NewTimer()
	agent.CollectHTTPStat = true
	agent.Verbose = verbose

	agent.NewrelicName = appname

	for k, v := range customCounters {
		simpleCountersMap[k] = &SimpleCounter{name: k, units: v}
		agent.AddCustomMetric(simpleCountersMap[k])
	}
	agent.Run()
	return nil
}
Ejemplo n.º 25
0
func InitNewrelicAgent() {

	license := beego.AppConfig.String("NewrelicLicense")
	if license == "" {
		beego.Warn("Please specify NewRelic license in the application config: NewrelicLicense=7bceac019c7dcafae1ef95be3e3a3ff8866de245")
		return
	}

	agent = gorelic.NewAgent()
	agent.NewrelicLicense = license

	agent.HTTPTimer = metrics.NewTimer()
	agent.CollectHTTPStat = true

	if beego.RunMode == "dev" {
		agent.Verbose = true
	}
	if verbose, err := beego.AppConfig.Bool("NewrelicVerbose"); err == nil {
		agent.Verbose = verbose
	}

	nameParts := []string{beego.AppConfig.String("appname")}
	switch strings.ToLower(beego.AppConfig.String("NewrelicAppnameRunmode")) {
	case "append":
		nameParts = append(nameParts, beego.RunMode)

	case "prepend":
		nameParts = append([]string{beego.RunMode}, nameParts...)
	}
	agent.NewrelicName = strings.Join(nameParts, SEPARATOR)
	agent.Run()

	beego.InsertFilter("*", beego.BeforeRouter, InitNewRelicTimer, false)
	beego.InsertFilter("*", beego.FinishRouter, ReportMetricsToNewrelic, false)

	beego.Info("NewRelic agent started")
}
Ejemplo n.º 26
0
// InitNewRelic start newrelic
func InitNewRelic() {
	agent := gorelic.NewAgent()
	agent.Verbose = true
	agent.NewrelicLicense = "0f9d8145340e20588fe6fe3df67349f6bcd806d8"
	agent.Run()
}
Ejemplo n.º 27
0
func main() {
	// Add the Stdout logger
	logger.AddOutput(logger.Stdout{
		MinLevel: logger.ERROR, //logger.DEBUG,
		Colored:  true,
	})

	// Load settings from config.toml in working directory
	settings := config.Load("./config.toml")

	/*logger.AddOutput(&logger.File{
		MinLevel: logger.WARNING,
		Path:     "./server.log",
	})*/

	// Load the aCI3 key
	err := aci.LoadKey(settings.NP.AnticheatKeyPath)
	if err != nil {
		logger.Fatalf("Cannot load aCI3 key; %s", err)
	} else {
		logger.Infof("Loaded aCI3 key")
	}

	// Start the NewRelic client if it's enabled in the config file
	if settings.NewRelic.Enabled {
		agent := gorelic.NewAgent()
		agent.Verbose = settings.NewRelic.Verbose
		agent.NewrelicName = settings.NewRelic.Name
		agent.NewrelicLicense = settings.NewRelic.License
		agent.Run()
	}

	// Generate a Jet database connector.
	// Here, err shows if the connection string syntax is valid.
	// The actual creds are checked during the first query.
	database, err := jet.Open(
		settings.Database.Driver,
		settings.Database.ConnectionString,
	)
	defer database.Close()

	if err != nil {
		logger.Fatalf("Cannot connect to database; %s", err)
	}

	// But Redis connects here! As far as I know, autoreconnect is implemented
	cache := redis.NewTCPClient(&redis.Options{
		Addr:     settings.Redis.Address,
		Password: settings.Redis.Password,
		DB:       int64(settings.Redis.Database),
	})
	defer cache.Close()

	// Set up a new environment object
	environment.SetEnvironment(&environment.Environment{
		Config:   settings,
		Database: database,
		Redis:    cache,
	})

	// This thing is massive
	// The main network platform server that game connects to
	if settings.NP.Enabled {
		np_server := np.New()
		go np_server.Start()
	}

	// HTTP-based remote authentication form and a simple API
	// Is supposed to replace half of 3k
	if settings.HTTP.Enabled {
		http_server := http.New()
		go http_server.Start()
	}

	/*if settings.PlayerLog.Enabled {
		playerlog_server := playerlog.Init(settings.PlayerLog)
		go playerlog_server.Start()
	}

	if settings.Misc.Enabled {
		misc_server := misc.Init(settings.Misc)
		go misc_server.Start()
	}*/

	// select{} stops execution of the program until all goroutines close
	// TODO: add panic recovery!
	if settings.NP.Enabled ||
		settings.PlayerLog.Enabled ||
		settings.Misc.Enabled ||
		settings.HTTP.Enabled {
		select {}
	}
}
Ejemplo n.º 28
0
func main() {
	//Get environment variables
	devStr := os.Getenv("REDUSEDEVELOPMODE")
	devMode = (devStr == "true")

	herokuProdStr := os.Getenv("REDUSE_HEROKU_PRODUCTION")
	herokuProduction = (herokuProdStr == "true")

	port := os.Getenv("PORT") //get the port that we are to run off of

	//get the database information from the environment
	dbName := os.Getenv("REDUSE_DB_NAME")
	dbAddress := os.Getenv("REDUSE_DB_ADDRESS")
	dbUsername := os.Getenv("REDUSE_DB_USERNAME")
	dbPassword := os.Getenv("REDUSE_DB_PASSWORD")

	//get the pertinent email information
	emailUsername := os.Getenv("REDUSE_EMAIL_USERNAME")
	emailPassword := os.Getenv("REDUSE_EMAIL_PASSWORD")
	adminEmails := os.Getenv("REDUSE_EMAIL_ADMIN_ADDRESSES")

	//Set up logging to stdout
	logger = log.New(os.Stdout, "", log.Lshortfile)
	web.SetLogger(logger)

	if devMode {
		logger.Println("Running in Develop mode")
	}

	if herokuProduction {
		logger.Println("Heroku Production flag set")
	}

	//Run startup code
	started, err := startup()
	if !started {
		logger.Println("Oops, looks like something went wrong with startup.")
		logger.Panic(err)
		return
	}

	//initialize the database (this also validates the database connection)
	err = initDatabase(dbName, dbAddress, dbUsername, dbPassword)
	if err != nil {
		logger.Println("Could not initialize database interface")
		logger.Panic(err.Error())
		return
	}

	//Initialize the email sending functionality
	err = initEmail(adminEmails, emailUsername, emailPassword)
	if err != nil {
		logger.Println("Could not initialize email")
		logger.Panic(err.Error())
		return
	}

	//Past this point, we should not have any panic()'s, rather any and all errors should be handled gracefully

	//don't do any of this stuff if we are in development mode (ie. production-only initialization goes here)
	if !devMode {
		//Set up the NewRelic agent
		agent := gorelic.NewAgent()
		agent.NewrelicLicense = os.Getenv("REDUSE_NEWRELIC_LICENSE_KEY")
		agent.NewrelicName = "Redu.se"
		agent.Run()
	}

	web.Get("/", home)
	web.Get("/page/disabled/?", showDisabled)
	web.Get("/page/terms/?", showTerms)
	web.Post("/page/generate/?", generate)
	web.Get("/page/report/?", reportLink)
	web.Post("/page/report/submit/?", submitReport)
	web.Get("/page/contact/?", contactPage)
	web.Post("/page/contact/submit/?", submitContact)
	web.Get("/rsrc/captcha/img/reload/(.+)\\.png", reloadCaptchaImage)
	web.Get("/rsrc/captcha/img/(.+)\\.png", serveCaptchaImage)
	//web.Get("/rsrc/captcha/audio/(.+)\\.wav", serveCaptchaAudio)
	web.Get("/(.+)/(.*)", serveLinkWithExtras)
	web.Get("/(.+)", serveLink)
	web.Run(":" + port)
}
Ejemplo n.º 29
0
func main() {
	// Load the configuration into a package-scope variable
	cfg = config.Load()

	// Start the NewRelic client if it's enabled in the config file
	if cfg.NewRelic.Enabled {
		agent = gorelic.NewAgent()
		agent.Verbose = cfg.NewRelic.Verbose
		agent.NewrelicName = cfg.NewRelic.Name
		agent.NewrelicLicense = cfg.NewRelic.License
		agent.Run()
	}

	// Connect to the database if logging is enabled in config
	if cfg.Logging.Enabled {
		connection, err := sql.Open("postgres", cfg.Logging.ConnectionString)
		if err != nil {
			log.Printf("Connection to the database failed; %s", err)
		}

		// Export the database connection to package scope
		db = connection
	}

	// Initialize a new martini server
	server := martini.Classic()

	// Allow CORS
	server.Use(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.Header().Set("Access-Control-Allow-Origin", "*")
	})

	// Bind the routes
	server.Get("/total", handleTotal)
	server.Get("/", handleList)

	// Initialize a new scheudler
	scheudle := cron.New()
	scheudle.AddFunc("@every 1m", prepareCache)

	// Call the cache function for the first time
	prepareCache()

	// Run threads
	scheudle.Start()

	// Run SSL if enabled
	if cfg.Binding.HttpsEnabled {
		go func() {
			err := http.ListenAndServeTLS(cfg.Binding.HttpsAddress,
				cfg.Binding.HttpsCertificatePath,
				cfg.Binding.HttpsKeyPath,
				server)

			if err != nil {
				log.Fatalf("Error while serving HTTPS; %s", err)
			}
		}()
	}

	// Run HTTP
	err := http.ListenAndServe(cfg.Binding.HttpAddress, server)
	if err != nil {
		log.Fatalf("Error while serving HTTP; %s", err)
	}
}
Ejemplo n.º 30
0
Archivo: main.go Proyecto: bootic/btcdn
func main() {

	maxProcs := runtime.NumCPU()
	runtime.GOMAXPROCS(maxProcs)

	var (
		listen_host        string
		fs_basepath        string
		fs_cachepath       string
		http_origin        string
		error_imgpath      string
		secret             string
		rate_limit_by_path int
		rate_limit_bursts  int
		concurrency        int
		newrelic_key       string
	)

	flag.StringVar(&listen_host, "listen", "localhost:3000", "HTTP host:port to listen for incoming requests")
	flag.StringVar(&fs_basepath, "basepath", "", "File system base path to lookup images")
	flag.StringVar(&fs_cachepath, "cachepath", "", "File system base path to cache images")
	flag.StringVar(&http_origin, "httporigin", "", "HTTP endpoint to lookup origin images")
	flag.StringVar(&error_imgpath, "errorimgpath", "./fixtures/error.png", "Error image path in local filesystem")
	flag.StringVar(&secret, "secret", "", "Secret used to check image signature")
	flag.StringVar(&newrelic_key, "newrelic", "", "NewRelic application key")
	flag.IntVar(&rate_limit_by_path, "ratelimit", 0, "Rate limit. Concurrent images per request path")
	flag.IntVar(&rate_limit_bursts, "bursts", 5, "Rate limits bursts")
	flag.IntVar(&concurrency, "concurrency", 0, "Max concurrent requests")

	flag.Parse()

	var store btcdn.Store
	var storeErr error
	var newrelic *gorelic.Agent

	if fs_basepath != "" {
		store, storeErr = btcdn.NewFsStore(fs_basepath)
	} else {
		store, storeErr = btcdn.NewHttpStore(http_origin)
	}

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

	pr, err := processor.New()
	if err != nil {
		log.Fatal(err)
	}

	imgSrv, err := btcdn.NewImageServer(store, pr, error_imgpath)
	if err != nil {
		log.Fatal(err)
	}

	router := mux.NewRouter()

	var srv http.Handler
	srv = router

	if secret == "" { // no security
		log.Println("No secret. Using ImageServer with no DoS protection")
		router.HandleFunc("/", imgSrv.ServeHTTP)
	} else { // secure server
		log.Println("Secret provided. Using ImageServer with DoS protection")
		srv = btcdn.NewSecureServer(imgSrv, secret, router)
	}

	// Only cache named sizes
	// to the filesystem for now
	if fs_cachepath != "" {
		log.Println("Caching named sizes to", fs_cachepath)
		cachedEndpoint := btcdn.NewCachedEndpoint(imgSrv, fs_cachepath)
		srv = btcdn.NewNamedSizesServer(cachedEndpoint, router)
	} else {
		srv = btcdn.NewNamedSizesServer(imgSrv, router)
	}

	// Setup rate-limited server
	if rate_limit_by_path > 0 {
		store, err := tstore.New(65536)
		if err != nil {
			log.Fatal(err)
		}
		quota := throttled.RateQuota{throttled.PerSec(rate_limit_by_path), rate_limit_bursts}
		rateLimiter, err := throttled.NewGCRARateLimiter(store, quota)
		if err != nil {
			log.Fatal(err)
		}

		httpRateLimiter := throttled.HTTPRateLimiter{
			RateLimiter: rateLimiter,
			VaryBy:      &throttled.VaryBy{Path: true},
		}

		log.Println("Rate limiting by path with ", rate_limit_by_path, "reqs. per second with bursts of ", rate_limit_bursts)
		srv = httpRateLimiter.RateLimit(srv)
	}

	// http.HandleFunc("/favicon.ico", FaviconHandler)

	var concurrencyPrompt string

	if concurrency > 0 {
		srv = httpool.Wrap(srv, concurrency)
		concurrencyPrompt = fmt.Sprintf("concurrency: %d", concurrency)
	}

	if newrelic_key != "" {
		newrelic = gorelic.NewAgent()
		newrelic.NewrelicLicense = newrelic_key
		newrelic.NewrelicName = "Btcdn (Go image resizer"
		newrelic.CollectHTTPStat = true

		newrelic.Run()

		srv = newrelic.WrapHTTPHandler(srv)
		log.Println("Newrelic support enabled")
	}

	log.Println("Serving on", listen_host, "cores:", maxProcs, "store:", concurrencyPrompt, store.String(), "error img:", error_imgpath)
	log.Fatal(http.ListenAndServe(listen_host, srv))
}