1 /* 2 Copyright 2016 The Kubernetes Authors. 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 interrupt 18 19 import ( 20 "os" 21 "os/signal" 22 "sync" 23 "syscall" 24 ) 25 26 // terminationSignals are signals that cause the program to exit in the 27 // supported platforms (linux, darwin, windows). 28 var terminationSignals = []os.Signal{syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT} 29 30 // Handler guarantees execution of notifications after a critical section (the function passed 31 // to a Run method), even in the presence of process termination. It guarantees exactly once 32 // invocation of the provided notify functions. 33 type Handler struct { 34 notify []func() 35 final func(os.Signal) 36 once sync.Once 37 } 38 39 // New creates a new handler that guarantees all notify functions are run after the critical 40 // section exits (or is interrupted by the OS), then invokes the final handler. If no final 41 // handler is specified, the default final is `os.Exit(1)`. A handler can only be used for 42 // one critical section. 43 func New(final func(os.Signal), notify ...func()) *Handler { 44 return &Handler{ 45 final: final, 46 notify: notify, 47 } 48 } 49 50 // Close executes all the notification handlers if they have not yet been executed. 51 func (h *Handler) Close() { 52 h.once.Do(func() { 53 for _, fn := range h.notify { 54 fn() 55 } 56 }) 57 } 58 59 // Signal is called when an os.Signal is received, and guarantees that all notifications 60 // are executed, then the final handler is executed. This function should only be called once 61 // per Handler instance. 62 func (h *Handler) Signal(s os.Signal) { 63 h.once.Do(func() { 64 for _, fn := range h.notify { 65 fn() 66 } 67 if h.final == nil { 68 os.Exit(1) 69 } 70 h.final(s) 71 }) 72 } 73 74 // Run ensures that any notifications are invoked after the provided fn exits (even if the 75 // process is interrupted by an OS termination signal). Notifications are only invoked once 76 // per Handler instance, so calling Run more than once will not behave as the user expects. 77 func (h *Handler) Run(fn func() error) error { 78 ch := make(chan os.Signal, 1) 79 signal.Notify(ch, terminationSignals...) 80 defer func() { 81 signal.Stop(ch) 82 close(ch) 83 }() 84 go func() { 85 sig, ok := <-ch 86 if !ok { 87 return 88 } 89 h.Signal(sig) 90 }() 91 defer h.Close() 92 return fn() 93 } 94