summaryrefslogtreecommitdiff
path: root/cmd/tealdbg/webdbg.go
blob: 2012127c64412d10a6daa23bd0653ca76457ef44 (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
// 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

//go:generate ./bundle_home_html.sh

import (
	"encoding/json"
	"fmt"
	"html/template"
	"log"
	"net/http"

	"github.com/algorand/go-algorand/protocol"
	"github.com/algorand/go-deadlock"
	"github.com/algorand/websocket"
	"github.com/gorilla/mux"
)

// WebPageFrontend is web page debugging frontend
type WebPageFrontend struct {
	mu         deadlock.Mutex
	sessions   map[string]wpaSession
	apiAddress string
	done       chan struct{}
}

type wpaSession struct {
	debugger      Control
	notifications chan Notification
}

// ExecID is a unique execution ID
type ExecID string

// ConfigRequest tells us what breakpoints to hit, if any
type ConfigRequest struct {
	debugConfig
	ExecID ExecID `json:"execid"`
}

// ContinueRequest tells a particular execution to continue
type ContinueRequest struct {
	ExecID ExecID `json:"execid"`
}

// WebPageFrontendParams initialization parameters
type WebPageFrontendParams struct {
	router     *mux.Router
	apiAddress string
}

// MakeWebPageFrontend creates new WebPageFrontend
func MakeWebPageFrontend(params *WebPageFrontendParams) (a *WebPageFrontend) {
	a = new(WebPageFrontend)
	a.sessions = make(map[string]wpaSession)
	a.apiAddress = params.apiAddress
	a.done = make(chan struct{})

	params.router.HandleFunc("/", a.homeHandler).Methods("GET")
	params.router.HandleFunc("/exec/step", a.stepHandler).Methods("POST")
	params.router.HandleFunc("/exec/config", a.configHandler).Methods("POST")
	params.router.HandleFunc("/exec/continue", a.continueHandler).Methods("POST")

	params.router.HandleFunc("/ws", a.subscribeHandler)

	return a
}

// SessionStarted registers new session
func (a *WebPageFrontend) SessionStarted(sid string, debugger Control, ch chan Notification) {
	a.mu.Lock()
	defer a.mu.Unlock()

	a.sessions[sid] = wpaSession{debugger, ch}

	log.Printf("Open http://%s in a web browser", a.apiAddress)
}

// SessionEnded removes the session
func (a *WebPageFrontend) SessionEnded(sid string) {
	a.mu.Lock()
	defer a.mu.Unlock()

	delete(a.sessions, sid)
}

// WaitForCompletion waits session to complete
func (a *WebPageFrontend) WaitForCompletion() {
	<-a.done
}

// URL returns an URL to access the latest debugging session
func (a *WebPageFrontend) URL() string {
	a.mu.Lock()
	defer a.mu.Unlock()
	if len(a.sessions) == 0 {
		return ""
	}

	return fmt.Sprintf("http://%s/", a.apiAddress)
}

func (a *WebPageFrontend) homeHandler(w http.ResponseWriter, r *http.Request) {
	home, err := template.New("home").Parse(homepage)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusOK)
	home.Execute(w, nil)
	return
}

func (a *WebPageFrontend) stepHandler(w http.ResponseWriter, r *http.Request) {
	// Decode a ConfigRequest
	var req ConfigRequest
	dec := json.NewDecoder(r.Body)
	err := dec.Decode(&req)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	// Ensure that we are trying to configure an execution we know about
	a.mu.Lock()
	s, ok := a.sessions[string(req.ExecID)]
	a.mu.Unlock()
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	s.debugger.Step()

	w.WriteHeader(http.StatusOK)
	return
}

func (a *WebPageFrontend) configHandler(w http.ResponseWriter, r *http.Request) {
	// Decode a ConfigRequest
	var req ConfigRequest
	dec := json.NewDecoder(r.Body)
	err := dec.Decode(&req)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	// Ensure that we are trying to configure an execution we know about
	a.mu.Lock()
	s, ok := a.sessions[string(req.ExecID)]
	a.mu.Unlock()
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	// Extract PC from config
	for line := range req.debugConfig.ActiveBreak {
		if req.debugConfig.NoBreak {
			err := s.debugger.RemoveBreakpoint(int(line))
			if err != nil {
				w.WriteHeader(http.StatusBadRequest)
				return
			}
		} else {
			err := s.debugger.SetBreakpoint(int(line))
			if err != nil {
				w.WriteHeader(http.StatusBadRequest)
				return
			}
		}
	}

	w.WriteHeader(http.StatusOK)
	return
}

func (a *WebPageFrontend) continueHandler(w http.ResponseWriter, r *http.Request) {
	// Decode a ContinueRequest
	var req ContinueRequest
	dec := json.NewDecoder(r.Body)
	err := dec.Decode(&req)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	a.mu.Lock()
	s, ok := a.sessions[string(req.ExecID)]
	a.mu.Unlock()
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	s.debugger.Resume()

	w.WriteHeader(http.StatusOK)
	return
}

func (a *WebPageFrontend) subscribeHandler(w http.ResponseWriter, r *http.Request) {
	defer func() {
		close(a.done)
	}()

	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Printf("subscribeHandler error: %s\n", err.Error())
		return
	}
	defer ws.Close()

	// Acknowledge connection
	event := Notification{
		Event: "connected",
	}
	enc := protocol.EncodeJSONStrict(&event)
	err = ws.WriteMessage(websocket.TextMessage, enc)
	if err != nil {
		return
	}

	a.mu.Lock()
	// TODO: FIXME: subscribe proto needs be updated and subscribeHandler have to know session ID
	// for now take the first session. In most cases there is only one session.
	var notifications chan Notification
	for _, s := range a.sessions {
		notifications = s.notifications
		break
	}
	a.mu.Unlock()

	// Wait on notifications and forward to the user
	for {
		select {
		case notification := <-notifications:
			enc := protocol.EncodeJSONStrict(&notification)
			err = ws.WriteMessage(websocket.TextMessage, enc)
			if err != nil {
				return
			}
		}
	}
}