func renderDefenseSelection(w http.ResponseWriter, r *http.Request, errorMessage string) {
	template := template.New("").Funcs(templateHelpers)
	_, err := template.ParseFiles("templates/setup_defense_selection.html")
	if err != nil {
		handleWebErr(w, err)
		return
	}

	matches, err := db.GetMatchesByType("elimination")
	if err != nil {
		handleWebErr(w, err)
		return
	}
	var unplayedMatches []Match
	for _, match := range matches {
		if match.Status != "complete" {
			unplayedMatches = append(unplayedMatches, match)
		}
	}

	data := struct {
		*EventSettings
		Matches      []Match
		DefenseNames map[string]string
		ErrorMessage string
	}{eventSettings, unplayedMatches, defenseNames, errorMessage}
	err = template.ExecuteTemplate(w, "setup_defense_selection.html", data)
	if err != nil {
		handleWebErr(w, err)
		return
	}
}
Ejemplo n.º 2
0
// Shows the page to edit the results for a match.
func MatchReviewEditGetHandler(w http.ResponseWriter, r *http.Request) {
	if !UserIsAdmin(w, r) {
		return
	}

	match, matchResult, _, err := getMatchResultFromRequest(r)
	if err != nil {
		handleWebErr(w, err)
		return
	}

	template, err := template.ParseFiles("templates/edit_match_result.html", "templates/base.html")
	if err != nil {
		handleWebErr(w, err)
		return
	}
	matchResultJson, err := matchResult.serialize()
	if err != nil {
		handleWebErr(w, err)
		return
	}
	data := struct {
		*EventSettings
		Match           *Match
		MatchResultJson *MatchResultDb
	}{eventSettings, match, matchResultJson}
	err = template.ExecuteTemplate(w, "base", data)
	if err != nil {
		handleWebErr(w, err)
		return
	}
}
Ejemplo n.º 3
0
// Renders the referee interface for assigning fouls.
func RefereeDisplayHandler(w http.ResponseWriter, r *http.Request) {
	template := template.New("").Funcs(templateHelpers)
	_, err := template.ParseFiles("templates/referee_display.html")
	if err != nil {
		handleWebErr(w, err)
		return
	}

	match := mainArena.currentMatch
	matchType := match.CapitalizedType()
	red1 := mainArena.AllianceStations["R1"].team
	if red1 == nil {
		red1 = &Team{}
	}
	red2 := mainArena.AllianceStations["R2"].team
	if red2 == nil {
		red2 = &Team{}
	}
	red3 := mainArena.AllianceStations["R3"].team
	if red3 == nil {
		red3 = &Team{}
	}
	blue1 := mainArena.AllianceStations["B1"].team
	if blue1 == nil {
		blue1 = &Team{}
	}
	blue2 := mainArena.AllianceStations["B2"].team
	if blue2 == nil {
		blue2 = &Team{}
	}
	blue3 := mainArena.AllianceStations["B3"].team
	if blue3 == nil {
		blue3 = &Team{}
	}
	data := struct {
		*EventSettings
		MatchType        string
		MatchDisplayName string
		Red1             *Team
		Red2             *Team
		Red3             *Team
		Blue1            *Team
		Blue2            *Team
		Blue3            *Team
		RedFouls         []Foul
		BlueFouls        []Foul
		RedCards         map[string]string
		BlueCards        map[string]string
		Rules            []string
		EntryEnabled     bool
	}{eventSettings, matchType, match.DisplayName, red1, red2, red3, blue1, blue2, blue3,
		mainArena.redRealtimeScore.Fouls, mainArena.blueRealtimeScore.Fouls, mainArena.redRealtimeScore.Cards,
		mainArena.blueRealtimeScore.Cards, rules,
		!(mainArena.redRealtimeScore.FoulsCommitted && mainArena.blueRealtimeScore.FoulsCommitted)}
	err = template.ExecuteTemplate(w, "referee_display.html", data)
	if err != nil {
		handleWebErr(w, err)
		return
	}
}
Ejemplo n.º 4
0
// Renders the scoring interface which enables input of scores in real-time.
func ScoringDisplayHandler(w http.ResponseWriter, r *http.Request) {
	if !UserIsAdmin(w, r) {
		return
	}

	vars := mux.Vars(r)
	alliance := vars["alliance"]
	if alliance != "red" && alliance != "blue" {
		handleWebErr(w, fmt.Errorf("Invalid alliance '%s'.", alliance))
		return
	}

	template, err := template.ParseFiles("templates/scoring_display.html", "templates/base.html")
	if err != nil {
		handleWebErr(w, err)
		return
	}
	data := struct {
		*EventSettings
		Alliance string
	}{eventSettings, alliance}
	err = template.ExecuteTemplate(w, "base", data)
	if err != nil {
		handleWebErr(w, err)
		return
	}
}
// Renders the team number and status display shown above each alliance station.
func AllianceStationDisplayHandler(w http.ResponseWriter, r *http.Request) {
	if !UserIsReader(w, r) {
		return
	}

	template := template.New("").Funcs(templateHelpers)
	_, err := template.ParseFiles("templates/alliance_station_display.html")
	if err != nil {
		handleWebErr(w, err)
		return
	}

	displayId := ""
	if _, ok := r.URL.Query()["displayId"]; ok {
		// Register the display in memory by its ID so that it can be configured to a certain station.
		displayId = r.URL.Query()["displayId"][0]
	}

	data := struct {
		*EventSettings
		DisplayId string
	}{eventSettings, displayId}
	err = template.ExecuteTemplate(w, "alliance_station_display.html", data)
	if err != nil {
		handleWebErr(w, err)
		return
	}
}
Ejemplo n.º 6
0
func executeTemplate(rootTemplte *template.Template, templateName string, machine datasource.Machine, hostAddr string) (string, error) {
	template := rootTemplte.Lookup(templateName)

	if template == nil {
		return "", fmt.Errorf("template with name=%s wasn't found for root=%s",
			templateName, rootTemplte)
	}

	buf := new(bytes.Buffer)
	template.Funcs(map[string]interface{}{
		"V": func(key string) string {
			flag, err := machine.GetFlag(key)
			if err != nil { // TODO excepts Not-Found
				logging.Log(templatesDebugTag,
					"Error while getting flag key=%s for machine=%s: %s",
					key, machine.Name(), err)
				return ""
			}
			return flag
		},
		"b64": func(text string) string {
			return base64.StdEncoding.EncodeToString([]byte(text))
		},
		"b64template": func(templateName string) string {
			text, err := executeTemplate(rootTemplte, templateName, machine, hostAddr)
			if err != nil {
				logging.Log(templatesDebugTag,
					"Error while b64template for templateName=%s machine=%s: %s",
					templateName, machine.Name(), err)
				return ""
			}
			return base64.StdEncoding.EncodeToString([]byte(text))
		},
	})
	ip, _ := machine.IP()
	data := struct {
		Mac      string
		IP       string
		Hostname string
		Domain   string
		HostAddr string
	}{
		machine.Mac().String(),
		ip.String(),
		machine.Name(),
		machine.Domain(),
		hostAddr,
	}
	err := template.ExecuteTemplate(buf, templateName, &data)
	if err != nil {
		return "", err
	}
	str := buf.String()
	str = strings.Trim(str, "\n")
	return str, nil
}
Ejemplo n.º 7
0
// Shows the match play control interface.
func MatchPlayHandler(w http.ResponseWriter, r *http.Request) {
	if !UserIsAdmin(w, r) {
		return
	}

	practiceMatches, err := buildMatchPlayList("practice")
	if err != nil {
		handleWebErr(w, err)
		return
	}
	qualificationMatches, err := buildMatchPlayList("qualification")
	if err != nil {
		handleWebErr(w, err)
		return
	}
	eliminationMatches, err := buildMatchPlayList("elimination")
	if err != nil {
		handleWebErr(w, err)
		return
	}

	template := template.New("").Funcs(templateHelpers)
	_, err = template.ParseFiles("templates/match_play.html", "templates/base.html")
	if err != nil {
		handleWebErr(w, err)
		return
	}
	matchesByType := map[string]MatchPlayList{"practice": practiceMatches,
		"qualification": qualificationMatches, "elimination": eliminationMatches}
	if currentMatchType == "" {
		currentMatchType = "practice"
	}
	allowSubstitution := mainArena.currentMatch.Type != "qualification"
	matchResult, err := db.GetMatchResultForMatch(mainArena.currentMatch.Id)
	if err != nil {
		handleWebErr(w, err)
		return
	}
	isReplay := matchResult != nil
	data := struct {
		*EventSettings
		MatchesByType     map[string]MatchPlayList
		CurrentMatchType  string
		Match             *Match
		AllowSubstitution bool
		IsReplay          bool
	}{eventSettings, matchesByType, currentMatchType, mainArena.currentMatch, allowSubstitution, isReplay}
	err = template.ExecuteTemplate(w, "base", data)
	if err != nil {
		handleWebErr(w, err)
		return
	}
}
Ejemplo n.º 8
0
// Serves the root page of Cheesy Arena.
func IndexHandler(w http.ResponseWriter, r *http.Request) {
	template, err := template.ParseFiles("templates/index.html", "templates/base.html")
	if err != nil {
		handleWebErr(w, err)
		return
	}
	data := struct {
		*EventSettings
	}{eventSettings}
	err = template.ExecuteTemplate(w, "base", data)
	if err != nil {
		handleWebErr(w, err)
		return
	}
}
// Renders the announcer display which shows team info and scores for the current match.
func AnnouncerDisplayHandler(w http.ResponseWriter, r *http.Request) {
	template := template.New("").Funcs(templateHelpers)
	_, err := template.ParseFiles("templates/announcer_display.html", "templates/base.html")
	if err != nil {
		handleWebErr(w, err)
		return
	}
	data := struct {
		*EventSettings
	}{eventSettings}
	err = template.ExecuteTemplate(w, "base", data)
	if err != nil {
		handleWebErr(w, err)
		return
	}
}
Ejemplo n.º 10
0
// Shows the match review interface.
func MatchReviewHandler(w http.ResponseWriter, r *http.Request) {
	if !UserIsReader(w, r) {
		return
	}

	practiceMatches, err := buildMatchReviewList("practice")
	if err != nil {
		handleWebErr(w, err)
		return
	}
	qualificationMatches, err := buildMatchReviewList("qualification")
	if err != nil {
		handleWebErr(w, err)
		return
	}
	eliminationMatches, err := buildMatchReviewList("elimination")
	if err != nil {
		handleWebErr(w, err)
		return
	}

	template, err := template.ParseFiles("templates/match_review.html", "templates/base.html")
	if err != nil {
		handleWebErr(w, err)
		return
	}
	matchesByType := map[string][]MatchReviewListItem{"practice": practiceMatches,
		"qualification": qualificationMatches, "elimination": eliminationMatches}
	if currentMatchType == "" {
		currentMatchType = "practice"
	}
	data := struct {
		*EventSettings
		MatchesByType    map[string][]MatchReviewListItem
		CurrentMatchType string
	}{eventSettings, matchesByType, currentMatchType}
	err = template.ExecuteTemplate(w, "base", data)
	if err != nil {
		handleWebErr(w, err)
		return
	}
}
Ejemplo n.º 11
0
// Renders the audience display to be chroma keyed over the video feed.
func AudienceDisplayHandler(w http.ResponseWriter, r *http.Request) {
	if !UserIsReader(w, r) {
		return
	}

	template := template.New("").Funcs(templateHelpers)
	_, err := template.ParseFiles("templates/audience_display.html")
	if err != nil {
		handleWebErr(w, err)
		return
	}

	data := struct {
		*EventSettings
	}{eventSettings}
	err = template.ExecuteTemplate(w, "audience_display.html", data)
	if err != nil {
		handleWebErr(w, err)
		return
	}
}
Ejemplo n.º 12
0
// Renders the FTA diagnostic display.
func FtaDisplayHandler(w http.ResponseWriter, r *http.Request) {
	if !UserIsAdmin(w, r) {
		return
	}

	// Retrieve the next few matches to show which defenses they will require.
	numUpcomingMatches := 3
	matches, err := db.GetMatchesByType(mainArena.currentMatch.Type)
	if err != nil {
		handleWebErr(w, err)
		return
	}
	var upcomingMatches []Match
	for _, match := range matches {
		if match.Status != "complete" {
			upcomingMatches = append(upcomingMatches, match)
			if len(upcomingMatches) == numUpcomingMatches {
				break
			}
		}
	}

	template := template.New("").Funcs(templateHelpers)
	_, err = template.ParseFiles("templates/fta_display.html", "templates/base.html")
	if err != nil {
		handleWebErr(w, err)
		return
	}
	data := struct {
		*EventSettings
		UpcomingMatches []Match
		DefenseNames    map[string]string
	}{eventSettings, upcomingMatches, defenseNames}
	err = template.ExecuteTemplate(w, "base", data)
	if err != nil {
		handleWebErr(w, err)
		return
	}
}
Ejemplo n.º 13
0
func main() {

	flag.Parse()

	template, err := template.ParseGlob(pattern)
	if err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		return
	}

	file, _ := os.Open(jsonFile)
	buff := make([]byte, SIZE)
	count, _ := file.Read(buff)
	jsonData := buff[:count]
	data := make(map[string]interface{})
	if string(jsonData) != "" {
		if err := json.Unmarshal(jsonData, &data); err != nil {
			fmt.Fprintln(os.Stderr, err.Error())
			return
		}
	}

	template.ExecuteTemplate(os.Stdout, mainTemplate, data)
}
Ejemplo n.º 14
0
func executeTemplate(rootTemplte *template.Template, templateName string,
	ds datasource.DataSource, machineInterface datasource.MachineInterface,
	webServerAddr string) (string, error) {
	template := rootTemplte.Lookup(templateName)

	if template == nil {
		return "", fmt.Errorf("template with name=%s wasn't found for root=%v",
			templateName, rootTemplte)
	}

	mac := machineInterface.Mac().String()

	buf := new(bytes.Buffer)
	template.Funcs(map[string]interface{}{
		"V": func(key string) string {
			value, err := machineInterface.GetVariable(key)
			if err != nil {
				log.WithField("where", "templating.executeTemplate").WithError(err).Warn(
					"error while GetVariable")
			}
			return value
		},
		"b64": func(text string) string {
			return base64.StdEncoding.EncodeToString([]byte(text))
		},
		"b64template": func(templateName string) string {
			text, err := executeTemplate(rootTemplte, templateName, ds, machineInterface, webServerAddr)
			if err != nil {
				log.WithField("where", "templating.executeTemplate").WithError(err).Warnf(
					"error while executeTemplate(templateName=%s machine=%s)",
					templateName, mac)
				return ""
			}
			return base64.StdEncoding.EncodeToString([]byte(text))
		},
	})

	etcdMembers, _ := ds.EtcdMembers()

	machine, err := machineInterface.Machine(false, nil)
	if err != nil {
		return "", err
	}

	data := struct {
		Mac           string
		IP            string
		Hostname      string
		Domain        string
		WebServerAddr string
		EtcdEndpoints string
	}{
		mac,
		machine.IP.String(),
		machineInterface.Hostname(),
		ds.ClusterName(),
		webServerAddr,
		etcdMembers,
	}
	err = template.ExecuteTemplate(buf, templateName, &data)
	if err != nil {
		return "", err
	}
	str := buf.String()
	str = strings.Trim(str, "\n")
	return str, nil
}
Ejemplo n.º 15
0
func generateSvg(id string) ([]byte, error) {

	template, err := template.New("node").Parse(`{{define "NODE"}}<<table border="0" cellspacing="0">
		<tr ><td colspan="2" port="port1" border="1" bgcolor="lightblue">{{.Name}}</td></tr>
		<tr ><td colspan="2" port="port2" border="1">{{.Target}}</td></tr>
		<tr>
			<td port="port2" border="1">{{.Engine}}</td>
			<td port="port8" border="1">{{.Artifact}}</td>
		</tr>
		{{range .Args}}
		<tr ><td colspan="2" port="port2" border="1">{{.}}</td></tr>
		{{end}}
		<tr ><td colspan="2" port="port2" border="1">{{.Outputs}}</td></tr>
		</table>>{{end}}`)

	// Creates a new graph
	g := gographviz.NewGraph()
	//g.AddAttr("", "rankdir", "LR")
	// Now read the json input
	var v orchestrator.Graph

	resp, err := http.Get(fmt.Sprintf("%v/%v", OrchestratorUrl, id))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	//body, err := ioutil.ReadAll(resp.Body)

	dec := json.NewDecoder(resp.Body)
	if err := dec.Decode(&v); err != nil {
		return nil, err
	}

	// Now for each node, create a node
	g.SetName("Execution")
	g.SetDir(true)
	m := make(map[int]string)
	// Now add every node
	// Hack: If node has no Engine and no Artiface, and if sum(row)=sum(col)=0, skip it
	for i, _ := range v.Nodes {
		sumr := int64(0)
		sumc := int64(0)
		for r := 0; r < v.Digraph.Dim(); r++ {
			sumr = sumr + v.Digraph.At(v.Nodes[i].ID, r)
			sumc = sumc + v.Digraph.At(r, v.Nodes[i].ID)
		}
		if v.Nodes[i].Artifact == "" && sumr == 0 && sumc == 0 {
			continue
		}
		tmp := make([]string, 2)
		v.Nodes[i].Name = strings.Replace(v.Nodes[i].Name, "-", "_", -1)
		tmp = strings.SplitAfter(v.Nodes[i].Name, ":")
		v.Nodes[i].Name = strings.Replace(v.Nodes[i].Name, ":", "_", -1)
		if len(tmp) != 2 {
			tmp[0] = v.Nodes[i].Name
			tmp = append(tmp, "")
		}
		var out bytes.Buffer
		err = template.ExecuteTemplate(&out, "NODE", v.Nodes[i])
		g.AddNode("G", v.Nodes[i].Name,
			map[string]string{
				"id": fmt.Sprintf("\"%v\"", strconv.Itoa(v.Nodes[i].ID)),
				//"label": fmt.Sprintf("\"%v|%v\"", tmp[0], tmp[1]),
				"label": out.String(),
				//"label": fmt.Sprintf("\"%v|%v|%v|%v|%v\"", tmp[0], tmp[1], v.Nodes[i].Engine, v.Nodes[i].Artifact, v.Nodes[i].Args[:]),
				"shape": "\"record\"",
				"style": "\"rounded\"",
			})
		m[v.Nodes[i].ID] = v.Nodes[i].Name
	}
	for r := 0; r < v.Digraph.Dim(); r++ {
		for c := 0; c < v.Digraph.Dim(); c++ {
			if v.Digraph.At(r, c) != 0 {
				//g.AddEdge(fmt.Sprintf("%v:%v", m[r], r), fmt.Sprintf("%v:%v", m[c], c), true, nil)
				g.AddEdge(m[r], m[c], true, nil)
			}
		}
	}
	// Now add the edges
	s := g.String()
	d := exec.Command("dot", "-Tsvg")

	// Set the stdin stdout and stderr of the dot subprocess
	stdinOfDotProcess, err := d.StdinPipe()
	if err != nil {
		return nil, err

	}
	defer stdinOfDotProcess.Close() // the doc says subProcess.Wait will close it, but I'm not sure, so I kept this line
	readCloser, err := d.StdoutPipe()
	if err != nil {
		return nil, err

	}
	d.Stderr = os.Stderr

	// Actually run the dot subprocess
	if err = d.Start(); err != nil { //Use start, not run
		fmt.Println("An error occured: ", err) //replace with logger, or anything you want
	}
	fmt.Fprintf(stdinOfDotProcess, s)
	stdinOfDotProcess.Close()

	// Read from stdout and store it in the correct structure
	var buf bytes.Buffer
	buf.ReadFrom(readCloser)

	err = d.Wait()
	if err != nil {
		fmt.Println(s)
	}

	return buf.Bytes(), nil
}
Ejemplo n.º 16
-1
func main() {

	var pattern string
	flag.StringVar(&pattern, "p", "templates/*.html", "template pattern like template/*.html")
	template, err := template.ParseGlob(pattern)
	if err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
	}

	var mainTemplate string
	flag.StringVar(&mainTemplate, "t", "index", "main template like index")
	template.ExecuteTemplate(os.Stdout, mainTemplate, nil)
}