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

don't fail if can't save config due to EROFS or EPERM #213

Merged
merged 3 commits into from
Oct 5, 2023
Merged
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
58 changes: 37 additions & 21 deletions agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"bufio"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"net"
Expand Down Expand Up @@ -74,32 +75,14 @@ type Options struct {
// Note: The agent exposes an endpoint via a TCP connection that can be used by
// any program on the system. Review your security requirements before starting
// the agent.
func Listen(opts Options) error {
func Listen(opts Options) (err error) {
mu.Lock()
defer mu.Unlock()

if portfile != "" {
return fmt.Errorf("gops: agent already listening at: %v", listener.Addr())
}

// new
gopsdir := opts.ConfigDir
if gopsdir == "" {
cfgDir, err := internal.ConfigDir()
if err != nil {
return err
}
gopsdir = cfgDir
}

err := os.MkdirAll(gopsdir, os.ModePerm)
if err != nil {
return err
}
if opts.ShutdownCleanup {
gracefulShutdown()
}

addr := opts.Addr
if addr == "" {
addr = defaultAddr
Expand All @@ -112,13 +95,16 @@ func Listen(opts Options) error {
if err != nil {
return err
}

port := listener.Addr().(*net.TCPAddr).Port
portfile = filepath.Join(gopsdir, strconv.Itoa(os.Getpid()))
err = os.WriteFile(portfile, []byte(strconv.Itoa(port)), os.ModePerm)
err = saveConfig(opts, port)
if err != nil {
return err
}

if opts.ShutdownCleanup {
gracefulShutdown()
}
go listen(listener)
return nil
}
Expand Down Expand Up @@ -149,6 +135,36 @@ func listen(l net.Listener) {
}
}

func saveConfig(opts Options, port int) (err error) {
gopsdir := opts.ConfigDir
if gopsdir == "" {
cfgDir, err := internal.ConfigDir()
if err != nil {
return err
}
gopsdir = cfgDir
}

err = os.MkdirAll(gopsdir, os.ModePerm)
if errors.Is(err, syscall.EROFS) || errors.Is(err, syscall.EPERM) { // ignore and work in remote mode only
return nil
}
if err != nil {
return err
}

portfile = filepath.Join(gopsdir, strconv.Itoa(os.Getpid()))
err = os.WriteFile(portfile, []byte(strconv.Itoa(port)), os.ModePerm)
if errors.Is(err, syscall.EROFS) || errors.Is(err, syscall.EPERM) { // ignore and work in remote mode only
return nil
}
if err != nil {
return err
}

return nil
}

func gracefulShutdown() {
c := make(chan os.Signal, 1)
gosignal.Notify(c, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
Expand Down