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, 22:30 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 caddy |
| 16 | |
| 17 | import ( |
| 18 | "context" |
| 19 | "os" |
| 20 | "os/signal" |
| 21 | |
| 22 | "go.uber.org/zap" |
| 23 | ) |
| 24 | |
| 25 | // TrapSignals create signal/interrupt handlers as best it can for the |
| 26 | // current OS. This is a rather invasive function to call in a Go program |
| 27 | // that captures signals already, so in that case it would be better to |
| 28 | // implement these handlers yourself. |
| 29 | func TrapSignals() { |
| 30 | trapSignalsCrossPlatform() |
| 31 | trapSignalsPosix() |
| 32 | } |
| 33 | |
| 34 | // trapSignalsCrossPlatform captures SIGINT or interrupt (depending |
| 35 | // on the OS), which initiates a graceful shutdown. A second SIGINT |
| 36 | // or interrupt will forcefully exit the process immediately. |
| 37 | func trapSignalsCrossPlatform() { |
| 38 | go func() { |
| 39 | shutdown := make(chan os.Signal, 1) |
| 40 | signal.Notify(shutdown, os.Interrupt) |
| 41 | |
| 42 | for i := 0; true; i++ { |
| 43 | <-shutdown |
| 44 | |
| 45 | if i > 0 { |
| 46 | Log().Warn("force quit", zap.String("signal", "SIGINT")) |
| 47 | os.Exit(ExitCodeForceQuit) |
| 48 | } |
| 49 | |
| 50 | Log().Info("shutting down", zap.String("signal", "SIGINT")) |
| 51 | go exitProcessFromSignal("SIGINT") |
| 52 | } |
| 53 | }() |
| 54 | } |
| 55 | |
| 56 | // exitProcessFromSignal exits the process from a system signal. |
| 57 | func exitProcessFromSignal(sigName string) { |
| 58 | logger := Log().With(zap.String("signal", sigName)) |
| 59 | exitProcess(context.TODO(), logger) |
| 60 | } |
| 61 | |
| 62 | // Exit codes. Generally, you should NOT |
| 63 | // automatically restart the process if the |
| 64 | // exit code is ExitCodeFailedStartup (1). |
| 65 | const ( |
| 66 | ExitCodeSuccess = iota |
| 67 | ExitCodeFailedStartup |
| 68 | ExitCodeForceQuit |
| 69 | ExitCodeFailedQuit |
| 70 | ) |