本文整理匯總了Golang中github.com/flynn/flynn/pkg/shutdown.BeforeExit函數的典型用法代碼示例。如果您正苦於以下問題:Golang BeforeExit函數的具體用法?Golang BeforeExit怎麽用?Golang BeforeExit使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了BeforeExit函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: main
func main() {
defer shutdown.Exit()
apiPort := os.Getenv("PORT")
if apiPort == "" {
apiPort = "5000"
}
logAddr := flag.String("logaddr", ":3000", "syslog input listen address")
apiAddr := flag.String("apiaddr", ":"+apiPort, "api listen address")
flag.Parse()
a := NewAggregator(*logAddr)
if err := a.Start(); err != nil {
shutdown.Fatal(err)
}
shutdown.BeforeExit(a.Shutdown)
listener, err := reuseport.NewReusablePortListener("tcp4", *apiAddr)
if err != nil {
shutdown.Fatal(err)
}
hb, err := discoverd.AddServiceAndRegister("flynn-logaggregator", *logAddr)
if err != nil {
shutdown.Fatal(err)
}
shutdown.BeforeExit(func() { hb.Close() })
shutdown.Fatal(http.Serve(listener, apiHandler(a)))
}
示例2: main
func main() {
serviceName := os.Getenv("FLYNN_POSTGRES")
if serviceName == "" {
serviceName = "postgres"
}
singleton := os.Getenv("SINGLETON") == "true"
password := os.Getenv("PGPASSWORD")
const dataDir = "/data"
idFile := filepath.Join(dataDir, "instance_id")
idBytes, err := ioutil.ReadFile(idFile)
if err != nil && !os.IsNotExist(err) {
shutdown.Fatalf("error reading instance ID: %s", err)
}
id := string(idBytes)
if len(id) == 0 {
id = random.UUID()
if err := ioutil.WriteFile(idFile, []byte(id), 0644); err != nil {
shutdown.Fatalf("error writing instance ID: %s", err)
}
}
err = discoverd.DefaultClient.AddService(serviceName, &discoverd.ServiceConfig{
LeaderType: discoverd.LeaderTypeManual,
})
if err != nil && !httphelper.IsObjectExistsError(err) {
shutdown.Fatal(err)
}
inst := &discoverd.Instance{
Addr: ":5432",
Meta: map[string]string{pgIdKey: id},
}
hb, err := discoverd.DefaultClient.RegisterInstance(serviceName, inst)
if err != nil {
shutdown.Fatal(err)
}
shutdown.BeforeExit(func() { hb.Close() })
log := log15.New("app", "postgres")
pg := NewPostgres(Config{
ID: id,
Singleton: singleton,
DataDir: filepath.Join(dataDir, "db"),
BinDir: "/usr/lib/postgresql/9.5/bin/",
Password: password,
Logger: log.New("component", "postgres"),
ExtWhitelist: true,
WaitUpstream: true,
SHMType: "posix",
})
dd := sd.NewDiscoverd(discoverd.DefaultClient.Service(serviceName), log.New("component", "discoverd"))
peer := state.NewPeer(inst, id, pgIdKey, singleton, dd, pg, log.New("component", "peer"))
shutdown.BeforeExit(func() { peer.Close() })
go peer.Run()
shutdown.Fatal(ServeHTTP(pg.(*Postgres), peer, hb, log.New("component", "http")))
// TODO(titanous): clean shutdown of postgres
}
示例3: main
func main() {
log := logger.New("fn", "main")
log.Info("creating controller client")
client, err := controller.NewClient("", os.Getenv("AUTH_KEY"))
if err != nil {
log.Error("error creating controller client", "err", err)
shutdown.Fatal(err)
}
log.Info("connecting to postgres")
db := postgres.Wait(nil, schema.PrepareStatements)
shutdown.BeforeExit(func() { db.Close() })
go func() {
status.AddHandler(func() status.Status {
_, err := db.ConnPool.Exec("ping")
if err != nil {
return status.Unhealthy
}
return status.Healthy
})
addr := ":" + os.Getenv("PORT")
hb, err := discoverd.AddServiceAndRegister("controller-worker", addr)
if err != nil {
shutdown.Fatal(err)
}
shutdown.BeforeExit(func() { hb.Close() })
shutdown.Fatal(http.ListenAndServe(addr, nil))
}()
workers := que.NewWorkerPool(
que.NewClient(db.ConnPool),
que.WorkMap{
"deployment": deployment.JobHandler(db, client, logger),
"app_deletion": app_deletion.JobHandler(db, client, logger),
"domain_migration": domain_migration.JobHandler(db, client, logger),
"release_cleanup": release_cleanup.JobHandler(db, client, logger),
"app_garbage_collection": app_garbage_collection.JobHandler(db, client, logger),
},
workerCount,
)
workers.Interval = 5 * time.Second
log.Info("starting workers", "count", workerCount, "interval", workers.Interval)
workers.Start()
shutdown.BeforeExit(func() { workers.Shutdown() })
select {} // block and keep running
}
示例4: main
func main() {
defer shutdown.Exit()
dsn := &mariadb.DSN{
Host: serviceHost + ":3306",
User: "flynn",
Password: os.Getenv("MYSQL_PWD"),
Database: "mysql",
}
db, err := sql.Open("mysql", dsn.String())
api := &API{db}
router := httprouter.New()
router.POST("/databases", httphelper.WrapHandler(api.createDatabase))
router.DELETE("/databases", httphelper.WrapHandler(api.dropDatabase))
router.GET("/ping", httphelper.WrapHandler(api.ping))
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
addr := ":" + port
hb, err := discoverd.AddServiceAndRegister(serviceName+"-api", addr)
if err != nil {
shutdown.Fatal(err)
}
shutdown.BeforeExit(func() { hb.Close() })
handler := httphelper.ContextInjector(serviceName+"-api", httphelper.NewRequestLogger(router))
shutdown.Fatal(http.ListenAndServe(addr, handler))
}
示例5: main
func main() {
defer shutdown.Exit()
api := &API{}
router := httprouter.New()
router.POST("/databases", api.createDatabase)
router.DELETE("/databases", api.dropDatabase)
router.GET("/ping", api.ping)
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
addr := ":" + port
hb, err := discoverd.AddServiceAndRegister(serviceName+"-api", addr)
if err != nil {
shutdown.Fatal(err)
}
shutdown.BeforeExit(func() { hb.Close() })
handler := httphelper.ContextInjector(serviceName+"-api", httphelper.NewRequestLogger(router))
shutdown.Fatal(http.ListenAndServe(addr, handler))
}
示例6: main
/*
ish: the Inexusable/Insecure/Internet SHell.
*/
func main() {
defer shutdown.Exit()
name := os.Getenv("NAME")
port := os.Getenv("PORT")
addr := ":" + port
if name == "" {
name = "ish-service"
}
l, err := net.Listen("tcp", addr)
if err != nil {
shutdown.Fatal(err)
}
defer l.Close()
hb, err := discoverd.AddServiceAndRegister(name, addr)
if err != nil {
shutdown.Fatal(err)
}
shutdown.BeforeExit(func() { hb.Close() })
http.HandleFunc("/ish", ish)
if err := http.Serve(l, nil); err != nil {
shutdown.Fatal(err)
}
}
示例7: main
func main() {
defer shutdown.Exit()
db := postgres.Wait(&postgres.Conf{
Service: serviceName,
User: "flynn",
Password: os.Getenv("PGPASSWORD"),
Database: "postgres",
}, nil)
api := &pgAPI{db}
router := httprouter.New()
router.POST("/databases", httphelper.WrapHandler(api.createDatabase))
router.DELETE("/databases", httphelper.WrapHandler(api.dropDatabase))
router.GET("/ping", httphelper.WrapHandler(api.ping))
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
addr := ":" + port
hb, err := discoverd.AddServiceAndRegister(serviceName+"-api", addr)
if err != nil {
shutdown.Fatal(err)
}
shutdown.BeforeExit(func() { hb.Close() })
handler := httphelper.ContextInjector(serviceName+"-api", httphelper.NewRequestLogger(router))
shutdown.Fatal(http.ListenAndServe(addr, handler))
}
示例8: Register
func (d *discoverdWrapper) Register() (bool, error) {
log := logger.New("fn", "discoverd.Register")
log.Info("registering with service discovery")
hb, err := discoverd.AddServiceAndRegister(serviceName, d.addr)
if err != nil {
log.Error("error registering with service discovery", "err", err)
return false, err
}
shutdown.BeforeExit(func() { hb.Close() })
selfAddr := hb.Addr()
log = log.New("self.addr", selfAddr)
service := discoverd.NewService(serviceName)
var leaders chan *discoverd.Instance
var stream stream.Stream
connect := func() (err error) {
log.Info("connecting service leader stream")
leaders = make(chan *discoverd.Instance)
stream, err = service.Leaders(leaders)
if err != nil {
log.Error("error connecting service leader stream", "err", err)
}
return
}
if err := connect(); err != nil {
return false, err
}
go func() {
outer:
for {
for leader := range leaders {
if leader == nil {
// a nil leader indicates there are no instances for
// the service, ignore and wait for an actual leader
log.Warn("received nil leader event")
continue
}
log.Info("received leader event", "leader.addr", leader.Addr)
d.leader <- leader.Addr == selfAddr
}
log.Warn("service leader stream disconnected", "err", stream.Err())
for {
if err := connect(); err == nil {
continue outer
}
time.Sleep(100 * time.Millisecond)
}
}
}()
select {
case isLeader := <-d.leader:
return isLeader, nil
case <-time.After(30 * time.Second):
return false, errors.New("timed out waiting for current service leader")
}
}
示例9: Run
// Run executes the program.
func (m *Main) Run() error {
m.Logger.Info("running")
// Read or generate the instance identifier from file.
id, err := m.readID(filepath.Join(m.DataDir, "instance_id"))
if err != nil {
return err
}
m.Process.ID = id
m.Process.DataDir = m.DataDir
m.Process.Logger = m.Logger.New("component", "process", "id", id)
// Start process.
m.Logger.Info("starting process", "id", id)
if err := m.Process.Start(); err != nil {
m.Logger.Error("error starting process", "err", err)
return err
}
// Add service to discoverd registry.
m.Logger.Info("adding service", "name", m.ServiceName)
if err = m.DiscoverdClient.AddService(m.ServiceName, nil); err != nil && !httphelper.IsObjectExistsError(err) {
m.Logger.Error("error adding discoverd service", "err", err)
return err
}
inst := &discoverd.Instance{
Addr: ":" + m.Process.Port,
Meta: map[string]string{"REDIS_ID": id},
}
// Register instance and retain heartbeater.
m.Logger.Info("registering instance", "addr", inst.Addr, "meta", inst.Meta)
hb, err := m.DiscoverdClient.RegisterInstance(m.ServiceName, inst)
if err != nil {
m.Logger.Error("error registering discoverd instance", "err", err)
return err
}
m.hb = hb
shutdown.BeforeExit(func() { hb.Close() })
m.Logger.Info("opening port", "addr", m.Addr)
// Open HTTP port.
ln, err := net.Listen("tcp", m.Addr)
if err != nil {
m.Logger.Error("error opening port", "err", err)
return err
}
m.ln = ln
// Initialize and server handler.
m.Logger.Info("serving http api")
h := redis.NewHandler()
h.Process = m.Process
h.Heartbeater = m.hb
h.Logger = m.Logger.New("component", "http")
go func() { http.Serve(ln, h) }()
return nil
}
示例10: runServer
func runServer(_ *docopt.Args) error {
addr := ":" + os.Getenv("PORT")
db := postgres.Wait(nil, nil)
if err := dbMigrations.Migrate(db); err != nil {
return fmt.Errorf("error running DB migrations: %s", err)
}
mux := http.NewServeMux()
repo, err := data.NewFileRepoFromEnv(db)
if err != nil {
return err
}
hb, err := discoverd.AddServiceAndRegister("blobstore", addr)
if err != nil {
return err
}
shutdown.BeforeExit(func() { hb.Close() })
log.Println("Blobstore serving files on " + addr)
mux.Handle("/", handler(repo))
mux.Handle(status.Path, status.Handler(func() status.Status {
if err := db.Exec("SELECT 1"); err != nil {
return status.Unhealthy
}
return status.Healthy
}))
h := httphelper.ContextInjector("blobstore", httphelper.NewRequestLogger(mux))
return http.ListenAndServe(addr, h)
}
示例11: main
func main() {
log := logger.New("fn", "main")
log.Info("creating controller client")
client, err := controller.NewClient("", os.Getenv("AUTH_KEY"))
if err != nil {
log.Error("error creating controller client", "err", err)
shutdown.Fatal()
}
log.Info("connecting to postgres")
db := postgres.Wait("", "")
log.Info("creating postgres connection pool")
pgxpool, err := pgx.NewConnPool(pgx.ConnPoolConfig{
ConnConfig: pgx.ConnConfig{
Host: os.Getenv("PGHOST"),
User: os.Getenv("PGUSER"),
Password: os.Getenv("PGPASSWORD"),
Database: os.Getenv("PGDATABASE"),
},
AfterConnect: que.PrepareStatements,
MaxConnections: workerCount,
})
if err != nil {
log.Error("error creating postgres connection pool", "err", err)
shutdown.Fatal()
}
shutdown.BeforeExit(func() { pgxpool.Close() })
workers := que.NewWorkerPool(
que.NewClient(pgxpool),
que.WorkMap{
"deployment": deployment.JobHandler(db, client, logger),
"app_deletion": app_deletion.JobHandler(db, client, logger),
},
workerCount,
)
workers.Interval = 5 * time.Second
log.Info("starting workers", "count", workerCount, "interval", workers.Interval)
workers.Start()
shutdown.BeforeExit(func() { workers.Shutdown() })
select {} // block and keep running
}
示例12: main
func main() {
defer shutdown.Exit()
apiPort := os.Getenv("PORT")
if apiPort == "" {
apiPort = "5000"
}
logAddr := flag.String("logaddr", ":3000", "syslog input listen address")
apiAddr := flag.String("apiaddr", ":"+apiPort, "api listen address")
snapshotPath := flag.String("snapshot", "", "snapshot path")
flag.Parse()
a := NewAggregator(*logAddr)
if *snapshotPath != "" {
if err := a.ReplaySnapshot(*snapshotPath); err != nil {
shutdown.Fatal(err)
}
shutdown.BeforeExit(func() {
if err := a.TakeSnapshot(*snapshotPath); err != nil {
log15.Error("snapshot error", "err", err)
}
})
}
if err := a.Start(); err != nil {
shutdown.Fatal(err)
}
shutdown.BeforeExit(a.Shutdown)
listener, err := net.Listen("tcp4", *apiAddr)
if err != nil {
shutdown.Fatal(err)
}
hb, err := discoverd.AddServiceAndRegister("flynn-logaggregator", *logAddr)
if err != nil {
shutdown.Fatal(err)
}
shutdown.BeforeExit(func() { hb.Close() })
shutdown.Fatal(http.Serve(listener, apiHandler(a)))
}
示例13: main
func main() {
serviceName := os.Getenv("FLYNN_POSTGRES")
if serviceName == "" {
serviceName = "postgres"
}
singleton := os.Getenv("SINGLETON") == "true"
password := os.Getenv("PGPASSWORD")
err := discoverd.DefaultClient.AddService(serviceName, &discoverd.ServiceConfig{
LeaderType: discoverd.LeaderTypeManual,
})
if err != nil && !httphelper.IsObjectExistsError(err) {
shutdown.Fatal(err)
}
inst := &discoverd.Instance{Addr: ":5432"}
hb, err := discoverd.DefaultClient.RegisterInstance(serviceName, inst)
if err != nil {
shutdown.Fatal(err)
}
shutdown.BeforeExit(func() { hb.Close() })
log := log15.New("app", "postgres")
pg := NewPostgres(Config{
ID: inst.ID,
Singleton: singleton,
BinDir: "/usr/lib/postgresql/9.4/bin/",
Password: password,
Logger: log.New("component", "postgres"),
ExtWhitelist: true,
WaitUpstream: true,
// TODO(titanous) investigate this:
SHMType: "sysv", // the default on 9.4, 'posix' is not currently supported in our containers
})
dd := NewDiscoverd(discoverd.DefaultClient.Service(serviceName), log.New("component", "discoverd"))
peer := state.NewPeer(inst, singleton, dd, pg, log.New("component", "peer"))
shutdown.BeforeExit(func() { peer.Close() })
go peer.Run()
shutdown.Fatal(ServeHTTP(pg.(*Postgres), peer, hb, log.New("component", "http")))
// TODO(titanous): clean shutdown of postgres
}
示例14: main
func main() {
defer shutdown.Exit()
grohl.AddContext("app", "controller-scheduler")
grohl.Log(grohl.Data{"at": "start"})
go startHTTPServer()
if period := os.Getenv("BACKOFF_PERIOD"); period != "" {
var err error
backoffPeriod, err = time.ParseDuration(period)
if err != nil {
shutdown.Fatal(err)
}
grohl.Log(grohl.Data{"at": "backoff_period", "period": backoffPeriod.String()})
}
cc, err := controller.NewClient("", os.Getenv("AUTH_KEY"))
if err != nil {
shutdown.Fatal(err)
}
c := newContext(cc, cluster.NewClient())
c.watchHosts()
grohl.Log(grohl.Data{"at": "leaderwait"})
hb, err := discoverd.AddServiceAndRegister("controller-scheduler", ":"+os.Getenv("PORT"))
if err != nil {
shutdown.Fatal(err)
}
shutdown.BeforeExit(func() { hb.Close() })
leaders := make(chan *discoverd.Instance)
stream, err := discoverd.NewService("controller-scheduler").Leaders(leaders)
if err != nil {
shutdown.Fatal(err)
}
for leader := range leaders {
if leader.Addr == hb.Addr() {
break
}
}
if err := stream.Err(); err != nil {
// TODO: handle discoverd errors
shutdown.Fatal(err)
}
stream.Close()
// TODO: handle demotion
grohl.Log(grohl.Data{"at": "leader"})
// TODO: periodic full cluster sync for anti-entropy
c.watchFormations()
}
示例15: NewDiscoverdManager
func NewDiscoverdManager(backend Backend, mux *logmux.LogMux, hostID, publishAddr string) *DiscoverdManager {
d := &DiscoverdManager{
backend: backend,
mux: mux,
inst: &discoverd.Instance{
Addr: publishAddr,
Meta: map[string]string{"id": hostID},
},
}
shutdown.BeforeExit(d.Close)
return d
}