~emersion/drmdb

ref: afa09d62c88148514522c9254c46ed41cdc1eb69 drmdb/server.go -rw-r--r-- 10.5 KiB View raw
afa09d62Simon Ser Move database functions to a separate package 1 year, 2 months ago
                                                                                
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
package drmdb

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"sort"
	"strconv"
	"strings"

	"git.sr.ht/~emersion/drmdb/database"
	"git.sr.ht/~emersion/drmdb/drmtree"
	"git.sr.ht/~emersion/drmdb/treefmt"
	"git.sr.ht/~emersion/go-drm"
	"git.sr.ht/~emersion/go-hwids"
	"github.com/labstack/echo/v4"
)

func badRequest(c echo.Context, msg string, err error) error {
	if err != nil {
		c.Logger().Printf("%v: %v", msg, err)
	}
	return c.String(http.StatusBadRequest, "Error: "+msg+"\n")
}

func loadPCIIDs() (vendors map[uint16]string, devices map[uint32]string, err error) {
	vendors = make(map[uint16]string)
	devices = make(map[uint32]string)

	db, err := hwids.OpenPCI()
	if err != nil {
		return nil, nil, err
	}
	defer db.Close()

	for {
		id, err := db.NextID()
		if err == io.EOF {
			break
		} else if err != nil {
			return nil, nil, err
		}

		switch id.Type {
		case hwids.PCIVendor:
			vendors[id.Vendor] = id.VendorName
		case hwids.PCIDevice:
			k := uint32(id.Vendor)<<16 | uint32(id.Device)
			devices[k] = id.DeviceName
		}
	}

	return vendors, devices, db.Close()
}

func New() *echo.Echo {
	e := echo.New()

	if err := database.Init(); err != nil {
		e.Logger.Fatal("Failed to initialize database:", err)
	}

	var err error
	e.Renderer, err = loadTemplates()
	if err != nil {
		e.Logger.Fatal("Failed to load templates:", err)
	}

	pciVendors, pciDevices, err := loadPCIIDs()
	if err != nil {
		e.Logger.Error("Failed to load PCI IDs:", err)
	}

	e.GET("/", func(c echo.Context) error {
		return c.Render(http.StatusOK, "index.html", struct{
			Host string
		}{c.Request().Host})
	})

	e.POST("/submit", func(c echo.Context) error {
		lr := io.LimitedReader{R: c.Request().Body, N: 512 * 1024}
		var nodes drmtree.NodeMap
		if err := json.NewDecoder(&lr).Decode(&nodes); err != nil {
			return badRequest(c, "invalid JSON", err)
		} else if len(nodes) == 0 {
			return badRequest(c, "data is empty", nil)
		}

		success := false
		for name, n := range nodes {
			if key, err := database.Store(n); err != nil {
				fmt.Fprintf(c.Response(), "%s: error: %v\n", name, err)
			} else {
				u := "https://" + c.Request().Host + "/devices/" + key
				fmt.Fprintf(c.Response(), "%s: data uploaded to %s\n", name, u)
				success = true
			}
		}

		if success {
			fmt.Fprintf(c.Response(), "Thanks!\n")
		}
		return nil
	})

	e.GET("/snapshot.tar.gz", func(c echo.Context) error {
		h := c.Response().Header()
		h.Set("Content-Type", "application/gzip")
		h.Set("Content-Disposition", "attachment; filename=\"drmdb-snapshot.tar.gz\"")
		return writeSnapshot(c.Response())
	})

	e.GET("/drivers", func(c echo.Context) error {
		var drivers []*drmtree.Driver
		err := walkLatest(walkLatestDriver, func(k string, n *drmtree.Node) error {
			drivers = append(drivers, n.Driver)
			return nil
		})
		if err != nil {
			return err
		}

		return c.Render(http.StatusOK, "drivers.html", struct {
			Drivers []*drmtree.Driver
		}{drivers})
	})

	e.GET("/devices", func(c echo.Context) error {
		type deviceData struct {
			Key     string
			BusID   string
			BusType drm.BusType
			Vendor  string
			Name    string
			Driver  string
		}

		var devices []deviceData
		err := walkLatest(walkLatestDevice, func(k string, n *drmtree.Node) error {
			data := deviceData{
				Key: k,
				BusID: n.Device.BusID(),
				BusType: n.Device.BusType,
				Driver:  n.Driver.Name,
			}

			switch dev := n.Device.DeviceData.(type) {
			case *drmtree.DevicePCI:
				data.Vendor = pciVendors[uint16(dev.Vendor)]
				data.Name = pciDevices[dev.Vendor<<16|dev.Device]
			case *drmtree.DevicePlatform:
				// No-op
			default:
				return nil
			}

			devices = append(devices, data)
			return nil
		})
		if err != nil {
			return err
		}

		return c.Render(http.StatusOK, "devices.html", struct {
			Devices []deviceData
		}{devices})
	})

	e.GET("/devices/:key", func(c echo.Context) error {
		type altDeviceData struct {
			Key    string
			Driver *drmtree.Driver
		}

		key := c.Param("key")
		raw := false
		if strings.HasSuffix(key, ".json") {
			key = strings.TrimSuffix(key, ".json")
			raw = true
		}

		n, err := database.Load(key)
		if err != nil {
			if os.IsNotExist(err) {
				return c.String(http.StatusNotFound, "no such device")
			}
			return err
		}

		if raw {
			return c.JSON(http.StatusOK, n)
		} else {
			var altDevices []altDeviceData
			err := database.Walk(func(k string, alt *drmtree.Node) error {
				if k == key {
					return nil
				}
				if alt.Device.BusType != n.Device.BusType || alt.Device.BusID() != n.Device.BusID() {
					return nil
				}

				altDevices = append(altDevices, altDeviceData{
					Key: k,
					Driver: alt.Driver,
				})
				return nil
			})
			if err != nil {
				return err
			}

			sort.Slice(altDevices, func(i, j int) bool {
				a, b := altDevices[i], altDevices[j]
				return !driverLess(a.Driver, b.Driver)
			})

			tf := treefmt.NewMemoryFormatter()
			n.FormatTree(tf)

			return c.Render(http.StatusOK, "device.html", struct {
				Key        string
				Node       *drmtree.Node
				Tree       []treefmt.Memory
				AltDevices []altDeviceData
			}{key, n, tf.Tree(), altDevices})
		}
	})

	e.GET("/capabilities", func(c echo.Context) error {
		var drivers []string
		caps := make(map[string]map[string]*uint64)
		clientCaps := make(map[string]map[string]bool)
		err := walkLatest(walkLatestDriver, func(k string, n *drmtree.Node) error {
			drv := n.Driver.Name
			drivers = append(drivers, drv)

			for name, val := range n.Driver.Caps {
				if _, ok := caps[name]; !ok {
					caps[name] = make(map[string]*uint64)
				}
				caps[name][drv] = val
			}

			for name, supported := range n.Driver.ClientCaps {
				if _, ok := clientCaps[name]; !ok {
					clientCaps[name] = make(map[string]bool)
				}
				clientCaps[name][drv] = supported
			}

			return nil
		})
		if err != nil {
			return err
		}

		return c.Render(http.StatusOK, "capabilities.html", struct {
			Drivers    []string
			Caps       map[string]map[string]*uint64
			ClientCaps map[string]map[string]bool
		}{drivers, caps, clientCaps})
	})

	e.GET("/properties", func(c echo.Context) error {
		type propertyData struct {
			Type       drm.PropertyType
			ObjectType drm.ObjectType
			Drivers    map[string]bool
		}

		drivers := make(map[string]struct{})
		props := make(map[string]propertyData)
		err := database.Walk(func(k string, n *drmtree.Node) error {
			drv := n.Driver.Name
			drivers[drv] = struct{}{}

			return walkNodeProps(n, func(obj drm.AnyID, name string, prop *drmtree.Property) error {
				if _, ok := props[name]; !ok {
					props[name] = propertyData{
						Type:       prop.Type,
						ObjectType: obj.Type(),
						Drivers:    make(map[string]bool),
					}
				}
				props[name].Drivers[drv] = true
				return nil
			})
		})
		if err != nil {
			return err
		}

		return c.Render(http.StatusOK, "properties.html", struct {
			Drivers    map[string]struct{}
			Properties map[string]propertyData
		}{drivers, props})
	})

	e.GET("/properties/:obj/:name", func(c echo.Context) error {
		var objectType drm.ObjectType
		if i, err := strconv.Atoi(c.Param("obj")); err != nil {
			return c.String(http.StatusBadRequest, "invalid object type")
		} else {
			objectType = drm.ObjectType(i)
		}
		propertyName := c.Param("name")

		found := false;
		var property drmtree.Property

		drivers := make(map[string]bool)
		err := database.Walk(func(k string, n *drmtree.Node) error {
			drivers[n.Driver.Name] = false

			return walkNodeProps(n, func(obj drm.AnyID, name string, p *drmtree.Property) error {
				if obj.Type() != objectType || name != propertyName {
					return nil
				}
				drivers[n.Driver.Name] = true
				found = true
				property = *p
				return nil
			})
		})
		if err != nil {
			return err
		}
		if !found {
			return c.String(http.StatusNotFound, "property not found")
		}

		var flags []string
		if property.Atomic {
			flags = append(flags, "atomic")
		}
		if property.Immutable {
			flags = append(flags, "immutable")
		}

		return c.Render(http.StatusOK, "property.html", struct {
			Name       string
			Prop       *drmtree.Property
			ObjectType drm.ObjectType
			Flags      []string
			Drivers    map[string]bool
		}{propertyName, &property, objectType, flags, drivers})
	})

	e.GET("/formats", func(c echo.Context) error {
		type modifierAndFormat struct {
			mod drm.Modifier
			fmt drm.Format
		}
		type formatData struct {
			Modifier drm.Modifier
			Format drm.Format
			Planes map[drm.PlaneType]int
			Drivers map[string]int
		}

		planeFilter := -1
		if s := c.QueryParam("plane"); s != "" {
			var err error
			if planeFilter, err = strconv.Atoi(s); err != nil {
				return c.String(http.StatusBadRequest, "invalid plane")
			}
		}
		driverFilter := c.QueryParam("driver")

		// For each (modifier, format) pair, build two tables by walking each
		// device:
		// - Number of devices supporting it by plane type (max: number of
		//   devices having such a plane)
		// - Number of devices supporting it by driver (max: number of devices
		//   supported by the driver)
		planes := make(map[drm.PlaneType]int)
		drivers := make(map[string]int)
		formats := make(map[modifierAndFormat]formatData)
		err := walkLatest(walkLatestDevice, func(k string, n *drmtree.Node) error {
			if driverFilter != "" && n.Driver.Name != driverFilter {
				return nil
			}

			drivers[n.Driver.Name]++

			planeFormats := make(map[drm.PlaneType]map[modifierAndFormat]bool)
			driverFormats := make(map[modifierAndFormat]bool)

			for _, plane := range n.Planes {
				if planeFilter >= 0 && plane.Type() != drm.PlaneType(planeFilter) {
					continue
				}

				if _, ok := planeFormats[plane.Type()]; !ok {
					planeFormats[plane.Type()] = make(map[modifierAndFormat]bool)
					planes[plane.Type()]++
				}

				inFormats := plane.InFormats()
				for _, mod := range inFormats {
					for _, fmt := range mod.Formats {
						k := modifierAndFormat{mod.Modifier, fmt}
						if _, ok := formats[k]; !ok {
							formats[k] = formatData{
								Modifier: mod.Modifier,
								Format: fmt,
								Planes: make(map[drm.PlaneType]int),
								Drivers: make(map[string]int),
							}
						}

						if !planeFormats[plane.Type()][k] {
							formats[k].Planes[plane.Type()]++
							planeFormats[plane.Type()][k] = true
						}

						if !driverFormats[k] {
							formats[k].Drivers[n.Driver.Name]++
							driverFormats[k] = true
						}
					}
				}
			}
			return nil
		})
		if err != nil {
			return err
		}

		return c.Render(http.StatusOK, "formats.html", struct {
			Planes map[drm.PlaneType]int
			Drivers map[string]int
			Formats map[modifierAndFormat]formatData
		}{planes, drivers, formats})
	})

	e.Static("/assets", "public/assets")

	return e
}