summaryrefslogtreecommitdiff
path: root/test/commandandcontrol/cc_service/main.go
blob: b0d58f721d20bea6d68a45161e8de7b3dceef2f1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// Copyright (C) 2019-2024 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand.  If not, see <https://www.gnu.org/licenses/>.

package main

import (
	"flag"
	"html/template"
	"net/http"

	"github.com/algorand/websocket"

	"github.com/algorand/go-algorand/logging"
	"github.com/algorand/go-algorand/test/commandandcontrol/lib"
)

var addr = flag.String("addr", "localhost:8080", "http service address")

var upgrader = websocket.Upgrader{} // use default options

var clients = make(map[*websocket.Conn]bool)              // map of connected clients
var clientBroadcast = make(chan []byte, 100)              // client broadcast channel
var agents = make(map[*websocket.Conn]bool)               // map of connected agents
var agentBroadcast = make(chan lib.CCServiceRequest, 100) // agent broadcast channel

var log = logging.NewLogger()

func main() {
	flag.Parse()

	http.HandleFunc("/client", handleClientConnections)
	http.HandleFunc("/agent", handleAgentConnections)
	http.HandleFunc("/", webHome)
	go broadcastToAgents()
	go broadcastToClients()
	log.Infof("cc service listening for connections: %s", *addr)
	err := http.ListenAndServe(*addr, nil)
	if err != nil {
		log.Errorf("starting http service resulted in error: %v", err)
	}
}

func handleClientConnections(w http.ResponseWriter, r *http.Request) {
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Error("upgrade:", err)
		return
	}
	ws.Unsafe = true

	log.Infof("handleClientConnections() with client: %s", ws.RemoteAddr())

	clients[ws] = true

	go monitorClient(ws)
}

func handleAgentConnections(w http.ResponseWriter, r *http.Request) {
	// Upgrade initial GET request to a websocket
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Error("problem initializing agent web socket", err)
		return
	}
	ws.Unsafe = true
	log.Infof("handleAgentConnections() new client: %v", ws.RemoteAddr())
	// Register our new client
	agents[ws] = true
	log.Infof("handleAgentConnections client count: %d", len(agents))
	go monitorAgent(ws)
}

func monitorAgent(ws *websocket.Conn) {

	defer func() {
		log.Infof("closing client: %s", ws.RemoteAddr())
		err := ws.Close()
		if err != nil {
			log.Errorf("error closing agent websocket %v", err)
		}
	}()

	for {
		var message []byte
		var messageType int
		messageType, message, err := ws.ReadMessage()
		if err != nil {
			log.Errorf("error: %v", err)
			break
		}
		switch messageType {
		case websocket.TextMessage:
			log.Infof("received text from agent: %s", message)
			clientBroadcast <- message
			break
		default:
			log.Infof("received other from agent: %s", message)
			break
		}
	}
	// remove the agent from the agent broadcast list
	delete(agents, ws)
}

func monitorClient(ws *websocket.Conn) {

	defer func() {
		log.Infof("closing client: %s", ws.RemoteAddr())
		err := ws.Close()
		if err != nil {
			log.Errorf("error closing agent websocket %v", err)
		}
	}()

	for {
		var managementServiceRequest lib.CCServiceRequest
		err := ws.ReadJSON(&managementServiceRequest)
		if err != nil {
			log.Errorf("error: %v", err)
			break
		}

		log.Infof("recv: %+v", managementServiceRequest)
		for index := range managementServiceRequest.TargetAgentList {
			log.Infof("target agent : %s", managementServiceRequest.TargetAgentList[index])
		}
		sendCommandToAgents(managementServiceRequest)
		err = ws.WriteJSON(managementServiceRequest)
		if err != nil {
			log.Warnf("error sending response to client: %v", err)
			break
		}
	}
	// remove the client from the client broadcast list
	delete(clients, ws)
}

func sendCommandToAgents(managementServiceRequest lib.CCServiceRequest) {
	log.Infof("sendCommandToAgents() sending command %+v", managementServiceRequest)
	log.Infof("sendCommandToAgents() there are %d agents", len(agents))

	agentBroadcast <- managementServiceRequest
}

func broadcastToAgents() {
	log.Infof("broadcastToAgents()\n")
	for {
		// Grab the next message from the agentBroadcast channel
		msg := <-agentBroadcast

		log.Infof("broadcastToAgents: there are %d agents", len(agents))

		// Send it out to every agent that is currently connected
		for agent := range agents {
			log.Infof("broadcastToAgents() sending message %+v", msg)

			err := agent.WriteJSON(msg)
			if err != nil {
				log.Errorf("error: %v", err)
				err = agent.Close()
				if err != nil {
					log.Errorf("error closing agent connection: %v", err)
				}
				delete(agents, agent)
			}
		}
	}
}

func broadcastToClients() {
	log.Infof("broadcastToClients()\n")
	for {
		// Grab the next message from the agentBroadcast channel
		msg := <-clientBroadcast

		log.Infof("broadcastToClients: there are %d clients", len(clients))

		// Send it out to every client that is currently connected
		for client := range clients {
			log.Infof("broadcastToClients() sending message %sn", msg)

			err := client.WriteMessage(websocket.TextMessage, msg)
			if err != nil {
				log.Warnf("can't write to client %v", err)
				err = client.Close()
				if err != nil {
					log.Warnf("closing agent connection: %v", err)
				}
				delete(clients, client)
			}
		}
	}
}

func webHome(w http.ResponseWriter, r *http.Request) {
	err := homeTemplate.Execute(w, "ws://"+r.Host+"/client")
	if err != nil {
		log.Errorf("error from web service: %v", err)
	}
}

var homeTemplate = template.Must(template.New("").Parse(`
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>  
window.addEventListener("load", function(evt) {

    var output = document.getElementById("output");
    var component = document.getElementById("component");
    var command = document.getElementById("command");
    var parameters = document.getElementById("parameters");
    var targetList = document.getElementById("targetList");
    var ws;

    var print = function(message) {
        var d = document.createElement("div");
        d.innerHTML = message;
        output.appendChild(d);
    };

    document.getElementById("open").onclick = function(evt) {
        if (ws) {
            return false;
        }
        ws = new WebSocket("{{.}}");
        ws.onopen = function(evt) {
            print("OPEN");
        }
        ws.onclose = function(evt) {
            print("CLOSE");
            ws = null;
        }
        ws.onmessage = function(evt) {
            print("RESPONSE: " + evt.data);
        }
        ws.onerror = function(evt) {
            print("ERROR: " + evt.data);
        }
        return false;
    };

    document.getElementById("send").onclick = function(evt) {
        if (!ws) {
            return false;
        }
        print("SEND: " + command.value);
        tempTargetList = targetList.value.split(",")
		serviceRequest = JSON.stringify({
			'component': component.value,
			'command': command.value,
             'parameters' : parameters.value,
			'targetAgentList': tempTargetList
		});
 		print("sending json: " + serviceRequest);
		ws.send(serviceRequest);
        return false;
    };

    document.getElementById("close").onclick = function(evt) {
        if (!ws) {
            return false;
        }
        ws.close();
        return false;
    };

});
</script>
</head>
<body>
<table>
<tr><td valign="top" width="50%">
<p>Click "Open" to create a connection to the server, 
"Send" to send a message to the server and "Close" to close the connection. 
You can change the message and send multiple times.
<p>
<form>
<button id="open">Open</button>
<button id="close">Close</button>

<p><label>Component:</label>
<input id="component" type="text" value="pingpong">

<p><label>Command:</label>
<input id="command" type="text" value="start">

<p><label>Parameters:</label>
<input id="parameters" type="text" maxlength="100" size="100" value='{"SrcAccount":"","DelayBetweenTxn": 100,"RandomizeFee":false,"RandomizeAmt":false,"RandomizeDst":false,"MaxFee":5,"MaxAmt":20,"NumPartAccounts":10,"RunTime":10000,"RestTime":10000,"RefreshTime":10000,"MinAccountFunds":100000}'>

<p><label>Target List:</label>
<input id="targetList" type="text" value="Host1:Node1, Host1:Primary">

<button id="send">Send</button>
</form>
</td><td valign="top" width="50%">
<div id="output"></div>
</td></tr></table>
</body>
</html>
`))