blob: e0314e6d1d211ba5e1faf2155b7f1ea3d22e9856 [file] [log] [blame]
David K. Bainbridge732957f2016-10-06 22:36:59 -07001// Copyright 2016 Open Networking Laboratory
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.
14package main
15
16import (
David K. Bainbridge528b3182017-01-23 08:51:59 -080017 "flag"
David K. Bainbridge732957f2016-10-06 22:36:59 -070018 "fmt"
19 "github.com/Sirupsen/logrus"
20 "github.com/gorilla/mux"
21 "github.com/kelseyhightower/envconfig"
22 "net/http"
David K. Bainbridge528b3182017-01-23 08:51:59 -080023 "os"
David K. Bainbridge17911b42017-01-09 20:53:22 -080024 "regexp"
David K. Bainbridge732957f2016-10-06 22:36:59 -070025 "strconv"
David K. Bainbridge17911b42017-01-09 20:53:22 -080026 "strings"
David K. Bainbridge732957f2016-10-06 22:36:59 -070027 "sync"
28 "text/template"
29 "time"
30)
31
David K. Bainbridge528b3182017-01-23 08:51:59 -080032const appName = "HARVESTER"
33
David K. Bainbridge732957f2016-10-06 22:36:59 -070034// application application configuration and internal state
35type application struct {
David K. Bainbridge17911b42017-01-09 20:53:22 -080036 Port int `default:"4246" desc:"port on which the service will listen for requests"`
37 Listen string `default:"0.0.0.0" desc:"IP on which the service will listen for requests"`
38 LogLevel string `default:"warning" envconfig:"LOG_LEVEL" desc:"log output level"`
39 LogFormat string `default:"text" envconfig:"LOG_FORMAT" desc:"format of log messages"`
40 DHCPLeaseFile string `default:"/harvester/dhcpd.leases" envconfig:"DHCP_LEASE_FILE" desc:"lease file to parse for lease information"`
41 OutputFile string `envconfig:"OUTPUT_FILE" desc:"name of file to output discovered lease in bind9 format"`
42 OutputFormat string `default:"{{.ClientHostname}}\tIN A {{.IPAddress}}\t; {{.HardwareAddress}}" envconfig:"OUTPUT_FORMAT" desc:"specifies the single entry format when outputing to a file"`
43 VerifyLeases bool `default:"true" envconfig:"VERIFY_LEASES" desc:"verifies leases with a ping"`
44 VerifyTimeout time.Duration `default:"1s" envconfig:"VERIFY_TIMEOUT" desc:"max timeout (RTT) to wait for verification pings"`
45 VerifyWithUDP bool `default:"false" envconfig:"VERIFY_WITH_UDP" desc:"use UDP instead of raw sockets for ping verification"`
46 QueryPeriod time.Duration `default:"30s" envconfig:"QUERY_PERIOD" desc:"period at which the DHCP lease file is processed"`
47 QuietPeriod time.Duration `default:"2s" envconfing:"QUIET_PERIOD" desc:"period to wait between accepting parse requests"`
48 RequestTimeout time.Duration `default:"10s" envconfig:"REQUEST_TIMEOUT" desc:"period to wait for processing when requesting a DHCP lease database parsing"`
49 RNDCUpdate bool `default:"false" envconfig:"RNDC_UPDATE" desc:"determines if the harvester reloads the DNS servers after harvest"`
50 RNDCAddress string `default:"127.0.0.1" envconfig:"RNDC_ADDRESS" desc:"IP address of the DNS server to contact via RNDC"`
51 RNDCPort int `default:"954" envconfig:"RNDC_PORT" desc:"port of the DNS server to contact via RNDC"`
52 RNDCKeyFile string `default:"/key/rndc.conf.maas" envconfig:"RNDC_KEY_FILE" desc:"key file, with default, to contact DNS server"`
53 RNDCZone string `default:"cord.lab" envconfig:"RNDC_ZONE" desc:"zone to reload"`
54 BadClientNames []string `default:"localhost" envconfig:"BAD_CLIENT_NAMES" desc:"list of invalid hostnames for clients"`
55 ClientNameTemplate string `default:"UKN-{{with $x:=.HardwareAddress|print}}{{regex $x \":\" \"\"}}{{end}}" envconfig:"CLIENT_NAME_TEMPLATE" desc:"template for generated host name"`
David K. Bainbridge732957f2016-10-06 22:36:59 -070056
David K. Bainbridge528b3182017-01-23 08:51:59 -080057 appFlags *flag.FlagSet `ignored:"true"`
David K. Bainbridge17911b42017-01-09 20:53:22 -080058 log *logrus.Logger `ignored:"true"`
59 interchange sync.RWMutex `ignored:"true"`
60 leases map[string]*Lease `ignored:"true"`
61 byHardware map[string]*Lease `ignored:"true"`
62 byHostname map[string]*Lease `ignored:"true"`
63 outputTemplate *template.Template `ignored:"true"`
64 requests chan *chan uint `ignored:"true"`
65 clientNameTemplate *template.Template `ignored:"true"`
66 badClientNames map[string]bool `ignored:"true"`
David K. Bainbridge732957f2016-10-06 22:36:59 -070067}
68
69func main() {
David K. Bainbridge528b3182017-01-23 08:51:59 -080070
David K. Bainbridge732957f2016-10-06 22:36:59 -070071 // initialize application state
72 app := &application{
73 log: logrus.New(),
David K. Bainbridge528b3182017-01-23 08:51:59 -080074 appFlags: flag.NewFlagSet("", flag.ContinueOnError),
David K. Bainbridge732957f2016-10-06 22:36:59 -070075 requests: make(chan *chan uint, 100),
76 }
77
David K. Bainbridge528b3182017-01-23 08:51:59 -080078 app.appFlags.Usage = func() {
79 envconfig.Usage(appName, app)
80 }
81 if err := app.appFlags.Parse(os.Args[1:]); err != nil {
82 if err != flag.ErrHelp {
83 os.Exit(1)
84 } else {
85 return
86 }
87 }
88
David K. Bainbridge732957f2016-10-06 22:36:59 -070089 // process and validate the application configuration
90 err := envconfig.Process("HARVESTER", app)
91 if err != nil {
92 app.log.Fatalf("unable to parse configuration options : %s", err)
93 }
94 switch app.LogFormat {
95 case "json":
96 app.log.Formatter = &logrus.JSONFormatter{}
97 default:
98 app.log.Formatter = &logrus.TextFormatter{
99 FullTimestamp: true,
100 ForceColors: true,
101 }
102 }
103 level, err := logrus.ParseLevel(app.LogLevel)
104 if err != nil {
105 level = logrus.WarnLevel
106 }
107 app.log.Level = level
108
109 app.outputTemplate, err = template.New("harvester").Parse(app.OutputFormat)
110 if err != nil {
111 app.log.Fatalf("invalid output file format specified : %s", err)
112 }
113
114 // output the configuration
115 app.log.Infof(`Configuration:
David K. Bainbridge17911b42017-01-09 20:53:22 -0800116 LISTEN: %s
117 PORT: %d
118 LOG_LEVEL: %s
119 LOG_FORMAT: %s
120 DHCP_LEASE_FILE: %s
121 OUTPUT_FILE: %s
122 OUTPUT_FORMAT: %s
123 VERIFY_LEASES: %t
124 VERIFY_TIMEOUT: %s
125 VERIFY_WITH_UDP: %t
126 QUERY_PERIOD: %s
127 QUIET_PERIOD: %s
128 REQUEST_TIMEOUT: %s
129 RNDC_UPDATE: %t
130 RNDC_ADDRESS: %s
131 RNDC_PORT: %d
132 RNDC_KEY_FILE: %s
133 RNDC_ZONE: %s
134 BAD_CLIENT_NAMES: %s
135 CLIENT_NAME_TEMPLATE: %s`,
David K. Bainbridge732957f2016-10-06 22:36:59 -0700136 app.Listen, app.Port,
137 app.LogLevel, app.LogFormat,
138 app.DHCPLeaseFile, app.OutputFile, strconv.Quote(app.OutputFormat),
139 app.VerifyLeases, app.VerifyTimeout, app.VerifyWithUDP,
140 app.QueryPeriod, app.QuietPeriod, app.RequestTimeout,
David K. Bainbridge17911b42017-01-09 20:53:22 -0800141 app.RNDCUpdate, app.RNDCAddress, app.RNDCPort, app.RNDCKeyFile, app.RNDCZone,
142 strings.Join(app.BadClientNames[:], ","), app.ClientNameTemplate)
143
144 app.clientNameTemplate, err = template.New("harvester").Funcs(template.FuncMap{
145 "regex": func(target, match, replace string) string {
146 re := regexp.MustCompile(match)
147 return re.ReplaceAllString(target, replace)
148 },
149 }).Parse(app.ClientNameTemplate)
150 if err != nil {
151 app.log.Fatalf("Unable to parse client host name template %s", err)
152 }
153
154 app.badClientNames = make(map[string]bool)
155 for _, bad := range app.BadClientNames {
156 app.badClientNames[bad] = true
157 }
David K. Bainbridge732957f2016-10-06 22:36:59 -0700158
159 // establish REST end points
160 router := mux.NewRouter()
161 router.HandleFunc("/lease/", app.listLeasesHandler).Methods("GET")
162 router.HandleFunc("/lease/{ip}", app.getLeaseHandler).Methods("GET")
163 router.HandleFunc("/lease/hardware/{mac}", app.getLeaseByHardware).Methods("GET")
164 router.HandleFunc("/lease/hostname/{name}", app.getLeaseByHostname).Methods("GET")
165 router.HandleFunc("/harvest/", app.doHarvestHandler).Methods("POST")
166 router.HandleFunc("/harvest", app.doHarvestHandler).Methods("POST")
167 http.Handle("/", router)
168
169 // start DHCP lease file synchronization handler
170 go app.syncRequestHandler(app.requests)
171
172 // start loop to periodically synchronize DHCP lease file
173 go app.syncFromDHCPLeaseFileLoop(app.requests)
174
175 // listen for REST requests
176 http.ListenAndServe(fmt.Sprintf("%s:%d", app.Listen, app.Port), nil)
177}