dashboard.go 12.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// Copyright 2017 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package dashboard

19 20 21
//go:generate yarn --cwd ./assets install
//go:generate yarn --cwd ./assets build
//go:generate go-bindata -nometadata -o assets.go -prefix assets -nocompress -pkg dashboard assets/index.html assets/bundle.js
22
//go:generate sh -c "sed 's#var _bundleJs#//nolint:misspell\\\n&#' assets.go > assets.go.tmp && mv assets.go.tmp assets.go"
23
//go:generate sh -c "sed 's#var _indexHtml#//nolint:misspell\\\n&#' assets.go > assets.go.tmp && mv assets.go.tmp assets.go"
24
//go:generate gofmt -w -s assets.go
25 26 27 28 29

import (
	"fmt"
	"net"
	"net/http"
30
	"runtime"
31 32 33 34
	"sync"
	"sync/atomic"
	"time"

35
	"github.com/elastic/gosigar"
36
	"github.com/ethereum/go-ethereum/log"
37
	"github.com/ethereum/go-ethereum/metrics"
38
	"github.com/ethereum/go-ethereum/p2p"
39
	"github.com/ethereum/go-ethereum/params"
40 41 42 43 44
	"github.com/ethereum/go-ethereum/rpc"
	"golang.org/x/net/websocket"
)

const (
45 46 47 48 49 50 51 52
	activeMemorySampleLimit   = 200 // Maximum number of active memory data samples
	virtualMemorySampleLimit  = 200 // Maximum number of virtual memory data samples
	networkIngressSampleLimit = 200 // Maximum number of network ingress data samples
	networkEgressSampleLimit  = 200 // Maximum number of network egress data samples
	processCPUSampleLimit     = 200 // Maximum number of process cpu data samples
	systemCPUSampleLimit      = 200 // Maximum number of system cpu data samples
	diskReadSampleLimit       = 200 // Maximum number of disk read data samples
	diskWriteSampleLimit      = 200 // Maximum number of disk write data samples
53 54
)

55
var nextID uint32 // Next connection id
56 57 58 59 60 61 62

// Dashboard contains the dashboard internals.
type Dashboard struct {
	config *Config

	listener net.Listener
	conns    map[uint32]*client // Currently live websocket connections
63
	charts   *SystemMessage
64
	commit   string
65
	lock     sync.RWMutex // Lock protecting the dashboard's internals
66 67 68 69 70 71 72 73

	quit chan chan error // Channel used for graceful exit
	wg   sync.WaitGroup
}

// client represents active websocket connection with a remote browser.
type client struct {
	conn   *websocket.Conn // Particular live websocket connection
74
	msg    chan Message    // Message queue for the update messages
75 76 77 78
	logger log.Logger      // Logger for the particular live websocket connection
}

// New creates a new dashboard instance with the given configuration.
79
func New(config *Config, commit string) (*Dashboard, error) {
80 81
	now := time.Now()
	db := &Dashboard{
82 83 84
		conns:  make(map[uint32]*client),
		config: config,
		quit:   make(chan chan error),
85
		charts: &SystemMessage{
86 87 88 89 90 91 92 93
			ActiveMemory:   emptyChartEntries(now, activeMemorySampleLimit, config.Refresh),
			VirtualMemory:  emptyChartEntries(now, virtualMemorySampleLimit, config.Refresh),
			NetworkIngress: emptyChartEntries(now, networkIngressSampleLimit, config.Refresh),
			NetworkEgress:  emptyChartEntries(now, networkEgressSampleLimit, config.Refresh),
			ProcessCPU:     emptyChartEntries(now, processCPUSampleLimit, config.Refresh),
			SystemCPU:      emptyChartEntries(now, systemCPUSampleLimit, config.Refresh),
			DiskRead:       emptyChartEntries(now, diskReadSampleLimit, config.Refresh),
			DiskWrite:      emptyChartEntries(now, diskWriteSampleLimit, config.Refresh),
94
		},
95
		commit: commit,
96 97 98 99 100 101 102 103 104 105 106 107 108
	}
	return db, nil
}

// emptyChartEntries returns a ChartEntry array containing limit number of empty samples.
func emptyChartEntries(t time.Time, limit int, refresh time.Duration) ChartEntries {
	ce := make(ChartEntries, limit)
	for i := 0; i < limit; i++ {
		ce[i] = &ChartEntry{
			Time: t.Add(-time.Duration(i) * refresh),
		}
	}
	return ce
109 110 111 112 113 114 115 116 117 118
}

// Protocols is a meaningless implementation of node.Service.
func (db *Dashboard) Protocols() []p2p.Protocol { return nil }

// APIs is a meaningless implementation of node.Service.
func (db *Dashboard) APIs() []rpc.API { return nil }

// Start implements node.Service, starting the data collection thread and the listening server of the dashboard.
func (db *Dashboard) Start(server *p2p.Server) error {
119 120
	log.Info("Starting dashboard")

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
	db.wg.Add(2)
	go db.collectData()
	go db.collectLogs() // In case of removing this line change 2 back to 1 in wg.Add.

	http.HandleFunc("/", db.webHandler)
	http.Handle("/api", websocket.Handler(db.apiHandler))

	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", db.config.Host, db.config.Port))
	if err != nil {
		return err
	}
	db.listener = listener

	go http.Serve(listener, nil)

	return nil
}

// Stop implements node.Service, stopping the data collection thread and the connection listener of the dashboard.
func (db *Dashboard) Stop() error {
	// Close the connection listener.
	var errs []error
	if err := db.listener.Close(); err != nil {
		errs = append(errs, err)
	}
	// Close the collectors.
	errc := make(chan error, 1)
	for i := 0; i < 2; i++ {
		db.quit <- errc
		if err := <-errc; err != nil {
			errs = append(errs, err)
		}
	}
	// Close the connections.
	db.lock.Lock()
	for _, c := range db.conns {
		if err := c.conn.Close(); err != nil {
			c.logger.Warn("Failed to close connection", "err", err)
		}
	}
	db.lock.Unlock()

	// Wait until every goroutine terminates.
	db.wg.Wait()
	log.Info("Dashboard stopped")

	var err error
	if len(errs) > 0 {
		err = fmt.Errorf("%v", errs)
	}

	return err
}

// webHandler handles all non-api requests, simply flattening and returning the dashboard website.
func (db *Dashboard) webHandler(w http.ResponseWriter, r *http.Request) {
	log.Debug("Request", "URL", r.URL)

	path := r.URL.String()
	if path == "/" {
181
		path = "/index.html"
182
	}
183
	blob, err := Asset(path[1:])
184 185 186 187 188 189 190 191 192 193
	if err != nil {
		log.Warn("Failed to load the asset", "path", path, "err", err)
		http.Error(w, "not found", http.StatusNotFound)
		return
	}
	w.Write(blob)
}

// apiHandler handles requests for the dashboard.
func (db *Dashboard) apiHandler(conn *websocket.Conn) {
194
	id := atomic.AddUint32(&nextID, 1)
195 196
	client := &client{
		conn:   conn,
197
		msg:    make(chan Message, 128),
198 199
		logger: log.New("id", id),
	}
200
	done := make(chan struct{})
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219

	// Start listening for messages to send.
	db.wg.Add(1)
	go func() {
		defer db.wg.Done()

		for {
			select {
			case <-done:
				return
			case msg := <-client.msg:
				if err := websocket.JSON.Send(client.conn, msg); err != nil {
					client.logger.Warn("Failed to send the message", "msg", msg, "err", err)
					client.conn.Close()
					return
				}
			}
		}
	}()
220 221 222 223 224

	versionMeta := ""
	if len(params.VersionMeta) > 0 {
		versionMeta = fmt.Sprintf(" (%s)", params.VersionMeta)
	}
225
	// Send the past data.
226
	client.msg <- Message{
227 228 229 230
		General: &GeneralMessage{
			Version: fmt.Sprintf("v%d.%d.%d%s", params.VersionMajor, params.VersionMinor, params.VersionPatch, versionMeta),
			Commit:  db.commit,
		},
231
		System: &SystemMessage{
232 233 234 235 236 237 238 239
			ActiveMemory:   db.charts.ActiveMemory,
			VirtualMemory:  db.charts.VirtualMemory,
			NetworkIngress: db.charts.NetworkIngress,
			NetworkEgress:  db.charts.NetworkEgress,
			ProcessCPU:     db.charts.ProcessCPU,
			SystemCPU:      db.charts.SystemCPU,
			DiskRead:       db.charts.DiskRead,
			DiskWrite:      db.charts.DiskWrite,
240
		},
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
	}
	// Start tracking the connection and drop at connection loss.
	db.lock.Lock()
	db.conns[id] = client
	db.lock.Unlock()
	defer func() {
		db.lock.Lock()
		delete(db.conns, id)
		db.lock.Unlock()
	}()
	for {
		fail := []byte{}
		if _, err := conn.Read(fail); err != nil {
			close(done)
			return
		}
		// Ignore all messages
	}
}

// collectData collects the required data to plot on the dashboard.
func (db *Dashboard) collectData() {
	defer db.wg.Done()
264 265 266
	systemCPUUsage := gosigar.Cpu{}
	systemCPUUsage.Get()
	var (
267 268
		mem runtime.MemStats

269 270 271 272
		prevNetworkIngress = metrics.DefaultRegistry.Get("p2p/InboundTraffic").(metrics.Meter).Count()
		prevNetworkEgress  = metrics.DefaultRegistry.Get("p2p/OutboundTraffic").(metrics.Meter).Count()
		prevProcessCPUTime = getProcessCPUTime()
		prevSystemCPUUsage = systemCPUUsage
273 274
		prevDiskRead       = metrics.DefaultRegistry.Get("eth/db/chaindata/disk/read").(metrics.Meter).Count()
		prevDiskWrite      = metrics.DefaultRegistry.Get("eth/db/chaindata/disk/write").(metrics.Meter).Count()
275 276 277 278

		frequency = float64(db.config.Refresh / time.Second)
		numCPU    = float64(runtime.NumCPU())
	)
279 280 281 282 283 284 285

	for {
		select {
		case errc := <-db.quit:
			errc <- nil
			return
		case <-time.After(db.config.Refresh):
286 287 288 289 290 291
			systemCPUUsage.Get()
			var (
				curNetworkIngress = metrics.DefaultRegistry.Get("p2p/InboundTraffic").(metrics.Meter).Count()
				curNetworkEgress  = metrics.DefaultRegistry.Get("p2p/OutboundTraffic").(metrics.Meter).Count()
				curProcessCPUTime = getProcessCPUTime()
				curSystemCPUUsage = systemCPUUsage
292 293
				curDiskRead       = metrics.DefaultRegistry.Get("eth/db/chaindata/disk/read").(metrics.Meter).Count()
				curDiskWrite      = metrics.DefaultRegistry.Get("eth/db/chaindata/disk/write").(metrics.Meter).Count()
294 295 296 297

				deltaNetworkIngress = float64(curNetworkIngress - prevNetworkIngress)
				deltaNetworkEgress  = float64(curNetworkEgress - prevNetworkEgress)
				deltaProcessCPUTime = curProcessCPUTime - prevProcessCPUTime
298
				deltaSystemCPUUsage = curSystemCPUUsage.Delta(prevSystemCPUUsage)
299 300 301 302 303 304 305 306 307 308
				deltaDiskRead       = curDiskRead - prevDiskRead
				deltaDiskWrite      = curDiskWrite - prevDiskWrite
			)
			prevNetworkIngress = curNetworkIngress
			prevNetworkEgress = curNetworkEgress
			prevProcessCPUTime = curProcessCPUTime
			prevSystemCPUUsage = curSystemCPUUsage
			prevDiskRead = curDiskRead
			prevDiskWrite = curDiskWrite

309
			now := time.Now()
310 311 312

			runtime.ReadMemStats(&mem)
			activeMemory := &ChartEntry{
313
				Time:  now,
314
				Value: float64(mem.Alloc) / frequency,
315
			}
316
			virtualMemory := &ChartEntry{
317
				Time:  now,
318
				Value: float64(mem.Sys) / frequency,
319
			}
320 321 322
			networkIngress := &ChartEntry{
				Time:  now,
				Value: deltaNetworkIngress / frequency,
323
			}
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
			networkEgress := &ChartEntry{
				Time:  now,
				Value: deltaNetworkEgress / frequency,
			}
			processCPU := &ChartEntry{
				Time:  now,
				Value: deltaProcessCPUTime / frequency / numCPU * 100,
			}
			systemCPU := &ChartEntry{
				Time:  now,
				Value: float64(deltaSystemCPUUsage.Sys+deltaSystemCPUUsage.User) / frequency / numCPU,
			}
			diskRead := &ChartEntry{
				Time:  now,
				Value: float64(deltaDiskRead) / frequency,
			}
			diskWrite := &ChartEntry{
				Time:  now,
				Value: float64(deltaDiskWrite) / frequency,
343
			}
344 345 346 347 348 349 350 351
			db.charts.ActiveMemory = append(db.charts.ActiveMemory[1:], activeMemory)
			db.charts.VirtualMemory = append(db.charts.VirtualMemory[1:], virtualMemory)
			db.charts.NetworkIngress = append(db.charts.NetworkIngress[1:], networkIngress)
			db.charts.NetworkEgress = append(db.charts.NetworkEgress[1:], networkEgress)
			db.charts.ProcessCPU = append(db.charts.ProcessCPU[1:], processCPU)
			db.charts.SystemCPU = append(db.charts.SystemCPU[1:], systemCPU)
			db.charts.DiskRead = append(db.charts.DiskRead[1:], diskRead)
			db.charts.DiskWrite = append(db.charts.DiskRead[1:], diskWrite)
352 353

			db.sendToAll(&Message{
354
				System: &SystemMessage{
355 356 357 358 359 360 361 362
					ActiveMemory:   ChartEntries{activeMemory},
					VirtualMemory:  ChartEntries{virtualMemory},
					NetworkIngress: ChartEntries{networkIngress},
					NetworkEgress:  ChartEntries{networkEgress},
					ProcessCPU:     ChartEntries{processCPU},
					SystemCPU:      ChartEntries{systemCPU},
					DiskRead:       ChartEntries{diskRead},
					DiskWrite:      ChartEntries{diskWrite},
363
				},
364 365 366 367 368 369 370 371 372
			})
		}
	}
}

// collectLogs collects and sends the logs to the active dashboards.
func (db *Dashboard) collectLogs() {
	defer db.wg.Done()

373
	id := 1
374 375 376 377 378 379 380
	// TODO (kurkomisi): log collection comes here.
	for {
		select {
		case errc := <-db.quit:
			errc <- nil
			return
		case <-time.After(db.config.Refresh / 2):
381 382
			db.sendToAll(&Message{
				Logs: &LogsMessage{
383
					Log: []string{fmt.Sprintf("%-4d: This is a fake log.", id)},
384
				},
385
			})
386
			id++
387 388 389 390 391
		}
	}
}

// sendToAll sends the given message to the active dashboards.
392
func (db *Dashboard) sendToAll(msg *Message) {
393 394 395 396 397 398 399 400 401 402
	db.lock.Lock()
	for _, c := range db.conns {
		select {
		case c.msg <- *msg:
		default:
			c.conn.Close()
		}
	}
	db.lock.Unlock()
}