2017-09-17 23:54:23 +02:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"net/http/pprof"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ControlJob struct {
|
|
|
|
Name string
|
|
|
|
sockaddr *net.UnixAddr
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewControlJob(name, sockpath string) (j *ControlJob, err error) {
|
|
|
|
j = &ControlJob{Name: name}
|
|
|
|
|
|
|
|
j.sockaddr, err = net.ResolveUnixAddr("unix", sockpath)
|
|
|
|
if err != nil {
|
|
|
|
err = errors.Wrap(err, "cannot resolve unix address")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
func (j *ControlJob) JobName() string {
|
|
|
|
return j.Name
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
ControlJobEndpointProfile string = "/debug/pprof/profile"
|
|
|
|
)
|
|
|
|
|
|
|
|
func (j *ControlJob) JobStart(ctx context.Context) {
|
|
|
|
|
|
|
|
log := ctx.Value(contextKeyLog).(Logger)
|
2017-09-23 11:07:08 +02:00
|
|
|
defer log.Info("control job finished")
|
2017-09-17 23:54:23 +02:00
|
|
|
|
|
|
|
l, err := ListenUnixPrivate(j.sockaddr)
|
|
|
|
if err != nil {
|
2017-09-23 11:07:08 +02:00
|
|
|
log.WithError(err).Error("error listening")
|
2017-09-17 23:54:23 +02:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
mux := http.NewServeMux()
|
|
|
|
mux.Handle(ControlJobEndpointProfile, requestLogger{log, pprof.Profile})
|
|
|
|
server := http.Server{Handler: mux}
|
|
|
|
|
|
|
|
outer:
|
|
|
|
for {
|
|
|
|
|
|
|
|
served := make(chan error)
|
|
|
|
go func() {
|
|
|
|
served <- server.Serve(l)
|
|
|
|
close(served)
|
|
|
|
}()
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
2017-09-22 14:13:58 +02:00
|
|
|
log.WithError(err).Info("contex done")
|
2017-09-17 23:54:23 +02:00
|
|
|
server.Shutdown(context.Background())
|
|
|
|
break outer
|
|
|
|
case err = <-served:
|
|
|
|
if err != nil {
|
2017-09-22 14:13:58 +02:00
|
|
|
log.WithError(err).Error("error serving")
|
2017-09-17 23:54:23 +02:00
|
|
|
break outer
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
type requestLogger struct {
|
|
|
|
log Logger
|
|
|
|
handlerFunc func(w http.ResponseWriter, r *http.Request)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l requestLogger) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
2017-09-22 14:13:58 +02:00
|
|
|
log := l.log.WithField("method", r.Method).WithField("url", r.URL)
|
2017-09-23 11:07:08 +02:00
|
|
|
log.Info("start")
|
2017-09-17 23:54:23 +02:00
|
|
|
l.handlerFunc(w, r)
|
2017-09-23 11:07:08 +02:00
|
|
|
log.Info("finish")
|
2017-09-17 23:54:23 +02:00
|
|
|
}
|