...
1
18
19 package api
20
21 import (
22 "discovery/config"
23 "discovery/db"
24 "discovery/errors"
25 "discovery/log"
26 "discovery/types"
27 "discovery/utils"
28 "encoding/json"
29 "io"
30 "net"
31 "net/http"
32 )
33
34 func ServersGetList(w http.ResponseWriter, r *http.Request) {
35
36 if r.Header.Get("User-Agent") == utils.UserAgentMachine {
37 clientIp := net.ParseIP(utils.IsolateIPFromPort(r.Header.Get(config.GetParamIp)))
38 if len(clientIp) > 0 {
39 log.Log.Debug("Machine %s requested list, adding/updating my list", clientIp)
40 err := db.MachineAdd(&types.Machine{
41 IP: r.Header.Get(config.GetParamIp),
42 Name: r.Header.Get(config.GetParamName),
43 GroupName: r.Header.Get(config.GetParamGroupName),
44 Alive: true,
45 DeadPolls: 0,
46 }, true)
47 if err != nil {
48 log.Log.Debugf("Cannot add machine %s: %s", r.Header.Get(config.GetParamIp), err.Error())
49 }
50 } else {
51 log.Log.Debugf("Requestor %s is a machine but its IP is not valid", r.RemoteAddr)
52 }
53 } else {
54 log.Log.Debugf("Success, User-Agent: \"%s\"", r.Header.Get("User-Agent"))
55 }
56
57
58 aliveMachines, err := db.MachinesGetAlive()
59
60 if aliveMachines == nil {
61 aliveMachines = []types.Machine{}
62 }
63
64 out, err := json.Marshal(aliveMachines)
65 if err != nil {
66 log.Log.Debugf("Cannot marshal json")
67 errors.ReplyWithError(w, errors.GenericError)
68 return
69 }
70
71 w.Header().Set("Content-Type", "application/json")
72
73 w.Header().Set(config.GetParamIp, config.GetMachineIp())
74 w.Header().Set(config.GetParamName, config.GetMachineId())
75 w.Header().Set(config.GetParamGroupName, config.GetMachineGroupName())
76
77 _, _ = io.WriteString(w, string(out))
78 }
79
80 func ServersReset(w http.ResponseWriter, r *http.Request) {
81 err := db.MachineRemoveAll()
82 if err != nil {
83 log.Log.Errorf("Cannot delete all machines: %s", err)
84 w.WriteHeader(500)
85 return
86 }
87
88 w.WriteHeader(200)
89 }
90
View as plain text