small pixel drawing of a pufferfish gore

status.go

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
package main

import (
	"bytes"
	"context"
	"debug/buildinfo"
	"encoding/json"
	"fmt"
	"html/template"
	"io"
	"log"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
	"sync/atomic"
	"time"

	"j3s.sh/gore/internal/assets"
	"j3s.sh/gore/internal/module"

	"golang.org/x/sys/unix"
)

func parseMeminfo() map[string]int64 {
	meminfo, err := os.ReadFile("/proc/meminfo")
	if err != nil {
		return nil
	}
	vals := make(map[string]int64)
	for _, line := range strings.Split(string(meminfo), "\n") {
		if !strings.HasPrefix(line, "MemTotal") &&
			!strings.HasPrefix(line, "MemAvailable") {
			continue
		}
		parts := strings.Split(line, ":")
		if len(parts) < 2 {
			continue
		}
		val, err := strconv.ParseInt(strings.TrimSpace(strings.TrimSuffix(parts[1], " kB")), 0, 64)
		if err != nil {
			continue
		}
		vals[parts[0]] = val * 1024 // KiB to B
	}
	return vals
}

// readFile0 returns the file contents or an empty string if the file could not
// be read. All bytes from any \0 byte onwards are stripped (as found in
// /proc/device-tree/model).
//
// Additionally, whitespace is trimmed.
func readFile0(filename string) string {
	b, _ := os.ReadFile(filename)
	if idx := bytes.IndexByte(b, 0); idx > -1 {
		b = b[:idx]
	}
	return string(bytes.TrimSpace(b))
}

var modelCache atomic.Value // of string

// Model returns a human readable description of the current device model,
// e.g. “Raspberry Pi 4 Model B Rev 1.1” or “PC Engines apu2” or “QEMU”
// or ultimately “unknown model”.
func Model() string {
	if s, ok := modelCache.Load().(string); ok {
		return s
	}
	andCache := func(s string) string {
		modelCache.Store(s)
		return s
	}
	// the supported Raspberry Pis have this file
	if m := readFile0("/proc/device-tree/model"); m != "" {
		return andCache(m)
	}
	// The PC Engines apu2c4 (and other PCs) have this file instead:
	vendor := readFile0("/sys/class/dmi/id/board_vendor")
	name := readFile0("/sys/class/dmi/id/board_name")
	if vendor != "" || name != "" {
		return andCache(vendor + " " + name)
	}
	// QEMU has none of that. But it does say "QEMU" here, so use this as
	// another fallback:
	if v := readFile0("/sys/class/dmi/id/sys_vendor"); v != "" {
		return andCache(v)
	}
	// If we can't find anything else, at least return some non-empty string so
	// fbstatus doesn't render funny with empty parens. Plus this gives people
	// something to grep for to add more model detection.
	return "unknown model"
}

func readModuleInfo(path string) (string, error) {
	bi, err := buildinfo.ReadFile(path)
	if err != nil {
		return "", err
	}
	lines := strings.Split(strings.TrimSpace(bi.String()), "\n")
	shortened := make([]string, len(lines))
	for idx, line := range lines {
		row := strings.Split(line, "\t")
		if len(row) > 3 {
			row = row[:3]
		}
		shortened[idx] = strings.Join(row, "\t")
	}
	return strings.Join(shortened, "\n"), nil
}

func parseUtsname(u unix.Utsname) string {
	if u == (unix.Utsname{}) {
		// Empty utsname, no info to parse.
		return "unknown"
	}

	str := func(b [65]byte) string {
		// Trim all trailing NULL bytes.
		return string(bytes.TrimRight(b[:], "\x00"))
	}

	return fmt.Sprintf("%s %s (%s)",
		str(u.Sysname), str(u.Release), str(u.Machine))
}

func jsonRequested(r *http.Request) bool {
	// When this function was introduced, it incorrectly checked the
	// Content-Type header (which specifies the type of the body, if any), where
	// it should have looked at the Accept header. Hence, we now consider both,
	// at least for some time.
	return strings.Contains(strings.ToLower(r.Header.Get("Accept")), "application/json") ||
		strings.Contains(strings.ToLower(r.Header.Get("Content-type")), "application/json")
}

func eventStreamRequested(r *http.Request) bool {
	return strings.Contains(strings.ToLower(r.Header.Get("Accept")), "text/event-stream")
}

var templates = template.Must(template.New("root").
	Funcs(map[string]interface{}{
		"shortenSHA256": func(hash string) string {
			if len(hash) > 10 {
				return hash[:10]
			}
			return hash
		},
		"restarting": func(t time.Time) bool {
			return time.Since(t).Seconds() < 5
		},

		"last": func(s []string) string {
			if len(s) == 0 {
				return ""
			}
			return s[len(s)-1]
		},

		"megabytes": func(val int64) string {
			return fmt.Sprintf("%.1f MiB", float64(val)/1024/1024)
		},

		"gigabytes": func(val int64) string {
			return fmt.Sprintf("%.1f GiB", float64(val)/1024/1024/1024)
		},

		"baseName": func(path string) string {
			return filepath.Base(path)
		},

		"initRss": func() int64 {
			return rssOfPid(1)
		},

		"rssPercentage": func(meminfo map[string]int64, rss int64) string {
			used := float64(meminfo["MemTotal"] - meminfo["MemAvailable"])
			return fmt.Sprintf("%.f", float64(rss)/used*100)
		},
	}).
	ParseFS(assets.Assets, "*.tmpl"))

func initStatus() {
	model := Model()

	var uname unix.Utsname
	if err := unix.Uname(&uname); err != nil {
		log.Printf("getting uname: %v", err)
	}
	kernel := parseUtsname(uname)

	http.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")

		token := xsrfTokenFromCookies(r.Cookies())
		if token == 0 {
			// Only generate a new XSRF token if the old one is expired, so that
			// loading a different form in the background doesn’t render the
			// current one unusable.
			token = xsrfToken()
		}

		http.SetCookie(w, &http.Cookie{
			Name:     "gore_xsrf",
			Value:    fmt.Sprintf("%d", token),
			Expires:  time.Now().Add(24 * time.Hour),
			HttpOnly: true,
		})

		path := r.FormValue("path")
		svc := findSvc(path)
		if svc == nil {
			http.Error(w, "service not found", http.StatusNotFound)
			return
		}

		if jsonRequested(r) {
			b, err := json.Marshal(svc)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}

			w.Header().Set("Content-Type", "application/json")
			_, _ = w.Write(b)
			return
		}

		var buf bytes.Buffer
		if err := templates.ExecuteTemplate(&buf, "status.tmpl", struct {
			Service        *service
			BuildTimestamp string
			Hostname       string
			Model          string
			XsrfToken      int32
			Kernel         string
		}{
			Service:   svc,
			Model:     model,
			XsrfToken: token,
			Kernel:    kernel,
		}); err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		status := "started"
		if svc.Stopped() {
			status = "stopped"
		}
		w.Header().Set("X-Gore-Status", status)
		w.Header().Set("X-Gore-GOARCH", runtime.GOARCH)
		io.Copy(w, &buf)
	})

	http.HandleFunc("/log", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Access-Control-Allow-Origin", "*")

		evtStream := eventStreamRequested(r)
		if evtStream {
			w.Header().Set("Content-type", "text/event-stream")
		}

		path := r.FormValue("path")
		svc := findSvc(path)
		if svc == nil {
			http.Error(w, "service not found", http.StatusNotFound)
			return
		}

		streamName := r.FormValue("stream")

		var stream <-chan string
		var closeFunc func()

		switch streamName {
		case "stdout":
			stream, closeFunc = svc.Stdout.Stream()
		case "stderr":
			stream, closeFunc = svc.Stderr.Stream()
		default:
			http.Error(w, "stream not found", http.StatusNotFound)
			return
		}
		defer closeFunc()

		for {
			select {
			case line := <-stream:
				// See https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events for description
				// of server-sent events protocol.
				if evtStream {
					line = fmt.Sprintf("data: %s\n", line)
				}
				if _, err := fmt.Fprintln(w, line); err != nil {
					return
				}
				if f, ok := w.(http.Flusher); ok {
					f.Flush()
				}
			case <-r.Context().Done():
				// Client closed stream. Stop and release all resources immediately.
				return
			}
		}
	})
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
	services.Lock()
	defer services.Unlock()
	status := struct {
		Services       []*service
		BuildTimestamp string
		Meminfo        map[string]int64
		Hostname       string
	}{
		Services: services.S,
		Meminfo:  parseMeminfo(),
	}

	if jsonRequested(r) {
		b, err := json.Marshal(status)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		_, _ = w.Write(b)
		return
	}

	var buf bytes.Buffer
	if err := templates.ExecuteTemplate(&buf, "overview.tmpl", status); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	io.Copy(w, &buf)
}

func addHandler(w http.ResponseWriter, r *http.Request) {
	formInput := r.FormValue("path")
	if formInput == "" {
		http.Error(w, "Module URL is required (e.g. git.j3s.sh/vore@latest)", http.StatusBadRequest)
		return
	}

	path, version, found := strings.Cut(formInput, "@")
	fmt.Println(path, version)
	if !found {
		version = "latest"
	}

	// First:  we resolve da module using le proxies
	resolved, err := module.Resolve(context.TODO(), path, version)
	if err != nil {
		msg := fmt.Sprintf("Failed to resolve module: %v", err)
		fmt.Fprintf(w, msg)
		log.Println(msg)
		return
	}

	log.Printf(`Adding the following package to gore:
  Go package  : %s
  in Go module: %s`, path, resolved.Module)

	// Next: we install da binary, based on le module data
	buildDir := filepath.Join("builddir", resolved.Module)
	if _, err := os.Stat(buildDir); err != nil {
		log.Printf("Creating builddir for module %s", resolved.Module)
		if err := os.MkdirAll(buildDir, 0755); err != nil {
			log.Printf("Failed to create builddir for module %s: %v", resolved.Module, err)
			return
		}
	}

	//	if _, err := os.Stat(filepath.Join(buildDir, "go.mod")); err == nil {
	//		log.Printf("Adding require line to existing go.mod")
	//	} else {
	//		log.Printf("Creating go.mod based on upstream go.mod")
	//		modf, err := modfile.Parse("go.mod", resolved.GoMod, nil)
	//		if err != nil {
	//			log.Printf("parsing old go.mod: %v", err)
	//			return
	//		}
	//		if err := modf.AddModuleStmt("gore/build/" + resolved.Module); err != nil {
	//			log.Println(err)
	//			return
	//		}
	//
	//		b, err := modf.Format()
	//		if err != nil {
	//			log.Println(err)
	//			return
	//		}

	//		if err := os.WriteFile(filepath.Join(buildDir, "go.mod"), b, 0600); err != nil {
	//			log.Println(err)
	//			return
	//		}
	//	}

	get := exec.Command("go", "install", resolved.Module+"@"+resolved.Version)
	absoluteInstallPath, err := filepath.Abs(filepath.Join(buildDir + "@" + resolved.Version))
	if err != nil {
		fmt.Fprintf(w, "oopsie woopsie, we made a fucky wu- actually, you know what? 500 internal server error. fuck you.")
		log.Println(err)
		return
	}
	get.Env = append(os.Environ(), "CGO_ENABLED=0", "GOBIN="+absoluteInstallPath)
	get.Stdout = os.Stdout
	get.Stderr = os.Stderr
	if err := get.Run(); err != nil {
		fmt.Fprintf(w, "oopsie woopsie, we made a fucky wu- actually, you know what? 500 internal server error. fuck you.")
		log.Println(err)
		return
	}

	// add to service list

	http.Redirect(w, r, "/", http.StatusSeeOther)
}