Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS
Mirrored from https://github.com/Slazee/caddy.git
Synced Nov 10, 23:45 UTC
| 1 | // Copyright 2015 Matthew Holt and The Caddy Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | // Package notify provides facilities for notifying process managers |
| 16 | // of state changes, mainly for when running as a system service. |
| 17 | package notify |
| 18 | |
| 19 | import ( |
| 20 | "fmt" |
| 21 | "net" |
| 22 | "os" |
| 23 | "strings" |
| 24 | ) |
| 25 | |
| 26 | // The documentation about this IPC protocol is available here: |
| 27 | // https://www.freedesktop.org/software/systemd/man/sd_notify.html |
| 28 | |
| 29 | func sdNotify(payload string) error { |
| 30 | if socketPath == "" { |
| 31 | return nil |
| 32 | } |
| 33 | |
| 34 | socketAddr := &net.UnixAddr{ |
| 35 | Name: socketPath, |
| 36 | Net: "unixgram", |
| 37 | } |
| 38 | |
| 39 | conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr) |
| 40 | if err != nil { |
| 41 | return err |
| 42 | } |
| 43 | defer conn.Close() |
| 44 | |
| 45 | _, err = conn.Write([]byte(payload)) |
| 46 | return err |
| 47 | } |
| 48 | |
| 49 | // Ready notifies systemd that caddy has finished its |
| 50 | // initialization routines. |
| 51 | func Ready() error { |
| 52 | return sdNotify("READY=1") |
| 53 | } |
| 54 | |
| 55 | // Reloading notifies systemd that caddy is reloading its config. |
| 56 | func Reloading() error { |
| 57 | return sdNotify("RELOADING=1") |
| 58 | } |
| 59 | |
| 60 | // Stopping notifies systemd that caddy is stopping. |
| 61 | func Stopping() error { |
| 62 | return sdNotify("STOPPING=1") |
| 63 | } |
| 64 | |
| 65 | // Status sends systemd an updated status message. |
| 66 | func Status(msg string) error { |
| 67 | return sdNotify("STATUS=" + msg) |
| 68 | } |
| 69 | |
| 70 | // Error is like Status, but sends systemd an error message |
| 71 | // instead, with an optional errno-style error number. |
| 72 | func Error(err error, errno int) error { |
| 73 | collapsedErr := strings.ReplaceAll(err.Error(), "\n", " ") |
| 74 | msg := fmt.Sprintf("STATUS=%s", collapsedErr) |
| 75 | if errno > 0 { |
| 76 | msg += fmt.Sprintf("\nERRNO=%d", errno) |
| 77 | } |
| 78 | return sdNotify(msg) |
| 79 | } |
| 80 | |
| 81 | var socketPath, _ = os.LookupEnv("NOTIFY_SOCKET") |