| 1 | // Copyright © SAS Institute Inc. |
| 2 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | // you may not use this file except in compliance with the License. |
| 4 | // You may obtain a copy of the License at |
| 5 | // |
| 6 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | // |
| 8 | // Unless required by applicable law or agreed to in writing, software |
| 9 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | // See the License for the specific language governing permissions and |
| 12 | // limitations under the License. |
| 13 | // |
| 14 | //go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris |
| 15 | // +build darwin dragonfly freebsd linux netbsd openbsd solaris |
| 16 | |
| 17 | package activatecmd |
| 18 | |
| 19 | import ( |
| 20 | "context" |
| 21 | "encoding/json" |
| 22 | "errors" |
| 23 | "fmt" |
| 24 | "log" |
| 25 | "net" |
| 26 | "os" |
| 27 | "os/exec" |
| 28 | "strconv" |
| 29 | "sync" |
| 30 | "syscall" |
| 31 | "time" |
| 32 | |
| 33 | "golang.org/x/sync/errgroup" |
| 34 | "golang.org/x/sys/unix" |
| 35 | |
| 36 | "github.com/sassoftware/relic/v7/internal/closeonce" |
| 37 | ) |
| 38 | |
| 39 | // Listener implements a channel that receives ready notifications from spawned processes |
| 40 | type Listener struct { |
| 41 | once sync.Once |
| 42 | closed closeonce.Closed |
| 43 | ready chan int |
| 44 | stopping chan int |
| 45 | eg *errgroup.Group |
| 46 | ctx context.Context |
| 47 | cancel context.CancelFunc |
| 48 | } |
| 49 | |
| 50 | func (l *Listener) initialize() { |
| 51 | l.ctx, l.cancel = context.WithCancel(context.Background()) |
| 52 | l.eg, l.ctx = errgroup.WithContext(l.ctx) |
| 53 | l.ready = make(chan int, 10) |
| 54 | l.stopping = make(chan int, 10) |
| 55 | } |
| 56 | |
| 57 | // Ready returns a channel that receives PIDs that are ready |
| 58 | func (l *Listener) Ready() <-chan int { |
| 59 | l.once.Do(l.initialize) |
| 60 | return l.ready |
| 61 | } |
| 62 | |
| 63 | // Stopping returns a channel that receives PIDs that are stopping |
| 64 | func (l *Listener) Stopping() <-chan int { |
| 65 | l.once.Do(l.initialize) |
| 66 | return l.stopping |
| 67 | } |
| 68 | |
| 69 | // Close shuts down all notification sockets |
| 70 | func (l *Listener) Close() error { |
| 71 | l.once.Do(l.initialize) |
| 72 | return l.closed.Close(func() error { |
| 73 | l.cancel() |
| 74 | err := l.eg.Wait() |
| 75 | close(l.ready) |
| 76 | close(l.stopping) |
| 77 | return err |
| 78 | }) |
| 79 | } |
| 80 | |
| 81 | // Attach a notification socket to a new child process. The returned "detach" |
| 82 | // function must be invoked on cleanup, and should be invoked after Start() |
| 83 | // returns. |
| 84 | func (l *Listener) Attach(cmd *exec.Cmd) (detach func(), err error) { |
| 85 | l.once.Do(l.initialize) |
| 86 | if l.closed.Closed() { |
| 87 | return nil, errors.New("listener is closed") |
| 88 | } |
| 89 | if cmd.Env == nil { |
| 90 | cmd.Env = ClearEnv(os.Environ()) |
| 91 | } |
| 92 | parentEnd, childEnd, err := socketpair() |
| 93 | if err != nil { |
| 94 | return nil, err |
| 95 | } |
| 96 | cmd.Env = append(cmd.Env, fmt.Sprintf("EINHORN_SOCK_FD=%d", 3+len(cmd.ExtraFiles))) |
| 97 | cmd.ExtraFiles = append(cmd.ExtraFiles, childEnd) |
| 98 | go func() { |
| 99 | <-l.ctx.Done() |
| 100 | parentEnd.Close() |
| 101 | }() |
| 102 | l.eg.Go(func() error { return l.listen(parentEnd) }) |
| 103 | detach = func() { childEnd.Close() } |
| 104 | return detach, nil |
| 105 | } |
| 106 | |
| 107 | // Consume packets from a socket and forward them to the main channel until ctx is cancelled |
| 108 | func (l *Listener) listen(sock net.PacketConn) error { |
| 109 | buf := make([]byte, 4096) |
| 110 | failures := 0 |
| 111 | var payload struct { |
| 112 | Command string `json:"command"` |
| 113 | PID int `json:"pid"` |
| 114 | } |
| 115 | for l.ctx.Err() == nil { |
| 116 | n, _, err := sock.ReadFrom(buf) |
| 117 | if err != nil { |
| 118 | if l.ctx.Err() != nil { |
| 119 | return nil |
| 120 | } |
| 121 | log.Printf("error: failed to read from notify socket: %s", err) |
| 122 | failures++ |
| 123 | if failures > 100 { |
| 124 | return err |
| 125 | } |
| 126 | time.Sleep(100 * time.Millisecond) |
| 127 | } |
| 128 | failures = 0 |
| 129 | if err := json.Unmarshal(buf[:n], &payload); err != nil { |
| 130 | log.Printf("error: failed to decode notification: %s", err) |
| 131 | continue |
| 132 | } |
| 133 | switch payload.Command { |
| 134 | case "worker:ack": |
| 135 | l.ready <- payload.PID |
| 136 | case "worker:stopping": |
| 137 | l.stopping <- payload.PID |
| 138 | } |
| 139 | } |
| 140 | return nil |
| 141 | } |
| 142 | |
| 143 | // Create a socketpair with the parent end wrapped in a PacketConn and the child end as a plain *os.File |
| 144 | func socketpair() (parentEnd net.PacketConn, childEnd *os.File, err error) { |
| 145 | files, err := socketpairFiles() |
| 146 | if err != nil { |
| 147 | return nil, nil, err |
| 148 | } |
| 149 | defer func() { |
| 150 | // FilePacketConn will dup this so always close it |
| 151 | _ = files[0].Close() |
| 152 | }() |
| 153 | childEnd = files[1] |
| 154 | if err = unix.SetNonblock(int(files[0].Fd()), true); err == nil { |
| 155 | parentEnd, err = net.FilePacketConn(files[0]) |
| 156 | if err == nil { |
| 157 | return parentEnd, childEnd, nil |
| 158 | } |
| 159 | } |
| 160 | _ = files[1].Close() |
| 161 | return nil, nil, err |
| 162 | } |
| 163 | |
| 164 | // Create a socketpair as *os.File objects. must hold the fork lock to ensure that no file descriptors are leaked to a child process before CloseOnExec can be set. |
| 165 | func socketpairFiles() (files [2]*os.File, err error) { |
| 166 | syscall.ForkLock.RLock() |
| 167 | defer syscall.ForkLock.RUnlock() |
| 168 | fds, err := unix.Socketpair(unix.AF_UNIX, unix.SOCK_DGRAM, 0) |
| 169 | if err == nil { |
| 170 | unix.CloseOnExec(fds[0]) |
| 171 | unix.CloseOnExec(fds[1]) |
| 172 | files[0] = os.NewFile(uintptr(fds[0]), "<socketpair>") |
| 173 | files[1] = os.NewFile(uintptr(fds[1]), "<socketpair>") |
| 174 | } |
| 175 | return |
| 176 | } |
| 177 | |
| 178 | // DaemonStopping is used by the child process to indicate it is no longer |
| 179 | // serving requests and will exit soon. |
| 180 | func DaemonStopping() error { |
| 181 | fd, err := strconv.Atoi(os.Getenv("EINHORN_SOCK_FD")) |
| 182 | if err != nil { |
| 183 | return err |
| 184 | } |
| 185 | message := fmt.Sprintf(`{"command":"worker:stopping", "pid":%d}`+"\n", os.Getpid()) |
| 186 | _, err = unix.Write(fd, []byte(message)) |
| 187 | return err |
| 188 | } |