blob: c63b347d10f2744dfb18d8460ec84f3a91e475ae [file] [log] [blame]
David K. Bainbridge215e0242017-09-05 23:18:24 -07001// Copyright 2017 the original author or authors.
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
15package main
16
17import (
18 "net/http"
19
20 "bytes"
21
22 "github.com/gorilla/mux"
23 "sync"
24)
25
26var configMutex sync.Mutex
27
28type Listener struct {
29 ListenOn string
30 Update chan []byte
31
32 router *mux.Router
33 clusterConfig []byte
34}
35
36func (l *Listener) Init() {
37 l.router = mux.NewRouter()
38 l.router.HandleFunc("/config", l.ConfigHandler).Methods("GET")
39 l.router.HandleFunc("/config/", l.ConfigHandler).Methods("GET")
40 l.clusterConfig = []byte("{}")
41 l.Update = make(chan []byte)
42 go l.updateHandler()
43}
44
45func (l *Listener) updateHandler() {
46 for {
47 next := <-l.Update
48
49 if !bytes.Equal(next, l.clusterConfig) {
50 log.Info("Cluster configuration modified")
51 configMutex.Lock()
52 l.clusterConfig = next
53 configMutex.Unlock()
54 } else {
55 log.Debug("Cluster update received, w/o change")
56 }
57 }
58}
59
60func (l *Listener) ListenAndServe() error {
61 log.Infof("Starting to listen for cluster configuration requests on '%s'",
62 l.ListenOn)
63 return http.ListenAndServe(l.ListenOn, l.router)
64}
65
66func (l *Listener) ConfigHandler(w http.ResponseWriter, r *http.Request) {
67 configMutex.Lock()
68 local := l.clusterConfig
69 configMutex.Unlock()
70 if len(local) == 0 {
71 w.WriteHeader(http.StatusNoContent)
72 return
73 }
74 w.Header().Add("content-type", "application/json")
75 w.Write(local)
76 return
77}