Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(ipc): improve event code #46

Merged
merged 1 commit into from
Jun 26, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 3 additions & 11 deletions cmd/ovm/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,17 +68,9 @@ func main() {
exit(1)
}

{
if err := event.Init(opt); err != nil {
_ = log.Errorf("event init error: %v", err)
exit(1)
}

g := errgroup.Group{}
event.Subscribe(&g)
cleans = append(cleans, func() {
_ = g.Wait()
})
if err := event.Setup(opt); err != nil {
_ = log.Errorf("event init error: %v", err)
exit(1)
}

agent, err := sshagentsock.Start(opt.SSHAuthSocketPath, log)
Expand Down
33 changes: 17 additions & 16 deletions pkg/ipc/event/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"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 key string
Expand Down Expand Up @@ -48,7 +47,10 @@ type event struct {

var e *event

func Init(opt *cli.Context) error {
// see: https://github.com/Code-Hex/go-infinity-channel/issues/1
var waitDone = make(chan struct{})

func Setup(opt *cli.Context) error {
log, err := logger.New(opt.LogPath, opt.Name+"-event")
if err != nil {
return err
Expand All @@ -75,15 +77,7 @@ func Init(opt *cli.Context) error {
channel: infinity.NewChannel[*datum](),
}

return nil
}

func Subscribe(g *errgroup.Group) {
if e == nil {
return
}

g.Go(func() error {
go func() {
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)
Expand All @@ -98,14 +92,13 @@ func Subscribe(g *errgroup.Group) {
}

if datum.message == string(Exit) {
e.channel.Close()
e = nil
return nil
waitDone <- struct{}{}
return
}
}
}()

return nil
})
return nil
}

func NotifyApp(name app) {
Expand All @@ -117,6 +110,14 @@ func NotifyApp(name app) {
name: kApp,
message: string(name),
}

// wait for the event to be processed
// Exit event indicates the main process exit
if string(name) == string(Exit) {
<-waitDone
close(waitDone)
e.channel.Close()
}
}

func NotifyError(err error) {
Expand Down