blob: 27e237a5962a36c88796749a523343e47a6cfed8 [file] [log] [blame]
David K. Bainbridge8bc905c2016-05-31 14:07:10 -07001package main
2
3import (
4 "fmt"
David K. Bainbridgea9c2e0a2016-07-01 18:33:50 -07005 "github.com/Sirupsen/logrus"
David K. Bainbridge8bc905c2016-05-31 14:07:10 -07006 "github.com/gorilla/mux"
7 "github.com/kelseyhightower/envconfig"
David K. Bainbridge8bc905c2016-05-31 14:07:10 -07008 "net/http"
9)
10
11type Config struct {
David K. Bainbridgea9c2e0a2016-07-01 18:33:50 -070012 Port int `default:"4242"`
13 Listen string `default:"0.0.0.0"`
14 Network string `default:"10.0.0.0/24"`
15 Skip int `default:"1"`
16 LogLevel string `default:"warning" envconfig:"LOG_LEVEL"`
17 LogFormat string `default:"text" envconfig:"LOG_FORMAT"`
David K. Bainbridge8bc905c2016-05-31 14:07:10 -070018}
19
20type Context struct {
21 storage Storage
22}
23
David K. Bainbridgea9c2e0a2016-07-01 18:33:50 -070024var log = logrus.New()
25
David K. Bainbridge8bc905c2016-05-31 14:07:10 -070026func main() {
27 context := &Context{}
28
29 config := Config{}
30 err := envconfig.Process("ALLOCATE", &config)
31 if err != nil {
David K. Bainbridgea9c2e0a2016-07-01 18:33:50 -070032 log.Fatalf("Unable to parse configuration options : %s", err)
David K. Bainbridge8bc905c2016-05-31 14:07:10 -070033 }
34
David K. Bainbridgea9c2e0a2016-07-01 18:33:50 -070035 switch config.LogFormat {
36 case "json":
37 log.Formatter = &logrus.JSONFormatter{}
38 default:
39 log.Formatter = &logrus.TextFormatter{
40 FullTimestamp: true,
41 ForceColors: true,
42 }
43 }
44
45 level, err := logrus.ParseLevel(config.LogLevel)
46 if err != nil {
47 level = logrus.WarnLevel
48 }
49 log.Level = level
50
51 log.Infof(`Configuration:
David K. Bainbridge8bc905c2016-05-31 14:07:10 -070052 Listen: %s
53 Port: %d
David K. Bainbridge252cc2c2016-06-02 22:28:59 -070054 Network: %s
David K. Bainbridgea9c2e0a2016-07-01 18:33:50 -070055 SKip: %d
56 Log Level: %s
57 Log Format: %s`, config.Listen, config.Port, config.Network, config.Skip,
58 config.LogLevel, config.LogFormat)
David K. Bainbridge8bc905c2016-05-31 14:07:10 -070059
60 context.storage = &MemoryStorage{}
David K. Bainbridge252cc2c2016-06-02 22:28:59 -070061 context.storage.Init(config.Network, config.Skip)
David K. Bainbridge8bc905c2016-05-31 14:07:10 -070062
63 router := mux.NewRouter()
64 router.HandleFunc("/allocations/{mac}", context.ReleaseAllocationHandler).Methods("DELETE")
65 router.HandleFunc("/allocations/{mac}", context.AllocationHandler).Methods("GET")
66 router.HandleFunc("/allocations/", context.ListAllocationsHandler).Methods("GET")
67 router.HandleFunc("/addresses/{ip}", context.FreeAddressHandler).Methods("DELETE")
68 http.Handle("/", router)
69
70 http.ListenAndServe(fmt.Sprintf("%s:%d", config.Listen, config.Port), nil)
71}