<commit_before>package clui

import (
	term "github.com/nsf/termbox-go"
)

const (
	ElemPrintable = iota
	ElemBackColor
	ElemTextColor
	ElemLineBreak
	ElemEndOfText
)

type TextElementType int

type TextElement struct {
	Type TextElementType
	Ch   rune
	Fg   term.Attribute
	Bg   term.Attribute
}

type ColorParser struct {
	text     []rune
	index    int
	defBack  term.Attribute
	defText  term.Attribute
	currBack term.Attribute
	currText term.Attribute
}

func NewColorParser(str string, defText, defBack term.Attribute) *ColorParser {
	p := new(ColorParser)
	p.text = []rune(str)
	p.defBack, p.defText = defBack, defText
	p.currBack, p.currText = defBack, defText
	return p
}

func (p *ColorParser) parseColor() (term.Attribute, TextElementType, bool) {
	newIdx := p.index + 1
	length := len(p.text)
	ok := true

	const (
		StepType = iota
		StepColon
		StepValue
	)

	var (
		cText string
		attr  term.Attribute
		t     TextElementType
		step  int = StepType
		done  bool
	)

	for {
		if newIdx >= length {
			ok = false
			break
		}

		switch step {
		case StepType:
			c := p.text[newIdx]
			if c == 't' || c == 'f' {
				t = ElemTextColor
			} else if c == 'b' {
				t = ElemBackColor
			} else {
				ok = false
				break
			}
			step = StepColon
			newIdx++
		case StepColon:
			c := p.text[newIdx]
			if c != ':' {
				ok = false
				break
			}
			newIdx++
			step = StepValue
		case StepValue:
			c := p.text[newIdx]
			if c == '>' {
				p.index = newIdx + 1
				if cText == "" {
					attr = ColorDefault
				} else {
					attr = StringToColor(cText)
				}
				done = true
				break
			} else {
				if c != ' ' || cText != "" {
					cText += string(c)
				}
				newIdx++
			}
		}

		if done || !ok {
			break
		}
	}

	return attr, t, ok
}

func (p *ColorParser) NextElement() TextElement {
	if p.index >= len(p.text) {
		return TextElement{Type: ElemEndOfText}
	}

	if p.text[p.index] == '\n' {
		p.index++
		return TextElement{Type: ElemLineBreak}
	}

	if p.text[p.index] != '<' {
		p.index++
		return TextElement{Type: ElemPrintable, Ch: p.text[p.index-1], Fg: p.currText, Bg: p.currBack}
	}

	attr, atype, ok := p.parseColor()
	// logger.Printf("PARSED: %v, %v, %v (at %v)", attr, atype, ok, p.index)
	if !ok {
		p.index++
		return TextElement{Type: ElemPrintable, Ch: p.text[p.index-1], Fg: p.currText, Bg: p.currBack}
	}

	if atype == ElemBackColor {
		if attr == ColorDefault {
			p.currBack = p.defBack
		} else {
			p.currBack = attr
		}
	} else if atype == ElemTextColor {
		if attr == ColorDefault {
			p.currText = p.defText
		} else {
			p.currText = attr
		}
	}
	return TextElement{Type: atype, Fg: p.currText, Bg: p.currBack}
}
<commit_msg>#24 - add docs for ColorParser<commit_after>package clui

import (
	term "github.com/nsf/termbox-go"
)

// TextElementType type of the parsed element of the string
type TextElementType int

// TextElementType values
const (
	// ElemPrintable - the item is a rune
	ElemPrintable = iota
	// ElemBackColor - the item sets new background color
	ElemBackColor
	// ElemTextColor - the item sets new text color
	ElemTextColor
	// ElemLineBreak - line break
	ElemLineBreak
	// ElemEndOfText - the string parsing has complited
	ElemEndOfText
)

// TextElement is currently parsed text element
type TextElement struct {
	// Type is an element type
	Type TextElementType
	// Ch is a parsed rune, it is filled only if Type is ElemPrintable
	Ch rune
	// Fg is a text color for the rune
	Fg term.Attribute
	// Bg is a background color for the rune
	Bg term.Attribute
}

// ColorParser is a string parser to process a text with color tags
// inside the string
type ColorParser struct {
	text     []rune
	index    int
	defBack  term.Attribute
	defText  term.Attribute
	currBack term.Attribute
	currText term.Attribute
}

// NewColorParser creates a new string parser.
// str is a string to parse.
// defText is a default text color.
// defBack is a default background color.
// Default colors are applied in case of reset color tag
func NewColorParser(str string, defText, defBack term.Attribute) *ColorParser {
	p := new(ColorParser)
	p.text = []rune(str)
	p.defBack, p.defText = defBack, defText
	p.currBack, p.currText = defBack, defText
	return p
}

func (p *ColorParser) parseColor() (term.Attribute, TextElementType, bool) {
	newIdx := p.index + 1
	length := len(p.text)
	ok := true

	const (
		StepType = iota
		StepColon
		StepValue
	)

	var (
		cText string
		attr  term.Attribute
		t     TextElementType
		done  bool
	)
	step := StepType

	for {
		if newIdx >= length {
			ok = false
			break
		}

		switch step {
		case StepType:
			c := p.text[newIdx]
			if c == 't' || c == 'f' {
				t = ElemTextColor
			} else if c == 'b' {
				t = ElemBackColor
			} else {
				ok = false
				break
			}
			step = StepColon
			newIdx++
		case StepColon:
			c := p.text[newIdx]
			if c != ':' {
				ok = false
				break
			}
			newIdx++
			step = StepValue
		case StepValue:
			c := p.text[newIdx]
			if c == '>' {
				p.index = newIdx + 1
				if cText == "" {
					attr = ColorDefault
				} else {
					attr = StringToColor(cText)
				}
				done = true
				break
			} else {
				if c != ' ' || cText != "" {
					cText += string(c)
				}
				newIdx++
			}
		}

		if done || !ok {
			break
		}
	}

	return attr, t, ok
}

// NextElement parses and returns the next string element
func (p *ColorParser) NextElement() TextElement {
	if p.index >= len(p.text) {
		return TextElement{Type: ElemEndOfText}
	}

	if p.text[p.index] == '\n' {
		p.index++
		return TextElement{Type: ElemLineBreak}
	}

	if p.text[p.index] != '<' {
		p.index++
		return TextElement{Type: ElemPrintable, Ch: p.text[p.index-1], Fg: p.currText, Bg: p.currBack}
	}

	attr, atype, ok := p.parseColor()
	if !ok {
		p.index++
		return TextElement{Type: ElemPrintable, Ch: p.text[p.index-1], Fg: p.currText, Bg: p.currBack}
	}

	if atype == ElemBackColor {
		if attr == ColorDefault {
			p.currBack = p.defBack
		} else {
			p.currBack = attr
		}
	} else if atype == ElemTextColor {
		if attr == ColorDefault {
			p.currText = p.defText
		} else {
			p.currText = attr
		}
	}
	return TextElement{Type: atype, Fg: p.currText, Bg: p.currBack}
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/abh/dns"
	. "launchpad.net/gocheck"
	"net"
	"strings"
	"time"
)

const (
	PORT = ":8853"
)

type ServeSuite struct {
}

var _ = Suite(&ServeSuite{})

func (s *ServeSuite) SetUpSuite(c *C) {

	// log.Println("Setting up serve test suite")

	Zones := make(Zones)
	setupPgeodnsZone(Zones)
	zonesReadDir("dns", Zones)

	go listenAndServe(PORT)

	time.Sleep(200 * time.Millisecond)
}

func (s *ServeSuite) TestServing(c *C) {

	r := exchange(c, "_status.pgeodns.", dns.TypeTXT)
	txt := r.Answer[0].(*dns.TXT).Txt[0]
	if !strings.HasPrefix(txt, "{") {
		c.Log("Unexpected result for _status.pgeodns", txt)
		c.Fail()
	}

	// Allow _country and _status queries as long as the first label is that
	r = exchange(c, "_country.foo.pgeodns.", dns.TypeTXT)
	txt = r.Answer[0].(*dns.TXT).Txt[0]
	// Got appropriate response for _country txt query
	if !strings.HasPrefix(txt, "127.0.0.1:") {
		c.Log("Unexpected result for _country.foo.pgeodns", txt)
		c.Fail()
	}

	// Make sure A requests for _status doesn't NXDOMAIN
	r = exchange(c, "_status.pgeodns.", dns.TypeA)
	c.Check(r.Answer, HasLen, 0)
	// Got one SOA record
	c.Check(r.Ns, HasLen, 1)
	// NOERROR for A request
	c.Check(r.Rcode, Equals, dns.RcodeSuccess)

	r = exchange(c, "bar.test.example.com.", dns.TypeA)
	ip := r.Answer[0].(*dns.A).A
	c.Check(ip.String(), Equals, "192.168.1.2")

	r = exchange(c, "test.example.com.", dns.TypeSOA)
	soa := r.Answer[0].(*dns.SOA)
	serial := soa.Serial
	c.Check(int(serial), Equals, 3)

	// no AAAA records for 'bar', so check we get a soa record back
	r = exchange(c, "test.example.com.", dns.TypeAAAA)
	soa2 := r.Ns[0].(*dns.SOA)
	c.Check(soa, DeepEquals, soa2)

	// CNAMEs
	r = exchange(c, "www.test.example.com.", dns.TypeA)
	c.Check(r.Answer[0].(*dns.CNAME).Target, Equals, "geo.bitnames.com.")

	// MX
	r = exchange(c, "test.example.com.", dns.TypeMX)
	c.Check(r.Answer[0].(*dns.MX).Mx, Equals, "mx.example.net.")
	c.Check(r.Answer[1].(*dns.MX).Mx, Equals, "mx2.example.net.")
	c.Check(r.Answer[1].(*dns.MX).Preference, Equals, uint16(20))
}

func (s *ServeSuite) TestServingAliases(c *C) {
	// Alias, no geo matches
	r := exchange(c, "bar-alias.test.example.com.", dns.TypeA)
	ip := r.Answer[0].(*dns.A).A
	c.Check(ip.String(), Equals, "192.168.1.2")

	// Alias to a cname record
	r = exchange(c, "www-alias.test.example.com.", dns.TypeA)
	c.Check(r.Answer[0].(*dns.CNAME).Target, Equals, "geo.bitnames.com.")

	// Alias returning a cname, with geo overrides
	r = exchangeSubnet(c, "www-alias.test.example.com.", dns.TypeA, "194.239.134.1")
	c.Check(r.Answer, HasLen, 1)
	if len(r.Answer) > 0 {
		c.Check(r.Answer[0].(*dns.CNAME).Target, Equals, "geo-europe.bitnames.com.")
	}

	// Alias to Ns records
	r = exchange(c, "sub-alias.test.example.org.", dns.TypeNS)
	c.Check(r.Answer[0].(*dns.NS).Ns, Equals, "ns1.example.com.")

}

func (s *ServeSuite) TestServingEDNS(c *C) {
	// MX test
	r := exchangeSubnet(c, "test.example.com.", dns.TypeMX, "194.239.134.1")
	c.Check(r.Answer, HasLen, 1)
	if len(r.Answer) > 0 {
		c.Check(r.Answer[0].(*dns.MX).Mx, Equals, "mx-eu.example.net.")
	}

	c.Log("Testing www.test.example.com from .dk, should match www.europe (a cname)")

	r = exchangeSubnet(c, "www.test.example.com.", dns.TypeA, "194.239.134.0")
	c.Check(r.Answer, HasLen, 1)
	if len(r.Answer) > 0 {
		// EDNS-SUBNET test (request A, respond CNAME)
		c.Check(r.Answer[0].(*dns.CNAME).Target, Equals, "geo-europe.bitnames.com.")
	}

}

func exchangeSubnet(c *C, name string, dnstype uint16, ip string) *dns.Msg {
	msg := new(dns.Msg)

	msg.SetQuestion(name, dnstype)

	o := new(dns.OPT)
	o.Hdr.Name = "."
	o.Hdr.Rrtype = dns.TypeOPT
	e := new(dns.EDNS0_SUBNET)
	e.Code = dns.EDNS0SUBNET
	e.SourceScope = 0
	e.Address = net.ParseIP(ip)
	e.Family = 1 // IP4
	e.SourceNetmask = net.IPv4len * 8
	o.Option = append(o.Option, e)
	msg.Extra = append(msg.Extra, o)

	c.Log("msg", msg)

	return dorequest(c, msg)
}

func exchange(c *C, name string, dnstype uint16) *dns.Msg {
	msg := new(dns.Msg)

	msg.SetQuestion(name, dnstype)
	return dorequest(c, msg)
}

func dorequest(c *C, msg *dns.Msg) *dns.Msg {
	cli := new(dns.Client)
	r, _, err := cli.Exchange(msg, "127.0.0.1"+PORT)
	if err != nil {
		c.Log("err", err)
		c.Fail()
	}
	return r
}
<commit_msg>Add benchmark test<commit_after>package main

import (
	"github.com/abh/dns"
	. "launchpad.net/gocheck"
	"net"
	"strings"
	"time"
)

const (
	PORT = ":8853"
)

type ServeSuite struct {
}

var _ = Suite(&ServeSuite{})

func (s *ServeSuite) SetUpSuite(c *C) {

	// log.Println("Setting up serve test suite")

	Zones := make(Zones)
	setupPgeodnsZone(Zones)
	zonesReadDir("dns", Zones)

	go listenAndServe(PORT)

	time.Sleep(200 * time.Millisecond)
}

func (s *ServeSuite) TestServing(c *C) {

	r := exchange(c, "_status.pgeodns.", dns.TypeTXT)
	txt := r.Answer[0].(*dns.TXT).Txt[0]
	if !strings.HasPrefix(txt, "{") {
		c.Log("Unexpected result for _status.pgeodns", txt)
		c.Fail()
	}

	// Allow _country and _status queries as long as the first label is that
	r = exchange(c, "_country.foo.pgeodns.", dns.TypeTXT)
	txt = r.Answer[0].(*dns.TXT).Txt[0]
	// Got appropriate response for _country txt query
	if !strings.HasPrefix(txt, "127.0.0.1:") {
		c.Log("Unexpected result for _country.foo.pgeodns", txt)
		c.Fail()
	}

	// Make sure A requests for _status doesn't NXDOMAIN
	r = exchange(c, "_status.pgeodns.", dns.TypeA)
	c.Check(r.Answer, HasLen, 0)
	// Got one SOA record
	c.Check(r.Ns, HasLen, 1)
	// NOERROR for A request
	c.Check(r.Rcode, Equals, dns.RcodeSuccess)

	r = exchange(c, "bar.test.example.com.", dns.TypeA)
	ip := r.Answer[0].(*dns.A).A
	c.Check(ip.String(), Equals, "192.168.1.2")

	r = exchange(c, "test.example.com.", dns.TypeSOA)
	soa := r.Answer[0].(*dns.SOA)
	serial := soa.Serial
	c.Check(int(serial), Equals, 3)

	// no AAAA records for 'bar', so check we get a soa record back
	r = exchange(c, "test.example.com.", dns.TypeAAAA)
	soa2 := r.Ns[0].(*dns.SOA)
	c.Check(soa, DeepEquals, soa2)

	// CNAMEs
	r = exchange(c, "www.test.example.com.", dns.TypeA)
	c.Check(r.Answer[0].(*dns.CNAME).Target, Equals, "geo.bitnames.com.")

	// MX
	r = exchange(c, "test.example.com.", dns.TypeMX)
	c.Check(r.Answer[0].(*dns.MX).Mx, Equals, "mx.example.net.")
	c.Check(r.Answer[1].(*dns.MX).Mx, Equals, "mx2.example.net.")
	c.Check(r.Answer[1].(*dns.MX).Preference, Equals, uint16(20))
}

func (s *ServeSuite) TestServingAliases(c *C) {
	// Alias, no geo matches
	r := exchange(c, "bar-alias.test.example.com.", dns.TypeA)
	ip := r.Answer[0].(*dns.A).A
	c.Check(ip.String(), Equals, "192.168.1.2")

	// Alias to a cname record
	r = exchange(c, "www-alias.test.example.com.", dns.TypeA)
	c.Check(r.Answer[0].(*dns.CNAME).Target, Equals, "geo.bitnames.com.")

	// Alias returning a cname, with geo overrides
	r = exchangeSubnet(c, "www-alias.test.example.com.", dns.TypeA, "194.239.134.1")
	c.Check(r.Answer, HasLen, 1)
	if len(r.Answer) > 0 {
		c.Check(r.Answer[0].(*dns.CNAME).Target, Equals, "geo-europe.bitnames.com.")
	}

	// Alias to Ns records
	r = exchange(c, "sub-alias.test.example.org.", dns.TypeNS)
	c.Check(r.Answer[0].(*dns.NS).Ns, Equals, "ns1.example.com.")

}

func (s *ServeSuite) TestServingEDNS(c *C) {
	// MX test
	r := exchangeSubnet(c, "test.example.com.", dns.TypeMX, "194.239.134.1")
	c.Check(r.Answer, HasLen, 1)
	if len(r.Answer) > 0 {
		c.Check(r.Answer[0].(*dns.MX).Mx, Equals, "mx-eu.example.net.")
	}

	c.Log("Testing www.test.example.com from .dk, should match www.europe (a cname)")

	r = exchangeSubnet(c, "www.test.example.com.", dns.TypeA, "194.239.134.0")
	c.Check(r.Answer, HasLen, 1)
	if len(r.Answer) > 0 {
		// EDNS-SUBNET test (request A, respond CNAME)
		c.Check(r.Answer[0].(*dns.CNAME).Target, Equals, "geo-europe.bitnames.com.")
	}

}

func (s *ServeSuite) BenchmarkServing(c *C) {
	for i := 0; i < c.N; i++ {
		exchange(c, "_country.foo.pgeodns.", dns.TypeTXT)
	}
}

func exchangeSubnet(c *C, name string, dnstype uint16, ip string) *dns.Msg {
	msg := new(dns.Msg)

	msg.SetQuestion(name, dnstype)

	o := new(dns.OPT)
	o.Hdr.Name = "."
	o.Hdr.Rrtype = dns.TypeOPT
	e := new(dns.EDNS0_SUBNET)
	e.Code = dns.EDNS0SUBNET
	e.SourceScope = 0
	e.Address = net.ParseIP(ip)
	e.Family = 1 // IP4
	e.SourceNetmask = net.IPv4len * 8
	o.Option = append(o.Option, e)
	msg.Extra = append(msg.Extra, o)

	c.Log("msg", msg)

	return dorequest(c, msg)
}

func exchange(c *C, name string, dnstype uint16) *dns.Msg {
	msg := new(dns.Msg)

	msg.SetQuestion(name, dnstype)
	return dorequest(c, msg)
}

func dorequest(c *C, msg *dns.Msg) *dns.Msg {
	cli := new(dns.Client)
	r, _, err := cli.Exchange(msg, "127.0.0.1"+PORT)
	if err != nil {
		c.Log("err", err)
		c.Fail()
	}
	return r
}
<|endoftext|>


<commit_before>package server

import (
	"net/http"

	"github.com/Shopify/voucher"
	log "github.com/sirupsen/logrus"
)

func init() {
	log.SetFormatter(&log.JSONFormatter{})
}

// LogRequests logs the request fields to stdout as Info
func LogRequests(r *http.Request) {
	r.ParseForm()
	log.WithFields(log.Fields{
		"url":  r.URL,
		"path": r.URL.Path,
		"form": r.Form,
	}).Info("Request Info")
}

// LogResult logs each test run as Info
func LogResult(response voucher.Response) {
	log.WithFields(log.Fields{
		"image":   response.Image,
		"results": response.Results,
	}).Info("Test Status")
}

// LogError logs server errors to stdout as Error
func LogError(err error) {
	log.Errorf("Server error: %s", err)
}
<commit_msg>splits logging into the individual result<commit_after>package server

import (
	"net/http"

	"github.com/Shopify/voucher"
	log "github.com/sirupsen/logrus"
)

func init() {
	log.SetFormatter(&log.JSONFormatter{})
}

// LogRequests logs the request fields to stdout as Info
func LogRequests(r *http.Request) {
	r.ParseForm()
	log.WithFields(log.Fields{
		"url":  r.URL,
		"path": r.URL.Path,
		"form": r.Form,
	}).Info("Request Info")
}

// LogResult logs each test run as Info
func LogResult(response voucher.Response) {
	for _, result := range response.Results {
		log.WithFields(log.Fields{
			"check":    result.Name,
			"image":    response.Image,
			"passed":   result.Success,
			"attested": result.Attested,
			"error":    result.Err,
		}).Info("Check Result")
	}
}

// LogError logs server errors to stdout as Error
func LogError(err error) {
	log.Errorf("Server error: %s", err)
}
<|endoftext|>


<commit_before>package network

import (
	"fmt"
	"math"

	"github.com/mpreath/netcalc/utils"
)

type NetworkNode struct {
	Network *Network       `json:"network,omitempty"`
	Subnets []*NetworkNode `json:"subnets,omitempty"`
}

func (node *NetworkNode) Split() error {
	bc := utils.GetBitsInMask(node.Network.Mask) + 1
	if bc < 31 {
		new_mask, err := utils.GetMaskFromBits(bc)
		if err != nil {
			return err
		}
		// left will contain the lower value
		left_network, err := GenerateNetworkFromBits(node.Network.Address, new_mask)
		if err != nil {
			return err
		}

		node.Subnets = append(node.Subnets, &NetworkNode{Network: left_network})

		// right will contain the larger value
		right_network, err := GenerateNetworkFromBits(left_network.BroadcastAddress+1, new_mask)
		if err != nil {
			return err
		}

		node.Subnets = append(node.Subnets, &NetworkNode{Network: right_network})

	} else {
		return fmt.Errorf("network:Split: network doesn't support being split")
	}

	return nil
}

func GetNetworkCount(node *NetworkNode) int {
	if node == nil {
		return 0
	} else if len(node.Subnets) == 0 {
		return 1
	} else {
		return GetNetworkCount(node.Subnets[0]) + GetNetworkCount(node.Subnets[1])
	}
}

func SplitToHostCount(node *NetworkNode, host_count int) error {
	current_mask_bc := utils.GetBitsInMask(node.Network.Mask)
	if current_mask_bc >= 30 {
		// this is the longest mask we support
		return nil
	}
	current_bc := 32 - current_mask_bc
	current_hc := int(math.Pow(2, float64(current_bc)))
	future_bc := current_bc - 1 // need to look ahead into the future
	future_hc := int(math.Pow(2, float64(future_bc)))

	if current_hc >= host_count && future_hc < host_count {
		// this is our recursive base case
		return nil
	} else if current_hc < host_count {
		// requirements too large, raise an error
		return fmt.Errorf("network.SplitToHostCount: network can't support that many hosts")
	} else {
		err := node.Split()
		if err != nil {
			return err
		}
		err = SplitToHostCount(node.Subnets[0], host_count)
		if err != nil {
			return err
		}
		err = SplitToHostCount(node.Subnets[1], host_count)
		if err != nil {
			return err
		}
	}

	return nil
}

func SplitToNetCount(node *NetworkNode, net_count int) error {
	longest_valid_mask, _ := utils.GetMaskFromBits(30)
	if net_count <= 0 {
		// this is our recursive base case
		return nil
	} else if node.Network.Mask == longest_valid_mask {
		// can't split any more
		return fmt.Errorf("network.SplitToNetCount: network can't support that many subnetworks")
	} else {
		err := node.Split()
		if err != nil {
			return err
		}
		err = SplitToNetCount(node.Subnets[0], net_count-2)
		if err != nil {
			return err
		}
		err = SplitToNetCount(node.Subnets[1], net_count-2)
		if err != nil {
			return err
		}
	}

	return nil
}
<commit_msg>added NetworkNodeToArray method<commit_after>package network

import (
	"fmt"
	"math"

	"github.com/mpreath/netcalc/utils"
)

type NetworkNode struct {
	Network *Network       `json:"network,omitempty"`
	Subnets []*NetworkNode `json:"subnets,omitempty"`
}

func (node *NetworkNode) Split() error {
	bc := utils.GetBitsInMask(node.Network.Mask) + 1
	if bc < 31 {
		new_mask, err := utils.GetMaskFromBits(bc)
		if err != nil {
			return err
		}
		// left will contain the lower value
		left_network, err := GenerateNetworkFromBits(node.Network.Address, new_mask)
		if err != nil {
			return err
		}

		node.Subnets = append(node.Subnets, &NetworkNode{Network: left_network})

		// right will contain the larger value
		right_network, err := GenerateNetworkFromBits(left_network.BroadcastAddress+1, new_mask)
		if err != nil {
			return err
		}

		node.Subnets = append(node.Subnets, &NetworkNode{Network: right_network})

	} else {
		return fmt.Errorf("network:Split: network doesn't support being split")
	}

	return nil
}

func GetNetworkCount(node *NetworkNode) int {
	if node == nil {
		return 0
	} else if len(node.Subnets) == 0 {
		return 1
	} else {
		return GetNetworkCount(node.Subnets[0]) + GetNetworkCount(node.Subnets[1])
	}
}

func SplitToHostCount(node *NetworkNode, host_count int) error {
	current_mask_bc := utils.GetBitsInMask(node.Network.Mask)
	if current_mask_bc >= 30 {
		// this is the longest mask we support
		return nil
	}
	current_bc := 32 - current_mask_bc
	current_hc := int(math.Pow(2, float64(current_bc)))
	future_bc := current_bc - 1 // need to look ahead into the future
	future_hc := int(math.Pow(2, float64(future_bc)))

	if current_hc >= host_count && future_hc < host_count {
		// this is our recursive base case
		return nil
	} else if current_hc < host_count {
		// requirements too large, raise an error
		return fmt.Errorf("network.SplitToHostCount: network can't support that many hosts")
	} else {
		err := node.Split()
		if err != nil {
			return err
		}
		err = SplitToHostCount(node.Subnets[0], host_count)
		if err != nil {
			return err
		}
		err = SplitToHostCount(node.Subnets[1], host_count)
		if err != nil {
			return err
		}
	}

	return nil
}

func SplitToNetCount(node *NetworkNode, net_count int) error {
	longest_valid_mask, _ := utils.GetMaskFromBits(30)
	if net_count <= 0 {
		// this is our recursive base case
		return nil
	} else if node.Network.Mask == longest_valid_mask {
		// can't split any more
		return fmt.Errorf("network.SplitToNetCount: network can't support that many subnetworks")
	} else {
		err := node.Split()
		if err != nil {
			return err
		}
		err = SplitToNetCount(node.Subnets[0], net_count-2)
		if err != nil {
			return err
		}
		err = SplitToNetCount(node.Subnets[1], net_count-2)
		if err != nil {
			return err
		}
	}

	return nil
}

func NetworkNodeToArray(node *NetworkNode) []*Network {
	var narr []*Network
	if len(node.Subnets) > 0 {
		narr = append(narr, NetworkNodeToArray(node.Subnets[0])...)
		narr = append(narr, NetworkNodeToArray(node.Subnets[1])...)
	} else if len(node.Subnets) == 0 {
		narr = append(narr, node.Network)
	}
	return narr
}
<|endoftext|>


<commit_before>/*
Copyright 2019 The Kubernetes Authors.

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.
*/

package protokube

import (
	"fmt"
	"os"
	"os/exec"
	"strings"

	"k8s.io/klog/v2"
)

// applyChannel is responsible for applying the channel manifests
func applyChannel(channel string) error {
	// We don't embed the channels code because we expect this will eventually be part of kubectl
	klog.Infof("checking channel: %q", channel)

	out, err := execChannels("apply", "channel", channel, "--v=4", "--yes")
	klog.V(4).Infof("apply channel output was: %v", out)
	return err
}

func execChannels(args ...string) (string, error) {
	kubectlPath := "/opt/kops/bin/channels"
	cmd := exec.Command(kubectlPath, args...)
	env := os.Environ()
	cmd.Env = env

	human := strings.Join(cmd.Args, " ")
	klog.V(2).Infof("Running command: %s", human)
	output, err := cmd.CombinedOutput()
	if err != nil {
		klog.Infof("error running %s:", human)
		klog.Info(string(output))
		return string(output), fmt.Errorf("error running channels: %v", err)
	}

	return string(output), err
}
<commit_msg>Fix copy/paste typo<commit_after>/*
Copyright 2019 The Kubernetes Authors.

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.
*/

package protokube

import (
	"fmt"
	"os"
	"os/exec"
	"strings"

	"k8s.io/klog/v2"
)

// applyChannel is responsible for applying the channel manifests
func applyChannel(channel string) error {
	// We don't embed the channels code because we expect this will eventually be part of kubectl
	klog.Infof("checking channel: %q", channel)

	out, err := execChannels("apply", "channel", channel, "--v=4", "--yes")
	klog.V(4).Infof("apply channel output was: %v", out)
	return err
}

func execChannels(args ...string) (string, error) {
	channelsPath := "/opt/kops/bin/channels"
	cmd := exec.Command(channelsPath, args...)
	env := os.Environ()
	cmd.Env = env

	human := strings.Join(cmd.Args, " ")
	klog.V(2).Infof("Running command: %s", human)
	output, err := cmd.CombinedOutput()
	if err != nil {
		klog.Infof("error running %s:", human)
		klog.Info(string(output))
		return string(output), fmt.Errorf("error running channels: %v", err)
	}

	return string(output), err
}
<|endoftext|>


<commit_before>// Copyright 2014 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package docker

import (
	"sort"
	"time"

	"github.com/tsuru/tsuru/provision"
	"gopkg.in/check.v1"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

func (s *S) getContainerCollection(appName string, containerIds ...string) func() {
	coll := collection()
	for _, containerId := range containerIds {
		container := container{AppName: appName, ID: containerId}
		coll.Insert(container)
	}
	return func() {
		for _, containerId := range containerIds {
			coll.Remove(bson.M{"id": containerId})
		}
		coll.Close()
	}
}

func (s *S) TestListContainersByApp(c *check.C) {
	var result []container
	coll := collection()
	defer coll.Close()
	coll.Insert(
		container{ID: "Hey", Type: "python", AppName: "myapp", HostAddr: "http://cittavld1180.globoi.com"},
		container{ID: "Ho", Type: "python", AppName: "myapp", HostAddr: "http://cittavld1182.globoi.com"},
		container{ID: "Let's Go", Type: "java", AppName: "other", HostAddr: "http://cittavld597.globoi.com"},
	)
	defer coll.RemoveAll(bson.M{"appname": "myapp"})
	result, err := listContainersByApp("myapp")
	c.Assert(err, check.IsNil)
	c.Assert(len(result), check.Equals, 2)
	check := (result[0].ID == "Hey" && result[1].ID == "Ho") || (result[0].ID == "Ho" && result[1].ID == "Hey")
	c.Assert(check, check.Equals, true)
}

func (s *S) TestListContainersByHost(c *check.C) {
	var result []container
	coll := collection()
	defer coll.Close()
	coll.Insert(
		container{ID: "1", Type: "python", AppName: "myapp", HostAddr: "http://cittavld1182.globoi.com"},
		container{ID: "2", Type: "python", AppName: "wat", HostAddr: "http://cittavld1182.globoi.com"},
		container{ID: "3", Type: "java", AppName: "masoq", HostAddr: "http://cittavld9999.globoi.com"},
	)
	defer coll.RemoveAll(bson.M{"hostaddr": "http://cittavld1182.globoi.com"})
	result, err := listContainersByHost("http://cittavld1182.globoi.com")
	c.Assert(err, check.IsNil)
	c.Assert(len(result), check.Equals, 2)
	check := (result[0].ID == "1" && result[1].ID == "2") || (result[0].ID == "2" && result[1].ID == "1")
	c.Assert(check, check.Equals, true)
}

func (s *S) TestListAllContainers(c *check.C) {
	appName := "some-app"
	containerIds := []string{"some-container-1", "some-container-2"}
	cleanupFunc := s.getContainerCollection(appName, containerIds...)
	defer cleanupFunc()
	containers, err := listAllContainers()
	c.Assert(err, check.IsNil)
	c.Assert(len(containers), check.Equals, 2)
	check := (containers[0].ID == containerIds[0] && containers[1].ID == containerIds[1]) ||
		(containers[0].ID == containerIds[1] && containers[1].ID == containerIds[0])
	c.Assert(check, check.Equals, true)
}

func (s *S) TestUpdateContainers(c *check.C) {
	appName := "myapp"
	containerIds := []string{"some-container-1", "some-container-2", "some-container-3"}
	cleanupFunc := s.getContainerCollection(appName, containerIds...)
	defer cleanupFunc()
	err := updateContainers(bson.M{"appname": "myapp"}, bson.M{"$set": bson.M{"appname": "yourapp"}})
	c.Assert(err, check.IsNil)
	containers, err := listAllContainers()
	c.Assert(err, check.IsNil)
	c.Assert(len(containers), check.Equals, 3)
	ids := make([]string, len(containers))
	names := make([]string, len(containers))
	for i, container := range containers {
		ids[i] = container.ID
		names[i] = container.AppName
	}
	sort.Strings(ids)
	c.Assert(ids, check.DeepEquals, containerIds)
	c.Assert(names, check.DeepEquals, []string{"yourapp", "yourapp", "yourapp"})
}

func (s *S) TestGetOneContainerByAppName(c *check.C) {
	appName := "some-app"
	containerIds := []string{"some-container-1", "some-container-2"}
	cleanupFunc := s.getContainerCollection(appName, containerIds...)
	defer cleanupFunc()
	container, err := getOneContainerByAppName(appName)
	c.Assert(err, check.IsNil)
	c.Assert(container.AppName, check.Equals, appName)
	checkId := container.ID == containerIds[0] || container.ID == containerIds[1]
	c.Assert(checkId, check.Equals, true)
}

func (s *S) TestShouldNotGetOneContainerByAppName(c *check.C) {
	coll := collection()
	defer coll.Close()
	container, err := getOneContainerByAppName("unexisting-app-name")
	c.Assert(err, check.NotNil)
	c.Assert(container, check.IsNil)
}

func (s *S) TestGetContainerCountForAppName(c *check.C) {
	appName := "some-app"
	containerIds := []string{"some-container-1", "some-container-2"}
	cleanupFunc := s.getContainerCollection(appName, containerIds...)
	defer cleanupFunc()
	count, err := getContainerCountForAppName(appName)
	c.Assert(err, check.IsNil)
	c.Assert(count, check.Equals, len(containerIds))
}

func (s *S) TestGetContainerPartialIdAmbiguous(c *check.C) {
	containerIds := []string{"container-1", "container-2"}
	cleanupFunc := s.getContainerCollection("some-app", containerIds...)
	defer cleanupFunc()
	_, err := getContainer("container")
	c.Assert(err, check.Equals, errAmbiguousContainer)
}

func (s *S) TestGetContainerPartialIdNotFound(c *check.C) {
	containerIds := []string{"container-1", "container-2"}
	cleanupFunc := s.getContainerCollection("some-app", containerIds...)
	defer cleanupFunc()
	_, err := getContainer("container-9")
	c.Assert(err, check.Equals, mgo.ErrNotFound)
}

func (s *S) TestGetContainerPartialId(c *check.C) {
	containerIds := []string{"container-a1", "container-b2"}
	cleanupFunc := s.getContainerCollection("some-app", containerIds...)
	defer cleanupFunc()
	cont, err := getContainer("container-a")
	c.Assert(err, check.IsNil)
	c.Assert(cont.ID, check.Equals, "container-a1")
}

func (s *S) TestListContainersByAppOrderedByStatus(c *check.C) {
	coll := collection()
	defer coll.Close()
	coll.Insert(
		container{AppName: "myapp", ID: "0", Status: provision.StatusStarted.String()},
		container{AppName: "myapp", ID: "1", Status: provision.StatusBuilding.String()},
		container{AppName: "myapp", ID: "2", Status: provision.StatusError.String()},
		container{AppName: "myapp", ID: "3", Status: provision.StatusCreated.String()},
		container{AppName: "myapp", ID: "4", Status: provision.StatusStopped.String()},
		container{AppName: "myapp", ID: "5", Status: provision.StatusStarting.String()},
	)
	defer coll.RemoveAll(bson.M{"appname": "myapp"})
	containers, err := listContainersByAppOrderedByStatus("myapp")
	c.Assert(err, check.IsNil)
	c.Assert(len(containers), check.Equals, 6)
	c.Assert(containers[0].Status, check.Equals, provision.StatusCreated.String())
	c.Assert(containers[1].Status, check.Equals, provision.StatusBuilding.String())
	c.Assert(containers[2].Status, check.Equals, provision.StatusError.String())
	c.Assert(containers[3].Status, check.Equals, provision.StatusStopped.String())
	c.Assert(containers[4].Status, check.Equals, provision.StatusStarting.String())
	c.Assert(containers[5].Status, check.Equals, provision.StatusStarted.String())
}

func (S) TestcontainerSliceLen(c *check.C) {
	containers := containerSlice{container{}, container{}}
	c.Assert(containers.Len(), check.Equals, 2)
}

func (S) TestcontainerSliceLess(c *check.C) {
	containers := containerSlice{
		container{Name: "b", Status: provision.StatusError.String()},
		container{Name: "d", Status: provision.StatusBuilding.String()},
		container{Name: "e", Status: provision.StatusStarted.String()},
		container{Name: "s", Status: provision.StatusStarting.String()},
		container{Name: "z", Status: provision.StatusStopped.String()},
		container{Name: "p", Status: provision.StatusCreated.String()},
	}
	c.Assert(containers.Less(0, 1), check.Equals, false)
	c.Assert(containers.Less(1, 2), check.Equals, true)
	c.Assert(containers.Less(2, 0), check.Equals, false)
	c.Assert(containers.Less(3, 2), check.Equals, true)
	c.Assert(containers.Less(3, 1), check.Equals, false)
	c.Assert(containers.Less(4, 3), check.Equals, true)
	c.Assert(containers.Less(4, 1), check.Equals, false)
	c.Assert(containers.Less(5, 1), check.Equals, true)
	c.Assert(containers.Less(5, 0), check.Equals, true)
}

func (S) TestcontainerSliceSwap(c *check.C) {
	containers := containerSlice{
		container{Name: "b", Status: provision.StatusError.String()},
		container{Name: "f", Status: provision.StatusBuilding.String()},
		container{Name: "g", Status: provision.StatusStarted.String()},
	}
	containers.Swap(0, 1)
	c.Assert(containers[0].Status, check.Equals, provision.StatusBuilding.String())
	c.Assert(containers[1].Status, check.Equals, provision.StatusError.String())
}

func (S) TestcontainerSliceSort(c *check.C) {
	containers := containerSlice{
		container{Name: "f", Status: provision.StatusBuilding.String()},
		container{Name: "g", Status: provision.StatusStarted.String()},
		container{Name: "b", Status: provision.StatusError.String()},
	}
	c.Assert(sort.IsSorted(containers), check.Equals, false)
	sort.Sort(containers)
	c.Assert(sort.IsSorted(containers), check.Equals, true)
}

func (S) TestListUnresponsiveContainers(c *check.C) {
	var result []container
	coll := collection()
	defer coll.Close()
	now := time.Now().UTC()
	coll.Insert(
		container{ID: "c1", AppName: "app_time_test", LastSuccessStatusUpdate: now, HostPort: "80"},
		container{ID: "c2", AppName: "app_time_test", LastSuccessStatusUpdate: now.Add(-1 * time.Minute), HostPort: "80"},
		container{ID: "c3", AppName: "app_time_test", LastSuccessStatusUpdate: now.Add(-5 * time.Minute), HostPort: "80"},
	)
	defer coll.RemoveAll(bson.M{"appname": "app_time_test"})
	result, err := listUnresponsiveContainers(3 * time.Minute)
	c.Assert(err, check.IsNil)
	c.Assert(len(result), check.Equals, 1)
	c.Assert(result[0].ID, check.Equals, "c3")
}

func (S) TestListUnresponsiveContainersNoHostPort(c *check.C) {
	var result []container
	coll := collection()
	defer coll.Close()
	now := time.Now().UTC()
	coll.Insert(
		container{ID: "c1", AppName: "app_time_test", LastSuccessStatusUpdate: now.Add(-10 * time.Minute)},
	)
	defer coll.RemoveAll(bson.M{"appname": "app_time_test"})
	result, err := listUnresponsiveContainers(3 * time.Minute)
	c.Assert(err, check.IsNil)
	c.Assert(len(result), check.Equals, 0)
}

func (S) TestListUnresponsiveContainersStopped(c *check.C) {
	var result []container
	coll := collection()
	defer coll.Close()
	now := time.Now().UTC()
	coll.Insert(
		container{ID: "c1", AppName: "app_time_test",
			LastSuccessStatusUpdate: now.Add(-5 * time.Minute), HostPort: "80", Status: provision.StatusStopped.String()},
		container{ID: "c2", AppName: "app_time_test",
			LastSuccessStatusUpdate: now.Add(-5 * time.Minute), HostPort: "80", Status: provision.StatusStarted.String()},
	)
	defer coll.RemoveAll(bson.M{"appname": "app_time_test"})
	result, err := listUnresponsiveContainers(3 * time.Minute)
	c.Assert(err, check.IsNil)
	c.Assert(len(result), check.Equals, 1)
	c.Assert(result[0].ID, check.Equals, "c2")
}

func (S) TestListRunnableContainersByApp(c *check.C) {
	var result []container
	coll := collection()
	defer coll.Close()
	coll.Insert(
		container{Name: "a", AppName: "myapp", Status: provision.StatusCreated.String()},
		container{Name: "b", AppName: "myapp", Status: provision.StatusBuilding.String()},
		container{Name: "c", AppName: "myapp", Status: provision.StatusStarting.String()},
		container{Name: "d", AppName: "myapp", Status: provision.StatusError.String()},
		container{Name: "e", AppName: "myapp", Status: provision.StatusStarted.String()},
		container{Name: "f", AppName: "myapp", Status: provision.StatusStopped.String()},
	)
	defer coll.RemoveAll(bson.M{"appname": "myapp"})
	result, err := listRunnableContainersByApp("myapp")
	c.Assert(err, check.IsNil)
	c.Assert(len(result), check.Equals, 3)
	var names []string
	for _, c := range result {
		names = append(names, c.Name)
	}
	sort.Strings(names)
	c.Assert(names, check.DeepEquals, []string{"c", "d", "e"})
}
<commit_msg>provision/docker: fix shadowing check package name<commit_after>// Copyright 2014 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package docker

import (
	"sort"
	"time"

	"github.com/tsuru/tsuru/provision"
	"gopkg.in/check.v1"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

func (s *S) getContainerCollection(appName string, containerIds ...string) func() {
	coll := collection()
	for _, containerId := range containerIds {
		container := container{AppName: appName, ID: containerId}
		coll.Insert(container)
	}
	return func() {
		for _, containerId := range containerIds {
			coll.Remove(bson.M{"id": containerId})
		}
		coll.Close()
	}
}

func (s *S) TestListContainersByApp(c *check.C) {
	var result []container
	coll := collection()
	defer coll.Close()
	coll.Insert(
		container{ID: "Hey", Type: "python", AppName: "myapp", HostAddr: "http://cittavld1180.globoi.com"},
		container{ID: "Ho", Type: "python", AppName: "myapp", HostAddr: "http://cittavld1182.globoi.com"},
		container{ID: "Let's Go", Type: "java", AppName: "other", HostAddr: "http://cittavld597.globoi.com"},
	)
	defer coll.RemoveAll(bson.M{"appname": "myapp"})
	result, err := listContainersByApp("myapp")
	c.Assert(err, check.IsNil)
	c.Assert(len(result), check.Equals, 2)
	cond := (result[0].ID == "Hey" && result[1].ID == "Ho") || (result[0].ID == "Ho" && result[1].ID == "Hey")
	c.Assert(cond, check.Equals, true)
}

func (s *S) TestListContainersByHost(c *check.C) {
	var result []container
	coll := collection()
	defer coll.Close()
	coll.Insert(
		container{ID: "1", Type: "python", AppName: "myapp", HostAddr: "http://cittavld1182.globoi.com"},
		container{ID: "2", Type: "python", AppName: "wat", HostAddr: "http://cittavld1182.globoi.com"},
		container{ID: "3", Type: "java", AppName: "masoq", HostAddr: "http://cittavld9999.globoi.com"},
	)
	defer coll.RemoveAll(bson.M{"hostaddr": "http://cittavld1182.globoi.com"})
	result, err := listContainersByHost("http://cittavld1182.globoi.com")
	c.Assert(err, check.IsNil)
	c.Assert(len(result), check.Equals, 2)
	cond := (result[0].ID == "1" && result[1].ID == "2") || (result[0].ID == "2" && result[1].ID == "1")
	c.Assert(cond, check.Equals, true)
}

func (s *S) TestListAllContainers(c *check.C) {
	appName := "some-app"
	containerIds := []string{"some-container-1", "some-container-2"}
	cleanupFunc := s.getContainerCollection(appName, containerIds...)
	defer cleanupFunc()
	containers, err := listAllContainers()
	c.Assert(err, check.IsNil)
	c.Assert(len(containers), check.Equals, 2)
	cond := (containers[0].ID == containerIds[0] && containers[1].ID == containerIds[1]) ||
		(containers[0].ID == containerIds[1] && containers[1].ID == containerIds[0])
	c.Assert(cond, check.Equals, true)
}

func (s *S) TestUpdateContainers(c *check.C) {
	appName := "myapp"
	containerIds := []string{"some-container-1", "some-container-2", "some-container-3"}
	cleanupFunc := s.getContainerCollection(appName, containerIds...)
	defer cleanupFunc()
	err := updateContainers(bson.M{"appname": "myapp"}, bson.M{"$set": bson.M{"appname": "yourapp"}})
	c.Assert(err, check.IsNil)
	containers, err := listAllContainers()
	c.Assert(err, check.IsNil)
	c.Assert(len(containers), check.Equals, 3)
	ids := make([]string, len(containers))
	names := make([]string, len(containers))
	for i, container := range containers {
		ids[i] = container.ID
		names[i] = container.AppName
	}
	sort.Strings(ids)
	c.Assert(ids, check.DeepEquals, containerIds)
	c.Assert(names, check.DeepEquals, []string{"yourapp", "yourapp", "yourapp"})
}

func (s *S) TestGetOneContainerByAppName(c *check.C) {
	appName := "some-app"
	containerIds := []string{"some-container-1", "some-container-2"}
	cleanupFunc := s.getContainerCollection(appName, containerIds...)
	defer cleanupFunc()
	container, err := getOneContainerByAppName(appName)
	c.Assert(err, check.IsNil)
	c.Assert(container.AppName, check.Equals, appName)
	checkId := container.ID == containerIds[0] || container.ID == containerIds[1]
	c.Assert(checkId, check.Equals, true)
}

func (s *S) TestShouldNotGetOneContainerByAppName(c *check.C) {
	coll := collection()
	defer coll.Close()
	container, err := getOneContainerByAppName("unexisting-app-name")
	c.Assert(err, check.NotNil)
	c.Assert(container, check.IsNil)
}

func (s *S) TestGetContainerCountForAppName(c *check.C) {
	appName := "some-app"
	containerIds := []string{"some-container-1", "some-container-2"}
	cleanupFunc := s.getContainerCollection(appName, containerIds...)
	defer cleanupFunc()
	count, err := getContainerCountForAppName(appName)
	c.Assert(err, check.IsNil)
	c.Assert(count, check.Equals, len(containerIds))
}

func (s *S) TestGetContainerPartialIdAmbiguous(c *check.C) {
	containerIds := []string{"container-1", "container-2"}
	cleanupFunc := s.getContainerCollection("some-app", containerIds...)
	defer cleanupFunc()
	_, err := getContainer("container")
	c.Assert(err, check.Equals, errAmbiguousContainer)
}

func (s *S) TestGetContainerPartialIdNotFound(c *check.C) {
	containerIds := []string{"container-1", "container-2"}
	cleanupFunc := s.getContainerCollection("some-app", containerIds...)
	defer cleanupFunc()
	_, err := getContainer("container-9")
	c.Assert(err, check.Equals, mgo.ErrNotFound)
}

func (s *S) TestGetContainerPartialId(c *check.C) {
	containerIds := []string{"container-a1", "container-b2"}
	cleanupFunc := s.getContainerCollection("some-app", containerIds...)
	defer cleanupFunc()
	cont, err := getContainer("container-a")
	c.Assert(err, check.IsNil)
	c.Assert(cont.ID, check.Equals, "container-a1")
}

func (s *S) TestListContainersByAppOrderedByStatus(c *check.C) {
	coll := collection()
	defer coll.Close()
	coll.Insert(
		container{AppName: "myapp", ID: "0", Status: provision.StatusStarted.String()},
		container{AppName: "myapp", ID: "1", Status: provision.StatusBuilding.String()},
		container{AppName: "myapp", ID: "2", Status: provision.StatusError.String()},
		container{AppName: "myapp", ID: "3", Status: provision.StatusCreated.String()},
		container{AppName: "myapp", ID: "4", Status: provision.StatusStopped.String()},
		container{AppName: "myapp", ID: "5", Status: provision.StatusStarting.String()},
	)
	defer coll.RemoveAll(bson.M{"appname": "myapp"})
	containers, err := listContainersByAppOrderedByStatus("myapp")
	c.Assert(err, check.IsNil)
	c.Assert(len(containers), check.Equals, 6)
	c.Assert(containers[0].Status, check.Equals, provision.StatusCreated.String())
	c.Assert(containers[1].Status, check.Equals, provision.StatusBuilding.String())
	c.Assert(containers[2].Status, check.Equals, provision.StatusError.String())
	c.Assert(containers[3].Status, check.Equals, provision.StatusStopped.String())
	c.Assert(containers[4].Status, check.Equals, provision.StatusStarting.String())
	c.Assert(containers[5].Status, check.Equals, provision.StatusStarted.String())
}

func (S) TestcontainerSliceLen(c *check.C) {
	containers := containerSlice{container{}, container{}}
	c.Assert(containers.Len(), check.Equals, 2)
}

func (S) TestcontainerSliceLess(c *check.C) {
	containers := containerSlice{
		container{Name: "b", Status: provision.StatusError.String()},
		container{Name: "d", Status: provision.StatusBuilding.String()},
		container{Name: "e", Status: provision.StatusStarted.String()},
		container{Name: "s", Status: provision.StatusStarting.String()},
		container{Name: "z", Status: provision.StatusStopped.String()},
		container{Name: "p", Status: provision.StatusCreated.String()},
	}
	c.Assert(containers.Less(0, 1), check.Equals, false)
	c.Assert(containers.Less(1, 2), check.Equals, true)
	c.Assert(containers.Less(2, 0), check.Equals, false)
	c.Assert(containers.Less(3, 2), check.Equals, true)
	c.Assert(containers.Less(3, 1), check.Equals, false)
	c.Assert(containers.Less(4, 3), check.Equals, true)
	c.Assert(containers.Less(4, 1), check.Equals, false)
	c.Assert(containers.Less(5, 1), check.Equals, true)
	c.Assert(containers.Less(5, 0), check.Equals, true)
}

func (S) TestcontainerSliceSwap(c *check.C) {
	containers := containerSlice{
		container{Name: "b", Status: provision.StatusError.String()},
		container{Name: "f", Status: provision.StatusBuilding.String()},
		container{Name: "g", Status: provision.StatusStarted.String()},
	}
	containers.Swap(0, 1)
	c.Assert(containers[0].Status, check.Equals, provision.StatusBuilding.String())
	c.Assert(containers[1].Status, check.Equals, provision.StatusError.String())
}

func (S) TestcontainerSliceSort(c *check.C) {
	containers := containerSlice{
		container{Name: "f", Status: provision.StatusBuilding.String()},
		container{Name: "g", Status: provision.StatusStarted.String()},
		container{Name: "b", Status: provision.StatusError.String()},
	}
	c.Assert(sort.IsSorted(containers), check.Equals, false)
	sort.Sort(containers)
	c.Assert(sort.IsSorted(containers), check.Equals, true)
}

func (S) TestListUnresponsiveContainers(c *check.C) {
	var result []container
	coll := collection()
	defer coll.Close()
	now := time.Now().UTC()
	coll.Insert(
		container{ID: "c1", AppName: "app_time_test", LastSuccessStatusUpdate: now, HostPort: "80"},
		container{ID: "c2", AppName: "app_time_test", LastSuccessStatusUpdate: now.Add(-1 * time.Minute), HostPort: "80"},
		container{ID: "c3", AppName: "app_time_test", LastSuccessStatusUpdate: now.Add(-5 * time.Minute), HostPort: "80"},
	)
	defer coll.RemoveAll(bson.M{"appname": "app_time_test"})
	result, err := listUnresponsiveContainers(3 * time.Minute)
	c.Assert(err, check.IsNil)
	c.Assert(len(result), check.Equals, 1)
	c.Assert(result[0].ID, check.Equals, "c3")
}

func (S) TestListUnresponsiveContainersNoHostPort(c *check.C) {
	var result []container
	coll := collection()
	defer coll.Close()
	now := time.Now().UTC()
	coll.Insert(
		container{ID: "c1", AppName: "app_time_test", LastSuccessStatusUpdate: now.Add(-10 * time.Minute)},
	)
	defer coll.RemoveAll(bson.M{"appname": "app_time_test"})
	result, err := listUnresponsiveContainers(3 * time.Minute)
	c.Assert(err, check.IsNil)
	c.Assert(len(result), check.Equals, 0)
}

func (S) TestListUnresponsiveContainersStopped(c *check.C) {
	var result []container
	coll := collection()
	defer coll.Close()
	now := time.Now().UTC()
	coll.Insert(
		container{ID: "c1", AppName: "app_time_test",
			LastSuccessStatusUpdate: now.Add(-5 * time.Minute), HostPort: "80", Status: provision.StatusStopped.String()},
		container{ID: "c2", AppName: "app_time_test",
			LastSuccessStatusUpdate: now.Add(-5 * time.Minute), HostPort: "80", Status: provision.StatusStarted.String()},
	)
	defer coll.RemoveAll(bson.M{"appname": "app_time_test"})
	result, err := listUnresponsiveContainers(3 * time.Minute)
	c.Assert(err, check.IsNil)
	c.Assert(len(result), check.Equals, 1)
	c.Assert(result[0].ID, check.Equals, "c2")
}

func (S) TestListRunnableContainersByApp(c *check.C) {
	var result []container
	coll := collection()
	defer coll.Close()
	coll.Insert(
		container{Name: "a", AppName: "myapp", Status: provision.StatusCreated.String()},
		container{Name: "b", AppName: "myapp", Status: provision.StatusBuilding.String()},
		container{Name: "c", AppName: "myapp", Status: provision.StatusStarting.String()},
		container{Name: "d", AppName: "myapp", Status: provision.StatusError.String()},
		container{Name: "e", AppName: "myapp", Status: provision.StatusStarted.String()},
		container{Name: "f", AppName: "myapp", Status: provision.StatusStopped.String()},
	)
	defer coll.RemoveAll(bson.M{"appname": "myapp"})
	result, err := listRunnableContainersByApp("myapp")
	c.Assert(err, check.IsNil)
	c.Assert(len(result), check.Equals, 3)
	var names []string
	for _, c := range result {
		names = append(names, c.Name)
	}
	sort.Strings(names)
	c.Assert(names, check.DeepEquals, []string{"c", "d", "e"})
}
<|endoftext|>


<commit_before>package bench

import (
	"time"
)

type Stats struct {
	Min   time.Duration
	Max   time.Duration
	Total time.Duration
	Num   int64
}

func NewStats() *Stats {
	return &Stats{
		Min: 1<<63 - 1,
	}
}

func (s *Stats) Add(td time.Duration) {
	s.Num += 1
	s.Total += td
	if td < s.Min {
		s.Min = td
	}
	if td > s.Max {
		s.Max = td
	}
}

func (s *Stats) Avg() time.Duration {
	return s.Total / time.Duration(s.Num)
}

func AddToResults(s *Stats, results map[string]interface{}) {
	results["min"] = s.Min
	results["max"] = s.Max
	results["avg"] = s.Avg()
}
<commit_msg>add option to save all stats<commit_after>package bench

import (
	"time"
)

type Stats struct {
	Min     time.Duration
	Max     time.Duration
	Total   time.Duration
	Num     int64
	All     []time.Duration
	SaveAll bool
}

func NewStats() *Stats {
	return &Stats{
		Min: 1<<63 - 1,
		All: make([]time.Duration, 0),
	}
}

func (s *Stats) Add(td time.Duration) {
	if s.SaveAll {
		s.All = append(s.All, td)
	}
	s.Num += 1
	s.Total += td
	if td < s.Min {
		s.Min = td
	}
	if td > s.Max {
		s.Max = td
	}
}

func (s *Stats) Avg() time.Duration {
	return s.Total / time.Duration(s.Num)
}

func AddToResults(s *Stats, results map[string]interface{}) {
	results["min"] = s.Min
	results["max"] = s.Max
	results["avg"] = s.Avg()
	if s.SaveAll {
		results["all"] = s.All
	}
}
<|endoftext|>


<commit_before>package models

import (
	"fmt"
	sq "github.com/Masterminds/squirrel"
	"strings"
)

type Activity struct {
	Id                uint64         `json:"id"`
	Event             string         `json:"event"`
	TargetId          uint64         `json:"target_id"`
	SourceId          uint64         `json:"source_id"`
	TargetObjectId    uint64         `json:"target_object_id"`
	RetweetedStatusId JsonNullUInt64 `json:"retweeted_status_id"`
	CreatedOn         int            `json:"created_at"`
}

func (m *Model) LoadActivities(userIdStr string, maxIdStr string, sinceIdStr string) []*Activity {
	db, err := m.Open()
	if err != nil {
		panic(err.Error())
	}
	defer db.Close()

	toId := func(id string) string {
		if id == "" {
			return ""
		} else if strings.Contains(id, ":") {
			fields := strings.Split(id, ":")
			stmtOut, err := db.Prepare("SELECT id FROM activity WHERE target_object_id = ? AND event = ? AND source_id = ? LIMIT 1")
			if err != nil {
				fmt.Println(err.Error())
				return ""
			}
			defer stmtOut.Close()
			var dbId string
			fmt.Printf("target_object_id:%s event:%s source_id:%s\n", fields[0], fields[1], fields[2])
			err = stmtOut.QueryRow(fields[0], fields[1], fields[2]).Scan(&dbId)
			if err != nil {
				fmt.Println(err.Error())
				return ""
			}
			return dbId
		} else {
			return id
		}
	}

	maxId := toId(maxIdStr)
	sinceId := toId(sinceIdStr)

	stmt := sq.
		Select("id, event, target_id, source_id, target_object_id, retweeted_status_id, created_at").
		From("activity").
		Where(sq.Eq{"target_id": userIdStr}).
		OrderBy("id DESC").
		Limit(200)

	if maxId != "" {
		stmt = stmt.Where(sq.LtOrEq{"id": maxId})
	}

	if sinceId != "" {
		stmt = stmt.Where(sq.GtOrEq{"id": sinceId})
	}

	sql, args, err := stmt.ToSql()
	if err != nil {
		panic(err.Error())
	}

	fmt.Printf("maxId:%s sinceId:%s sql:%s\n", maxId, sinceId, sql)

	rows, err := db.Query(sql, args...)
	if err != nil {
		panic(err.Error())
	}
	defer rows.Close()

	activities := []*Activity{}

	for rows.Next() {
		var id uint64
		var event string
		var targetId uint64
		var sourceId uint64
		var targetObjectId uint64
		var retweetedStatusId JsonNullUInt64
		var createdOn int
		err = rows.Scan(&id, &event, &targetId, &sourceId, &targetObjectId, &retweetedStatusId, &createdOn)
		if err != nil {
			panic(err.Error())
		}
		activity := &Activity{
			Id:                id,
			Event:             event,
			TargetId:          targetId,
			SourceId:          sourceId,
			TargetObjectId:    targetObjectId,
			RetweetedStatusId: retweetedStatusId,
			CreatedOn:         createdOn,
		}
		activities = append(activities, activity)
	}

	return activities
}
<commit_msg>Limit 200 => 100<commit_after>package models

import (
	"fmt"
	sq "github.com/Masterminds/squirrel"
	"strings"
)

type Activity struct {
	Id                uint64         `json:"id"`
	Event             string         `json:"event"`
	TargetId          uint64         `json:"target_id"`
	SourceId          uint64         `json:"source_id"`
	TargetObjectId    uint64         `json:"target_object_id"`
	RetweetedStatusId JsonNullUInt64 `json:"retweeted_status_id"`
	CreatedOn         int            `json:"created_at"`
}

func (m *Model) LoadActivities(userIdStr string, maxIdStr string, sinceIdStr string) []*Activity {
	db, err := m.Open()
	if err != nil {
		panic(err.Error())
	}
	defer db.Close()

	toId := func(id string) string {
		if id == "" {
			return ""
		} else if strings.Contains(id, ":") {
			fields := strings.Split(id, ":")
			stmtOut, err := db.Prepare("SELECT id FROM activity WHERE target_object_id = ? AND event = ? AND source_id = ? LIMIT 1")
			if err != nil {
				fmt.Println(err.Error())
				return ""
			}
			defer stmtOut.Close()
			var dbId string
			fmt.Printf("target_object_id:%s event:%s source_id:%s\n", fields[0], fields[1], fields[2])
			err = stmtOut.QueryRow(fields[0], fields[1], fields[2]).Scan(&dbId)
			if err != nil {
				fmt.Println(err.Error())
				return ""
			}
			return dbId
		} else {
			return id
		}
	}

	maxId := toId(maxIdStr)
	sinceId := toId(sinceIdStr)

	stmt := sq.
		Select("id, event, target_id, source_id, target_object_id, retweeted_status_id, created_at").
		From("activity").
		Where(sq.Eq{"target_id": userIdStr}).
		OrderBy("id DESC").
		Limit(100)

	if maxId != "" {
		stmt = stmt.Where(sq.LtOrEq{"id": maxId})
	}

	if sinceId != "" {
		stmt = stmt.Where(sq.GtOrEq{"id": sinceId})
	}

	sql, args, err := stmt.ToSql()
	if err != nil {
		panic(err.Error())
	}

	fmt.Printf("maxId:%s sinceId:%s sql:%s\n", maxId, sinceId, sql)

	rows, err := db.Query(sql, args...)
	if err != nil {
		panic(err.Error())
	}
	defer rows.Close()

	activities := []*Activity{}

	for rows.Next() {
		var id uint64
		var event string
		var targetId uint64
		var sourceId uint64
		var targetObjectId uint64
		var retweetedStatusId JsonNullUInt64
		var createdOn int
		err = rows.Scan(&id, &event, &targetId, &sourceId, &targetObjectId, &retweetedStatusId, &createdOn)
		if err != nil {
			panic(err.Error())
		}
		activity := &Activity{
			Id:                id,
			Event:             event,
			TargetId:          targetId,
			SourceId:          sourceId,
			TargetObjectId:    targetObjectId,
			RetweetedStatusId: retweetedStatusId,
			CreatedOn:         createdOn,
		}
		activities = append(activities, activity)
	}

	return activities
}
<|endoftext|>


<commit_before>package text

import (
	"image/color"
	"math"
	"unicode"
	"unicode/utf8"

	"github.com/faiface/pixel"
	"golang.org/x/image/font"
)

var ASCII []rune

func init() {
	ASCII = make([]rune, unicode.MaxASCII-32)
	for i := range ASCII {
		ASCII[i] = rune(32 + i)
	}
}

func RangeTable(table *unicode.RangeTable) []rune {
	var runes []rune
	for _, rng := range table.R16 {
		for r := rng.Lo; r <= rng.Hi; r += rng.Stride {
			runes = append(runes, rune(r))
		}
	}
	for _, rng := range table.R32 {
		for r := rng.Lo; r <= rng.Hi; r += rng.Stride {
			runes = append(runes, rune(r))
		}
	}
	return runes
}

type Text struct {
	Orig pixel.Vec
	Dot  pixel.Vec

	atlas *Atlas

	lineHeight float64
	tabWidth   float64

	buf    []byte
	prevR  rune
	bounds pixel.Rect
	glyph  pixel.TrianglesData
	tris   pixel.TrianglesData

	mat    pixel.Matrix
	col    pixel.RGBA
	trans  pixel.TrianglesData
	transD pixel.Drawer
	dirty  bool
}

func New(face font.Face, runeSets ...[]rune) *Text {
	runes := []rune{unicode.ReplacementChar}
	for _, set := range runeSets {
		runes = append(runes, set...)
	}

	atlas := NewAtlas(face, runes)

	txt := &Text{
		atlas:      atlas,
		lineHeight: atlas.LineHeight(),
		tabWidth:   atlas.Glyph(' ').Advance * 4,
		mat:        pixel.IM,
		col:        pixel.Alpha(1),
	}

	txt.glyph.SetLen(6)
	for i := range txt.glyph {
		txt.glyph[i].Color = pixel.Alpha(1)
		txt.glyph[i].Intensity = 1
	}

	txt.transD.Picture = txt.atlas.pic
	txt.transD.Triangles = &txt.trans

	txt.Clear()

	return txt
}

func (txt *Text) Atlas() *Atlas {
	return txt.atlas
}

func (txt *Text) SetMatrix(m pixel.Matrix) {
	if txt.mat != m {
		txt.mat = m
		txt.dirty = true
	}
}

func (txt *Text) SetColorMask(c color.Color) {
	rgba := pixel.ToRGBA(c)
	if txt.col != rgba {
		txt.col = rgba
		txt.dirty = true
	}
}

func (txt *Text) Bounds() pixel.Rect {
	return txt.bounds
}

func (txt *Text) BoundsOf(s string) pixel.Rect {
	dot := txt.Dot
	prevR := txt.prevR
	bounds := pixel.Rect{}

	for _, r := range s {
		var control bool
		dot, control = txt.controlRune(r, dot)
		if control {
			continue
		}

		var b pixel.Rect
		_, _, b, dot = txt.Atlas().DrawRune(prevR, r, dot)

		if bounds.W()*bounds.H() == 0 {
			bounds = b
		} else {
			bounds = bounds.Union(b)
		}

		prevR = r
	}

	return bounds
}

func (txt *Text) Color(c color.Color) {
	rgba := pixel.ToRGBA(c)
	for i := range txt.glyph {
		txt.glyph[i].Color = rgba
	}
}

func (txt *Text) LineHeight(scale float64) {
	txt.lineHeight = scale
}

func (txt *Text) TabWidth(width float64) {
	txt.tabWidth = width
}

func (txt *Text) Clear() {
	txt.prevR = -1
	txt.bounds = pixel.Rect{}
	txt.tris.SetLen(0)
	txt.dirty = true
}

func (txt *Text) Write(p []byte) (n int, err error) {
	txt.buf = append(txt.buf, p...)
	txt.drawBuf()
	return len(p), nil
}

func (txt *Text) WriteString(s string) (n int, err error) {
	txt.buf = append(txt.buf, s...)
	txt.drawBuf()
	return len(s), nil
}

func (txt *Text) WriteByte(c byte) error {
	txt.buf = append(txt.buf, c)
	txt.drawBuf()
	return nil
}

func (txt *Text) WriteRune(r rune) (n int, err error) {
	var b [4]byte
	n = utf8.EncodeRune(b[:], r)
	txt.buf = append(txt.buf, b[:n]...)
	txt.drawBuf()
	return n, nil
}

// controlRune checks if r is a control rune (newline, tab, ...). If it is, a new dot position and
// true is returned. If r is not a control rune, the original dot and false is returned.
func (txt *Text) controlRune(r rune, dot pixel.Vec) (newDot pixel.Vec, control bool) {
	switch r {
	case '\n':
		dot -= pixel.Y(txt.lineHeight)
		dot = dot.WithX(txt.Orig.X())
	case '\r':
		dot = dot.WithX(txt.Orig.X())
	case '\t':
		rem := math.Mod(dot.X()-txt.Orig.X(), txt.tabWidth)
		rem = math.Mod(rem, rem+txt.tabWidth)
		if rem == 0 {
			rem = txt.tabWidth
		}
		dot += pixel.X(rem)
	default:
		return dot, false
	}
	return dot, true
}

func (txt *Text) drawBuf() {
	for utf8.FullRune(txt.buf) {
		r, size := utf8.DecodeRune(txt.buf)
		txt.buf = txt.buf[size:]

		var control bool
		txt.Dot, control = txt.controlRune(r, txt.Dot)
		if control {
			continue
		}

		var rect, frame, bounds pixel.Rect
		rect, frame, bounds, txt.Dot = txt.Atlas().DrawRune(txt.prevR, r, txt.Dot)

		txt.prevR = r

		rv := [...]pixel.Vec{pixel.V(rect.Min.X(), rect.Min.Y()),
			pixel.V(rect.Max.X(), rect.Min.Y()),
			pixel.V(rect.Max.X(), rect.Max.Y()),
			pixel.V(rect.Min.X(), rect.Max.Y()),
		}

		fv := [...]pixel.Vec{pixel.V(frame.Min.X(), frame.Min.Y()),
			pixel.V(frame.Max.X(), frame.Min.Y()),
			pixel.V(frame.Max.X(), frame.Max.Y()),
			pixel.V(frame.Min.X(), frame.Max.Y()),
		}

		for i, j := range [...]int{0, 1, 2, 0, 2, 3} {
			txt.glyph[i].Position = rv[j]
			txt.glyph[i].Picture = fv[j]
		}

		txt.tris = append(txt.tris, txt.glyph...)
		txt.dirty = true

		if txt.bounds.W()*txt.bounds.H() == 0 {
			txt.bounds = bounds
		} else {
			txt.bounds = txt.bounds.Union(bounds)
		}
	}
}

func (txt *Text) Draw(t pixel.Target) {
	if txt.dirty {
		txt.trans.SetLen(txt.tris.Len())
		txt.trans.Update(&txt.tris)

		for i := range txt.trans {
			txt.trans[i].Position = txt.mat.Project(txt.trans[i].Position)
			txt.trans[i].Color = txt.trans[i].Color.Mul(txt.col)
		}

		txt.transD.Dirty()
		txt.dirty = false
	}

	txt.transD.Draw(t)
}
<commit_msg>rename Text.LineHeight(scale) -> height, since now it's absolute height<commit_after>package text

import (
	"image/color"
	"math"
	"unicode"
	"unicode/utf8"

	"github.com/faiface/pixel"
	"golang.org/x/image/font"
)

var ASCII []rune

func init() {
	ASCII = make([]rune, unicode.MaxASCII-32)
	for i := range ASCII {
		ASCII[i] = rune(32 + i)
	}
}

func RangeTable(table *unicode.RangeTable) []rune {
	var runes []rune
	for _, rng := range table.R16 {
		for r := rng.Lo; r <= rng.Hi; r += rng.Stride {
			runes = append(runes, rune(r))
		}
	}
	for _, rng := range table.R32 {
		for r := rng.Lo; r <= rng.Hi; r += rng.Stride {
			runes = append(runes, rune(r))
		}
	}
	return runes
}

type Text struct {
	Orig pixel.Vec
	Dot  pixel.Vec

	atlas *Atlas

	lineHeight float64
	tabWidth   float64

	buf    []byte
	prevR  rune
	bounds pixel.Rect
	glyph  pixel.TrianglesData
	tris   pixel.TrianglesData

	mat    pixel.Matrix
	col    pixel.RGBA
	trans  pixel.TrianglesData
	transD pixel.Drawer
	dirty  bool
}

func New(face font.Face, runeSets ...[]rune) *Text {
	runes := []rune{unicode.ReplacementChar}
	for _, set := range runeSets {
		runes = append(runes, set...)
	}

	atlas := NewAtlas(face, runes)

	txt := &Text{
		atlas:      atlas,
		lineHeight: atlas.LineHeight(),
		tabWidth:   atlas.Glyph(' ').Advance * 4,
		mat:        pixel.IM,
		col:        pixel.Alpha(1),
	}

	txt.glyph.SetLen(6)
	for i := range txt.glyph {
		txt.glyph[i].Color = pixel.Alpha(1)
		txt.glyph[i].Intensity = 1
	}

	txt.transD.Picture = txt.atlas.pic
	txt.transD.Triangles = &txt.trans

	txt.Clear()

	return txt
}

func (txt *Text) Atlas() *Atlas {
	return txt.atlas
}

func (txt *Text) SetMatrix(m pixel.Matrix) {
	if txt.mat != m {
		txt.mat = m
		txt.dirty = true
	}
}

func (txt *Text) SetColorMask(c color.Color) {
	rgba := pixel.ToRGBA(c)
	if txt.col != rgba {
		txt.col = rgba
		txt.dirty = true
	}
}

func (txt *Text) Bounds() pixel.Rect {
	return txt.bounds
}

func (txt *Text) BoundsOf(s string) pixel.Rect {
	dot := txt.Dot
	prevR := txt.prevR
	bounds := pixel.Rect{}

	for _, r := range s {
		var control bool
		dot, control = txt.controlRune(r, dot)
		if control {
			continue
		}

		var b pixel.Rect
		_, _, b, dot = txt.Atlas().DrawRune(prevR, r, dot)

		if bounds.W()*bounds.H() == 0 {
			bounds = b
		} else {
			bounds = bounds.Union(b)
		}

		prevR = r
	}

	return bounds
}

func (txt *Text) Color(c color.Color) {
	rgba := pixel.ToRGBA(c)
	for i := range txt.glyph {
		txt.glyph[i].Color = rgba
	}
}

func (txt *Text) LineHeight(height float64) {
	txt.lineHeight = height
}

func (txt *Text) TabWidth(width float64) {
	txt.tabWidth = width
}

func (txt *Text) Clear() {
	txt.prevR = -1
	txt.bounds = pixel.Rect{}
	txt.tris.SetLen(0)
	txt.dirty = true
}

func (txt *Text) Write(p []byte) (n int, err error) {
	txt.buf = append(txt.buf, p...)
	txt.drawBuf()
	return len(p), nil
}

func (txt *Text) WriteString(s string) (n int, err error) {
	txt.buf = append(txt.buf, s...)
	txt.drawBuf()
	return len(s), nil
}

func (txt *Text) WriteByte(c byte) error {
	txt.buf = append(txt.buf, c)
	txt.drawBuf()
	return nil
}

func (txt *Text) WriteRune(r rune) (n int, err error) {
	var b [4]byte
	n = utf8.EncodeRune(b[:], r)
	txt.buf = append(txt.buf, b[:n]...)
	txt.drawBuf()
	return n, nil
}

// controlRune checks if r is a control rune (newline, tab, ...). If it is, a new dot position and
// true is returned. If r is not a control rune, the original dot and false is returned.
func (txt *Text) controlRune(r rune, dot pixel.Vec) (newDot pixel.Vec, control bool) {
	switch r {
	case '\n':
		dot -= pixel.Y(txt.lineHeight)
		dot = dot.WithX(txt.Orig.X())
	case '\r':
		dot = dot.WithX(txt.Orig.X())
	case '\t':
		rem := math.Mod(dot.X()-txt.Orig.X(), txt.tabWidth)
		rem = math.Mod(rem, rem+txt.tabWidth)
		if rem == 0 {
			rem = txt.tabWidth
		}
		dot += pixel.X(rem)
	default:
		return dot, false
	}
	return dot, true
}

func (txt *Text) drawBuf() {
	for utf8.FullRune(txt.buf) {
		r, size := utf8.DecodeRune(txt.buf)
		txt.buf = txt.buf[size:]

		var control bool
		txt.Dot, control = txt.controlRune(r, txt.Dot)
		if control {
			continue
		}

		var rect, frame, bounds pixel.Rect
		rect, frame, bounds, txt.Dot = txt.Atlas().DrawRune(txt.prevR, r, txt.Dot)

		txt.prevR = r

		rv := [...]pixel.Vec{pixel.V(rect.Min.X(), rect.Min.Y()),
			pixel.V(rect.Max.X(), rect.Min.Y()),
			pixel.V(rect.Max.X(), rect.Max.Y()),
			pixel.V(rect.Min.X(), rect.Max.Y()),
		}

		fv := [...]pixel.Vec{pixel.V(frame.Min.X(), frame.Min.Y()),
			pixel.V(frame.Max.X(), frame.Min.Y()),
			pixel.V(frame.Max.X(), frame.Max.Y()),
			pixel.V(frame.Min.X(), frame.Max.Y()),
		}

		for i, j := range [...]int{0, 1, 2, 0, 2, 3} {
			txt.glyph[i].Position = rv[j]
			txt.glyph[i].Picture = fv[j]
		}

		txt.tris = append(txt.tris, txt.glyph...)
		txt.dirty = true

		if txt.bounds.W()*txt.bounds.H() == 0 {
			txt.bounds = bounds
		} else {
			txt.bounds = txt.bounds.Union(bounds)
		}
	}
}

func (txt *Text) Draw(t pixel.Target) {
	if txt.dirty {
		txt.trans.SetLen(txt.tris.Len())
		txt.trans.Update(&txt.tris)

		for i := range txt.trans {
			txt.trans[i].Position = txt.mat.Project(txt.trans[i].Position)
			txt.trans[i].Color = txt.trans[i].Color.Mul(txt.col)
		}

		txt.transD.Dirty()
		txt.dirty = false
	}

	txt.transD.Draw(t)
}
<|endoftext|>


<commit_before>package api

import (
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"regexp"

	"github.com/AlekSi/pointer"
	log "github.com/Sirupsen/logrus"
	"github.com/diyan/assimilator/interfaces"
	"github.com/diyan/assimilator/models"
	"github.com/labstack/echo"
	uuid "github.com/satori/go.uuid"
)

func storeGetView(c echo.Context) error {
	return renderNotImplemented(c)
}

var eventIDRegex = regexp.MustCompile("^[a-fA-F0-9]{32}$")

var validPlatforms = map[string]bool{
	"as3":        true,
	"c":          true,
	"cfml":       true,
	"cocoa":      true,
	"csharp":     true,
	"go":         true,
	"java":       true,
	"javascript": true,
	"node":       true,
	"objc":       true,
	"other":      true,
	"perl":       true,
	"php":        true,
	"python":     true,
	"ruby":       true,
	"elixir":     true,
	"haskell":    true,
	"groovy":     true,
}

type EventDetails struct {
	models.EventDetails
	interfaces.EventInterfaces
}

func anyTypeToString(v interface{}) string {
	if v != nil {
		return fmt.Sprint(v)
	}
	return ""
}

func simpleTypeToString(v interface{}) (rv string, ok bool) {
	ok = true
	switch v.(type) {
	case string, bool, float64: // JSON basic types
		rv = fmt.Sprint(v)
	case nil:
		rv = ""
	default:
		ok = false
	}
	return
}

// TODO implement interfaces for breadcrumbs, request, user (used by JavaScript client)
func bindRequest(project models.Project, requestBody io.ReadCloser, event *EventDetails) error {
	event.ProjectID = project.ID

	rawEvent := map[string]interface{}{}
	if err := json.NewDecoder(requestBody).Decode(&rawEvent); err != nil {
		return err
	}
	// Ensure all keys are expected
	// Bind event attributes
	// Bind event interfaces

	if rawEventID, ok := rawEvent["event_id"]; ok {
		if eventID, ok := rawEventID.(string); ok {
			if eventIDRegex.MatchString(eventID) {
				event.EventID = eventID
			} else {
				trackError(event, "event_id", eventID, errors.New("value does not match regex pattern"))
				event.EventID = newUUIDHexString()
			}
		} else {
			return errors.New("Invalid value for event_id")
		}
	} else {
		event.EventID = newUUIDHexString()
	}

	if rawCulprit, ok := rawEvent["culprit"]; ok {
		if culprit, ok := rawCulprit.(string); ok {
			event.Culprit = culprit
		} else {
			return errors.New("Invalid value for culprit")
		}
	}

	event.Logger = anyTypeToString(rawEvent["logger"]) // TODO check code
	event.Release = pointer.ToString(anyTypeToString(rawEvent["release"]))

	rawPlatform := anyTypeToString(rawEvent["platform"])
	if validPlatforms[rawPlatform] {
		event.Platform = rawPlatform
	} else {
		event.Platform = "other"
	}

	if timestamp, ok := rawEvent["timestamp"]; ok {
		if err := bindTimestamp(timestamp, event); err != nil {
			trackError(event, "timestamp", timestamp, err)
		}
	}

	if rawFingerprint, ok := rawEvent["fingerprint"]; ok {
		invalidFingerprint := false
		if fingerprintSlice, ok := rawFingerprint.([]interface{}); ok {
			for _, fingerprintLine := range fingerprintSlice {
				if value, ok := simpleTypeToString(fingerprintLine); ok {
					event.Fingerprint = append(event.Fingerprint, anyTypeToString(value))
				} else {
					invalidFingerprint = true
				}
				switch value := fingerprintLine.(type) {

				case string, bool, float64:
					event.Fingerprint = append(event.Fingerprint, anyTypeToString(value))
				default:
					invalidFingerprint = true
				}
			}
		} else {
			invalidFingerprint = true
		}
		if invalidFingerprint {
			trackError(event, "fingerprint", rawFingerprint, errors.New("array of booleans, numbers, strings is expected"))
			event.Fingerprint = nil // all or nothing
		}
	}

	if rawModules, ok := rawEvent["modules"]; ok {
		if modules, ok := rawModules.(map[string]interface{}); ok {
			event.Modules = modules
		} else {
			trackError(event, "modules", rawModules, errors.New("type is not map[string]interface{}"))
		}
	}

	if rawExtra, ok := rawEvent["extra"]; ok {
		if extra, ok := rawExtra.(map[string]interface{}); ok {
			// TODO HTTP POST uses `extra` name but HTTP GET uses `context` name
			event.Context = extra
		} else {
			trackError(event, "extra", rawExtra, errors.New("type is not map[string]interface{}"))
		}
	}

	// Valid tags are both {"tagKey": "tagValue"} and [["tagKey", "tagValue"]]
	if rawTags, ok := rawEvent["tags"]; ok {
		if tagsMap, ok := rawTags.(map[string]interface{}); ok {
			for k, v := range tagsMap {
				// TODO check length of tag key and tag value
				event.Tags = append(event.Tags, models.TagKeyValue{
					Key: anyTypeToString(k), Value: anyTypeToString(v),
				})
			}
		} else if tagsSlice, ok := rawTags.([]interface{}); ok {
			for _, tagBlob := range tagsSlice {
				// TODO safe type assertion
				tag := tagBlob.([]interface{})
				// TODO check length of tag key and tag value
				event.Tags = append(event.Tags, models.TagKeyValue{
					Key: anyTypeToString(tag[0]), Value: anyTypeToString(tag[1]),
				})
			}
		} else {
			trackError(event, "tags", rawTags, errors.New("type is neither map[string]interface{} nor []interface{}"))
		}
	}

	// TODO handle error
	event.EventInterfaces.UnmarshalAPI(rawEvent)
	//pp.Print(event)
	return nil
}

func trackError(event *EventDetails, name string, value interface{}, err error) {
	log.WithFields(log.Fields{
		name:  value,
		"err": err,
	}).Debug("Discarded invalid value")
	event.Errors = append(event.Errors, models.EventError{
		Type:  models.EventErrorInvalidData,
		Name:  name,
		Value: value,
	})
}

func storePostView(c echo.Context) error {
	// TODO move GetProject to the package shared between api/endpoints and web/api
	//project := GetProject(c)
	project := models.Project{ID: 1}
	event := EventDetails{}
	if err := bindRequest(project, c.Request().Body, &event); err != nil {
		return err
	}
	return c.JSON(200, map[string]string{"id": event.EventID})
}

// TODO timestamp could be either float or string
func bindTimestamp(timestamp interface{}, event *EventDetails) error {
	return nil
}

func newUUIDHexString() string {
	return hex.EncodeToString(uuid.NewV4().Bytes())
}
<commit_msg>Use mapstructure for EventDetails.UnmarshalAPI<commit_after>package api

import (
	"encoding/hex"
	"encoding/json"
	"io"
	"regexp"

	"github.com/diyan/assimilator/interfaces"
	"github.com/diyan/assimilator/models"
	"github.com/k0kubun/pp"
	"github.com/labstack/echo"
	"github.com/mitchellh/mapstructure"
	"github.com/pkg/errors"
	uuid "github.com/satori/go.uuid"
)

func storeGetView(c echo.Context) error {
	return renderNotImplemented(c)
}

var eventIDRegex = regexp.MustCompile("^[a-fA-F0-9]{32}$")

var validPlatforms = map[string]bool{
	"as3":        true,
	"c":          true,
	"cfml":       true,
	"cocoa":      true,
	"csharp":     true,
	"go":         true,
	"java":       true,
	"javascript": true,
	"node":       true,
	"objc":       true,
	"other":      true,
	"perl":       true,
	"php":        true,
	"python":     true,
	"ruby":       true,
	"elixir":     true,
	"haskell":    true,
	"groovy":     true,
}

type EventDetails struct {
	models.EventDetails
	interfaces.EventInterfaces
}

// TODO implement interfaces for breadcrumbs, request, user (used by JavaScript client)
func bindRequest(project models.Project, requestBody io.ReadCloser, event *EventDetails) error {
	event.ProjectID = project.ID

	rawEvent := map[string]interface{}{}
	if err := json.NewDecoder(requestBody).Decode(&rawEvent); err != nil {
		return err
	}
	// Ensure all keys are expected
	// Bind event attributes
	// Bind event interfaces

	metadata := mapstructure.Metadata{}
	decodeHook := mapstructure.ComposeDecodeHookFunc(models.TimeDecodeHook, models.TagsDecodeHook)
	config := mapstructure.DecoderConfig{
		DecodeHook:       decodeHook,
		Metadata:         &metadata,
		WeaklyTypedInput: false,
		Result:           &event.EventDetails,
	}
	decoder, err := mapstructure.NewDecoder(&config)
	if err != nil {
		pp.Print(err)
		return errors.Wrapf(err, "can not parse request body to event details")
	}
	if err := decoder.Decode(rawEvent); err != nil {
		pp.Print(err)
		errors.Wrapf(err, "can not parse request body to event details")
	}
	if !validPlatforms[event.Platform] {
		event.Platform = "other"
	}
	//pp.Print(metadata.Unused)
	//pp.Print(event)

	// TODO handle error
	event.EventInterfaces.UnmarshalAPI(rawEvent)
	return nil
}

func storePostView(c echo.Context) error {
	// TODO move GetProject to the package shared between api/endpoints and web/api
	//project := GetProject(c)
	project := models.Project{ID: 1}
	event := EventDetails{}
	if err := bindRequest(project, c.Request().Body, &event); err != nil {
		return err
	}
	return c.JSON(200, map[string]string{"id": event.EventID})
}

func newUUIDHexString() string {
	return hex.EncodeToString(uuid.NewV4().Bytes())
}
<|endoftext|>


<commit_before>/*
Copyright 2015 The Kubernetes Authors 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.
*/

package github

import (
	"fmt"
	"time"

	"k8s.io/kubernetes/pkg/util"

	"github.com/golang/glog"
	"github.com/google/go-github/github"
	"golang.org/x/oauth2"
)

func MakeClient(token string) *github.Client {
	if len(token) > 0 {
		ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
		tc := oauth2.NewClient(oauth2.NoContext, ts)
		return github.NewClient(tc)
	}
	return github.NewClient(nil)
}

func hasLabel(labels []github.Label, name string) bool {
	for i := range labels {
		label := &labels[i]
		if label.Name != nil && *label.Name == name {
			return true
		}
	}
	return false
}

func hasLabels(labels []github.Label, names []string) bool {
	for i := range names {
		if !hasLabel(labels, names[i]) {
			return false
		}
	}
	return true
}

func fetchAllPRs(client *github.Client, user, project string) ([]github.PullRequest, error) {
	page := 1
	var result []github.PullRequest
	for {
		glog.V(4).Infof("Fetching page %d", page)
		listOpts := &github.PullRequestListOptions{
			Sort:        "desc",
			ListOptions: github.ListOptions{PerPage: 100, Page: page},
		}
		prs, response, err := client.PullRequests.List(user, project, listOpts)
		if err != nil {
			return nil, err
		}
		result = append(result, prs...)
		if response.LastPage == 0 || response.LastPage == page {
			break
		}
		page++
	}
	return result, nil
}

type PRFunction func(*github.Client, *github.PullRequest, *github.Issue) error

type FilterConfig struct {
	MinPRNumber            int
	UserWhitelist          []string
	WhitelistOverride      string
	RequiredStatusContexts []string
}

func lastModifiedTime(client *github.Client, user, project string, pr *github.PullRequest) (*time.Time, error) {
	list, _, err := client.PullRequests.ListCommits(user, project, *pr.Number, &github.ListOptions{})
	if err != nil {
		return nil, err
	}
	var lastModified *time.Time
	for ix := range list {
		item := list[ix]
		if lastModified == nil || item.Commit.Committer.Date.After(*lastModified) {
			lastModified = item.Commit.Committer.Date
		}
	}
	return lastModified, nil
}

func validateLGTMAfterPush(client *github.Client, user, project string, pr *github.PullRequest, lastModifiedTime *time.Time) (bool, error) {
	var lgtmTime *time.Time
	events, _, err := client.Issues.ListIssueEvents(user, project, *pr.Number, &github.ListOptions{})
	if err != nil {
		glog.Errorf("Error getting events for issue: %v", err)
		return false, err
	}
	for ix := range events {
		event := &events[ix]
		if *event.Event == "labeled" && *event.Label.Name == "lgtm" {
			if lgtmTime == nil || event.CreatedAt.After(*lgtmTime) {
				lgtmTime = event.CreatedAt
			}
		}
	}
	if lgtmTime == nil {
		return false, fmt.Errorf("Couldn't find time for LGTM label, this shouldn't happen, skipping PR: %d", *pr.Number)
	}
	return lastModifiedTime.Before(*lgtmTime), nil
}

// For each PR in the project that matches:
//   * pr.Number > minPRNumber
//   * is mergeable
//   * has labels "cla: yes", "lgtm"
//   * combinedStatus = 'success' (e.g. all hooks have finished success in github)
// Run the specified function
func ForEachCandidatePRDo(client *github.Client, user, project string, fn PRFunction, once bool, config *FilterConfig) error {
	// Get all PRs
	prs, err := fetchAllPRs(client, user, project)
	if err != nil {
		return err
	}

	userSet := util.StringSet{}
	userSet.Insert(config.UserWhitelist...)

	for ix := range prs {
		if prs[ix].User == nil || prs[ix].User.Login == nil {
			glog.V(2).Infof("Skipping PR %d with no user info %v.", *prs[ix].Number, *prs[ix].User)
			continue
		}
		if *prs[ix].Number < config.MinPRNumber {
			glog.V(6).Infof("Dropping %d < %d", *prs[ix].Number, config.MinPRNumber)
			continue
		}
		pr, _, err := client.PullRequests.Get(user, project, *prs[ix].Number)
		if err != nil {
			glog.Errorf("Error getting pull request: %v", err)
			continue
		}
		glog.V(2).Infof("----==== %d ====----", *pr.Number)

		// Labels are actually stored in the Issues API, not the Pull Request API
		issue, _, err := client.Issues.Get(user, project, *pr.Number)
		if err != nil {
			glog.Errorf("Failed to get issue for PR: %v", err)
			continue
		}

		glog.V(8).Infof("%v", issue.Labels)
		if !hasLabels(issue.Labels, []string{"lgtm", "cla: yes"}) {
			continue
		}
		if !hasLabel(issue.Labels, config.WhitelistOverride) && !userSet.Has(*prs[ix].User.Login) {
			glog.V(4).Infof("Dropping %d since %s isn't in whitelist and %s isn't present", *prs[ix].Number, *prs[ix].User.Login, config.WhitelistOverride)
			continue
		}

		lastModifiedTime, err := lastModifiedTime(client, user, project, pr)
		if err != nil {
			glog.Errorf("Failed to get last modified time, skipping PR: %d", *pr.Number)
			continue
		}
		if ok, err := validateLGTMAfterPush(client, user, project, pr, lastModifiedTime); err != nil {
			glog.Errorf("Error validating LGTM: %v, Skipping: %d", err, *pr.Number)
			continue
		} else if !ok {
			glog.Errorf("PR pushed after LGTM, attempting to remove LGTM and skipping")
			staleLGTMBody := "LGTM was before last commit, removing LGTM"
			if _, _, err := client.Issues.CreateComment(user, project, *pr.Number, &github.IssueComment{Body: &staleLGTMBody}); err != nil {
				glog.Warningf("Failed to create remove label comment: %v", err)
			}
			if _, err := client.Issues.RemoveLabelForIssue(user, project, *pr.Number, "lgtm"); err != nil {
				glog.Warningf("Failed to remove 'lgtm' label for stale lgtm on %d", *pr.Number)
			}
			continue
		}

		// This is annoying, github appears to only temporarily cache mergeability, if it is nil, wait
		// for an async refresh and retry.
		if pr.Mergeable == nil {
			glog.Infof("Waiting for mergeability on %s %d", *pr.Title, *pr.Number)
			// TODO: determine what a good empirical setting for this is.
			time.Sleep(10 * time.Second)
			pr, _, err = client.PullRequests.Get(user, project, *prs[ix].Number)
		}
		if pr.Mergeable == nil {
			glog.Errorf("No mergeability information for %s %d, Skipping.", *pr.Title, *pr.Number)
			continue
		}
		if !*pr.Mergeable {
			continue
		}

		// Validate the status information for this PR
		ok, err := ValidateStatus(client, user, project, *pr.Number, config.RequiredStatusContexts, false)
		if err != nil {
			glog.Errorf("Error validating PR status: %v", err)
			continue
		}
		if !ok {
			continue
		}
		if err := fn(client, pr, issue); err != nil {
			glog.Errorf("Failed to run user function: %v", err)
			continue
		}
		if once {
			break
		}
	}
	return nil
}

func getCommitStatus(client *github.Client, user, project string, prNumber int) ([]*github.CombinedStatus, error) {
	commits, _, err := client.PullRequests.ListCommits(user, project, prNumber, &github.ListOptions{})
	if err != nil {
		return nil, err
	}
	commitStatus := make([]*github.CombinedStatus, len(commits))
	for ix := range commits {
		commit := &commits[ix]
		statusList, _, err := client.Repositories.GetCombinedStatus(user, project, *commit.SHA, &github.ListOptions{})
		if err != nil {
			return nil, err
		}
		commitStatus[ix] = statusList
	}
	return commitStatus, nil
}

// Gets the current status of a PR by introspecting the status of the commits in the PR.
// The rules are:
//    * If any member of the 'requiredContexts' list is missing, it is 'incomplete'
//    * If any commit is 'pending', the PR is 'pending'
//    * If any commit is 'error', the PR is in 'error'
//    * If any commit is 'failure', the PR is 'failure'
//    * Otherwise the PR is 'success'
func GetStatus(client *github.Client, user, project string, prNumber int, requiredContexts []string) (string, error) {
	statusList, err := getCommitStatus(client, user, project, prNumber)
	if err != nil {
		return "", err
	}
	return computeStatus(statusList, requiredContexts), nil
}

func computeStatus(statusList []*github.CombinedStatus, requiredContexts []string) string {
	states := util.StringSet{}
	providers := util.StringSet{}
	for ix := range statusList {
		status := statusList[ix]
		glog.V(8).Infof("Checking commit: %s", *status.SHA)
		glog.V(8).Infof("Checking commit: %v", status)
		states.Insert(*status.State)

		for _, subStatus := range status.Statuses {
			glog.V(8).Infof("Found status from: %v", subStatus)
			providers.Insert(*subStatus.Context)
		}
	}
	for _, provider := range requiredContexts {
		if !providers.Has(provider) {
			glog.V(8).Infof("Failed to find %s in %v", provider, providers)
			return "incomplete"
		}
	}

	switch {
	case states.Has("pending"):
		return "pending"
	case states.Has("error"):
		return "error"
	case states.Has("failure"):
		return "failure"
	default:
		return "success"
	}
}

// Make sure that the combined status for all commits in a PR is 'success'
// if 'waitForPending' is true, this function will wait until the PR is no longer pending (all checks have run)
func ValidateStatus(client *github.Client, user, project string, prNumber int, requiredContexts []string, waitOnPending bool) (bool, error) {
	pending := true
	for pending {
		status, err := GetStatus(client, user, project, prNumber, requiredContexts)
		if err != nil {
			return false, err
		}
		switch status {
		case "error", "failure":
			return false, nil
		case "pending":
			if !waitOnPending {
				return false, nil
			}
			pending = true
			glog.V(4).Info("PR is pending, waiting for 30 seconds")
			time.Sleep(30 * time.Second)
		case "success":
			return true, nil
		case "incomplete":
			return false, nil
		default:
			return false, fmt.Errorf("unknown status: %s", status)
		}
	}
	return true, nil
}

// Wait for a PR to move into Pending.  This is useful because the request to test a PR again
// is asynchronous with the PR actually moving into a pending state
// TODO: add a timeout
func WaitForPending(client *github.Client, user, project string, prNumber int) error {
	for {
		status, err := GetStatus(client, user, project, prNumber, []string{})
		if err != nil {
			return err
		}
		if status == "pending" {
			return nil
		}
		glog.V(4).Info("PR is not pending, waiting for 30 seconds")
		time.Sleep(30 * time.Second)
	}
}
<commit_msg>Add rate limiting and http caching to the github client.<commit_after>/*
Copyright 2015 The Kubernetes Authors 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.
*/

package github

import (
	"fmt"
	"net/http"
	"time"

	"k8s.io/kubernetes/pkg/util"

	"github.com/golang/glog"
	"github.com/google/go-github/github"
	"github.com/gregjones/httpcache"
	"golang.org/x/oauth2"
)

type RateLimitRoundTripper struct {
	delegate http.RoundTripper
	throttle util.RateLimiter
}

func (r *RateLimitRoundTripper) RoundTrip(req *http.Request) (resp *http.Response, err error) {
	r.throttle.Accept()
	return r.delegate.RoundTrip(req)
}

func MakeClient(token string) *github.Client {
	var client *http.Client
	cacheTransport := httpcache.NewMemoryCacheTransport()
	if len(token) > 0 {
		rateLimitTransport := &RateLimitRoundTripper{
			delegate: cacheTransport,
			// Global limit is 5000 Q/Hour, try to only use 1800 to make room for other apps
			throttle: util.NewTokenBucketRateLimiter(0.5, 10),
		}
		ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
		client = &http.Client{
			Transport: &oauth2.Transport{
				Base:   rateLimitTransport,
				Source: oauth2.ReuseTokenSource(nil, ts),
			},
		}
	} else {
		rateLimitTransport := &RateLimitRoundTripper{
			delegate: cacheTransport,
			throttle: util.NewTokenBucketRateLimiter(0.01, 10),
		}
		client = &http.Client{
			Transport: rateLimitTransport,
		}
	}
	return github.NewClient(client)
}

func hasLabel(labels []github.Label, name string) bool {
	for i := range labels {
		label := &labels[i]
		if label.Name != nil && *label.Name == name {
			return true
		}
	}
	return false
}

func hasLabels(labels []github.Label, names []string) bool {
	for i := range names {
		if !hasLabel(labels, names[i]) {
			return false
		}
	}
	return true
}

func fetchAllPRs(client *github.Client, user, project string) ([]github.PullRequest, error) {
	page := 1
	var result []github.PullRequest
	for {
		glog.V(4).Infof("Fetching page %d", page)
		listOpts := &github.PullRequestListOptions{
			Sort:        "desc",
			ListOptions: github.ListOptions{PerPage: 100, Page: page},
		}
		prs, response, err := client.PullRequests.List(user, project, listOpts)
		if err != nil {
			return nil, err
		}
		result = append(result, prs...)
		if response.LastPage == 0 || response.LastPage == page {
			break
		}
		page++
	}
	return result, nil
}

type PRFunction func(*github.Client, *github.PullRequest, *github.Issue) error

type FilterConfig struct {
	MinPRNumber            int
	UserWhitelist          []string
	WhitelistOverride      string
	RequiredStatusContexts []string
}

func lastModifiedTime(client *github.Client, user, project string, pr *github.PullRequest) (*time.Time, error) {
	list, _, err := client.PullRequests.ListCommits(user, project, *pr.Number, &github.ListOptions{})
	if err != nil {
		return nil, err
	}
	var lastModified *time.Time
	for ix := range list {
		item := list[ix]
		if lastModified == nil || item.Commit.Committer.Date.After(*lastModified) {
			lastModified = item.Commit.Committer.Date
		}
	}
	return lastModified, nil
}

func validateLGTMAfterPush(client *github.Client, user, project string, pr *github.PullRequest, lastModifiedTime *time.Time) (bool, error) {
	var lgtmTime *time.Time
	events, _, err := client.Issues.ListIssueEvents(user, project, *pr.Number, &github.ListOptions{})
	if err != nil {
		glog.Errorf("Error getting events for issue: %v", err)
		return false, err
	}
	for ix := range events {
		event := &events[ix]
		if *event.Event == "labeled" && *event.Label.Name == "lgtm" {
			if lgtmTime == nil || event.CreatedAt.After(*lgtmTime) {
				lgtmTime = event.CreatedAt
			}
		}
	}
	if lgtmTime == nil {
		return false, fmt.Errorf("Couldn't find time for LGTM label, this shouldn't happen, skipping PR: %d", *pr.Number)
	}
	return lastModifiedTime.Before(*lgtmTime), nil
}

// For each PR in the project that matches:
//   * pr.Number > minPRNumber
//   * is mergeable
//   * has labels "cla: yes", "lgtm"
//   * combinedStatus = 'success' (e.g. all hooks have finished success in github)
// Run the specified function
func ForEachCandidatePRDo(client *github.Client, user, project string, fn PRFunction, once bool, config *FilterConfig) error {
	// Get all PRs
	prs, err := fetchAllPRs(client, user, project)
	if err != nil {
		return err
	}

	userSet := util.StringSet{}
	userSet.Insert(config.UserWhitelist...)

	for ix := range prs {
		if prs[ix].User == nil || prs[ix].User.Login == nil {
			glog.V(2).Infof("Skipping PR %d with no user info %v.", *prs[ix].Number, *prs[ix].User)
			continue
		}
		if *prs[ix].Number < config.MinPRNumber {
			glog.V(6).Infof("Dropping %d < %d", *prs[ix].Number, config.MinPRNumber)
			continue
		}
		pr, _, err := client.PullRequests.Get(user, project, *prs[ix].Number)
		if err != nil {
			glog.Errorf("Error getting pull request: %v", err)
			continue
		}
		glog.V(2).Infof("----==== %d ====----", *pr.Number)

		// Labels are actually stored in the Issues API, not the Pull Request API
		issue, _, err := client.Issues.Get(user, project, *pr.Number)
		if err != nil {
			glog.Errorf("Failed to get issue for PR: %v", err)
			continue
		}

		glog.V(8).Infof("%v", issue.Labels)
		if !hasLabels(issue.Labels, []string{"lgtm", "cla: yes"}) {
			continue
		}
		if !hasLabel(issue.Labels, config.WhitelistOverride) && !userSet.Has(*prs[ix].User.Login) {
			glog.V(4).Infof("Dropping %d since %s isn't in whitelist and %s isn't present", *prs[ix].Number, *prs[ix].User.Login, config.WhitelistOverride)
			continue
		}

		lastModifiedTime, err := lastModifiedTime(client, user, project, pr)
		if err != nil {
			glog.Errorf("Failed to get last modified time, skipping PR: %d", *pr.Number)
			continue
		}
		if ok, err := validateLGTMAfterPush(client, user, project, pr, lastModifiedTime); err != nil {
			glog.Errorf("Error validating LGTM: %v, Skipping: %d", err, *pr.Number)
			continue
		} else if !ok {
			glog.Errorf("PR pushed after LGTM, attempting to remove LGTM and skipping")
			staleLGTMBody := "LGTM was before last commit, removing LGTM"
			if _, _, err := client.Issues.CreateComment(user, project, *pr.Number, &github.IssueComment{Body: &staleLGTMBody}); err != nil {
				glog.Warningf("Failed to create remove label comment: %v", err)
			}
			if _, err := client.Issues.RemoveLabelForIssue(user, project, *pr.Number, "lgtm"); err != nil {
				glog.Warningf("Failed to remove 'lgtm' label for stale lgtm on %d", *pr.Number)
			}
			continue
		}

		// This is annoying, github appears to only temporarily cache mergeability, if it is nil, wait
		// for an async refresh and retry.
		if pr.Mergeable == nil {
			glog.Infof("Waiting for mergeability on %s %d", *pr.Title, *pr.Number)
			// TODO: determine what a good empirical setting for this is.
			time.Sleep(10 * time.Second)
			pr, _, err = client.PullRequests.Get(user, project, *prs[ix].Number)
		}
		if pr.Mergeable == nil {
			glog.Errorf("No mergeability information for %s %d, Skipping.", *pr.Title, *pr.Number)
			continue
		}
		if !*pr.Mergeable {
			continue
		}

		// Validate the status information for this PR
		ok, err := ValidateStatus(client, user, project, *pr.Number, config.RequiredStatusContexts, false)
		if err != nil {
			glog.Errorf("Error validating PR status: %v", err)
			continue
		}
		if !ok {
			continue
		}
		if err := fn(client, pr, issue); err != nil {
			glog.Errorf("Failed to run user function: %v", err)
			continue
		}
		if once {
			break
		}
	}
	return nil
}

func getCommitStatus(client *github.Client, user, project string, prNumber int) ([]*github.CombinedStatus, error) {
	commits, _, err := client.PullRequests.ListCommits(user, project, prNumber, &github.ListOptions{})
	if err != nil {
		return nil, err
	}
	commitStatus := make([]*github.CombinedStatus, len(commits))
	for ix := range commits {
		commit := &commits[ix]
		statusList, _, err := client.Repositories.GetCombinedStatus(user, project, *commit.SHA, &github.ListOptions{})
		if err != nil {
			return nil, err
		}
		commitStatus[ix] = statusList
	}
	return commitStatus, nil
}

// Gets the current status of a PR by introspecting the status of the commits in the PR.
// The rules are:
//    * If any member of the 'requiredContexts' list is missing, it is 'incomplete'
//    * If any commit is 'pending', the PR is 'pending'
//    * If any commit is 'error', the PR is in 'error'
//    * If any commit is 'failure', the PR is 'failure'
//    * Otherwise the PR is 'success'
func GetStatus(client *github.Client, user, project string, prNumber int, requiredContexts []string) (string, error) {
	statusList, err := getCommitStatus(client, user, project, prNumber)
	if err != nil {
		return "", err
	}
	return computeStatus(statusList, requiredContexts), nil
}

func computeStatus(statusList []*github.CombinedStatus, requiredContexts []string) string {
	states := util.StringSet{}
	providers := util.StringSet{}
	for ix := range statusList {
		status := statusList[ix]
		glog.V(8).Infof("Checking commit: %s", *status.SHA)
		glog.V(8).Infof("Checking commit: %v", status)
		states.Insert(*status.State)

		for _, subStatus := range status.Statuses {
			glog.V(8).Infof("Found status from: %v", subStatus)
			providers.Insert(*subStatus.Context)
		}
	}
	for _, provider := range requiredContexts {
		if !providers.Has(provider) {
			glog.V(8).Infof("Failed to find %s in %v", provider, providers)
			return "incomplete"
		}
	}

	switch {
	case states.Has("pending"):
		return "pending"
	case states.Has("error"):
		return "error"
	case states.Has("failure"):
		return "failure"
	default:
		return "success"
	}
}

// Make sure that the combined status for all commits in a PR is 'success'
// if 'waitForPending' is true, this function will wait until the PR is no longer pending (all checks have run)
func ValidateStatus(client *github.Client, user, project string, prNumber int, requiredContexts []string, waitOnPending bool) (bool, error) {
	pending := true
	for pending {
		status, err := GetStatus(client, user, project, prNumber, requiredContexts)
		if err != nil {
			return false, err
		}
		switch status {
		case "error", "failure":
			return false, nil
		case "pending":
			if !waitOnPending {
				return false, nil
			}
			pending = true
			glog.V(4).Info("PR is pending, waiting for 30 seconds")
			time.Sleep(30 * time.Second)
		case "success":
			return true, nil
		case "incomplete":
			return false, nil
		default:
			return false, fmt.Errorf("unknown status: %s", status)
		}
	}
	return true, nil
}

// Wait for a PR to move into Pending.  This is useful because the request to test a PR again
// is asynchronous with the PR actually moving into a pending state
// TODO: add a timeout
func WaitForPending(client *github.Client, user, project string, prNumber int) error {
	for {
		status, err := GetStatus(client, user, project, prNumber, []string{})
		if err != nil {
			return err
		}
		if status == "pending" {
			return nil
		}
		glog.V(4).Info("PR is not pending, waiting for 30 seconds")
		time.Sleep(30 * time.Second)
	}
}
<|endoftext|>