|
| 1 | +/* |
| 2 | +Copyright © 2021 Bisohns |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | +package cmd |
| 17 | + |
| 18 | +import ( |
| 19 | + "encoding/json" |
| 20 | + "fmt" |
| 21 | + "net/http" |
| 22 | + "os" |
| 23 | + "strconv" |
| 24 | + "strings" |
| 25 | + "sync" |
| 26 | + "time" |
| 27 | + |
| 28 | + "github.com/bisohns/saido/config" |
| 29 | + "github.com/bisohns/saido/driver" |
| 30 | + "github.com/bisohns/saido/inspector" |
| 31 | + "github.com/gorilla/handlers" |
| 32 | + "github.com/gorilla/websocket" |
| 33 | + log "github.com/sirupsen/logrus" |
| 34 | + "github.com/spf13/cobra" |
| 35 | +) |
| 36 | + |
| 37 | +const ( |
| 38 | + socketBufferSize = 1042 |
| 39 | + messageBufferSize = 256 |
| 40 | +) |
| 41 | + |
| 42 | +var ( |
| 43 | + port string |
| 44 | + server = http.NewServeMux() |
| 45 | + upgrader = &websocket.Upgrader{ |
| 46 | + ReadBufferSize: socketBufferSize, |
| 47 | + WriteBufferSize: socketBufferSize, |
| 48 | + CheckOrigin: func(r *http.Request) bool { |
| 49 | + return true |
| 50 | + }} |
| 51 | +) |
| 52 | + |
| 53 | +type FullMessage struct { |
| 54 | + Error bool |
| 55 | + Message interface{} |
| 56 | +} |
| 57 | + |
| 58 | +type Message struct { |
| 59 | + Host string |
| 60 | + Name string |
| 61 | + Data interface{} |
| 62 | +} |
| 63 | + |
| 64 | +type Client struct { |
| 65 | + Socket *websocket.Conn |
| 66 | + Send chan *FullMessage |
| 67 | +} |
| 68 | + |
| 69 | +// Write to websocket |
| 70 | +func (client *Client) Write() { |
| 71 | + defer client.Socket.Close() |
| 72 | + var err error |
| 73 | + for msg := range client.Send { |
| 74 | + err = client.Socket.WriteJSON(msg) |
| 75 | + if err != nil { |
| 76 | + log.Error("Error inside client write ", err) |
| 77 | + } |
| 78 | + } |
| 79 | +} |
| 80 | + |
| 81 | +type Hosts struct { |
| 82 | + Config *config.Config |
| 83 | + // Connections : hostname mapped to connection instances to reuse |
| 84 | + // across metrics |
| 85 | + mu sync.Mutex |
| 86 | + Drivers map[string]*driver.Driver |
| 87 | + Client chan *Client |
| 88 | + Start chan bool |
| 89 | +} |
| 90 | + |
| 91 | +func (hosts *Hosts) getDriver(address string) *driver.Driver { |
| 92 | + hosts.mu.Lock() |
| 93 | + defer hosts.mu.Unlock() |
| 94 | + return hosts.Drivers[address] |
| 95 | +} |
| 96 | + |
| 97 | +func (hosts *Hosts) resetDriver(host config.Host) { |
| 98 | + hosts.mu.Lock() |
| 99 | + defer hosts.mu.Unlock() |
| 100 | + hostDriver := host.Connection.ToDriver() |
| 101 | + hosts.Drivers[host.Address] = &hostDriver |
| 102 | +} |
| 103 | + |
| 104 | +func (hosts *Hosts) sendMetric(host config.Host, client *Client) { |
| 105 | + if hosts.getDriver(host.Address) == nil { |
| 106 | + hosts.resetDriver(host) |
| 107 | + } |
| 108 | + for _, metric := range config.GetDashboardInfoConfig(hosts.Config).Metrics { |
| 109 | + initializedMetric, err := inspector.Init(metric, hosts.getDriver(host.Address)) |
| 110 | + data, err := initializedMetric.Execute() |
| 111 | + if err == nil { |
| 112 | + var unmarsh interface{} |
| 113 | + json.Unmarshal(data, &unmarsh) |
| 114 | + message := &FullMessage{ |
| 115 | + Message: Message{ |
| 116 | + Host: host.Address, |
| 117 | + Name: metric, |
| 118 | + Data: unmarsh, |
| 119 | + }, |
| 120 | + Error: false, |
| 121 | + } |
| 122 | + client.Send <- message |
| 123 | + } else { |
| 124 | + // check for error 127 which means command was not found |
| 125 | + var errorContent string |
| 126 | + if !strings.Contains(fmt.Sprintf("%s", err), "127") { |
| 127 | + errorContent = fmt.Sprintf("Could not retrieve metric %s from driver %s with error %s, resetting connection...", metric, host.Address, err) |
| 128 | + } else { |
| 129 | + errorContent = fmt.Sprintf("Command %s not found on driver %s", metric, host.Address) |
| 130 | + } |
| 131 | + log.Error(errorContent) |
| 132 | + hosts.resetDriver(host) |
| 133 | + message := &FullMessage{ |
| 134 | + Message: errorContent, |
| 135 | + Error: true, |
| 136 | + } |
| 137 | + client.Send <- message |
| 138 | + } |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +func (hosts *Hosts) Run() { |
| 143 | + dashboardInfo := config.GetDashboardInfoConfig(hosts.Config) |
| 144 | + log.Debug("In Running") |
| 145 | + for { |
| 146 | + select { |
| 147 | + case client := <-hosts.Client: |
| 148 | + for { |
| 149 | + for _, host := range dashboardInfo.Hosts { |
| 150 | + go hosts.sendMetric(host, client) |
| 151 | + } |
| 152 | + log.Infof("Delaying for %d seconds", dashboardInfo.PollInterval) |
| 153 | + time.Sleep(time.Duration(dashboardInfo.PollInterval) * time.Second) |
| 154 | + } |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | +} |
| 159 | + |
| 160 | +func (hosts *Hosts) ServeHTTP(w http.ResponseWriter, req *http.Request) { |
| 161 | + socket, err := upgrader.Upgrade(w, req, nil) |
| 162 | + if err != nil { |
| 163 | + log.Fatal(err) |
| 164 | + return |
| 165 | + } |
| 166 | + client := &Client{ |
| 167 | + Socket: socket, |
| 168 | + Send: make(chan *FullMessage, messageBufferSize), |
| 169 | + } |
| 170 | + hosts.Client <- client |
| 171 | + client.Write() |
| 172 | +} |
| 173 | + |
| 174 | +func newHosts(cfg *config.Config) *Hosts { |
| 175 | + hosts := &Hosts{ |
| 176 | + Config: cfg, |
| 177 | + Drivers: make(map[string]*driver.Driver), |
| 178 | + Client: make(chan *Client), |
| 179 | + } |
| 180 | + return hosts |
| 181 | +} |
| 182 | + |
| 183 | +func setHostHandler(w http.ResponseWriter, r *http.Request) { |
| 184 | + b, _ := json.Marshal("Hello World") |
| 185 | + w.Write(b) |
| 186 | +} |
| 187 | + |
| 188 | +var apiCmd = &cobra.Command{ |
| 189 | + Use: "api", |
| 190 | + Short: "host saido as an API on a PORT env variable, fallback to set argument", |
| 191 | + Long: ``, |
| 192 | + Run: func(cmd *cobra.Command, args []string) { |
| 193 | + // server.HandleFunc("/set-hosts", SetHostHandler) |
| 194 | + // FIXME: set up cfg using set-hosts endpoint |
| 195 | + hosts := newHosts(cfg) |
| 196 | + server.HandleFunc("/set-hosts", setHostHandler) |
| 197 | + server.Handle("/metrics", hosts) |
| 198 | + log.Info("listening on :", port) |
| 199 | + _, err := strconv.Atoi(port) |
| 200 | + if err != nil { |
| 201 | + log.Fatal(err) |
| 202 | + } |
| 203 | + go hosts.Run() |
| 204 | + loggedRouters := handlers.LoggingHandler(os.Stdout, server) |
| 205 | + if err := http.ListenAndServe(":"+port, loggedRouters); err != nil { |
| 206 | + log.Fatal(err) |
| 207 | + } |
| 208 | + }, |
| 209 | +} |
| 210 | + |
| 211 | +func init() { |
| 212 | + apiCmd.Flags().StringVarP(&port, "port", "p", "3000", "Port to run application server on") |
| 213 | + rootCmd.AddCommand(apiCmd) |
| 214 | +} |
0 commit comments