-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathevent.go
124 lines (102 loc) · 2.26 KB
/
event.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
// SPDX-FileCopyrightText: 2024 OOMOL, Inc. <https://www.oomol.com>
// SPDX-License-Identifier: MPL-2.0
package event
import (
"context"
"fmt"
"net"
"net/http"
"net/url"
"time"
"github.com/Code-Hex/go-infinity-channel"
"github.com/oomol-lab/ovm/pkg/cli"
"github.com/oomol-lab/ovm/pkg/logger"
"golang.org/x/sync/errgroup"
)
type Name string
var (
Initializing Name = "Initializing"
GVProxyReady Name = "GVProxyReady"
IgnitionProgress Name = "IgnitionProgress"
IgnitionDone Name = "IgnitionDone"
VMReady Name = "VMReady"
Exit Name = "Exit"
Error Name = "Error"
)
type datum struct {
name Name
message string
}
type event struct {
client *http.Client
log *logger.Context
channel *infinity.Channel[*datum]
}
var e *event
func Init(opt *cli.Context) error {
log, err := logger.New(opt.LogPath, opt.Name+"-event")
if err != nil {
return err
}
if opt.EventSocketPath == "" {
log.Info("no socket path, event will not be sent")
return nil
}
c := &http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
var d net.Dialer
return d.DialContext(ctx, "unix", opt.EventSocketPath)
},
},
Timeout: 200 * time.Millisecond,
}
e = &event{
client: c,
log: log,
channel: infinity.NewChannel[*datum](),
}
return nil
}
func Subscribe(g *errgroup.Group) {
if e == nil {
return
}
g.Go(func() error {
for datum := range e.channel.Out() {
uri := fmt.Sprintf("http://ovm/notify?event=%s&message=%s", datum.name, url.QueryEscape(datum.message))
e.log.Infof("notify %s event to %s", datum.name, uri)
if resp, err := e.client.Get(uri); err != nil {
e.log.Warnf("notify %+v event failed: %v", *datum, err)
} else {
_ = resp.Body.Close()
if resp.StatusCode != http.StatusOK {
e.log.Warnf("notify %+v event failed, status code is: %d", *datum, resp.StatusCode)
}
}
if datum.name == Exit {
e.channel.Close()
e = nil
return nil
}
}
return nil
})
}
func Notify(name Name) {
if e == nil {
return
}
e.channel.In() <- &datum{
name: name,
}
}
func NotifyError(err error) {
if e == nil {
return
}
e.channel.In() <- &datum{
name: Error,
message: err.Error(),
}
}