github.com/noironetworks/cilium-net@v1.6.12/cilium-health/responder/main.go (about) 1 // Copyright 2019 Authors of Cilium 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 main 16 17 import ( 18 "context" 19 "fmt" 20 "os" 21 "os/signal" 22 "syscall" 23 24 "github.com/cilium/cilium/pkg/health/probe/responder" 25 "github.com/cilium/cilium/pkg/pidfile" 26 27 flag "github.com/spf13/pflag" 28 ) 29 30 func cancelOnSignal(cancel context.CancelFunc, sig ...os.Signal) { 31 c := make(chan os.Signal, 1) 32 signal.Notify(c, sig...) 33 go func() { 34 <-c 35 cancel() 36 }() 37 } 38 39 func main() { 40 var ( 41 pidfilePath string 42 listen int 43 ) 44 flag.StringVar(&pidfilePath, "pidfile", "", "Write pid to the specified file") 45 flag.IntVar(&listen, "listen", 4240, "Port on which the responder listens") 46 flag.Parse() 47 48 // Shutdown gracefully to halt server and remove pidfile 49 ctx, cancel := context.WithCancel(context.Background()) 50 cancelOnSignal(cancel, syscall.SIGINT, syscall.SIGHUP, syscall.SIGTERM, syscall.SIGQUIT) 51 52 srv := responder.NewServer(listen) 53 defer srv.Shutdown() 54 go func() { 55 if err := srv.Serve(); err != nil { 56 fmt.Fprintf(os.Stderr, "error while listening: %s\n", err.Error()) 57 cancel() 58 } 59 }() 60 61 if pidfilePath != "" { 62 defer pidfile.Clean() 63 if err := pidfile.Write(pidfilePath); err != nil { 64 fmt.Fprintf(os.Stderr, "cannot write pidfile: %s: %s\n", pidfilePath, err.Error()) 65 os.Exit(-1) 66 } 67 } 68 69 <-ctx.Done() 70 }