diff --git a/cmd/server/cmd.go b/cmd/server/cmd.go index a96f78e..689a6be 100644 --- a/cmd/server/cmd.go +++ b/cmd/server/cmd.go @@ -62,7 +62,7 @@ func (m *myShoes) Run() error { ctx := context.Background() eg.Go(func() error { - if err := web.Serve(m.ds); err != nil { + if err := web.Serve(ctx, m.ds); err != nil { return fmt.Errorf("failed to serve: %w", err) } return nil diff --git a/pkg/runner/runner.go b/pkg/runner/runner.go index 51153ab..50016b8 100644 --- a/pkg/runner/runner.go +++ b/pkg/runner/runner.go @@ -59,11 +59,13 @@ func (m *Manager) Loop(ctx context.Context) error { if err := m.doTargetToken(ctx); err != nil { logger.Logf(false, "failed to refresh token: %+v", err) } - case <-ticker.C: if err := m.do(ctx); err != nil { logger.Logf(false, "failed to starter: %+v", err) } + + case <-ctx.Done(): + return nil } } } @@ -79,7 +81,7 @@ func (m *Manager) do(ctx context.Context) error { logger.Logf(true, "found %d targets in datastore", len(targets)) for _, target := range targets { if err := m.removeRunner(ctx, &target); err != nil { - return fmt.Errorf("failed to delete runners: %w", err) + logger.Logf(true, "failed to delete runners (target: %s): %+v", target.RepoURL(), err) } } diff --git a/pkg/starter/starter.go b/pkg/starter/starter.go index 16040c4..5b16b43 100644 --- a/pkg/starter/starter.go +++ b/pkg/starter/starter.go @@ -49,6 +49,9 @@ func (s *Starter) Loop(ctx context.Context) error { if err := s.do(ctx); err != nil { logger.Logf(false, "failed to starter: %+v", err) } + + case <-ctx.Done(): + return nil } } } diff --git a/pkg/web/http.go b/pkg/web/http.go index 76c9c68..bb7904c 100644 --- a/pkg/web/http.go +++ b/pkg/web/http.go @@ -1,6 +1,7 @@ package web import ( + "context" "encoding/json" "fmt" "net/http" @@ -71,16 +72,29 @@ func NewMux(ds datastore.Datastore) *goji.Mux { } // Serve start webhook receiver -func Serve(ds datastore.Datastore) error { +func Serve(ctx context.Context, ds datastore.Datastore) error { mux := NewMux(ds) - listenAddress := fmt.Sprintf(":%d", config.Config.Port) - logger.Logf(false, "start webhook receiver, listen %s", listenAddress) - if err := http.ListenAndServe(listenAddress, mux); err != nil { - return fmt.Errorf("failed to listen and serve: %w", err) + s := &http.Server{ + Addr: listenAddress, + Handler: mux, } - return nil + errCh := make(chan error) + go func() { + defer close(errCh) + logger.Logf(false, "start webhook receiver, listen %s", listenAddress) + if err := s.ListenAndServe(); err != nil { + errCh <- fmt.Errorf("failed to listen and serve: %w", err) + } + }() + + select { + case <-ctx.Done(): + return s.Shutdown(ctx) + case err := <-errCh: + return fmt.Errorf("occured error in web serve: %w", err) + } } func apacheLogging(r *http.Request) {