<commit_before>package ui

import (
	"strings"
	"sync"

	"github.com/moncho/dry/search"
	"github.com/nsf/termbox-go"
)

const (
	endtext   = "(end)"
	starttext = "(start)"
)

//Less is a View specialization with less-like behavior and characteristics, meaning:
// * The cursor is always shown at the bottom of the screen.
// * Navigation is done using less keybindings.
// * Basic search is supported.
type Less struct {
	*View
	searchResult *search.Result
	filtering    bool
	following    bool
	refresh      chan struct{}

	sync.Mutex
}

//NewLess creates a view that partially simulates less.
func NewLess(theme *ColorTheme) *Less {
	width, height := termbox.Size()
	view := NewView("", 0, 0, width, height, true, theme)
	view.cursorY = height - 1 //Last line is at height -1
	less := &Less{
		View: view,
	}

	return less
}

//Focus sets the view as active, so it starts handling terminal events
//and user actions
func (less *Less) Focus(events <-chan termbox.Event) error {
	refreshChan := make(chan struct{}, 1)
	less.refresh = refreshChan
	less.newLineCallback = func() {
		if less.following {
			//ScrollToBottom refreshes the buffer as well
			less.ScrollToBottom()
		} else {
			less.refreshBuffer()
		}
	}
	inputMode := false
	inputBoxEventChan := make(chan termbox.Event)
	inputBoxOutput := make(chan string, 1)
	defer close(inputBoxOutput)
	defer close(inputBoxEventChan)
	defer func() {
		less.newLineCallback = func() {}
		close(refreshChan)
	}()

	go func() {
		for range less.refresh {
			clear(termbox.Attribute(less.View.theme.Fg), termbox.Attribute(less.View.theme.Bg))
			less.render()
		}
	}()
	//This ensures at least one refresh
	less.refreshBuffer()

loop:
	for {
		select {
		case input := <-inputBoxOutput:
			inputMode = false
			less.search(input)
			less.render()
		case event := <-events:
			switch event.Type {
			case termbox.EventKey:
				if !inputMode {
					if event.Key == termbox.KeyEsc {
						break loop
					} else if event.Key == termbox.KeyArrowDown { //cursor down
						less.ScrollDown()
					} else if event.Key == termbox.KeyArrowUp { // cursor up
						less.ScrollUp()
					} else if event.Key == termbox.KeyPgdn { //cursor one page down
						less.ScrollPageDown()
					} else if event.Key == termbox.KeyPgup { // cursor one page up
						less.ScrollPageUp()
					} else if event.Ch == 'f' {
						inputMode = true
						less.filtering = true
						go less.readInput(inputBoxEventChan, inputBoxOutput)
					} else if event.Ch == 'F' { //toggle follow
						less.flipFollow()
					} else if event.Ch == 'g' { //to the top of the view
						less.ScrollToTop()
					} else if event.Ch == 'G' { //to the bottom of the view
						less.ScrollToBottom()
					} else if event.Ch == 'N' { //to the top of the view
						less.gotoPreviousSearchHit()
					} else if event.Ch == 'n' { //to the bottom of the view
						less.gotoNextSearchHit()
					} else if event.Ch == '/' {
						inputMode = true
						less.filtering = false
						go less.readInput(inputBoxEventChan, inputBoxOutput)
					}
				} else {
					inputBoxEventChan <- event
				}
			}
		}
	}
	return nil
}

//Search searches in the view buffer for the given pattern
func (less *Less) search(pattern string) error {
	if pattern != "" {
		searchResult, err := search.NewSearch(less.lines, pattern)
		if err == nil {
			less.searchResult = searchResult
			if searchResult.Hits > 0 {
				_, y := less.Position()
				searchResult.InitialLine(y)
				less.gotoNextSearchHit()
			}
		} else {
			return err
		}
	} else {
		less.searchResult = nil
	}
	return nil
}

func (less *Less) readInput(inputBoxEventChan chan termbox.Event, inputBoxOutput chan string) error {
	_, height := less.ViewSize()
	eb := NewInputBox(0, height, ">>> ", inputBoxOutput, inputBoxEventChan, less.theme)
	eb.Focus()
	return nil
}

// Render renders the view buffer contents.
func (less *Less) render() {
	less.Lock()
	defer less.Unlock()
	clear(termbox.Attribute(less.View.theme.Fg), termbox.Attribute(less.View.theme.Bg))
	_, maxY := less.renderableArea()
	y := 0

	bufferStart := 0
	if less.bufferY < less.bufferSize() && less.bufferY > 0 {
		bufferStart = less.bufferY
	}
	for _, line := range less.lines[bufferStart:] {

		if y > maxY {
			break
		}
		less.renderLine(0, y, string(line))
		y++
	}

	less.renderStatusLine()
	less.drawCursor()
	termbox.Flush()
}

func (less *Less) flipFollow() {
	less.following = !less.following
	less.refreshBuffer()
}

//ScrollDown moves the cursor down one line
func (less *Less) ScrollDown() {
	less.scrollDown(1)
}

//ScrollUp moves the cursor up one line
func (less *Less) ScrollUp() {
	less.scrollUp(1)
}

//ScrollPageDown moves the buffer position down by the length of the screen,
//at the end of buffer it also moves the cursor position to the bottom
//of the screen
func (less *Less) ScrollPageDown() {
	_, height := less.ViewSize()
	less.scrollDown(height)

}

//ScrollPageUp moves the buffer position up by the length of the screen,
//at the beginning of buffer it also moves the cursor position to the beginning
//of the screen
func (less *Less) ScrollPageUp() {
	_, height := less.ViewSize()
	less.scrollUp(height)

}

//ScrollToBottom moves the cursor to the bottom of the view buffer
func (less *Less) ScrollToBottom() {
	less.bufferY = less.bufferSize() - less.y1
	less.refreshBuffer()

}

//ScrollToTop moves the cursor to the top of the view buffer
func (less *Less) ScrollToTop() {
	less.bufferY = 0
	less.refreshBuffer()
}

func (less *Less) atTheStartOfBuffer() bool {
	_, y := less.Position()
	return y == 0
}

func (less *Less) atTheEndOfBuffer() bool {
	viewLength := less.bufferSize()
	_, y := less.Position()
	_, height := less.ViewSize()
	return y+height >= viewLength-1
}

func (less *Less) bufferSize() int {
	return len(less.lines)
}

func (less *Less) gotoPreviousSearchHit() {
	sr := less.searchResult
	if sr != nil {
		x, _ := less.Position()
		if newy, err := sr.PreviousLine(); err == nil {
			less.setPosition(x, newy)
		}
	}
	less.refreshBuffer()
}
func (less *Less) gotoNextSearchHit() {
	sr := less.searchResult
	if sr != nil {
		x, _ := less.Position()
		if newY, err := sr.NextLine(); err == nil {
			less.setPosition(x, newY)
		}
	}
	less.refreshBuffer()
}

func (less *Less) refreshBuffer() {
	//Non blocking send. Since the refresh channel is buffered, losing
	//refresh messages because of a full buffer should not be a problem
	//since there is already a refresh message waiting to be processed.
	select {
	case less.refresh <- struct{}{}:
	default:
	}
}

//renderableArea return the part of the view size available for rendering.
func (less *Less) renderableArea() (int, int) {
	maxX, maxY := less.ViewSize()
	return maxX, maxY - 1
}

func (less *Less) renderLine(x int, y int, line string) (int, error) {
	var lines = 1
	maxWidth, _ := less.renderableArea()
	if less.searchResult != nil {
		//If markup support is active then it might happen that tags are present in the line
		//but since we are searching, markups are ignored and coloring output is
		//decided here.
		if strings.Contains(line, less.searchResult.Pattern) {
			if less.markup != nil {
				start, column := 0, 0
				for _, token := range Tokenize(line, SupportedTags) {
					if less.markup.IsTag(token) {

						continue
					}
					// Here comes the actual text: display it one character at a time.
					for _, char := range token {
						start = x + column
						column++
						termbox.SetCell(start, y, char, termbox.ColorYellow, termbox.Attribute(less.View.theme.Bg))
					}
				}
			} else {
				_, lines = renderString(x, y, maxWidth, line, termbox.ColorYellow, termbox.Attribute(less.View.theme.Bg))
			}
		} else if !less.filtering {
			return less.View.renderLine(x, y, line)
		}

	} else {
		return less.View.renderLine(x, y, line)
	}
	return lines, nil
}

//scrollDown moves the buffer position down by the given number of lines
func (less *Less) scrollDown(lines int) {
	_, height := less.ViewSize()
	viewLength := less.bufferSize()

	posX, posY := less.Position()
	//This is as down as scrolling can go
	maxY := viewLength - height
	if posY+lines < maxY {
		newOy := posY + lines
		if newOy >= viewLength {
			less.setPosition(posX, viewLength-height)
		} else {
			less.setPosition(posX, newOy)
		}
	} else {
		less.ScrollToBottom()
	}
	less.refreshBuffer()

}

//scrollUp moves the buffer position up by the given number of lines
func (less *Less) scrollUp(lines int) {
	ox, bufferY := less.Position()
	if bufferY-lines >= 0 {
		less.setPosition(ox, bufferY-lines)
	} else {
		less.setPosition(ox, 0)
	}
	less.refreshBuffer()
}

func (less *Less) renderStatusLine() {
	maxWidth, maxLength := less.ViewSize()
	var cursorX = 1
	status := less.statusLine()
	if less.atTheEndOfBuffer() {
		cursorX = len(endtext)
	} else if less.atTheStartOfBuffer() {
		cursorX = len(starttext)
	}
	renderString(0, maxLength, maxWidth, status, termbox.ColorWhite, termbox.Attribute(less.View.theme.Bg))
	less.cursorX = cursorX
}

func (less *Less) statusLine() string {
	maxWidth, _ := less.ViewSize()

	var start string
	switch {
	case less.atTheStartOfBuffer():
		start = starttext
	case less.atTheEndOfBuffer():
		start = endtext
	default:
		start = ":"
	}

	var end string
	if less.filtering && less.searchResult != nil {
		end = strings.Join([]string{less.searchResult.String(), "Filter: On"}, " ")
	} else {
		end = "Filter: Off"
	}

	if less.following {
		end = end + " Follow: On"
	} else {
		end = end + " Follow: Off"
	}

	return strings.Join(
		[]string{start, end},
		strings.Repeat(" ", maxWidth-len(start)-len(end)))
}

func (less *Less) drawCursor() {
	x, y := less.Cursor()

	termbox.SetCursor(x, y)
}

func clear(fg, bg termbox.Attribute) {
	termbox.Clear(fg, bg)
}
<commit_msg>Use "f" to toggle follow<commit_after>package ui

import (
	"strings"
	"sync"

	"github.com/moncho/dry/search"
	"github.com/nsf/termbox-go"
)

const (
	endtext   = "(end)"
	starttext = "(start)"
)

//Less is a View specialization with less-like behavior and characteristics, meaning:
// * The cursor is always shown at the bottom of the screen.
// * Navigation is done using less keybindings.
// * Basic search is supported.
type Less struct {
	*View
	searchResult *search.Result
	filtering    bool
	following    bool
	refresh      chan struct{}

	sync.Mutex
}

//NewLess creates a view that partially simulates less.
func NewLess(theme *ColorTheme) *Less {
	width, height := termbox.Size()
	view := NewView("", 0, 0, width, height, true, theme)
	view.cursorY = height - 1 //Last line is at height -1
	less := &Less{
		View: view,
	}

	return less
}

//Focus sets the view as active, so it starts handling terminal events
//and user actions
func (less *Less) Focus(events <-chan termbox.Event) error {
	refreshChan := make(chan struct{}, 1)
	less.refresh = refreshChan
	less.newLineCallback = func() {
		if less.following {
			//ScrollToBottom refreshes the buffer as well
			less.ScrollToBottom()
		} else {
			less.refreshBuffer()
		}
	}
	inputMode := false
	inputBoxEventChan := make(chan termbox.Event)
	inputBoxOutput := make(chan string, 1)
	defer close(inputBoxOutput)
	defer close(inputBoxEventChan)
	defer func() {
		less.newLineCallback = func() {}
		close(refreshChan)
	}()

	go func() {
		for range less.refresh {
			clear(termbox.Attribute(less.View.theme.Fg), termbox.Attribute(less.View.theme.Bg))
			less.render()
		}
	}()
	//This ensures at least one refresh
	less.refreshBuffer()

loop:
	for {
		select {
		case input := <-inputBoxOutput:
			inputMode = false
			less.search(input)
			less.render()
		case event := <-events:
			switch event.Type {
			case termbox.EventKey:
				if !inputMode {
					if event.Key == termbox.KeyEsc {
						break loop
					} else if event.Key == termbox.KeyArrowDown { //cursor down
						less.ScrollDown()
					} else if event.Key == termbox.KeyArrowUp { // cursor up
						less.ScrollUp()
					} else if event.Key == termbox.KeyPgdn { //cursor one page down
						less.ScrollPageDown()
					} else if event.Key == termbox.KeyPgup { // cursor one page up
						less.ScrollPageUp()
					} else if event.Ch == 'f' { //toggle follow
						less.flipFollow()
					} else if event.Ch == 'F' {
						inputMode = true
						less.filtering = true
						go less.readInput(inputBoxEventChan, inputBoxOutput)
					} else if event.Ch == 'g' { //to the top of the view
						less.ScrollToTop()
					} else if event.Ch == 'G' { //to the bottom of the view
						less.ScrollToBottom()
					} else if event.Ch == 'N' { //to the top of the view
						less.gotoPreviousSearchHit()
					} else if event.Ch == 'n' { //to the bottom of the view
						less.gotoNextSearchHit()
					} else if event.Ch == '/' {
						inputMode = true
						less.filtering = false
						go less.readInput(inputBoxEventChan, inputBoxOutput)
					}
				} else {
					inputBoxEventChan <- event
				}
			}
		}
	}
	return nil
}

//Search searches in the view buffer for the given pattern
func (less *Less) search(pattern string) error {
	if pattern != "" {
		searchResult, err := search.NewSearch(less.lines, pattern)
		if err == nil {
			less.searchResult = searchResult
			if searchResult.Hits > 0 {
				_, y := less.Position()
				searchResult.InitialLine(y)
				less.gotoNextSearchHit()
			}
		} else {
			return err
		}
	} else {
		less.searchResult = nil
	}
	return nil
}

func (less *Less) readInput(inputBoxEventChan chan termbox.Event, inputBoxOutput chan string) error {
	_, height := less.ViewSize()
	eb := NewInputBox(0, height, ">>> ", inputBoxOutput, inputBoxEventChan, less.theme)
	eb.Focus()
	return nil
}

// Render renders the view buffer contents.
func (less *Less) render() {
	less.Lock()
	defer less.Unlock()
	clear(termbox.Attribute(less.View.theme.Fg), termbox.Attribute(less.View.theme.Bg))
	_, maxY := less.renderableArea()
	y := 0

	bufferStart := 0
	if less.bufferY < less.bufferSize() && less.bufferY > 0 {
		bufferStart = less.bufferY
	}
	for _, line := range less.lines[bufferStart:] {

		if y > maxY {
			break
		}
		less.renderLine(0, y, string(line))
		y++
	}

	less.renderStatusLine()
	less.drawCursor()
	termbox.Flush()
}

func (less *Less) flipFollow() {
	less.following = !less.following
	less.refreshBuffer()
}

//ScrollDown moves the cursor down one line
func (less *Less) ScrollDown() {
	less.scrollDown(1)
}

//ScrollUp moves the cursor up one line
func (less *Less) ScrollUp() {
	less.scrollUp(1)
}

//ScrollPageDown moves the buffer position down by the length of the screen,
//at the end of buffer it also moves the cursor position to the bottom
//of the screen
func (less *Less) ScrollPageDown() {
	_, height := less.ViewSize()
	less.scrollDown(height)

}

//ScrollPageUp moves the buffer position up by the length of the screen,
//at the beginning of buffer it also moves the cursor position to the beginning
//of the screen
func (less *Less) ScrollPageUp() {
	_, height := less.ViewSize()
	less.scrollUp(height)

}

//ScrollToBottom moves the cursor to the bottom of the view buffer
func (less *Less) ScrollToBottom() {
	less.bufferY = less.bufferSize() - less.y1
	less.refreshBuffer()

}

//ScrollToTop moves the cursor to the top of the view buffer
func (less *Less) ScrollToTop() {
	less.bufferY = 0
	less.refreshBuffer()
}

func (less *Less) atTheStartOfBuffer() bool {
	_, y := less.Position()
	return y == 0
}

func (less *Less) atTheEndOfBuffer() bool {
	viewLength := less.bufferSize()
	_, y := less.Position()
	_, height := less.ViewSize()
	return y+height >= viewLength-1
}

func (less *Less) bufferSize() int {
	return len(less.lines)
}

func (less *Less) gotoPreviousSearchHit() {
	sr := less.searchResult
	if sr != nil {
		x, _ := less.Position()
		if newy, err := sr.PreviousLine(); err == nil {
			less.setPosition(x, newy)
		}
	}
	less.refreshBuffer()
}
func (less *Less) gotoNextSearchHit() {
	sr := less.searchResult
	if sr != nil {
		x, _ := less.Position()
		if newY, err := sr.NextLine(); err == nil {
			less.setPosition(x, newY)
		}
	}
	less.refreshBuffer()
}

func (less *Less) refreshBuffer() {
	//Non blocking send. Since the refresh channel is buffered, losing
	//refresh messages because of a full buffer should not be a problem
	//since there is already a refresh message waiting to be processed.
	select {
	case less.refresh <- struct{}{}:
	default:
	}
}

//renderableArea return the part of the view size available for rendering.
func (less *Less) renderableArea() (int, int) {
	maxX, maxY := less.ViewSize()
	return maxX, maxY - 1
}

func (less *Less) renderLine(x int, y int, line string) (int, error) {
	var lines = 1
	maxWidth, _ := less.renderableArea()
	if less.searchResult != nil {
		//If markup support is active then it might happen that tags are present in the line
		//but since we are searching, markups are ignored and coloring output is
		//decided here.
		if strings.Contains(line, less.searchResult.Pattern) {
			if less.markup != nil {
				start, column := 0, 0
				for _, token := range Tokenize(line, SupportedTags) {
					if less.markup.IsTag(token) {

						continue
					}
					// Here comes the actual text: display it one character at a time.
					for _, char := range token {
						start = x + column
						column++
						termbox.SetCell(start, y, char, termbox.ColorYellow, termbox.Attribute(less.View.theme.Bg))
					}
				}
			} else {
				_, lines = renderString(x, y, maxWidth, line, termbox.ColorYellow, termbox.Attribute(less.View.theme.Bg))
			}
		} else if !less.filtering {
			return less.View.renderLine(x, y, line)
		}

	} else {
		return less.View.renderLine(x, y, line)
	}
	return lines, nil
}

//scrollDown moves the buffer position down by the given number of lines
func (less *Less) scrollDown(lines int) {
	_, height := less.ViewSize()
	viewLength := less.bufferSize()

	posX, posY := less.Position()
	//This is as down as scrolling can go
	maxY := viewLength - height
	if posY+lines < maxY {
		newOy := posY + lines
		if newOy >= viewLength {
			less.setPosition(posX, viewLength-height)
		} else {
			less.setPosition(posX, newOy)
		}
	} else {
		less.ScrollToBottom()
	}
	less.refreshBuffer()

}

//scrollUp moves the buffer position up by the given number of lines
func (less *Less) scrollUp(lines int) {
	ox, bufferY := less.Position()
	if bufferY-lines >= 0 {
		less.setPosition(ox, bufferY-lines)
	} else {
		less.setPosition(ox, 0)
	}
	less.refreshBuffer()
}

func (less *Less) renderStatusLine() {
	maxWidth, maxLength := less.ViewSize()
	var cursorX = 1
	status := less.statusLine()
	if less.atTheEndOfBuffer() {
		cursorX = len(endtext)
	} else if less.atTheStartOfBuffer() {
		cursorX = len(starttext)
	}
	renderString(0, maxLength, maxWidth, status, termbox.ColorWhite, termbox.Attribute(less.View.theme.Bg))
	less.cursorX = cursorX
}

func (less *Less) statusLine() string {
	maxWidth, _ := less.ViewSize()

	var start string
	switch {
	case less.atTheStartOfBuffer():
		start = starttext
	case less.atTheEndOfBuffer():
		start = endtext
	default:
		start = ":"
	}

	var end string
	if less.filtering && less.searchResult != nil {
		end = strings.Join([]string{less.searchResult.String(), "Filter: On"}, " ")
	} else {
		end = "Filter: Off"
	}

	if less.following {
		end = end + " Follow: On"
	} else {
		end = end + " Follow: Off"
	}

	return strings.Join(
		[]string{start, end},
		strings.Repeat(" ", maxWidth-len(start)-len(end)))
}

func (less *Less) drawCursor() {
	x, y := less.Cursor()

	termbox.SetCursor(x, y)
}

func clear(fg, bg termbox.Attribute) {
	termbox.Clear(fg, bg)
}
<|endoftext|>


<commit_before>package ui

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/ninjasphere/go-ninja/api"
	"github.com/ninjasphere/go-ninja/config"
	"github.com/ninjasphere/go-ninja/logger"
	"github.com/ninjasphere/go-ninja/model"
)

/*
type Thing struct {
	Name   string `json:"name"`
	ID     string `json:"id"`
	Device Device
}

type Device struct {
	Name     string `json:"name"`
	ID       string `json:"id"`
	IDType   string `json:"idType"`
	Guid     string `json:"guid"`
	Channels []Channel
}

type Channel struct {
	Protocol string `json:"protocol"`
	Name     string `json:"channel"`
	ID       string `json:"id"`
}*/

var sameRoomOnly = config.Bool(true, "homecloud.sameRoomOnly")

var conn *ninja.Connection
var tasks []*request
var thingModel *ninja.ServiceClient

var log = logger.GetLogger("ui")

type request struct {
	thingType string
	protocol  string
	filter    func(thing *model.Thing) bool
	cb        func([]*ninja.ServiceClient, error)
}

var foundLocation = make(chan bool)

var roomID *string

func runTasks() {

	// Find this sphere's location, if we care..
	if sameRoomOnly {
		for _, thing := range allThings {
			if thing.Type == "node" && thing.Device != nil && thing.Device.NaturalID == config.Serial() {
				if thing.Location != nil && (roomID == nil || *roomID != *thing.Location) {
					// Got it.
					log.Infof("Got this sphere's location: %s", thing.Location)
					roomID = thing.Location
					select {
					case foundLocation <- true:
					default:
					}

					break
				}
			}
		}
	}

	for _, task := range tasks {
		go func(t *request) {
			t.cb(getChannelServices(t.thingType, t.protocol, t.filter))
		}(task)
	}

}

var allThings []model.Thing

func fetchAll() error {

	var things []model.Thing

	err := thingModel.Call("fetchAll", []interface{}{}, &things, time.Second*20)
	//err = client.Call("fetch", "c7ac05e0-9999-4d93-bfe3-a0b4bb5e7e78", &thing)

	if err != nil {
		return fmt.Errorf("Failed to get things!: %s", err)
	}

	allThings = things
	runTasks()

	return nil
}

func startSearchTasks(c *ninja.Connection) {
	conn = c
	thingModel = conn.GetServiceClient("$home/services/ThingModel")

	dirty := false

	setDirty := func(params *json.RawMessage, topicKeys map[string]string) bool {
		log.Infof("Devices added/removed/updated. Marking dirty.")
		dirty = true
		return true
	}

	go func() {
		for {
			time.Sleep(time.Second * 30)
			setDirty(nil, nil)
		}
	}()

	go func() {
		for {
			err := fetchAll()
			if err == nil {
				break
			}

			log.Warningf("Failed to get fetch all things: %s", err)
			time.Sleep(time.Second * 3)
		}
	}()

	if sameRoomOnly {
		<-foundLocation
	}

	thingModel.OnEvent("created", setDirty)
	thingModel.OnEvent("updated", setDirty)
	thingModel.OnEvent("deleted", setDirty)

	go func() {
		time.Sleep(time.Second * 10)
		for {
			time.Sleep(time.Second * 5)
			if dirty {
				fetchAll()
				dirty = false
			}
		}
	}()
}

func getChannelServicesContinuous(thingType string, protocol string, filter func(thing *model.Thing) bool, cb func([]*ninja.ServiceClient, error)) {

	if filter == nil {
		filter = func(thing *model.Thing) bool {
			return roomID != nil && (thing.Location != nil && *thing.Location == *roomID)
		}
	}

	tasks = append(tasks, &request{thingType, protocol, filter, cb})

	cb(getChannelServices(thingType, protocol, filter))
}

func getChannelServices(thingType string, protocol string, filter func(thing *model.Thing) bool) ([]*ninja.ServiceClient, error) {

	//time.Sleep(time.Second * 3)

	var services []*ninja.ServiceClient

	for _, thing := range allThings {
		if thing.Type == thingType {

			// Handle more than one channel with same protocol
			channel := getChannel(&thing, protocol)
			if channel != nil {
				if filter(&thing) {
					services = append(services, conn.GetServiceClientFromAnnouncement(channel.ServiceAnnouncement))
				}
			}
		}
	}
	return services, nil
}

func getChannel(thing *model.Thing, protocol string) *model.Channel {

	if thing.Device == nil || thing.Device.Channels == nil {
		return nil
	}

	for _, channel := range *thing.Device.Channels {
		if channel.Protocol == protocol {
			if thing.Device == nil {
				//spew.Dump("NO device on thing!", thing)
				return nil
			}

			return channel
		}
	}

	return nil
}
<commit_msg>Expose the device search tasks (temp)<commit_after>package ui

import (
	"encoding/json"
	"fmt"
	"time"

	"github.com/davecgh/go-spew/spew"
	"github.com/ninjasphere/go-ninja/api"
	"github.com/ninjasphere/go-ninja/config"
	"github.com/ninjasphere/go-ninja/logger"
	"github.com/ninjasphere/go-ninja/model"
)

/*
type Thing struct {
	Name   string `json:"name"`
	ID     string `json:"id"`
	Device Device
}

type Device struct {
	Name     string `json:"name"`
	ID       string `json:"id"`
	IDType   string `json:"idType"`
	Guid     string `json:"guid"`
	Channels []Channel
}

type Channel struct {
	Protocol string `json:"protocol"`
	Name     string `json:"channel"`
	ID       string `json:"id"`
}*/

var sameRoomOnly = config.Bool(true, "homecloud.sameRoomOnly")

var conn *ninja.Connection
var tasks []*request
var thingModel *ninja.ServiceClient

var log = logger.GetLogger("ui")

type request struct {
	thingType string
	protocol  string
	filter    func(thing *model.Thing) bool
	cb        func([]*ninja.ServiceClient, error)
}

var foundLocation = make(chan bool)

var roomID *string

func runTasks() {

	// Find this sphere's location, if we care..
	if sameRoomOnly {
		for _, thing := range allThings {
			if thing.Type == "node" && thing.Device != nil && thing.Device.NaturalID == config.Serial() {
				if thing.Location != nil && (roomID == nil || *roomID != *thing.Location) {
					// Got it.
					log.Infof("Got this sphere's location: %s", thing.Location)
					roomID = thing.Location
					select {
					case foundLocation <- true:
					default:
					}

					break
				}
			}
		}
	}

	for _, task := range tasks {
		go func(t *request) {
			t.cb(getChannelServices(t.thingType, t.protocol, t.filter))
		}(task)
	}

}

var allThings []model.Thing

func fetchAll() error {

	var things []model.Thing

	err := thingModel.Call("fetchAll", []interface{}{}, &things, time.Second*20)
	//err = client.Call("fetch", "c7ac05e0-9999-4d93-bfe3-a0b4bb5e7e78", &thing)

	if err != nil {
		return fmt.Errorf("Failed to get things!: %s", err)
	}

	allThings = things
	runTasks()

	return nil
}

func StartSearchTasks(c *ninja.Connection) {
	startSearchTasks(c)
}

func startSearchTasks(c *ninja.Connection) {
	conn = c
	thingModel = conn.GetServiceClient("$home/services/ThingModel")

	dirty := false

	setDirty := func(params *json.RawMessage, topicKeys map[string]string) bool {
		log.Infof("Devices added/removed/updated. Marking dirty.")
		dirty = true
		return true
	}

	go func() {
		for {
			time.Sleep(time.Second * 30)
			setDirty(nil, nil)
		}
	}()

	go func() {
		for {
			err := fetchAll()
			if err == nil {
				break
			}

			log.Warningf("Failed to get fetch all things: %s", err)
			time.Sleep(time.Second * 3)
		}
	}()

	if sameRoomOnly {
		<-foundLocation
	}

	thingModel.OnEvent("created", setDirty)
	thingModel.OnEvent("updated", setDirty)
	thingModel.OnEvent("deleted", setDirty)

	go func() {
		time.Sleep(time.Second * 10)
		for {
			time.Sleep(time.Second * 5)
			if dirty {
				fetchAll()
				dirty = false
			}
		}
	}()
}

func GetChannelServicesContinuous(thingType string, protocol string, filter func(thing *model.Thing) bool, cb func([]*ninja.ServiceClient, error)) {
	getChannelServicesContinuous(thingType, protocol, filter, cb)
}

func getChannelServicesContinuous(thingType string, protocol string, filter func(thing *model.Thing) bool, cb func([]*ninja.ServiceClient, error)) {

	if filter == nil {
		filter = func(thing *model.Thing) bool {
			return roomID != nil && (thing.Location != nil && *thing.Location == *roomID)
		}
	}

	tasks = append(tasks, &request{thingType, protocol, filter, cb})

	cb(getChannelServices(thingType, protocol, filter))
}

func getChannelServices(thingType string, protocol string, filter func(thing *model.Thing) bool) ([]*ninja.ServiceClient, error) {

	//time.Sleep(time.Second * 3)

	var services []*ninja.ServiceClient

	for _, thing := range allThings {
		if thing.Type == thingType {

			spew.Dump("Found the right thing", thing, "looking for protocol", protocol)

			// Handle more than one channel with same protocol
			channel := getChannel(&thing, protocol)
			if channel != nil {
				if filter(&thing) {
					services = append(services, conn.GetServiceClientFromAnnouncement(channel.ServiceAnnouncement))
				}
			}
		}
	}
	return services, nil
}

func getChannel(thing *model.Thing, protocol string) *model.Channel {

	if thing.Device == nil || thing.Device.Channels == nil {
		return nil
	}

	for _, channel := range *thing.Device.Channels {
		if channel.Protocol == protocol {
			if thing.Device == nil {
				//spew.Dump("NO device on thing!", thing)
				return nil
			}

			return channel
		}
	}

	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/gdamore/tcell"
	"github.com/mitchellh/go-homedir"
	"io/ioutil"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
)

// FileTypeRules represents a complete set of syntax rules for a filetype
type FileTypeRules struct {
	filetype string
	rules    []SyntaxRule
}

// SyntaxRule represents a regex to highlight in a certain style
type SyntaxRule struct {
	// What to highlight
	regex *regexp.Regexp
	// Any flags
	flags string
	// Whether this regex is a start=... end=... regex
	startend bool
	// How to highlight it
	style tcell.Style
}

var syntaxFiles map[[2]*regexp.Regexp]FileTypeRules

// LoadSyntaxFiles loads the syntax files from the default directory ~/.micro
func LoadSyntaxFiles() {
	dir, err := homedir.Dir()
	if err != nil {
		TermMessage("Error finding your home directory\nCan't load runtime files")
		return
	}
	LoadSyntaxFilesFromDir(dir + "/.micro/syntax")
}

// JoinRule takes a syntax rule (which can be multiple regular expressions)
// and joins it into one regular expression by ORing everything together
func JoinRule(rule string) string {
	split := strings.Split(rule, `" "`)
	joined := strings.Join(split, ")|(")
	joined = "(" + joined + ")"
	return joined
}

// LoadSyntaxFilesFromDir loads the syntax files from a specified directory
// To load the syntax files, we must fill the `syntaxFiles` map
// This involves finding the regex for syntax and if it exists, the regex
// for the header. Then we must get the text for the file and the filetype.
func LoadSyntaxFilesFromDir(dir string) {
	InitColorscheme()

	syntaxFiles = make(map[[2]*regexp.Regexp]FileTypeRules)
	files, _ := ioutil.ReadDir(dir)
	for _, f := range files {
		if filepath.Ext(f.Name()) == ".micro" {
			text, err := ioutil.ReadFile(dir + "/" + f.Name())
			filename := dir + "/" + f.Name()

			if err != nil {
				TermMessage("Error loading syntax files: " + err.Error())
				continue
			}
			lines := strings.Split(string(text), "\n")

			syntaxParser := regexp.MustCompile(`syntax "(.*?)"\s+"(.*)"+`)
			headerParser := regexp.MustCompile(`header "(.*)"`)

			ruleParser := regexp.MustCompile(`color (.*?)\s+(?:\((.*?)\)\s+)?"(.*)"`)
			ruleStartEndParser := regexp.MustCompile(`color (.*?)\s+(?:\((.*?)\)\s+)?start="(.*)"\s+end="(.*)"`)

			var syntaxRegex *regexp.Regexp
			var headerRegex *regexp.Regexp
			var filetype string
			var rules []SyntaxRule
			for lineNum, line := range lines {
				if strings.TrimSpace(line) == "" ||
					strings.TrimSpace(line)[0] == '#' {
					// Ignore this line
					continue
				}

				if strings.HasPrefix(line, "syntax") {
					syntaxMatches := syntaxParser.FindSubmatch([]byte(line))
					if len(syntaxMatches) == 3 {
						if syntaxRegex != nil {
							regexes := [2]*regexp.Regexp{syntaxRegex, headerRegex}
							syntaxFiles[regexes] = FileTypeRules{filetype, rules}
						}
						rules = rules[:0]

						filetype = string(syntaxMatches[1])
						extensions := JoinRule(string(syntaxMatches[2]))

						syntaxRegex, err = regexp.Compile(extensions)
						if err != nil {
							TermError(filename, lineNum, err.Error())
							continue
						}
					} else {
						TermError(filename, lineNum, "Syntax statement is not valid: "+line)
						continue
					}
				} else if strings.HasPrefix(line, "header") {
					headerMatches := headerParser.FindSubmatch([]byte(line))
					if len(headerMatches) == 2 {
						header := JoinRule(string(headerMatches[1]))

						headerRegex, err = regexp.Compile(header)
						if err != nil {
							TermError(filename, lineNum, "Regex error: "+err.Error())
							continue
						}
					} else {
						TermError(filename, lineNum, "Header statement is not valid: "+line)
						continue
					}
				} else {
					if ruleParser.MatchString(line) {
						submatch := ruleParser.FindSubmatch([]byte(line))
						var color string
						var regexStr string
						var flags string
						if len(submatch) == 4 {
							color = string(submatch[1])
							flags = string(submatch[2])
							regexStr = "(?" + flags + ")" + JoinRule(string(submatch[3]))
						} else if len(submatch) == 3 {
							color = string(submatch[1])
							regexStr = JoinRule(string(submatch[2]))
						} else {
							TermError(filename, lineNum, "Invalid statement: "+line)
						}
						regex, err := regexp.Compile(regexStr)
						if err != nil {
							TermError(filename, lineNum, err.Error())
							continue
						}

						st := tcell.StyleDefault
						if _, ok := colorscheme[color]; ok {
							st = colorscheme[color]
						} else {
							st = StringToStyle(color)
						}
						rules = append(rules, SyntaxRule{regex, flags, false, st})
					} else if ruleStartEndParser.MatchString(line) {
						submatch := ruleStartEndParser.FindSubmatch([]byte(line))
						var color string
						var start string
						var end string
						// Use m and s flags by default
						flags := "ms"
						if len(submatch) == 5 {
							color = string(submatch[1])
							flags += string(submatch[2])
							start = string(submatch[3])
							end = string(submatch[4])
						} else if len(submatch) == 4 {
							color = string(submatch[1])
							start = string(submatch[2])
							end = string(submatch[3])
						} else {
							TermError(filename, lineNum, "Invalid statement: "+line)
						}

						regex, err := regexp.Compile("(?" + flags + ")" + "(" + start + ").*?(" + end + ")")
						if err != nil {
							TermError(filename, lineNum, err.Error())
							continue
						}

						st := tcell.StyleDefault
						if _, ok := colorscheme[color]; ok {
							st = colorscheme[color]
						} else {
							st = StringToStyle(color)
						}
						rules = append(rules, SyntaxRule{regex, flags, true, st})
					}
				}
			}
			if syntaxRegex != nil {
				regexes := [2]*regexp.Regexp{syntaxRegex, headerRegex}
				syntaxFiles[regexes] = FileTypeRules{filetype, rules}
			}
		}
	}
}

// GetRules finds the syntax rules that should be used for the buffer
// and returns them. It also returns the filetype of the file
func GetRules(buf *Buffer) ([]SyntaxRule, string) {
	for r := range syntaxFiles {
		if r[0] != nil && r[0].MatchString(buf.path) {
			return syntaxFiles[r].rules, syntaxFiles[r].filetype
		} else if r[1] != nil && r[1].MatchString(buf.lines[0]) {
			return syntaxFiles[r].rules, syntaxFiles[r].filetype
		}
	}
	return nil, "Unknown"
}

// SyntaxMatches is an alias to a map from character numbers to styles,
// so map[3] represents the style of the third character
type SyntaxMatches [][]tcell.Style

// Match takes a buffer and returns the syntax matches a map specifying how it should be syntax highlighted
func Match(v *View) SyntaxMatches {
	buf := v.buf
	rules := v.buf.rules

	viewStart := v.topline
	viewEnd := v.topline + v.height
	if viewEnd > len(buf.lines) {
		viewEnd = len(buf.lines)
	}

	lines := buf.lines[viewStart:viewEnd]
	matches := make(SyntaxMatches, len(lines))

	for i, line := range lines {
		matches[i] = make([]tcell.Style, len(line))
	}

	totalStart := v.topline - synLinesUp
	totalEnd := v.topline + v.height + synLinesDown
	if totalStart < 0 {
		totalStart = 0
	}
	if totalEnd > len(buf.lines) {
		totalEnd = len(buf.lines)
	}

	str := strings.Join(buf.lines[totalStart:totalEnd], "\n")
	startNum := v.cursor.loc + v.cursor.Distance(0, totalStart)

	for _, rule := range rules {
		if rule.startend {
			if rule.regex.MatchString(str) {
				indicies := rule.regex.FindAllStringIndex(str, -1)
				for _, value := range indicies {
					value[0] += startNum
					value[1] += startNum
					for i := value[0]; i < value[1]; i++ {
						colNum, lineNum := GetPos(i, buf)
						if lineNum == -1 || colNum == -1 {
							continue
						}
						lineNum -= viewStart
						if lineNum >= 0 && lineNum < v.height {
							if lineNum >= len(matches) {
								v.m.Error("Line " + strconv.Itoa(lineNum))
							} else if colNum >= len(matches[lineNum]) {
								v.m.Error("Line " + strconv.Itoa(lineNum) + " Col " + strconv.Itoa(colNum) + " " + strconv.Itoa(len(matches[lineNum])))
							}
							matches[lineNum][colNum] = rule.style
						}
					}
				}
			}
		} else {
			for lineN, line := range lines {
				if rule.regex.MatchString(line) {
					indicies := rule.regex.FindAllStringIndex(line, -1)
					for _, value := range indicies {
						for i := value[0]; i < value[1]; i++ {
							matches[lineN][i] = rule.style
						}
					}
				}
			}
		}
	}

	return matches
}

// GetPos returns an x, y position given a character location in the buffer
func GetPos(loc int, buf *Buffer) (int, int) {
	charNum := 0
	x, y := 0, 0

	for i, line := range buf.lines {
		if charNum+Count(line) > loc {
			y = i
			x = loc - charNum
			return x, y
		}
		charNum += Count(line) + 1
	}

	return -1, -1
}
<commit_msg>Small optimization<commit_after>package main

import (
	"github.com/gdamore/tcell"
	"github.com/mitchellh/go-homedir"
	"io/ioutil"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"
)

// FileTypeRules represents a complete set of syntax rules for a filetype
type FileTypeRules struct {
	filetype string
	rules    []SyntaxRule
}

// SyntaxRule represents a regex to highlight in a certain style
type SyntaxRule struct {
	// What to highlight
	regex *regexp.Regexp
	// Any flags
	flags string
	// Whether this regex is a start=... end=... regex
	startend bool
	// How to highlight it
	style tcell.Style
}

var syntaxFiles map[[2]*regexp.Regexp]FileTypeRules

// LoadSyntaxFiles loads the syntax files from the default directory ~/.micro
func LoadSyntaxFiles() {
	dir, err := homedir.Dir()
	if err != nil {
		TermMessage("Error finding your home directory\nCan't load runtime files")
		return
	}
	LoadSyntaxFilesFromDir(dir + "/.micro/syntax")
}

// JoinRule takes a syntax rule (which can be multiple regular expressions)
// and joins it into one regular expression by ORing everything together
func JoinRule(rule string) string {
	split := strings.Split(rule, `" "`)
	joined := strings.Join(split, ")|(")
	joined = "(" + joined + ")"
	return joined
}

// LoadSyntaxFilesFromDir loads the syntax files from a specified directory
// To load the syntax files, we must fill the `syntaxFiles` map
// This involves finding the regex for syntax and if it exists, the regex
// for the header. Then we must get the text for the file and the filetype.
func LoadSyntaxFilesFromDir(dir string) {
	InitColorscheme()

	syntaxFiles = make(map[[2]*regexp.Regexp]FileTypeRules)
	files, _ := ioutil.ReadDir(dir)
	for _, f := range files {
		if filepath.Ext(f.Name()) == ".micro" {
			text, err := ioutil.ReadFile(dir + "/" + f.Name())
			filename := dir + "/" + f.Name()

			if err != nil {
				TermMessage("Error loading syntax files: " + err.Error())
				continue
			}
			lines := strings.Split(string(text), "\n")

			syntaxParser := regexp.MustCompile(`syntax "(.*?)"\s+"(.*)"+`)
			headerParser := regexp.MustCompile(`header "(.*)"`)

			ruleParser := regexp.MustCompile(`color (.*?)\s+(?:\((.*?)\)\s+)?"(.*)"`)
			ruleStartEndParser := regexp.MustCompile(`color (.*?)\s+(?:\((.*?)\)\s+)?start="(.*)"\s+end="(.*)"`)

			var syntaxRegex *regexp.Regexp
			var headerRegex *regexp.Regexp
			var filetype string
			var rules []SyntaxRule
			for lineNum, line := range lines {
				if strings.TrimSpace(line) == "" ||
					strings.TrimSpace(line)[0] == '#' {
					// Ignore this line
					continue
				}

				if strings.HasPrefix(line, "syntax") {
					syntaxMatches := syntaxParser.FindSubmatch([]byte(line))
					if len(syntaxMatches) == 3 {
						if syntaxRegex != nil {
							regexes := [2]*regexp.Regexp{syntaxRegex, headerRegex}
							syntaxFiles[regexes] = FileTypeRules{filetype, rules}
						}
						rules = rules[:0]

						filetype = string(syntaxMatches[1])
						extensions := JoinRule(string(syntaxMatches[2]))

						syntaxRegex, err = regexp.Compile(extensions)
						if err != nil {
							TermError(filename, lineNum, err.Error())
							continue
						}
					} else {
						TermError(filename, lineNum, "Syntax statement is not valid: "+line)
						continue
					}
				} else if strings.HasPrefix(line, "header") {
					headerMatches := headerParser.FindSubmatch([]byte(line))
					if len(headerMatches) == 2 {
						header := JoinRule(string(headerMatches[1]))

						headerRegex, err = regexp.Compile(header)
						if err != nil {
							TermError(filename, lineNum, "Regex error: "+err.Error())
							continue
						}
					} else {
						TermError(filename, lineNum, "Header statement is not valid: "+line)
						continue
					}
				} else {
					if ruleParser.MatchString(line) {
						submatch := ruleParser.FindSubmatch([]byte(line))
						var color string
						var regexStr string
						var flags string
						if len(submatch) == 4 {
							color = string(submatch[1])
							flags = string(submatch[2])
							regexStr = "(?" + flags + ")" + JoinRule(string(submatch[3]))
						} else if len(submatch) == 3 {
							color = string(submatch[1])
							regexStr = JoinRule(string(submatch[2]))
						} else {
							TermError(filename, lineNum, "Invalid statement: "+line)
						}
						regex, err := regexp.Compile(regexStr)
						if err != nil {
							TermError(filename, lineNum, err.Error())
							continue
						}

						st := tcell.StyleDefault
						if _, ok := colorscheme[color]; ok {
							st = colorscheme[color]
						} else {
							st = StringToStyle(color)
						}
						rules = append(rules, SyntaxRule{regex, flags, false, st})
					} else if ruleStartEndParser.MatchString(line) {
						submatch := ruleStartEndParser.FindSubmatch([]byte(line))
						var color string
						var start string
						var end string
						// Use m and s flags by default
						flags := "ms"
						if len(submatch) == 5 {
							color = string(submatch[1])
							flags += string(submatch[2])
							start = string(submatch[3])
							end = string(submatch[4])
						} else if len(submatch) == 4 {
							color = string(submatch[1])
							start = string(submatch[2])
							end = string(submatch[3])
						} else {
							TermError(filename, lineNum, "Invalid statement: "+line)
						}

						regex, err := regexp.Compile("(?" + flags + ")" + "(" + start + ").*?(" + end + ")")
						if err != nil {
							TermError(filename, lineNum, err.Error())
							continue
						}

						st := tcell.StyleDefault
						if _, ok := colorscheme[color]; ok {
							st = colorscheme[color]
						} else {
							st = StringToStyle(color)
						}
						rules = append(rules, SyntaxRule{regex, flags, true, st})
					}
				}
			}
			if syntaxRegex != nil {
				regexes := [2]*regexp.Regexp{syntaxRegex, headerRegex}
				syntaxFiles[regexes] = FileTypeRules{filetype, rules}
			}
		}
	}
}

// GetRules finds the syntax rules that should be used for the buffer
// and returns them. It also returns the filetype of the file
func GetRules(buf *Buffer) ([]SyntaxRule, string) {
	for r := range syntaxFiles {
		if r[0] != nil && r[0].MatchString(buf.path) {
			return syntaxFiles[r].rules, syntaxFiles[r].filetype
		} else if r[1] != nil && r[1].MatchString(buf.lines[0]) {
			return syntaxFiles[r].rules, syntaxFiles[r].filetype
		}
	}
	return nil, "Unknown"
}

// SyntaxMatches is an alias to a map from character numbers to styles,
// so map[3] represents the style of the third character
type SyntaxMatches [][]tcell.Style

// Match takes a buffer and returns the syntax matches a map specifying how it should be syntax highlighted
func Match(v *View) SyntaxMatches {
	buf := v.buf
	rules := v.buf.rules

	viewStart := v.topline
	viewEnd := v.topline + v.height
	if viewEnd > len(buf.lines) {
		viewEnd = len(buf.lines)
	}

	lines := buf.lines[viewStart:viewEnd]
	matches := make(SyntaxMatches, len(lines))

	for i, line := range lines {
		matches[i] = make([]tcell.Style, len(line))
	}

	totalStart := v.topline - synLinesUp
	totalEnd := v.topline + v.height + synLinesDown
	if totalStart < 0 {
		totalStart = 0
	}
	if totalEnd > len(buf.lines) {
		totalEnd = len(buf.lines)
	}

	str := strings.Join(buf.lines[totalStart:totalEnd], "\n")
	startNum := v.cursor.loc + v.cursor.Distance(0, totalStart)

	for _, rule := range rules {
		if rule.startend {
			if rule.regex.MatchString(str) {
				indicies := rule.regex.FindAllStringIndex(str, -1)
				for _, value := range indicies {
					value[0] += startNum
					value[1] += startNum
					for i := value[0]; i < value[1]; i++ {
						colNum, lineNum := GetPos(startNum, totalStart, i, buf)
						if lineNum == -1 || colNum == -1 {
							continue
						}
						lineNum -= viewStart
						if lineNum >= 0 && lineNum < v.height {
							if lineNum >= len(matches) {
								v.m.Error("Line " + strconv.Itoa(lineNum))
							} else if colNum >= len(matches[lineNum]) {
								v.m.Error("Line " + strconv.Itoa(lineNum) + " Col " + strconv.Itoa(colNum) + " " + strconv.Itoa(len(matches[lineNum])))
							}
							matches[lineNum][colNum] = rule.style
						}
					}
				}
			}
		} else {
			for lineN, line := range lines {
				if rule.regex.MatchString(line) {
					indicies := rule.regex.FindAllStringIndex(line, -1)
					for _, value := range indicies {
						for i := value[0]; i < value[1]; i++ {
							matches[lineN][i] = rule.style
						}
					}
				}
			}
		}
	}

	return matches
}

// GetPos returns an x, y position given a character location in the buffer
func GetPos(startLoc, startLine, loc int, buf *Buffer) (int, int) {
	charNum := startLoc
	x, y := 0, startLine

	for i, line := range buf.lines {
		if charNum+Count(line) > loc {
			y = i
			x = loc - charNum
			return x, y
		}
		charNum += Count(line) + 1
	}

	return -1, -1
}
<|endoftext|>


<commit_before>package dockerproxy

import (
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/fsouza/go-dockerclient"
	"golang.org/x/net/context"
)

var containerListOptions = docker.ListContainersOptions{
	Size:    false,
	Filters: map[string][]string{"status": []string{"running"}},
}

func (m *Manager) updater(ctx context.Context) {
	listener := debounceChannel(3*time.Second, m.update)
	for {
		select {
		case _, ok := <-listener:
			if !ok {
				return
			}
			t := time.Now()
			log.Info("updating containers")
			if err := m.updateContainers(); err != nil {
				log.WithError(err).Error("unable to update container mappings")
			}
			log.WithField("duration", time.Since(t)).Info("updated containers")
		case <-ctx.Done():
			return
		}
	}
}

func (m *Manager) updateContainers() error {
	client, err := m.newClient(m.d.Leader, 0)
	if err != nil {
		return err
	}

	containers, err := client.ListContainers(containerListOptions)
	if err != nil {
		return err
	}

	mapping, err := mapContainers(client, containers)
	if err != nil {
		return err
	}

	for _, v := range m.notify {
		if err := v.Update(mapping); err != nil {
			log.WithError(err).WithField("notifier", v.Name()).Error("unable to update mapping")
		}
	}

	return nil
}

// debounceChannel takes an input channel which may be noisy, and makes sure that the returned
// channel only gets called after `interval` time without being called.
func debounceChannel(interval time.Duration, input chan struct{}) chan struct{} {
	output := make(chan struct{})
	go func() {
		for {
			_, ok := <-input
			if !ok {
				close(output)
				return
			}
			select {
			case <-input:
			case <-time.After(interval):
				output <- struct{}{}
			}
		}
	}()
	return output
}
<commit_msg>updater: fix debounce to not hang<commit_after>package dockerproxy

import (
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/fsouza/go-dockerclient"
	"golang.org/x/net/context"
)

var containerListOptions = docker.ListContainersOptions{
	Size:    false,
	Filters: map[string][]string{"status": []string{"running"}},
}

func (m *Manager) updater(ctx context.Context) {
	listener := debounceChannel(3*time.Second, m.update)
	for {
		select {
		case _, ok := <-listener:
			if !ok {
				return
			}
			t := time.Now()
			log.Info("updating containers")
			if err := m.updateContainers(); err != nil {
				log.WithError(err).Error("unable to update container mappings")
			}
			log.WithField("duration", time.Since(t)).Info("updated containers")
		case <-ctx.Done():
			return
		}
	}
}

func (m *Manager) updateContainers() error {
	client, err := m.newClient(m.d.Leader, 0)
	if err != nil {
		return err
	}

	containers, err := client.ListContainers(containerListOptions)
	if err != nil {
		return err
	}

	mapping, err := mapContainers(client, containers)
	if err != nil {
		return err
	}

	for _, v := range m.notify {
		if err := v.Update(mapping); err != nil {
			log.WithError(err).WithField("notifier", v.Name()).Error("unable to update mapping")
		}
	}

	return nil
}

// debounceChannel takes an input channel which may be noisy, and makes sure that the returned
// channel only gets called after `interval` time without being called.
func debounceChannel(interval time.Duration, input chan struct{}) chan struct{} {
	output := make(chan struct{})
	go func() {
		for {
			_, ok := <-input
			if !ok {
				close(output)
				return
			}
		Triggered:
			for {
				select {
				case <-input:
				case <-time.After(interval):
					log.Info("debounce triggered, updating")
					output <- struct{}{}
					break Triggered
				}
			}
		}
	}()
	return output
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"github.com/pelletier/go-toml"
	//"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"strings"
	"text/template"
)

type config struct {
	emails      []string
	mailBinPath string
	ikachanUrl  string
	channel     string
}

type consulAlert struct {
	Timestamp string
	Node      string
	ServiceId string
	Service   string
	CheckId   string
	Check     string
	Status    string
	Output    string
	Notes     string
}

func (c *consulAlert) TrimmedOutput() string {
	return strings.TrimSpace(c.Output)
}

func (c *consulAlert) StatusString() string {
	status := strings.ToUpper(c.Status)
	switch c.Status {
	case "passing":
		return colorMsg(status, cGreen, cNone)
	case "critical":
		return colorMsg(status, cBlack, cRed)
	default:
		return colorMsg(status, cYellow, cNone)
	}
}

func (c *consulAlert) NodeString() string {
	return setIrcMode(ircUnderline) + c.Node + setIrcMode(ircCReset)
}

const (
	version = "0.0.1"
)

var (
	ircBodyTemplate = setIrcMode(ircBold) +
		"*** {{.Service}}({{.CheckId}}) is now {{.StatusString}}" +
		setIrcMode(ircBold) +
		" on {{.NodeString}}" +
		" - {{.TrimmedOutput}}"

	mailTitleTemplate = "Check {{.CheckId}} is now {{.Status}} on {{.Node}}"
	mailBodyTemplate  = `
{{.Service}}({{.CheckId}}) is now {{.Status}}
On node {{.Node}}

Output is:
  {{.TrimmedOutput}}
`

	logger = log.New(os.Stdout, "[consul-simple-notifier] ", log.LstdFlags)
)

func main() {
	var (
		justShowVersion bool
		configPath      string
		conf            config
		input           []consulAlert
	)

	flag.BoolVar(&justShowVersion, "v", false, "Show version")
	flag.BoolVar(&justShowVersion, "version", false, "Show version")

	flag.StringVar(&configPath, "c", "/etc/consul-simple-notifier.ini", "Config path")
	flag.Parse()

	if justShowVersion {
		showVersion()
		return
	}

	parsed, err := toml.LoadFile(configPath)
	if err != nil {
		panic(err.Error())
	}

	binPath := parsed.Get("email.binpath")
	if binPath == nil {
		conf.mailBinPath = "/bin/mail"
	} else {
		conf.mailBinPath = binPath.(string)
	}

	recipients := parsed.Get("email.recipients")
	for _, address := range recipients.([]interface{}) {
		conf.emails = append(conf.emails, address.(string))
	}

	conf.ikachanUrl = parsed.Get("ikachan.url").(string)
	conf.channel = parsed.Get("ikachan.channel").(string)
	logger.Printf("conf is: %+v\n", conf)

	err = json.NewDecoder(os.Stdin).Decode(&input)
	if err != nil {
		panic(err.Error())
	}
	logger.Printf("input json is: %+v\n", input)

	for _, content := range input {
		err := notifyEmail(conf.mailBinPath, conf.emails, content)
		if err != nil {
			panic(err)
		}
		err = notifyIkachan(conf.ikachanUrl, conf.channel, content)
		if err != nil {
			panic(err)
		}
	}
}

func notifyEmail(mainBinPath string, recipients []string, content consulAlert) error {
	for _, address := range recipients {
		var titleBuf, bodyBuf bytes.Buffer
		titleTmpl := template.Must(template.New("emailTitle").Parse(mailTitleTemplate))
		bodyTmpl := template.Must(template.New("emailBody").Parse(mailBodyTemplate))
		err := titleTmpl.Execute(&titleBuf, &content)
		err = bodyTmpl.Execute(&bodyBuf, &content)
		if err != nil {
			return err
		}
		title := titleBuf.String()

		logger.Printf("Sending... %s to %s\n", title, address)
		cmd := exec.Command(mainBinPath, "-s", title, address)
		stdin, err := cmd.StdinPipe()
		if err != nil {
			return err
		}

		if err := cmd.Start(); err != nil {
			return err
		}

		fmt.Fprint(stdin, bodyBuf.String())
		stdin.Close()
		logger.Printf("Send!\n")
		cmd.Wait()
	}
	return nil
}

func notifyIkachan(ikachanUrl string, channel string, content consulAlert) error {
	joinUrl := fmt.Sprintf("%s/join", ikachanUrl)
	noticeUrl := fmt.Sprintf("%s/notice", ikachanUrl)

	values := make(url.Values)
	values.Set("channel", channel)

	resp1, err := http.PostForm(joinUrl, values)
	if err != nil {
		return err
	}
	defer resp1.Body.Close()

	var bodyBuf bytes.Buffer
	bodyTmpl := template.Must(template.New("ircBody").Parse(ircBodyTemplate))
	err = bodyTmpl.Execute(&bodyBuf, &content)
	if err != nil {
		return err
	}
	body := bodyBuf.String()

	values.Set("message", body)

	logger.Printf("Posted! %+v", values)
	resp2, err := http.PostForm(noticeUrl, values)
	if err != nil {
		return err
	}
	defer resp2.Body.Close()

	return nil
}

func showVersion() {
	fmt.Printf("consul-simple-notifier version: %s\n", version)
}
<commit_msg>Use goroutine to send messages<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"github.com/pelletier/go-toml"
	//"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"strings"
	"sync"
	"text/template"
)

type config struct {
	emails      []string
	mailBinPath string
	ikachanUrl  string
	channel     string
}

type consulAlert struct {
	Timestamp string
	Node      string
	ServiceId string
	Service   string
	CheckId   string
	Check     string
	Status    string
	Output    string
	Notes     string
}

func (c *consulAlert) TrimmedOutput() string {
	return strings.TrimSpace(c.Output)
}

func (c *consulAlert) StatusString() string {
	status := strings.ToUpper(c.Status)
	switch c.Status {
	case "passing":
		return colorMsg(status, cGreen, cNone)
	case "critical":
		return colorMsg(status, cBlack, cRed)
	default:
		return colorMsg(status, cYellow, cNone)
	}
}

func (c *consulAlert) NodeString() string {
	return setIrcMode(ircUnderline) + c.Node + setIrcMode(ircCReset)
}

const (
	version = "0.0.1"
)

var (
	ircBodyTemplate = setIrcMode(ircBold) +
		"*** {{.Service}}({{.CheckId}}) is now {{.StatusString}}" +
		setIrcMode(ircBold) +
		" on {{.NodeString}}" +
		" - {{.TrimmedOutput}}"

	mailTitleTemplate = "Check {{.CheckId}} is now {{.Status}} on {{.Node}}"
	mailBodyTemplate  = `
{{.Service}}({{.CheckId}}) is now {{.Status}}
On node {{.Node}}

Output is:
  {{.TrimmedOutput}}
`

	logger = log.New(os.Stdout, "[consul-simple-notifier] ", log.LstdFlags)
)

func main() {
	var (
		justShowVersion bool
		configPath      string
		conf            config
		input           []consulAlert
	)

	flag.BoolVar(&justShowVersion, "v", false, "Show version")
	flag.BoolVar(&justShowVersion, "version", false, "Show version")

	flag.StringVar(&configPath, "c", "/etc/consul-simple-notifier.ini", "Config path")
	flag.Parse()

	if justShowVersion {
		showVersion()
		return
	}

	parsed, err := toml.LoadFile(configPath)
	if err != nil {
		panic(err.Error())
	}

	binPath := parsed.Get("email.binpath")
	if binPath == nil {
		conf.mailBinPath = "/bin/mail"
	} else {
		conf.mailBinPath = binPath.(string)
	}

	recipients := parsed.Get("email.recipients")
	for _, address := range recipients.([]interface{}) {
		conf.emails = append(conf.emails, address.(string))
	}

	conf.ikachanUrl = parsed.Get("ikachan.url").(string)
	conf.channel = parsed.Get("ikachan.channel").(string)
	logger.Printf("conf is: %+v\n", conf)

	err = json.NewDecoder(os.Stdin).Decode(&input)
	if err != nil {
		panic(err.Error())
	}
	logger.Printf("input json is: %+v\n", input)

	for _, content := range input {
		var wg sync.WaitGroup
		wg.Add((len(conf.emails) + 1))

		go func(_wg *sync.WaitGroup, _content *consulAlert) {
			for _, address := range conf.emails {
				err := notifyEmail(conf.mailBinPath, address, _content, _wg)
				if err != nil {
					panic(err)
				}
			}
		}(&wg, &content)
		go func(_wg *sync.WaitGroup, _content *consulAlert) {
			err = notifyIkachan(conf.ikachanUrl, conf.channel, _content, _wg)
			if err != nil {
				panic(err)
			}
		}(&wg, &content)
		wg.Wait()
	}
}

func notifyEmail(mainBinPath, address string, content *consulAlert, wg *sync.WaitGroup) error {
	var titleBuf, bodyBuf bytes.Buffer
	titleTmpl := template.Must(template.New("emailTitle").Parse(mailTitleTemplate))
	bodyTmpl := template.Must(template.New("emailBody").Parse(mailBodyTemplate))
	err := titleTmpl.Execute(&titleBuf, &content)
	err = bodyTmpl.Execute(&bodyBuf, &content)
	if err != nil {
		return err
	}
	title := titleBuf.String()

	logger.Printf("Sending... %s to %s\n", title, address)
	cmd := exec.Command(mainBinPath, "-s", title, address)
	stdin, err := cmd.StdinPipe()
	if err != nil {
		return err
	}

	if err := cmd.Start(); err != nil {
		return err
	}

	fmt.Fprint(stdin, bodyBuf.String())
	stdin.Close()
	logger.Printf("Send!\n")
	cmd.Wait()
	wg.Done()
	return nil
}

func notifyIkachan(ikachanUrl string, channel string, content *consulAlert, wg *sync.WaitGroup) error {
	joinUrl := fmt.Sprintf("%s/join", ikachanUrl)
	noticeUrl := fmt.Sprintf("%s/notice", ikachanUrl)

	values := make(url.Values)
	values.Set("channel", channel)

	resp1, err := http.PostForm(joinUrl, values)
	if err != nil {
		return err
	}
	defer resp1.Body.Close()

	var bodyBuf bytes.Buffer
	bodyTmpl := template.Must(template.New("ircBody").Parse(ircBodyTemplate))
	err = bodyTmpl.Execute(&bodyBuf, &content)
	if err != nil {
		return err
	}
	body := bodyBuf.String()

	values.Set("message", body)

	logger.Printf("Posted! %+v", values)
	resp2, err := http.PostForm(noticeUrl, values)
	if err != nil {
		return err
	}
	defer resp2.Body.Close()

	wg.Done()
	return nil
}

func showVersion() {
	fmt.Printf("consul-simple-notifier version: %s\n", version)
}
<|endoftext|>


<commit_before>// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Handler for CRI-O containers.
package crio

import (
	"fmt"
	"path"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/google/cadvisor/container"
	"github.com/google/cadvisor/container/common"
	containerlibcontainer "github.com/google/cadvisor/container/libcontainer"
	"github.com/google/cadvisor/fs"
	info "github.com/google/cadvisor/info/v1"

	cgroupfs "github.com/opencontainers/runc/libcontainer/cgroups/fs"
	libcontainerconfigs "github.com/opencontainers/runc/libcontainer/configs"
)

type crioContainerHandler struct {
	machineInfoFactory info.MachineInfoFactory

	// Absolute path to the cgroup hierarchies of this container.
	// (e.g.: "cpu" -> "/sys/fs/cgroup/cpu/test")
	cgroupPaths map[string]string

	// the CRI-O storage driver
	storageDriver    storageDriver
	fsInfo           fs.FsInfo
	rootfsStorageDir string

	// Metadata associated with the container.
	envs   map[string]string
	labels map[string]string

	// TODO
	// crio version handling...

	// Image name used for this container.
	image string

	// The network mode of the container
	// TODO

	// Filesystem handler.
	fsHandler common.FsHandler

	// The IP address of the container
	ipAddress string

	includedMetrics container.MetricSet

	reference info.ContainerReference

	libcontainerHandler *containerlibcontainer.Handler
}

var _ container.ContainerHandler = &crioContainerHandler{}

// newCrioContainerHandler returns a new container.ContainerHandler
func newCrioContainerHandler(
	client crioClient,
	name string,
	machineInfoFactory info.MachineInfoFactory,
	fsInfo fs.FsInfo,
	storageDriver storageDriver,
	storageDir string,
	cgroupSubsystems *containerlibcontainer.CgroupSubsystems,
	inHostNamespace bool,
	metadataEnvs []string,
	includedMetrics container.MetricSet,
) (container.ContainerHandler, error) {
	// Create the cgroup paths.
	cgroupPaths := common.MakeCgroupPaths(cgroupSubsystems.MountPoints, name)

	// Generate the equivalent cgroup manager for this container.
	cgroupManager := &cgroupfs.Manager{
		Cgroups: &libcontainerconfigs.Cgroup{
			Name: name,
		},
		Paths: cgroupPaths,
	}

	rootFs := "/"
	if !inHostNamespace {
		rootFs = "/rootfs"
		storageDir = path.Join(rootFs, storageDir)
	}

	id := ContainerNameToCrioId(name)

	cInfo, err := client.ContainerInfo(id)
	if err != nil {
		return nil, err
	}

	// passed to fs handler below ...
	// XXX: this is using the full container logpath, as constructed by the CRI
	// /var/log/pods/<pod_uuid>/container_instance.log
	// It's not actually a log dir, as the CRI doesn't have per-container dirs
	// under /var/log/pods/<pod_uuid>/
	// We can't use /var/log/pods/<pod_uuid>/ to count per-container log usage.
	// We use the container log file directly.
	storageLogDir := cInfo.LogPath

	// Determine the rootfs storage dir
	rootfsStorageDir := cInfo.Root
	// TODO(runcom): CRI-O doesn't strip /merged but we need to in order to
	// get device ID from root, otherwise, it's going to error out as overlay
	// mounts doesn't have fixed dev ids.
	rootfsStorageDir = strings.TrimSuffix(rootfsStorageDir, "/merged")
	switch storageDriver {
	case overlayStorageDriver, overlay2StorageDriver:
		// overlay and overlay2 driver are the same "overlay2" driver so treat
		// them the same.
		rootfsStorageDir = filepath.Join(rootfsStorageDir, "diff")
	}

	containerReference := info.ContainerReference{
		Id:        id,
		Name:      name,
		Aliases:   []string{cInfo.Name, id},
		Namespace: CrioNamespace,
	}

	libcontainerHandler := containerlibcontainer.NewHandler(cgroupManager, rootFs, cInfo.Pid, includedMetrics)

	// TODO: extract object mother method
	handler := &crioContainerHandler{
		machineInfoFactory:  machineInfoFactory,
		cgroupPaths:         cgroupPaths,
		storageDriver:       storageDriver,
		fsInfo:              fsInfo,
		rootfsStorageDir:    rootfsStorageDir,
		envs:                make(map[string]string),
		labels:              cInfo.Labels,
		includedMetrics:     includedMetrics,
		reference:           containerReference,
		libcontainerHandler: libcontainerHandler,
	}

	handler.image = cInfo.Image
	// TODO: we wantd to know graph driver DeviceId (dont think this is needed now)

	// ignore err and get zero as default, this happens with sandboxes, not sure why...
	// kube isn't sending restart count in labels for sandboxes.
	restartCount, _ := strconv.Atoi(cInfo.Annotations["io.kubernetes.container.restartCount"])
	// Only adds restartcount label if it's greater than 0
	if restartCount > 0 {
		handler.labels["restartcount"] = strconv.Itoa(restartCount)
	}

	handler.ipAddress = cInfo.IP

	// we optionally collect disk usage metrics
	if includedMetrics.Has(container.DiskUsageMetrics) {
		handler.fsHandler = common.NewFsHandler(common.DefaultPeriod, rootfsStorageDir, storageLogDir, fsInfo)
	}
	// TODO for env vars we wanted to show from container.Config.Env from whitelist
	//for _, exposedEnv := range metadataEnvs {
	//klog.V(4).Infof("TODO env whitelist: %v", exposedEnv)
	//}

	return handler, nil
}

func (self *crioContainerHandler) Start() {
	if self.fsHandler != nil {
		self.fsHandler.Start()
	}
}

func (self *crioContainerHandler) Cleanup() {
	if self.fsHandler != nil {
		self.fsHandler.Stop()
	}
}

func (self *crioContainerHandler) ContainerReference() (info.ContainerReference, error) {
	return self.reference, nil
}

func (self *crioContainerHandler) needNet() bool {
	if self.includedMetrics.Has(container.NetworkUsageMetrics) {
		return self.labels["io.kubernetes.container.name"] == "POD"
	}
	return false
}

func (self *crioContainerHandler) GetSpec() (info.ContainerSpec, error) {
	hasFilesystem := self.includedMetrics.Has(container.DiskUsageMetrics)
	spec, err := common.GetSpec(self.cgroupPaths, self.machineInfoFactory, self.needNet(), hasFilesystem)

	spec.Labels = self.labels
	spec.Envs = self.envs
	spec.Image = self.image

	return spec, err
}

func (self *crioContainerHandler) getFsStats(stats *info.ContainerStats) error {
	mi, err := self.machineInfoFactory.GetMachineInfo()
	if err != nil {
		return err
	}

	if self.includedMetrics.Has(container.DiskIOMetrics) {
		common.AssignDeviceNamesToDiskStats((*common.MachineInfoNamer)(mi), &stats.DiskIo)
	}

	if !self.includedMetrics.Has(container.DiskUsageMetrics) {
		return nil
	}
	var device string
	switch self.storageDriver {
	case overlay2StorageDriver, overlayStorageDriver:
		deviceInfo, err := self.fsInfo.GetDirFsDevice(self.rootfsStorageDir)
		if err != nil {
			return fmt.Errorf("unable to determine device info for dir: %v: %v", self.rootfsStorageDir, err)
		}
		device = deviceInfo.Device
	default:
		return nil
	}

	var (
		limit  uint64
		fsType string
	)

	// crio does not impose any filesystem limits for containers. So use capacity as limit.
	for _, fs := range mi.Filesystems {
		if fs.Device == device {
			limit = fs.Capacity
			fsType = fs.Type
			break
		}
	}

	fsStat := info.FsStats{Device: device, Type: fsType, Limit: limit}
	usage := self.fsHandler.Usage()
	fsStat.BaseUsage = usage.BaseUsageBytes
	fsStat.Usage = usage.TotalUsageBytes
	fsStat.Inodes = usage.InodeUsage

	stats.Filesystem = append(stats.Filesystem, fsStat)

	return nil
}

func (self *crioContainerHandler) GetStats() (*info.ContainerStats, error) {
	stats, err := self.libcontainerHandler.GetStats()
	if err != nil {
		return stats, err
	}
	// Clean up stats for containers that don't have their own network - this
	// includes containers running in Kubernetes pods that use the network of the
	// infrastructure container. This stops metrics being reported multiple times
	// for each container in a pod.
	if !self.needNet() {
		stats.Network = info.NetworkStats{}
	}

	// Get filesystem stats.
	err = self.getFsStats(stats)
	if err != nil {
		return stats, err
	}

	return stats, nil
}

func (self *crioContainerHandler) ListContainers(listType container.ListType) ([]info.ContainerReference, error) {
	// No-op for Docker driver.
	return []info.ContainerReference{}, nil
}

func (self *crioContainerHandler) GetCgroupPath(resource string) (string, error) {
	path, ok := self.cgroupPaths[resource]
	if !ok {
		return "", fmt.Errorf("could not find path for resource %q for container %q\n", resource, self.reference.Name)
	}
	return path, nil
}

func (self *crioContainerHandler) GetContainerLabels() map[string]string {
	return self.labels
}

func (self *crioContainerHandler) GetContainerIPAddress() string {
	return self.ipAddress
}

func (self *crioContainerHandler) ListProcesses(listType container.ListType) ([]int, error) {
	return self.libcontainerHandler.GetProcesses()
}

func (self *crioContainerHandler) Exists() bool {
	return common.CgroupExists(self.cgroupPaths)
}

func (self *crioContainerHandler) Type() container.ContainerType {
	return container.ContainerTypeCrio
}
<commit_msg>container/crio: retry getting pid if 0<commit_after>// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Handler for CRI-O containers.
package crio

import (
	"fmt"
	"path"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/google/cadvisor/container"
	"github.com/google/cadvisor/container/common"
	containerlibcontainer "github.com/google/cadvisor/container/libcontainer"
	"github.com/google/cadvisor/fs"
	info "github.com/google/cadvisor/info/v1"

	cgroupfs "github.com/opencontainers/runc/libcontainer/cgroups/fs"
	libcontainerconfigs "github.com/opencontainers/runc/libcontainer/configs"
)

type crioContainerHandler struct {
	client crioClient
	name   string

	machineInfoFactory info.MachineInfoFactory

	// Absolute path to the cgroup hierarchies of this container.
	// (e.g.: "cpu" -> "/sys/fs/cgroup/cpu/test")
	cgroupPaths map[string]string

	// the CRI-O storage driver
	storageDriver    storageDriver
	fsInfo           fs.FsInfo
	rootfsStorageDir string

	// Metadata associated with the container.
	envs   map[string]string
	labels map[string]string

	// TODO
	// crio version handling...

	// Image name used for this container.
	image string

	// The network mode of the container
	// TODO

	// Filesystem handler.
	fsHandler common.FsHandler

	// The IP address of the container
	ipAddress string

	includedMetrics container.MetricSet

	reference info.ContainerReference

	libcontainerHandler *containerlibcontainer.Handler
	cgroupManager       *cgroupfs.Manager
	rootFs              string
	pidKnown            bool
}

var _ container.ContainerHandler = &crioContainerHandler{}

// newCrioContainerHandler returns a new container.ContainerHandler
func newCrioContainerHandler(
	client crioClient,
	name string,
	machineInfoFactory info.MachineInfoFactory,
	fsInfo fs.FsInfo,
	storageDriver storageDriver,
	storageDir string,
	cgroupSubsystems *containerlibcontainer.CgroupSubsystems,
	inHostNamespace bool,
	metadataEnvs []string,
	includedMetrics container.MetricSet,
) (container.ContainerHandler, error) {
	// Create the cgroup paths.
	cgroupPaths := common.MakeCgroupPaths(cgroupSubsystems.MountPoints, name)

	// Generate the equivalent cgroup manager for this container.
	cgroupManager := &cgroupfs.Manager{
		Cgroups: &libcontainerconfigs.Cgroup{
			Name: name,
		},
		Paths: cgroupPaths,
	}

	rootFs := "/"
	if !inHostNamespace {
		rootFs = "/rootfs"
		storageDir = path.Join(rootFs, storageDir)
	}

	id := ContainerNameToCrioId(name)
	pidKnown := true

	cInfo, err := client.ContainerInfo(id)
	if err != nil {
		return nil, err
	}
	if cInfo.Pid == 0 {
		// If pid is not known yet, network related stats can not be retrieved by the
		// libcontainer handler GetStats().  In this case, the crio handler GetStats()
		// will reattempt to get the pid and, if now known, will construct the libcontainer
		// handler.  This libcontainer handler is then cached and reused without additional
		// calls to crio.
		pidKnown = false
	}

	// passed to fs handler below ...
	// XXX: this is using the full container logpath, as constructed by the CRI
	// /var/log/pods/<pod_uuid>/container_instance.log
	// It's not actually a log dir, as the CRI doesn't have per-container dirs
	// under /var/log/pods/<pod_uuid>/
	// We can't use /var/log/pods/<pod_uuid>/ to count per-container log usage.
	// We use the container log file directly.
	storageLogDir := cInfo.LogPath

	// Determine the rootfs storage dir
	rootfsStorageDir := cInfo.Root
	// TODO(runcom): CRI-O doesn't strip /merged but we need to in order to
	// get device ID from root, otherwise, it's going to error out as overlay
	// mounts doesn't have fixed dev ids.
	rootfsStorageDir = strings.TrimSuffix(rootfsStorageDir, "/merged")
	switch storageDriver {
	case overlayStorageDriver, overlay2StorageDriver:
		// overlay and overlay2 driver are the same "overlay2" driver so treat
		// them the same.
		rootfsStorageDir = filepath.Join(rootfsStorageDir, "diff")
	}

	containerReference := info.ContainerReference{
		Id:        id,
		Name:      name,
		Aliases:   []string{cInfo.Name, id},
		Namespace: CrioNamespace,
	}

	libcontainerHandler := containerlibcontainer.NewHandler(cgroupManager, rootFs, cInfo.Pid, includedMetrics)

	// TODO: extract object mother method
	handler := &crioContainerHandler{
		client:              client,
		name:                name,
		machineInfoFactory:  machineInfoFactory,
		cgroupPaths:         cgroupPaths,
		storageDriver:       storageDriver,
		fsInfo:              fsInfo,
		rootfsStorageDir:    rootfsStorageDir,
		envs:                make(map[string]string),
		labels:              cInfo.Labels,
		includedMetrics:     includedMetrics,
		reference:           containerReference,
		libcontainerHandler: libcontainerHandler,
		cgroupManager:       cgroupManager,
		rootFs:              rootFs,
		pidKnown:            pidKnown,
	}

	handler.image = cInfo.Image
	// TODO: we wantd to know graph driver DeviceId (dont think this is needed now)

	// ignore err and get zero as default, this happens with sandboxes, not sure why...
	// kube isn't sending restart count in labels for sandboxes.
	restartCount, _ := strconv.Atoi(cInfo.Annotations["io.kubernetes.container.restartCount"])
	// Only adds restartcount label if it's greater than 0
	if restartCount > 0 {
		handler.labels["restartcount"] = strconv.Itoa(restartCount)
	}

	handler.ipAddress = cInfo.IP

	// we optionally collect disk usage metrics
	if includedMetrics.Has(container.DiskUsageMetrics) {
		handler.fsHandler = common.NewFsHandler(common.DefaultPeriod, rootfsStorageDir, storageLogDir, fsInfo)
	}
	// TODO for env vars we wanted to show from container.Config.Env from whitelist
	//for _, exposedEnv := range metadataEnvs {
	//klog.V(4).Infof("TODO env whitelist: %v", exposedEnv)
	//}

	return handler, nil
}

func (self *crioContainerHandler) Start() {
	if self.fsHandler != nil {
		self.fsHandler.Start()
	}
}

func (self *crioContainerHandler) Cleanup() {
	if self.fsHandler != nil {
		self.fsHandler.Stop()
	}
}

func (self *crioContainerHandler) ContainerReference() (info.ContainerReference, error) {
	return self.reference, nil
}

func (self *crioContainerHandler) needNet() bool {
	if self.includedMetrics.Has(container.NetworkUsageMetrics) {
		return self.labels["io.kubernetes.container.name"] == "POD"
	}
	return false
}

func (self *crioContainerHandler) GetSpec() (info.ContainerSpec, error) {
	hasFilesystem := self.includedMetrics.Has(container.DiskUsageMetrics)
	spec, err := common.GetSpec(self.cgroupPaths, self.machineInfoFactory, self.needNet(), hasFilesystem)

	spec.Labels = self.labels
	spec.Envs = self.envs
	spec.Image = self.image

	return spec, err
}

func (self *crioContainerHandler) getFsStats(stats *info.ContainerStats) error {
	mi, err := self.machineInfoFactory.GetMachineInfo()
	if err != nil {
		return err
	}

	if self.includedMetrics.Has(container.DiskIOMetrics) {
		common.AssignDeviceNamesToDiskStats((*common.MachineInfoNamer)(mi), &stats.DiskIo)
	}

	if !self.includedMetrics.Has(container.DiskUsageMetrics) {
		return nil
	}
	var device string
	switch self.storageDriver {
	case overlay2StorageDriver, overlayStorageDriver:
		deviceInfo, err := self.fsInfo.GetDirFsDevice(self.rootfsStorageDir)
		if err != nil {
			return fmt.Errorf("unable to determine device info for dir: %v: %v", self.rootfsStorageDir, err)
		}
		device = deviceInfo.Device
	default:
		return nil
	}

	var (
		limit  uint64
		fsType string
	)

	// crio does not impose any filesystem limits for containers. So use capacity as limit.
	for _, fs := range mi.Filesystems {
		if fs.Device == device {
			limit = fs.Capacity
			fsType = fs.Type
			break
		}
	}

	fsStat := info.FsStats{Device: device, Type: fsType, Limit: limit}
	usage := self.fsHandler.Usage()
	fsStat.BaseUsage = usage.BaseUsageBytes
	fsStat.Usage = usage.TotalUsageBytes
	fsStat.Inodes = usage.InodeUsage

	stats.Filesystem = append(stats.Filesystem, fsStat)

	return nil
}

func (self *crioContainerHandler) getLibcontainerHandler() *containerlibcontainer.Handler {
	if self.pidKnown {
		return self.libcontainerHandler
	}

	id := ContainerNameToCrioId(self.name)

	cInfo, err := self.client.ContainerInfo(id)
	if err != nil || cInfo.Pid == 0 {
		return self.libcontainerHandler
	}

	self.pidKnown = true
	self.libcontainerHandler = containerlibcontainer.NewHandler(self.cgroupManager, self.rootFs, cInfo.Pid, self.includedMetrics)

	return self.libcontainerHandler
}

func (self *crioContainerHandler) GetStats() (*info.ContainerStats, error) {
	libcontainerHandler := self.getLibcontainerHandler()
	stats, err := libcontainerHandler.GetStats()
	if err != nil {
		return stats, err
	}
	// Clean up stats for containers that don't have their own network - this
	// includes containers running in Kubernetes pods that use the network of the
	// infrastructure container. This stops metrics being reported multiple times
	// for each container in a pod.
	if !self.needNet() {
		stats.Network = info.NetworkStats{}
	}

	// Get filesystem stats.
	err = self.getFsStats(stats)
	if err != nil {
		return stats, err
	}

	return stats, nil
}

func (self *crioContainerHandler) ListContainers(listType container.ListType) ([]info.ContainerReference, error) {
	// No-op for Docker driver.
	return []info.ContainerReference{}, nil
}

func (self *crioContainerHandler) GetCgroupPath(resource string) (string, error) {
	path, ok := self.cgroupPaths[resource]
	if !ok {
		return "", fmt.Errorf("could not find path for resource %q for container %q\n", resource, self.reference.Name)
	}
	return path, nil
}

func (self *crioContainerHandler) GetContainerLabels() map[string]string {
	return self.labels
}

func (self *crioContainerHandler) GetContainerIPAddress() string {
	return self.ipAddress
}

func (self *crioContainerHandler) ListProcesses(listType container.ListType) ([]int, error) {
	return self.libcontainerHandler.GetProcesses()
}

func (self *crioContainerHandler) Exists() bool {
	return common.CgroupExists(self.cgroupPaths)
}

func (self *crioContainerHandler) Type() container.ContainerType {
	return container.ContainerTypeCrio
}
<|endoftext|>


<commit_before>package upframe

import (
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"github.com/gorilla/sessions"
	"github.com/mholt/caddy/caddyhttp/httpserver"
	"github.com/upframe/fest/pages"
)

// Upframe is the startup struct
type Upframe struct {
	Next httpserver.Handler
	Root string
}

func (u Upframe) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	// Checks if a static file (not directory) exists for this path. If it doesn't, we
	// handle the request.
	if info, err := os.Stat(u.Root + r.URL.Path); !(os.IsNotExist(err) || info.IsDir()) {
		return u.Next.ServeHTTP(w, r)
	}

	// Gets the current session or creates a new one if there is some error
	// decrypting it or if it doesn't exist
	s, _ := store.Get(r, "upframe-auth")

	// If it is a new session, initialize it, setting 'IsLoggedIn' as false
	if s.IsNew {
		s.Values["IsLoggedIn"] = false
	}

	// Saves the session in the cookie and checks for errors. This is useful
	// to reset the expiration time.
	err := s.Save(r, w)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	// Routes the pages to the respective functions
	switch {
	case r.URL.Path == "/" && r.Method == http.MethodGet:
		return pages.IndexGET(w, r, s)
	case r.URL.Path == "/register" && r.Method == http.MethodGet:
		return pages.RegisterGET(w, r, s)
	case r.URL.Path == "/register" && r.Method == http.MethodPost:
		return pages.RegisterPOST(w, r, s)
	case r.URL.Path == "/login" && r.Method == http.MethodGet:
		return pages.LoginGET(w, r, s)
	case r.URL.Path == "/login" && r.Method == http.MethodPost:
		return pages.LoginPOST(w, r, s)
	case r.URL.Path == "/settings" && r.Method == http.MethodGet:
		return pages.SettingsGET(w, r, s)
	case r.URL.Path == "/settings" && r.Method == http.MethodPut:
		return pages.SettingsPUT(w, r, s)
	case r.URL.Path == "/settings/deactivate" && r.Method == http.MethodGet:
		return pages.DeactivateGET(w, r, s)
	case r.URL.Path == "/settings/deactivate" && r.Method == http.MethodPost:
		return pages.DeactivatePOST(w, r, s)
	case r.URL.Path == "/store" && r.Method == http.MethodGet:
		return pages.StoreGET(w, r, s)
	case r.URL.Path == "/cart" && r.Method == http.MethodGet:
		return pages.CartGET(w, r, s)
	case strings.HasPrefix(r.URL.Path, "/cart") && r.Method == http.MethodPost:
		return pages.CartPOST(w, r, s)
	case strings.HasPrefix(r.URL.Path, "/cart") && r.Method == http.MethodDelete:
		return pages.CartDELETE(w, r, s)
	case r.URL.Path == "/checkout" && r.Method == http.MethodGet:
		return pages.CheckoutGET(w, r, s)
	case r.URL.Path == "/logout":
		return logout(w, r, s)
	}

	// Admin router: if the user is an admin and the page starts with /admin
	if pages.IsAdmin(s) && strings.HasPrefix(r.URL.Path, "/admin") {
		if r.URL.Path == "/admin" && r.Method == http.MethodGet {
			return pages.RenderHTML(w, s, nil, "admin/home")
		}

		if strings.HasPrefix(r.URL.Path, "/admin/promocodes") {
			switch r.Method {
			case http.MethodGet:
				return pages.AdminPromocodesGET(w, r, s)
			case http.MethodPost:
				return pages.AdminPromocodesPOST(w, r)
			case http.MethodDelete:
				return pages.AdminPromocodesDELETE(w, r)
			case http.MethodPut:
				return pages.AdminPromocodesPUT(w, r)
			}
		}

		if strings.HasPrefix(r.URL.Path, "/admin/orders") {
			switch r.Method {
			case http.MethodGet:
				return pages.AdminOrdersGET(w, r, s)
			case http.MethodPost:
				return pages.AdminOrdersPOST(w, r)
			case http.MethodDelete:
				return pages.AdminOrdersDELETE(w, r)
			case http.MethodPut:
				return pages.AdminOrdersPUT(w, r)
			}
		}

		if strings.HasPrefix(r.URL.Path, "/admin/users") {
			switch r.Method {
			case http.MethodGet:
				return pages.AdminUsersGET(w, r, s)
			case http.MethodPost:
				return pages.AdminUsersPOST(w, r)
			case http.MethodDelete:
				return pages.AdminUsersDELETE(w, r)
			case http.MethodPut:
				return pages.AdminUsersPUT(w, r)
			}
		}

		if strings.HasPrefix(r.URL.Path, "/admin/products") {
			switch r.Method {
			case http.MethodGet:
				return pages.AdminProductsGET(w, r, s)
			case http.MethodPost:
				return pages.AdminProductsPOST(w, r)
			case http.MethodDelete:
				return pages.AdminProductsDELETE(w, r)
			case http.MethodPut:
				return pages.AdminProductsPUT(w, r)
			}
		}
	}

	// If the request doesn't match any route and it isn't a GET request
	// return a Status Not Implemented
	if r.Method != http.MethodGet {
		return http.StatusNotImplemented, nil
	}

	// Checks if there is a static template for this page. If so, show it!
	if _, err := os.Stat(filepath.Clean("templates/static" + r.URL.Path + ".tmpl")); err == nil {
		return pages.RenderHTML(w, nil, r.URL.Path)
	}

	// Return 404 Not Found for the rest
	return http.StatusNotFound, nil
}

// logout resets the session values and saves the cookie
func logout(w http.ResponseWriter, r *http.Request, s *sessions.Session) (int, error) {
	// Reset the session values
	s.Values = map[interface{}]interface{}{}
	s.Values["IsLoggedIn"] = false

	// Saves the session and checks for error
	err := s.Save(r, w)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
	return http.StatusOK, nil
}
<commit_msg>update<commit_after>package upframe

import (
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"github.com/gorilla/sessions"
	"github.com/mholt/caddy/caddyhttp/httpserver"
	"github.com/upframe/fest/models"
	"github.com/upframe/fest/pages"
)

// Upframe is the startup struct
type Upframe struct {
	Next httpserver.Handler
	Root string
}

func (u Upframe) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	// Checks if a static file (not directory) exists for this path. If it doesn't, we
	// handle the request.
	if info, err := os.Stat(u.Root + r.URL.Path); !(os.IsNotExist(err) || info.IsDir()) {
		return u.Next.ServeHTTP(w, r)
	}

	// Gets the current session or creates a new one if there is some error
	// decrypting it or if it doesn't exist
	s, _ := store.Get(r, "upframe-auth")

	// If it is a new session, initialize it, setting 'IsLoggedIn' as false
	if s.IsNew {
		s.Values["IsLoggedIn"] = false
	}

	// Refresh user information
	if pages.IsLoggedIn(s) {
		generic, err := models.GetUserByID(s.Values["UserID"].(int))
		if err != nil {
			return http.StatusInternalServerError, err
		}

		user := generic.(*models.User)
		s.Values["IsAdmin"] = user.Admin
		s.Values["FirstName"] = user.FirstName
		s.Values["LastName"] = user.LastName
		s.Values["Email"] = user.Email
		s.Values["Credit"] = user.Credit
		s.Values["Invites"] = user.Invites
	}

	// Saves the session in the cookie and checks for errors. This is useful
	// to reset the expiration time.
	err := s.Save(r, w)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	// Routes the pages to the respective functions
	switch {
	case r.URL.Path == "/" && r.Method == http.MethodGet:
		return pages.IndexGET(w, r, s)
	case r.URL.Path == "/register" && r.Method == http.MethodGet:
		return pages.RegisterGET(w, r, s)
	case r.URL.Path == "/register" && r.Method == http.MethodPost:
		return pages.RegisterPOST(w, r, s)
	case r.URL.Path == "/login" && r.Method == http.MethodGet:
		return pages.LoginGET(w, r, s)
	case r.URL.Path == "/login" && r.Method == http.MethodPost:
		return pages.LoginPOST(w, r, s)
	case r.URL.Path == "/settings" && r.Method == http.MethodGet:
		return pages.SettingsGET(w, r, s)
	case r.URL.Path == "/settings" && r.Method == http.MethodPut:
		return pages.SettingsPUT(w, r, s)
	case r.URL.Path == "/settings/deactivate" && r.Method == http.MethodGet:
		return pages.DeactivateGET(w, r, s)
	case r.URL.Path == "/settings/deactivate" && r.Method == http.MethodPost:
		return pages.DeactivatePOST(w, r, s)
	case r.URL.Path == "/store" && r.Method == http.MethodGet:
		return pages.StoreGET(w, r, s)
	case r.URL.Path == "/cart" && r.Method == http.MethodGet:
		return pages.CartGET(w, r, s)
	case strings.HasPrefix(r.URL.Path, "/cart") && r.Method == http.MethodPost:
		return pages.CartPOST(w, r, s)
	case strings.HasPrefix(r.URL.Path, "/cart") && r.Method == http.MethodDelete:
		return pages.CartDELETE(w, r, s)
	case r.URL.Path == "/checkout" && r.Method == http.MethodGet:
		return pages.CheckoutGET(w, r, s)
	case r.URL.Path == "/logout":
		return logout(w, r, s)
	}

	// Admin router: if the user is an admin and the page starts with /admin
	if pages.IsAdmin(s) && strings.HasPrefix(r.URL.Path, "/admin") {
		if r.URL.Path == "/admin" && r.Method == http.MethodGet {
			return pages.RenderHTML(w, s, nil, "admin/home")
		}

		if strings.HasPrefix(r.URL.Path, "/admin/promocodes") {
			switch r.Method {
			case http.MethodGet:
				return pages.AdminPromocodesGET(w, r, s)
			case http.MethodPost:
				return pages.AdminPromocodesPOST(w, r)
			case http.MethodDelete:
				return pages.AdminPromocodesDELETE(w, r)
			case http.MethodPut:
				return pages.AdminPromocodesPUT(w, r)
			}
		}

		if strings.HasPrefix(r.URL.Path, "/admin/orders") {
			switch r.Method {
			case http.MethodGet:
				return pages.AdminOrdersGET(w, r, s)
			case http.MethodPost:
				return pages.AdminOrdersPOST(w, r)
			case http.MethodDelete:
				return pages.AdminOrdersDELETE(w, r)
			case http.MethodPut:
				return pages.AdminOrdersPUT(w, r)
			}
		}

		if strings.HasPrefix(r.URL.Path, "/admin/users") {
			switch r.Method {
			case http.MethodGet:
				return pages.AdminUsersGET(w, r, s)
			case http.MethodPost:
				return pages.AdminUsersPOST(w, r)
			case http.MethodDelete:
				return pages.AdminUsersDELETE(w, r)
			case http.MethodPut:
				return pages.AdminUsersPUT(w, r)
			}
		}

		if strings.HasPrefix(r.URL.Path, "/admin/products") {
			switch r.Method {
			case http.MethodGet:
				return pages.AdminProductsGET(w, r, s)
			case http.MethodPost:
				return pages.AdminProductsPOST(w, r)
			case http.MethodDelete:
				return pages.AdminProductsDELETE(w, r)
			case http.MethodPut:
				return pages.AdminProductsPUT(w, r)
			}
		}
	}

	// If the request doesn't match any route and it isn't a GET request
	// return a Status Not Implemented
	if r.Method != http.MethodGet {
		return http.StatusNotImplemented, nil
	}

	// Checks if there is a static template for this page. If so, show it!
	if _, err := os.Stat(filepath.Clean("templates/static" + r.URL.Path + ".tmpl")); err == nil {
		return pages.RenderHTML(w, nil, r.URL.Path)
	}

	// Return 404 Not Found for the rest
	return http.StatusNotFound, nil
}

// logout resets the session values and saves the cookie
func logout(w http.ResponseWriter, r *http.Request, s *sessions.Session) (int, error) {
	// Reset the session values
	s.Values = map[interface{}]interface{}{}
	s.Values["IsLoggedIn"] = false

	// Saves the session and checks for error
	err := s.Save(r, w)
	if err != nil {
		return http.StatusInternalServerError, err
	}

	http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
	return http.StatusOK, nil
}
<|endoftext|>


<commit_before>// Copyright 2017 The WPT Dashboard Project. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package webapp

import (
	"html/template"
	"net/http"
)

var templates = template.Must(template.ParseGlob("templates/*.html"))

func init() {
	http.HandleFunc("/test-runs", testRunsHandler)
	http.HandleFunc("/about", aboutHandler)
	http.HandleFunc("/api/diff", apiDiffHandler)
	http.HandleFunc("/api/runs", apiTestRunsHandler)
	http.HandleFunc("/api/run", apiTestRunHandler)
	http.HandleFunc("/results", resultsRedirectHandler)
	http.HandleFunc("/", testHandler)
}
<commit_msg>Add some comments to the wpt.fyi paths<commit_after>// Copyright 2017 The WPT Dashboard Project. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package webapp

import (
	"html/template"
	"net/http"
)

var templates = template.Must(template.ParseGlob("templates/*.html"))

func init() {
	// Test run results, viewed by browser (default view)
	// For run results diff view, 'before' and 'after' params can be given.
	http.HandleFunc("/", testHandler)

	// About wpt.fyi
	http.HandleFunc("/about", aboutHandler)

	// List of all test runs, by SHA[0:10]
	http.HandleFunc("/test-runs", testRunsHandler)

	// API endpoint for diff of two test run summary JSON blobs.
	http.HandleFunc("/api/diff", apiDiffHandler)

	// API endpoint for listing all test runs for a given SHA.
	http.HandleFunc("/api/runs", apiTestRunsHandler)

	// API endpoint for a single test run.
	http.HandleFunc("/api/run", apiTestRunHandler)

	// API endpoint for redirecting to a run's summary JSON blob.
	http.HandleFunc("/results", resultsRedirectHandler)
}
<|endoftext|>