-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.go
91 lines (81 loc) · 1.99 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package lsnrhttpux
import (
"context"
"errors"
golog "log"
"net"
"net/http"
"os"
"sync"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
"github.com/opensvc/om3/daemon/daemonctx"
"github.com/opensvc/om3/daemon/listener/routehttp"
"github.com/opensvc/om3/util/funcopt"
"github.com/opensvc/om3/util/plog"
)
type (
T struct {
listener *net.Listener
log *plog.Logger
addr string
wg sync.WaitGroup
}
)
func New(ctx context.Context, opts ...funcopt.O) *T {
t := &T{
log: plog.NewDefaultLogger().Attr("pkg", "daemon/listener/lsnrhttpux").Attr("lsnr_type", "http_ux").WithPrefix("daemon: listener: ux: "),
}
if err := funcopt.Apply(t, opts...); err != nil {
t.log.Errorf("funcopt apply: %s", err)
return nil
}
t.log = t.log.Attr("lsnr_addr", t.addr)
return t
}
func (t *T) Start(ctx context.Context) error {
ctx = daemonctx.WithLsnrType(ctx, "ux")
errC := make(chan error)
t.log.Infof("starting")
if err := os.RemoveAll(t.addr); err != nil {
t.log.Errorf("remove file: %s", err)
return err
}
if listener, err := net.Listen("unix", t.addr); err != nil {
t.log.Errorf("listen failed: %s", err)
return err
} else {
t.listener = &listener
}
t.wg.Add(1)
go func(errC chan<- error) {
defer t.wg.Done()
ctx = daemonctx.WithListenAddr(ctx, t.addr)
s := &http2.Server{}
server := http.Server{
Handler: h2c.NewHandler(routehttp.New(ctx, false), s),
ErrorLog: golog.New(t.log.Logger(), "", 0),
}
t.log.Infof("started")
errC <- nil
if err := server.Serve(*t.listener); err != http.ErrServerClosed && !errors.Is(err, net.ErrClosed) {
t.log.Debugf("serve ends with unexpected error: %s", err)
}
t.log.Infof("serve stopped")
}(errC)
return <-errC
}
func (t *T) Stop() error {
t.log.Infof("stopping")
defer t.log.Infof("stopped")
if t.listener == nil {
t.log.Infof("listener already closed")
return nil
}
err := (*t.listener).Close()
if err != nil {
t.log.Errorf("listener Close failure: %s", err)
}
t.wg.Wait()
return err
}