| 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 !windows |
| 15 | // +build !windows |
| 16 | |
| 17 | package activation |
| 18 | |
| 19 | import ( |
| 20 | "fmt" |
| 21 | "net" |
| 22 | "os" |
| 23 | "strconv" |
| 24 | "syscall" |
| 25 | ) |
| 26 | |
| 27 | // DaemonReady signals to a parent init system or daemon manager that the |
| 28 | // daemon is finished starting up. Use after all listening sockets have been |
| 29 | // opened. |
| 30 | func DaemonReady() (err error) { |
| 31 | if name := os.Getenv("NOTIFY_SOCKET"); name != "" { |
| 32 | // systemd |
| 33 | if err2 := writePath(name, "unixgram", "READY=1"); err2 != nil { |
| 34 | err = err2 |
| 35 | } |
| 36 | } |
| 37 | if fdstr := os.Getenv("NOTIFY_FD"); fdstr != "" { |
| 38 | // github.com/pusher/crank |
| 39 | if err2 := writeFd(fdstr, "READY=1"); err2 != nil { |
| 40 | err = err2 |
| 41 | } |
| 42 | } |
| 43 | if fdstr := os.Getenv("EINHORN_SOCK_FD"); fdstr != "" { |
| 44 | // einhorn -g |
| 45 | if err2 := writeFd(fdstr, einhornReadyStr()); err2 != nil { |
| 46 | err = err2 |
| 47 | } |
| 48 | } else if name := os.Getenv("EINHORN_SOCK_PATH"); name != "" { |
| 49 | // github.com/stripe/einhorn |
| 50 | if err2 := writePath(name, "unix", einhornReadyStr()); err2 != nil { |
| 51 | err = err2 |
| 52 | } |
| 53 | } |
| 54 | return |
| 55 | } |
| 56 | |
| 57 | // write a string to the unix socket at the named path |
| 58 | func writePath(path, netType, message string) error { |
| 59 | sockAddr := &net.UnixAddr{Name: path, Net: netType} |
| 60 | conn, err := net.DialUnix(netType, nil, sockAddr) |
| 61 | if err != nil { |
| 62 | return err |
| 63 | } |
| 64 | defer conn.Close() |
| 65 | _, err = conn.Write([]byte(message)) |
| 66 | return err |
| 67 | } |
| 68 | |
| 69 | // write a string to a numeric file descriptor |
| 70 | func writeFd(fdstr, message string) error { |
| 71 | fd, err := strconv.Atoi(fdstr) |
| 72 | if err != nil { |
| 73 | return err |
| 74 | } |
| 75 | _, err = syscall.Write(fd, []byte(message)) |
| 76 | return err |
| 77 | } |
| 78 | |
| 79 | func einhornReadyStr() string { |
| 80 | return fmt.Sprintf(`{"command":"worker:ack", "pid":%d}`+"\n", os.Getpid()) |
| 81 | } |