| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | // |
| 16 | |
| 17 | package worker |
| 18 | |
| 19 | import ( |
| 20 | "bytes" |
| 21 | "context" |
| 22 | "crypto/rand" |
| 23 | "fmt" |
| 24 | "io" |
| 25 | "log" |
| 26 | "net" |
| 27 | "os" |
| 28 | "os/exec" |
| 29 | "sync" |
| 30 | "syscall" |
| 31 | "time" |
| 32 | |
| 33 | "github.com/sassoftware/relic/v7/config" |
| 34 | "github.com/sassoftware/relic/v7/internal/activation/activatecmd" |
| 35 | "github.com/sassoftware/relic/v7/internal/closeonce" |
| 36 | ) |
| 37 | |
| 38 | const ( |
| 39 | startTimeout = 60 * time.Second |
| 40 | restartDelay = 10 * time.Second |
| 41 | ) |
| 42 | |
| 43 | func getCookie() string { |
| 44 | cookieBytes := make([]byte, 8) |
| 45 | if _, err := io.ReadFull(rand.Reader, cookieBytes); err != nil { |
| 46 | panic(err) |
| 47 | } |
| 48 | return fmt.Sprintf("%x", cookieBytes) |
| 49 | } |
| 50 | |
| 51 | type WorkerToken struct { |
| 52 | config *config.Config |
| 53 | tconf *config.TokenConfig |
| 54 | cookie string |
| 55 | addr string |
| 56 | fdset *activatecmd.ListenerSet |
| 57 | notify *activatecmd.Listener |
| 58 | closed closeonce.Closed |
| 59 | wg sync.WaitGroup |
| 60 | ctx context.Context |
| 61 | cancel context.CancelFunc |
| 62 | |
| 63 | mu sync.Mutex |
| 64 | procs map[int]struct{} |
| 65 | procsExited chan int |
| 66 | } |
| 67 | |
| 68 | func New(config *config.Config, tokenName string) (*WorkerToken, error) { |
| 69 | tconf, err := config.GetToken(tokenName) |
| 70 | if err != nil { |
| 71 | return nil, err |
| 72 | } |
| 73 | lis, err := net.Listen("tcp", "127.0.0.1:0") |
| 74 | if err != nil { |
| 75 | return nil, err |
| 76 | } |
| 77 | fdset, err := activatecmd.NewListenerSet([]net.Listener{lis}) |
| 78 | if err != nil { |
| 79 | return nil, err |
| 80 | } |
| 81 | ctx, cancel := context.WithCancel(context.Background()) |
| 82 | t := &WorkerToken{ |
| 83 | config: config, |
| 84 | tconf: tconf, |
| 85 | cookie: getCookie(), |
| 86 | fdset: fdset, |
| 87 | notify: new(activatecmd.Listener), |
| 88 | addr: lis.Addr().String(), |
| 89 | ctx: ctx, |
| 90 | cancel: cancel, |
| 91 | procs: make(map[int]struct{}), |
| 92 | procsExited: make(chan int, 10), |
| 93 | } |
| 94 | lis.Close() // NewListenerSet dupes this so it's not needed anymore |
| 95 | if err := t.spawn(); err != nil { |
| 96 | return nil, err |
| 97 | } |
| 98 | t.wg.Add(1) |
| 99 | go t.monitor() |
| 100 | return t, nil |
| 101 | } |
| 102 | |
| 103 | func (t *WorkerToken) spawn() error { |
| 104 | // build cmdline and worker options |
| 105 | self, err := os.Executable() |
| 106 | if err != nil { |
| 107 | return err |
| 108 | } |
| 109 | cmd := exec.Command(os.Args[0], "worker", t.config.Path(), t.tconf.Name()) |
| 110 | cmd.Path = self |
| 111 | cmd.Stdin = bytes.NewReader([]byte(t.cookie)) |
| 112 | cmd.Stdout = os.Stdout |
| 113 | cmd.Stderr = os.Stderr |
| 114 | cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} |
| 115 | // attach shared listener socket |
| 116 | cmd.Env = activatecmd.ClearEnv(os.Environ()) |
| 117 | if err := t.fdset.Attach(cmd); err != nil { |
| 118 | return err |
| 119 | } |
| 120 | // attach notify socket so we know when the process is ready or if it died on init |
| 121 | detach, err := t.notify.Attach(cmd) |
| 122 | if err != nil { |
| 123 | return err |
| 124 | } |
| 125 | defer detach() |
| 126 | // start process and wait for ready state |
| 127 | if err := cmd.Start(); err != nil { |
| 128 | return err |
| 129 | } |
| 130 | detach() |
| 131 | pid := cmd.Process.Pid |
| 132 | exited := make(chan struct{}) |
| 133 | t.wg.Add(1) |
| 134 | go func() { |
| 135 | defer t.wg.Done() |
| 136 | _ = cmd.Wait() |
| 137 | t.procsExited <- pid |
| 138 | close(exited) |
| 139 | }() |
| 140 | t.mu.Lock() |
| 141 | t.procs[pid] = struct{}{} |
| 142 | t.mu.Unlock() |
| 143 | ctx, cancel := context.WithTimeout(context.Background(), startTimeout) |
| 144 | defer cancel() |
| 145 | select { |
| 146 | case <-t.notify.Ready(): |
| 147 | // ready |
| 148 | case <-ctx.Done(): |
| 149 | // timed out |
| 150 | _ = cmd.Process.Kill() |
| 151 | return fmt.Errorf("token \"%s\" worker timed out during startup", t.tconf.Name()) |
| 152 | case <-exited: |
| 153 | // terminated |
| 154 | return fmt.Errorf("token \"%s\" worker exited prematurely", t.tconf.Name()) |
| 155 | } |
| 156 | return nil |
| 157 | } |
| 158 | |
| 159 | func (t *WorkerToken) countWorkers() int { |
| 160 | t.mu.Lock() |
| 161 | n := len(t.procs) |
| 162 | t.mu.Unlock() |
| 163 | return n |
| 164 | } |
| 165 | |
| 166 | func (t *WorkerToken) monitor() { |
| 167 | defer t.wg.Done() |
| 168 | target := 1 |
| 169 | if t.config.Server != nil && t.config.Server.NumWorkers > 0 { |
| 170 | target = t.config.Server.NumWorkers |
| 171 | } |
| 172 | for t.ctx.Err() == nil { |
| 173 | for t.countWorkers() < target { |
| 174 | if err := t.spawn(); err != nil { |
| 175 | log.Printf("error: failed to spawn worker process: %s", err) |
| 176 | select { |
| 177 | case <-time.After(restartDelay): |
| 178 | case <-t.ctx.Done(): |
| 179 | return |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | select { |
| 184 | case <-t.ctx.Done(): |
| 185 | return |
| 186 | case pid := <-t.procsExited: |
| 187 | // process exited |
| 188 | t.removePid(pid) |
| 189 | case pid := <-t.notify.Stopping(): |
| 190 | // process hit an error and will exit soon |
| 191 | t.removePid(pid) |
| 192 | } |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | func (t *WorkerToken) removePid(pid int) { |
| 197 | t.mu.Lock() |
| 198 | delete(t.procs, pid) |
| 199 | t.mu.Unlock() |
| 200 | } |
| 201 | |
| 202 | func (t *WorkerToken) Close() error { |
| 203 | if t == nil { |
| 204 | return nil |
| 205 | } |
| 206 | return t.closed.Close(func() error { |
| 207 | t.cancel() |
| 208 | t.mu.Lock() |
| 209 | for pid := range t.procs { |
| 210 | _ = syscall.Kill(pid, syscall.SIGTERM) |
| 211 | } |
| 212 | t.mu.Unlock() |
| 213 | t.wg.Wait() |
| 214 | t.fdset.Close() |
| 215 | t.notify.Close() |
| 216 | return nil |
| 217 | }) |
| 218 | } |