-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
75 lines (63 loc) · 1.72 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
import (
"flag"
"fmt"
"os"
"os/signal"
"syscall"
"github.com/devincd/coredns-hosts-api/pkg/server"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"k8s.io/klog/v2"
)
var serverArgs server.Args
func main() {
cmd := newCommand()
if err := cmd.Execute(); err != nil {
klog.ErrorS(err, "Failed to execute the command")
os.Exit(-1)
}
}
func newCommand() *cobra.Command {
command := &cobra.Command{
Use: "coredns-hosts-server",
Short: "coredns web apis service for hosts",
Args: cobra.ExactArgs(0),
PreRunE: func(cmd *cobra.Command, args []string) error {
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
printFlags(cmd)
stopCh := make(chan struct{})
s, err := server.NewServer(serverArgs)
if err != nil {
return fmt.Errorf("failed to create server: %v", err)
}
if err := s.Run(stopCh); err != nil {
return fmt.Errorf("failed to start server: %v", err)
}
WaitSignal(stopCh)
return nil
},
}
addFlags(command)
return command
}
func addFlags(c *cobra.Command) {
klog.InitFlags(flag.CommandLine)
c.PersistentFlags().AddGoFlagSet(flag.CommandLine)
c.PersistentFlags().StringVar(&serverArgs.Kubeconfig, "kubeconfig", "", "absolute path to the kubeconfig file")
c.PersistentFlags().Int32Var(&serverArgs.Port, "port", 9080, "the web service port")
}
func printFlags(c *cobra.Command) {
c.PersistentFlags().VisitAll(func(flag *pflag.Flag) {
klog.Infof("FLAG: --%s=%q", flag.Name, flag.Value)
})
}
func WaitSignal(stop chan struct{}) {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
sigsInfo := <-sigs
klog.Infof("Receive the signal %s, and the server is terminating", sigsInfo.String())
close(stop)
}