dash.go 7.26 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
	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`")
27
	indexPage                   = flag.String("index-page", getenv("INDEX_PAGE", "/etc/float/admin_index.html"), "custom index page template `file`")
ale's avatar
ale committed
28 29 30 31

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

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

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

func readYAML(path string, obj interface{}) error {
50
	data, err := ioutil.ReadFile(path) // nolint: gosec
ale's avatar
ale committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
	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
67 68 69 70
func mustReadServiceMap() *ServiceMap {
	// Read services.yml.
	services := make(map[string]*Service)
	if err := readYAML(*floatServicesPath, &services); err != nil {
ale's avatar
ale committed
71 72
		log.Fatalf("error reading services file: %v", err)
	}
ale's avatar
ale committed
73 74
	// Add the name to every service, so we can iterate over values easily.
	for name, s := range services {
ale's avatar
ale committed
75 76
		s.Name = name
	}
ale's avatar
ale committed
77 78 79 80 81 82 83 84 85 86 87 88 89 90

	// 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
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
}

// 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
145
	ctx["ServiceMap"] = serviceMap
ale's avatar
ale committed
146 147 148 149 150 151 152 153 154 155 156 157 158 159
	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)
}

160 161 162 163
func handleServiceList(w http.ResponseWriter, r *http.Request) {
	renderTemplate(w, "service_list.html", nil)
}

ale's avatar
ale committed
164 165
func handleServiceDetails(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
ale's avatar
ale committed
166
	s, ok := serviceMap.Services[vars["service"]]
ale's avatar
ale committed
167 168 169 170 171 172 173 174 175 176 177 178
	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
179
	s, ok := serviceMap.Services[vars["service"]]
ale's avatar
ale committed
180 181 182 183 184 185 186
	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
187
			c = cc
ale's avatar
ale committed
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
			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)))
213
	setupRedirects(root.PathPrefix("/link/").Subrouter())
214
	root.Handle("/services", withDynamicHeaders(http.HandlerFunc(handleServiceList)))
ale's avatar
ale committed
215 216 217 218
	root.Handle("/", withDynamicHeaders(http.HandlerFunc(handleIndex)))
	return root
}

219 220 221 222 223 224 225 226
func loadCustomIndexPage(tpl *template.Template, path string) (*template.Template, error) {
	idxTpl, err := template.ParseFiles(path)
	if err != nil {
		return nil, err
	}
	return tpl.AddParseTree("index.html", idxTpl.Tree)
}

ale's avatar
ale committed
227 228 229 230 231
func main() {
	log.SetFlags(0)
	flag.Parse()

	tpl = mustParseEmbeddedTemplates()
232 233 234 235 236 237 238
	if *indexPage != "" {
		if newTpl, err := loadCustomIndexPage(tpl, *indexPage); err != nil {
			log.Printf("warning: error loading custom index page: %v", err)
		} else {
			tpl = newTpl
		}
	}
ale's avatar
ale committed
239
	config = mustReadConfig()
ale's avatar
ale committed
240
	serviceMap = mustReadServiceMap()
ale's avatar
ale committed
241 242 243 244 245 246 247 248 249 250 251 252 253

	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] }