dash.go 6.52 KB
Newer Older
ale's avatar
ale committed
1 2 3 4 5 6 7 8 9 10 11 12
package main

//go:generate go-bindata --nocompress --pkg main static/... templates/...
//go:generate go run scripts/sri.go --package main --output sri_auto.go static

import (
	"flag"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"
13
	"os"
ale's avatar
ale committed
14 15 16 17 18 19 20 21

	"git.autistici.org/ai3/go-common/serverutil"
	assetfs "github.com/elazarl/go-bindata-assetfs"
	"github.com/gorilla/mux"
	"gopkg.in/yaml.v2"
)

var (
ale's avatar
ale committed
22 23 24 25 26 27 28 29 30
	addr                        = flag.String("addr", getenv("ADDR", ":3000"), "tcp `address` to listen on")
	configPath                  = flag.String("config", getenv("CONFIG", "/etc/float/dashboard.yml"), "dashboard config `file`")
	floatServicesPath           = flag.String("services-file", getenv("SERVICES", "/etc/float/services.yml"), "float services `file`")
	floatServiceAssignmentsPath = flag.String("service-assignments-file", getenv("SERVICES", "/etc/float/service_assignments.yml"), "float service assignments map `file`")
	floatServiceMastersPath     = flag.String("service-masters-file", getenv("SERVICES", "/etc/float/service_masters.yml"), "float service masters map `file`")

	tpl        *template.Template
	config     *Config
	serviceMap *ServiceMap
ale's avatar
ale committed
31 32
)

33 34 35 36 37 38 39
func getenv(k, dflt string) string {
	if s := os.Getenv(k); s != "" {
		return s
	}
	return dflt
}

ale's avatar
ale committed
40 41 42
// Config for the application.
type Config struct {
	Domain        string                   `yaml:"domain"`
43
	PublicDomain  string                   `yaml:"public_domain"`
ale's avatar
ale committed
44 45 46 47 48
	LogoImagePath string                   `yaml:"logo_image"`
	HTTP          *serverutil.ServerConfig `yaml:"http_server"`
}

func readYAML(path string, obj interface{}) error {
49
	data, err := ioutil.ReadFile(path) // nolint: gosec
ale's avatar
ale committed
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
	if err != nil {
		return err
	}
	return yaml.Unmarshal(data, obj)
}

// Read the program's configuration file.
func mustReadConfig() *Config {
	var c Config
	if err := readYAML(*configPath, &c); err != nil {
		log.Fatalf("error reading configuration: %v", err)
	}
	return &c
}

// Read the configured services.
ale's avatar
ale committed
66 67 68 69
func mustReadServiceMap() *ServiceMap {
	// Read services.yml.
	services := make(map[string]*Service)
	if err := readYAML(*floatServicesPath, &services); err != nil {
ale's avatar
ale committed
70 71
		log.Fatalf("error reading services file: %v", err)
	}
ale's avatar
ale committed
72 73
	// Add the name to every service, so we can iterate over values easily.
	for name, s := range services {
ale's avatar
ale committed
74 75
		s.Name = name
	}
ale's avatar
ale committed
76 77 78 79 80 81 82 83 84 85 86 87 88 89

	// Read service_assignments.yml.
	assignments := make(map[string][]string)
	if err := readYAML(*floatServiceAssignmentsPath, &assignments); err != nil {
		log.Fatalf("error reading service assignments file: %v", err)
	}

	// Read service_masters.yml.
	masters := make(map[string]string)
	if err := readYAML(*floatServiceMastersPath, &masters); err != nil {
		log.Fatalf("error reading service masters file: %v", err)
	}

	return newServiceMap(services, assignments, masters)
ale's avatar
ale committed
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
}

// Parse the templates that are embedded with the binary (in bindata.go).
func mustParseEmbeddedTemplates() *template.Template {
	root := template.New("").Funcs(template.FuncMap{
		// Useful function to format something as YAML.
		"yaml": func(obj interface{}) string {
			if data, err := yaml.Marshal(obj); err == nil {
				return string(data)
			}
			return ""
		},
		"sri_script":     SRIScript,
		"sri_stylesheet": SRIStylesheet,
	})
	files, err := AssetDir("templates")
	if err != nil {
		log.Fatalf("no asset dir for templates: %v", err)
	}
	for _, f := range files {
		b, err := Asset("templates/" + f)
		if err != nil {
			log.Fatalf("could not read embedded template %s: %v", f, err)
		}
		if _, err := root.New(f).Parse(string(b)); err != nil {
			log.Fatalf("error parsing template %s: %v", f, err)
		}
	}
	return root
}

// A relatively strict CSP.
const contentSecurityPolicy = "default-src 'none'; img-src 'self' data:; script-src 'self'; style-src 'self'; font-src 'self';"

func withDynamicHeaders(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Pragma", "no-cache")
		w.Header().Set("Cache-Control", "no-store")
		w.Header().Set("Expires", "-1")
		w.Header().Set("X-Frame-Options", "NONE")
		w.Header().Set("X-XSS-Protection", "1; mode=block")
		w.Header().Set("X-Content-Type-Options", "nosniff")
		if w.Header().Get("Content-Security-Policy") == "" {
			w.Header().Set("Content-Security-Policy", contentSecurityPolicy)
		}
		h.ServeHTTP(w, r)
	})
}

func renderTemplate(w io.Writer, name string, ctx map[string]interface{}) {
	if ctx == nil {
		ctx = make(map[string]interface{})
	}
	ctx["Config"] = config
ale's avatar
ale committed
144
	ctx["ServiceMap"] = serviceMap
ale's avatar
ale committed
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
	if err := tpl.ExecuteTemplate(w, name, ctx); err != nil {
		log.Printf("template error: %v", err)
	}
}

func handleIndex(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}

	renderTemplate(w, "index.html", nil)
}

func handleServiceDetails(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
ale's avatar
ale committed
161
	s, ok := serviceMap.Services[vars["service"]]
ale's avatar
ale committed
162 163 164 165 166 167 168 169 170 171 172 173
	if !ok {
		http.NotFound(w, r)
		return
	}

	renderTemplate(w, "service_details.html", map[string]interface{}{
		"Service": s,
	})
}

func handleContainerDetails(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
ale's avatar
ale committed
174
	s, ok := serviceMap.Services[vars["service"]]
ale's avatar
ale committed
175 176 177 178 179 180 181
	if !ok {
		http.NotFound(w, r)
		return
	}
	var c *Container
	for _, cc := range s.Containers {
		if cc.Name == vars["container"] {
ale's avatar
ale committed
182
			c = cc
ale's avatar
ale committed
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
			break
		}
	}
	if c == nil {
		http.NotFound(w, r)
		return
	}

	renderTemplate(w, "container_details.html", map[string]interface{}{
		"Service":   s,
		"Container": c,
	})
}

// Create the HTTP server.
func makeServer() http.Handler {
	root := mux.NewRouter()
	root.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(&assetfs.AssetFS{
		Asset:     Asset,
		AssetDir:  AssetDir,
		AssetInfo: AssetInfo,
		Prefix:    "static",
	})))
	root.Handle("/service/{service}/details", withDynamicHeaders(http.HandlerFunc(handleServiceDetails)))
	root.Handle("/service/{service}/container/{container}/details", withDynamicHeaders(http.HandlerFunc(handleContainerDetails)))
208
	setupRedirects(root.PathPrefix("/link/").Subrouter())
ale's avatar
ale committed
209 210 211 212 213 214 215 216 217 218
	root.Handle("/", withDynamicHeaders(http.HandlerFunc(handleIndex)))
	return root
}

func main() {
	log.SetFlags(0)
	flag.Parse()

	tpl = mustParseEmbeddedTemplates()
	config = mustReadConfig()
ale's avatar
ale committed
219
	serviceMap = mustReadServiceMap()
ale's avatar
ale committed
220 221 222 223 224 225 226 227 228 229 230 231 232

	h := makeServer()

	if err := serverutil.Serve(h, config.HTTP, *addr); err != nil {
		log.Fatal(err)
	}
}

type sortedStringList []string

func (l sortedStringList) Len() int           { return len(l) }
func (l sortedStringList) Swap(i, j int)      { l[i], l[j] = l[j], l[i] }
func (l sortedStringList) Less(i, j int) bool { return l[i] < l[j] }