From a00a268256c3a6931fccad49a4ec8de8a8ae9724 Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Thu, 24 Jan 2019 22:04:58 -0500 Subject: [PATCH] m: implement Run function, which glues together mcfg.Populate, mrun.Start, and mrun.Stop --- m/m.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/m/m.go b/m/m.go index 7e35de2..4e639a9 100644 --- a/m/m.go +++ b/m/m.go @@ -5,7 +5,14 @@ package m import ( + "os" + "os/signal" + "github.com/mediocregopher/mediocre-go-lib/mcfg" + "github.com/mediocregopher/mediocre-go-lib/mctx" + "github.com/mediocregopher/mediocre-go-lib/merr" + "github.com/mediocregopher/mediocre-go-lib/mlog" + "github.com/mediocregopher/mediocre-go-lib/mrun" ) // CfgSource returns an mcfg.Source which takes in configuration info from the @@ -16,3 +23,34 @@ func CfgSource() mcfg.Source { mcfg.SourceCLI{}, } } + +// TODO Create a function, `NewService() mctx.Context` which preloads the +// context with log-level param. Will one day also add debug server. Problem +// comes because mlog isn't quite designed right and setting log-level from +// config won't propagate changes to child contexts which have already called +// mlog.From. + +// Run performs the work of populating configuration parameters, triggering the +// start event, waiting for an interrupt, and then triggering the stop event. +// Run will block until the stop event is done. If any errors are encountered a +// fatal is thrown. +func Run(ctx mctx.Context) { + log := mlog.From(ctx) + if err := mcfg.Populate(ctx, CfgSource()); err != nil { + log.Fatal("error populating configuration", merr.KV(err)) + } else if err := mrun.Start(ctx); err != nil { + log.Fatal("error triggering start event", merr.KV(err)) + } + + { + ch := make(chan os.Signal, 1) + signal.Notify(ch, os.Interrupt) + s := <-ch + log.Info("signal received, stopping", mlog.KV{"signal": s}) + } + + if err := mrun.Stop(ctx); err != nil { + log.Fatal("error triggering stop event", merr.KV(err)) + } + log.Info("exiting process") +}