<commit_before>// ToInsanity project main.go
package main

import (
	"github.com/mvdan/xurls"
    "github.com/PuerkitoBio/goquery"
//	"github.com/jeffail/gabs"
//		"fmt"
        "io/ioutil"
//        "log"
		"errors"
//		"time"
        "net/http"
		"strings"
//		"unicode/utf8"
		"sync"
		"net/url"
		"math/rand"
		"github.com/cheggaaa/pb"
)
type hitResponse struct {
    body string
    rawBody []byte
}
type hitRequest struct {
    url string
    userAgent string
    params string
	method string
}
func (self *hitRequest) Initialize() {
	self.userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.130 Safari/537.36"
	self.method = "GET"
}
var targetUrl = "http://www.google.co.in/"
var numOfSoldiers = 10
var numOfBattalions = 5
var numOfTargets = 1
var bar *pb.ProgressBar
func main() {
	targets := findTarget()
	bar = pb.StartNew(numOfSoldiers * numOfBattalions  * len(targets))
	bar.Format("<.- >")
    var missionIssuedWg sync.WaitGroup
	for _, target := range targets {
		missionIssuedWg.Add(1)
		ht := hitRequest{}
		ht.Initialize()
		ht.url = target
		go deploy(ht, &missionIssuedWg)
	}
	missionIssuedWg.Wait()
	bar.FinishPrint("Victory!")
}

func deploy(ht hitRequest, missionIssuedWg *sync.WaitGroup){
    var deployWg sync.WaitGroup
	for i := 0; i < numOfBattalions; i++ {
		deployWg.Add(1)
		attack(ht,&deployWg, i)
	}
	deployWg.Wait()
	missionIssuedWg.Done()
}
func getLocalLinks(doc *goquery.Document, domain string)([]string){
	u,_ := url.Parse(domain)
	host := u.Host
	var hrefs []string
	doc.Find("a").Each(func(i int, s *goquery.Selection) {
		link,linkExist := s.Attr("href")
    		if linkExist != false {
			if link == "#" || link == "/" || link == "" || strings.Index(link,"#") == 0 {
				return
			}
			if strings.Index(link,"/") == 0 {
				link = domain + link
			}
			u,_ = url.Parse(link)
			if host == u.Host {
				hrefs = append(hrefs,link)
			}
		}
  })
  return hrefs

}
//Finds the target
func findTarget()([]string){

//	var aurls []string
//	aurls = append(aurls,targetUrl)
//	return aurls

	hr, err := hit(hitRequest{url: targetUrl})

	doc, err := goquery.NewDocumentFromReader(strings.NewReader(hr.body))

	hrefsFromBody := xurls.Relaxed.FindAllString(doc.Text(), -1)
	if err != nil {
//		fmt.Println(doc)
	}
	domain := targetUrl
	hrefsFromDoc := getLocalLinks(doc,domain)
	hrefs := append(hrefsFromBody,hrefsFromDoc...)

	//append original to the list
	hrefs = append(hrefs,domain)
	RemoveDuplicatesStringSlice(&hrefs)
	ShuffleStringSlice(hrefs)
	var targets []string
	for i := 0; i < numOfTargets; i++ {
		url := hrefs[len(hrefs) - 1]
		if strings.Index(url,"@") > 0 {
			i--
			continue
		}
		targets = append(targets,url)
		hrefs = hrefs[:len(hrefs)-1]
	}
	RemoveDuplicatesStringSlice(&targets)
	return targets
}

func hit(ht hitRequest)(hitResponse, error){

		client := &http.Client{}
        req, err := http.NewRequest(ht.method, targetUrl, nil)
	    if err != nil {
				return hitResponse{},errors.New("Can't hit it")
        }
		if ht.userAgent != "" {
			req.Header.Set("User-Agent", ht.userAgent)
		}
        resp, err := client.Do(req)
        if err != nil {
				return hitResponse{},errors.New("Can't hit it")
        }
        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)

        if err != nil {
				return hitResponse{}, errors.New("Can't hit it")
        }
		return hitResponse{string(body),body}, nil
}

func attack(ht hitRequest,deployWg *sync.WaitGroup, numBattalion int){

    var wg sync.WaitGroup
	messages := make(chan int)
	for i := 0; i < numOfSoldiers; i++ {
		wg.Add(1)
		go kill(ht, messages, &wg, i, numBattalion)
	}
	wg.Wait()
	deployWg.Done()

}
func kill(ht hitRequest,messages chan int, wg *sync.WaitGroup, numSoldier int, numBattalion int){
	    hit(ht)
		bar.Increment()
		wg.Done()
		messages <- numSoldier
}

func getInstructions(done chan bool, str string){
        client := &http.Client{}

        req, err := http.NewRequest("GET", "http://httpbin.org/user-agent", nil)

	    if err != nil {
				done <- true
				return
        }

        req.Header.Set("User-Agent", "ToInsanity")

        resp, err := client.Do(req)
        if err != nil {
				done <- true
				return
        }

        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)
        if err != nil {
				done <- true
				return
        }
		body = body
		done <- true
}

func ShuffleStringSlice(a []string) {
    for i := range a {
        j := rand.Intn(i + 1)
        a[i], a[j] = a[j], a[i]
    }
}
func ShuffleIntegerSlice(a []int) {
    for i := range a {
        j := rand.Intn(i + 1)
        a[i], a[j] = a[j], a[i]
    }
}
func RemoveDuplicatesStringSlice(xs *[]string) {
	found := make(map[string]bool)
	j := 0
	for i, x := range *xs {
		if !found[x] {
			found[x] = true
			(*xs)[j] = (*xs)[i]
			j++
		}
	}
	*xs = (*xs)[:j]
}

<commit_msg>Cleanup<commit_after>// ToInsanity project main.go
package main

import (
	"github.com/mvdan/xurls"
    "github.com/PuerkitoBio/goquery"
        "io/ioutil"
		"errors"
        "net/http"
		"strings"
		"sync"
		"net/url"
		"math/rand"
		"github.com/cheggaaa/pb"
)
type hitResponse struct {
    body string
    rawBody []byte
}
type hitRequest struct {
    url string
    userAgent string
    params string
	method string
}
func (self *hitRequest) Initialize() {
	self.userAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.130 Safari/537.36"
	self.method = "GET"
}

var targetUrl = "http://www.google.co.in/"
var numOfSoldiers = 10
var numOfBattalions = 5
var numOfTargets = 1
var bar *pb.ProgressBar
func main() {
	targets := findTarget()
	bar = pb.StartNew(numOfSoldiers * numOfBattalions  * len(targets))
	bar.Format("<.- >")
    var missionIssuedWg sync.WaitGroup
	for _, target := range targets {
		missionIssuedWg.Add(1)
		ht := hitRequest{}
		ht.Initialize()
		ht.url = target
		go deploy(ht, &missionIssuedWg)
	}
	missionIssuedWg.Wait()
	bar.FinishPrint("Victory!")
}

func deploy(ht hitRequest, missionIssuedWg *sync.WaitGroup){
    var deployWg sync.WaitGroup
	for i := 0; i < numOfBattalions; i++ {
		deployWg.Add(1)
		attack(ht,&deployWg, i)
	}
	deployWg.Wait()
	missionIssuedWg.Done()
}
func getLocalLinks(doc *goquery.Document, domain string)([]string){
	u,_ := url.Parse(domain)
	host := u.Host
	var hrefs []string
	doc.Find("a").Each(func(i int, s *goquery.Selection) {
		link,linkExist := s.Attr("href")
    		if linkExist != false {
			if link == "#" || link == "/" || link == "" || strings.Index(link,"#") == 0 {
				return
			}
			if strings.Index(link,"/") == 0 {
				link = domain + link
			}
			u,_ = url.Parse(link)
			if host == u.Host {
				hrefs = append(hrefs,link)
			}
		}
  })
  return hrefs

}
//Finds the target
func findTarget()([]string){

	hr, err := hit(hitRequest{url: targetUrl})

	doc, err := goquery.NewDocumentFromReader(strings.NewReader(hr.body))

	hrefsFromBody := xurls.Relaxed.FindAllString(doc.Text(), -1)
	if err != nil {
//		fmt.Println(doc)
	}
	domain := targetUrl
	hrefsFromDoc := getLocalLinks(doc,domain)
	hrefs := append(hrefsFromBody,hrefsFromDoc...)

	//append original to the list
	hrefs = append(hrefs,domain)
	RemoveDuplicatesStringSlice(&hrefs)
	ShuffleStringSlice(hrefs)
	var targets []string
	for i := 0; i < numOfTargets; i++ {
		url := hrefs[len(hrefs) - 1]
		if strings.Index(url,"@") > 0 {
			i--
			continue
		}
		targets = append(targets,url)
		hrefs = hrefs[:len(hrefs)-1]
	}
	RemoveDuplicatesStringSlice(&targets)
	return targets
}

func hit(ht hitRequest)(hitResponse, error){

		client := &http.Client{}
        req, err := http.NewRequest(ht.method, targetUrl, nil)
	    if err != nil {
				return hitResponse{},errors.New("Can't hit it")
        }
		if ht.userAgent != "" {
			req.Header.Set("User-Agent", ht.userAgent)
		}
        resp, err := client.Do(req)
        if err != nil {
				return hitResponse{},errors.New("Can't hit it")
        }
        defer resp.Body.Close()
        body, err := ioutil.ReadAll(resp.Body)

        if err != nil {
				return hitResponse{}, errors.New("Can't hit it")
        }
		return hitResponse{string(body),body}, nil
}

func attack(ht hitRequest,deployWg *sync.WaitGroup, numBattalion int){

    var wg sync.WaitGroup
	messages := make(chan int)
	for i := 0; i < numOfSoldiers; i++ {
		wg.Add(1)
		go kill(ht, messages, &wg, i, numBattalion)
	}
	wg.Wait()
	deployWg.Done()

}
func kill(ht hitRequest,messages chan int, wg *sync.WaitGroup, numSoldier int, numBattalion int){
	    hit(ht)
		bar.Increment()
		wg.Done()
		messages <- numSoldier
}

func ShuffleStringSlice(a []string) {
    for i := range a {
        j := rand.Intn(i + 1)
        a[i], a[j] = a[j], a[i]
    }
}
func ShuffleIntegerSlice(a []int) {
    for i := range a {
        j := rand.Intn(i + 1)
        a[i], a[j] = a[j], a[i]
    }
}
func RemoveDuplicatesStringSlice(xs *[]string) {
	found := make(map[string]bool)
	j := 0
	for i, x := range *xs {
		if !found[x] {
			found[x] = true
			(*xs)[j] = (*xs)[i]
			j++
		}
	}
	*xs = (*xs)[:j]
}
<|endoftext|>


<commit_before>// TODO: don't hold on to everything forever.
// TODO: support gists.
// TODO: better auth story; prompt for oauth access and store it somewhere.
// TODO: support writing files if the ref is a branch.
// TODO: better docs, examples, tests, the usual.
package main

import (
	"encoding/base64"
	"errors"
	"flag"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"strings"

	"bazil.org/fuse"
	"bazil.org/fuse/fs"
	"github.com/google/go-github/github"
	"golang.org/x/net/context"
	"golang.org/x/oauth2"
)

var (
	token      = flag.String("token", "", "GitHub auth token")
	mountpoint = flag.String("mountpoint", "", "Mount point, default is current working directory")

	client *github.Client
)

func main() {
	flag.Parse()

	if *token == "" {
		log.Println("must provide -token")
		os.Exit(1)
	}
	client = github.NewClient(oauth2.NewClient(oauth2.NoContext, oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: *token},
	)))

	mp := *mountpoint
	if mp == "" {
		mp, _ = filepath.Abs(filepath.Dir(os.Args[0]))
	}
	c, err := fuse.Mount(mp)
	if err != nil {
		log.Printf("mount: %v", err)
		os.Exit(1)
	}
	defer c.Close()

	if err := fs.Serve(c, FS{}); err != nil {
		log.Printf("serve: %v", err)
		os.Exit(1)
	}

	<-c.Ready
	if err := c.MountError; err != nil {
		log.Printf("mount error: %v", err)
		os.Exit(1)
	}
}

// FS represents the filesystem. It serves the root directory.
type FS struct{}

// Root returns the rootDir, which serves the root directory.
func (FS) Root() (fs.Node, error) {
	return &rootDir{}, nil
}

// rootDir serves the root directory.
type rootDir struct{}

// Attr states that a rootDir is a directory.
func (*rootDir) Attr(_ context.Context, attr *fuse.Attr) error {
	*attr = fuse.Attr{Mode: os.ModeDir | 0555}
	return nil
}

// Lookup returns a node with the given name, if it exists.
//
// A node in this context is a user, if one with the name exists.
func (*rootDir) Lookup(_ context.Context, name string) (fs.Node, error) {
	if strings.ContainsRune(name, '.') { // Usernames can't contain '.'
		return nil, fuse.ENOENT
	}
	if _, _, err := client.Users.Get(name); err == nil {
		return &userDir{user: name}, nil
	}
	// If it wasn't a user name, try it as an org name.
	if _, _, err := client.Organizations.Get(name); err == nil {
		return &userDir{user: name}, nil
	}
	return nil, fuse.ENOENT
}

// ReadDirAll returns an empty list, since we can't list all GitHub users.
func (*rootDir) ReadDirAll(context.Context) ([]fuse.Dirent, error) {
	// TODO: return users/orgs we have already fetched instead of nothing
	// at all.
	return nil, nil
}

// userDir serves directories containing a user/org's repos.
type userDir struct {
	user  string
	repos []string
	err   error
}

// getRepos populates the cache of user's repos if necessary.
func (d *userDir) getRepos() {
	if d.repos != nil {
		return
	}
	repos, resp, err := client.Repositories.List(d.user, nil)
	// Ignore 404s, it may just mean the user is an org.
	if err != nil && resp.StatusCode != http.StatusNotFound {
		d.err = err
		log.Println(err)
		return
	}
	for _, r := range repos {
		d.repos = append(d.repos, *r.Name)
	}

	// Also check if the repos-by-org API returns any repos; there seem to
	// be inconsistent results for orgs, e.g.:
	// https://api.github.com/users/google/repos vs.
	// https://api.github.com/orgs/google/repos
	byOrg, resp, err := client.Repositories.ListByOrg(d.user, nil)
	// Ignore 404s, it may just mean the org is only a user.
	if err != nil && resp.StatusCode != http.StatusNotFound {
		d.err = err
		log.Println(err)
		return
	}
	for _, r := range byOrg {
		d.repos = append(d.repos, *r.Name)
	}
}

// Attr states that a userDir represents a directory.
func (d *userDir) Attr(_ context.Context, attr *fuse.Attr) error {
	*attr = fuse.Attr{Mode: os.ModeDir | 0555}
	return nil
}

// Lookup returns a node with the given name, if it exists.
//
// A node in this context is a repo owned by the user/org.
func (d *userDir) Lookup(_ context.Context, name string) (fs.Node, error) {
	if strings.ContainsRune(name, '.') { // Repos can't contain '.'
		return nil, fuse.ENOENT
	}
	d.getRepos()
	if d.err != nil {
		return nil, fuse.ENOENT
	}
	for _, r := range d.repos {
		if name == r {
			return &repoDir{userDir: d, repo: r}, nil
		}
	}
	return nil, fuse.ENOENT
}

// ReadDirAll returns a list of user's repos.
func (d *userDir) ReadDirAll(context.Context) ([]fuse.Dirent, error) {
	d.getRepos()
	if d.err != nil {
		return nil, fuse.ENOENT
	}
	var ents []fuse.Dirent
	for _, r := range d.repos {
		ents = append(ents, fuse.Dirent{Name: r, Type: fuse.DT_Dir})
	}
	return ents, nil
}

// repoDir serves directories containing a repo's refs.
type repoDir struct {
	*userDir
	repo string
	refs []string
	err  error
}

// getRefs populates the cache of possible refs if necessary.
//
// TODO: the values of these refs may change if the FS is mounted long-term;
// periodically refresh the list of refs and release things under them.
func (d *repoDir) getRefs() {
	if d.refs != nil {
		return
	}
	tags, _, err := client.Repositories.ListTags(d.user, d.repo, nil)
	if err != nil {
		d.err = err
		log.Println(err)
		return
	}
	for _, t := range tags {
		d.refs = append(d.refs, *t.Name)
	}
	branches, _, err := client.Repositories.ListBranches(d.user, d.repo, nil)
	if err != nil {
		d.err = err
		log.Println(err)
		return
	}
	for _, b := range branches {
		d.refs = append(d.refs, *b.Name)
	}
}

// Attr states that a repoDir is a directory.
func (d *repoDir) Attr(_ context.Context, attr *fuse.Attr) error {
	*attr = fuse.Attr{Mode: os.ModeDir | 0555}
	return nil
}

// Lookup returns a node with the given name, if it exists.
//
// A node in this context is a ref, if one with the name exists.
func (d *repoDir) Lookup(_ context.Context, name string) (fs.Node, error) {
	if strings.ContainsRune(name, '.') { // refs can't contain '.'
		return nil, fuse.ENOENT
	}
	d.getRefs()
	if d.err != nil {
		return nil, fuse.ENOENT
	}
	for _, r := range d.refs {
		if name == r {
			return &contentDir{repoDir: d, ref: r}, nil
		}
	}
	// Always return a contentDir, even if there isn't a branch/tag by that
	// name. This allows users to use a commit SHA as a directory name, and
	// further lookups will just use that SHA. If no commit exists with
	// that SHA, future failures will make that apparent.
	// TODO: only return a SHA dir if the name is [0-9a-f]+
	// TODO: actually look up whether the repo contains any commits with
	// the SHA.
	return &contentDir{repoDir: d, ref: name}, nil
}

// ReadDirAll returns a list of repo's refs.
func (d *repoDir) ReadDirAll(context.Context) ([]fuse.Dirent, error) {
	d.getRefs()
	if d.err != nil {
		return nil, fuse.ENOENT
	}
	var ents []fuse.Dirent
	for _, r := range d.refs {
		ents = append(ents, fuse.Dirent{Name: r, Type: fuse.DT_Dir})
	}
	return ents, nil
}

// contentDir serves directories and files contained in the repo at a ref.
type contentDir struct {
	*repoDir
	ref, path   string
	files, dirs []string
}

// getContents populates the cache of contents belonging at this path in the
// repo at the ref if necessary.
//
// TODO: contents may change if the FS is mounted long-term (e.g., the parent
// ref "master" changes or is deleted); periodically refresh the contents and
// release things under them.
func (d *contentDir) getContents() {
	if d.files != nil || d.dirs != nil {
		return
	}
	_, contents, _, err := client.Repositories.GetContents(d.user, d.repo, d.path, &github.RepositoryContentGetOptions{d.ref})
	if err != nil {
		d.err = err
		log.Println(err)
		return
	}
	for _, c := range contents {
		if *c.Type == "file" {
			d.files = append(d.files, *c.Name)
		} else if *c.Type == "dir" {
			d.dirs = append(d.dirs, *c.Name)
		}
	}
}

// Attr states that a contentDir is a directory.
func (d *contentDir) Attr(_ context.Context, attr *fuse.Attr) error {
	*attr = fuse.Attr{Mode: os.ModeDir | 0555}
	return nil
}

// Lookup returns a node with the given name, if it exists.
//
// A node in this context may be either a further contentDir if the path points
// to a directory in the repo, or it may be a contentFile if it points to a
// file in the repo.
func (d *contentDir) Lookup(_ context.Context, name string) (fs.Node, error) {
	d.getContents()
	if d.err != nil {
		return nil, fuse.ENOENT
	}
	for _, f := range d.files {
		if name == f {
			return &contentFile{contentDir: d, filename: filepath.Join(d.path, name)}, nil
		}
	}
	for _, dr := range d.dirs {
		if name == dr {
			return &contentDir{repoDir: d.repoDir, ref: d.ref, path: filepath.Join(d.path, name)}, nil
		}
	}
	return nil, fuse.ENOENT
}

// ReadDirAll returns a list of directories and files in the repo at the ref.
func (d *contentDir) ReadDirAll(context.Context) ([]fuse.Dirent, error) {
	d.getContents()
	if d.err != nil {
		return nil, fuse.ENOENT
	}
	var ents []fuse.Dirent
	for _, d := range d.dirs {
		ents = append(ents, fuse.Dirent{Name: d, Type: fuse.DT_Dir})
	}
	for _, f := range d.files {
		ents = append(ents, fuse.Dirent{Name: f, Type: fuse.DT_File})
	}
	return ents, nil
}

// contentFile serves file contents for leaf-node files in a repo at a ref.
type contentFile struct {
	*contentDir // embed user/repo/ref/path
	filename    string
	content     []byte
}

// getFile populates the cache of file contents if necessary.
func (d *contentFile) getFile() {
	if d.content != nil {
		return
	}
	path := filepath.Join(d.path, d.filename)
	contents, _, _, err := client.Repositories.GetContents(d.user, d.repo, path, &github.RepositoryContentGetOptions{d.ref})
	if err != nil {
		d.err = err
		log.Println(err)
		return
	}
	if contents == nil || contents.Content == nil {
		d.err = errors.New("nil content")
		log.Println(err)
		return
	}
	if *contents.Encoding == "base64" {
		l := base64.StdEncoding.DecodedLen(len(*contents.Content))
		d.content = make([]byte, l)
		n, err := base64.StdEncoding.Decode(d.content, []byte(*contents.Content))
		if err != nil {
			d.err = err
			log.Println(err)
			return
		}
		d.content = d.content[0:n] // trim any padding
	} else {
		d.content = []byte(*contents.Content)
	}
}

// Attr states that contentFile is a file and provides its size.
func (d *contentFile) Attr(_ context.Context, attr *fuse.Attr) error {
	d.getFile()
	if d.err != nil {
		// It's a file, we just don't know its size.
		*attr = fuse.Attr{Mode: os.FileMode(0) | 0555}
	} else {
		*attr = fuse.Attr{Size: uint64(len(d.content)), Mode: os.FileMode(0) | 0555}
	}
	return nil
}

// ReadAll returns all of the file's contents.
func (d *contentFile) ReadAll(context.Context) ([]byte, error) {
	d.getFile()
	if d.err != nil {
		return nil, fuse.ENOENT
	}
	return d.content, nil
}

// Read responds with a possible subset of the file's contents.
func (d *contentFile) Read(_ context.Context, req *fuse.ReadRequest, resp *fuse.ReadResponse) error {
	d.getFile()
	if d.err != nil {
		return fuse.ENOENT
	}
	*resp = fuse.ReadResponse{
		Data: d.content[req.Offset : req.Offset+int64(req.Size)],
	}
	return nil
}
<commit_msg>sha dirs must be valid shas, map > slice<commit_after>// TODO: don't hold on to everything forever.
// TODO: support gists.
// TODO: better auth story; prompt for oauth access and store it somewhere.
// TODO: support writing files if the ref is a branch.
// TODO: better docs, examples, tests, the usual.
package main

import (
	"encoding/base64"
	"errors"
	"flag"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"regexp"
	"strings"

	"bazil.org/fuse"
	"bazil.org/fuse/fs"
	"github.com/google/go-github/github"
	"golang.org/x/net/context"
	"golang.org/x/oauth2"
)

var (
	token      = flag.String("token", "", "GitHub auth token")
	mountpoint = flag.String("mountpoint", "", "Mount point, default is current working directory")

	shaRE = regexp.MustCompile(`^[0-9a-f]+$`)

	client *github.Client
)

func main() {
	flag.Parse()

	if *token == "" {
		log.Println("must provide -token")
		os.Exit(1)
	}
	client = github.NewClient(oauth2.NewClient(oauth2.NoContext, oauth2.StaticTokenSource(
		&oauth2.Token{AccessToken: *token},
	)))

	mp := *mountpoint
	if mp == "" {
		mp, _ = filepath.Abs(filepath.Dir(os.Args[0]))
	}
	c, err := fuse.Mount(mp)
	if err != nil {
		log.Printf("mount: %v", err)
		os.Exit(1)
	}
	defer c.Close()

	if err := fs.Serve(c, FS{}); err != nil {
		log.Printf("serve: %v", err)
		os.Exit(1)
	}

	<-c.Ready
	if err := c.MountError; err != nil {
		log.Printf("mount error: %v", err)
		os.Exit(1)
	}
}

// FS represents the filesystem. It serves the root directory.
type FS struct{}

// Root returns the rootDir, which serves the root directory.
func (FS) Root() (fs.Node, error) {
	return &rootDir{}, nil
}

// rootDir serves the root directory.
type rootDir struct{}

// Attr states that a rootDir is a directory.
func (*rootDir) Attr(_ context.Context, attr *fuse.Attr) error {
	*attr = fuse.Attr{Mode: os.ModeDir | 0555}
	return nil
}

// Lookup returns a node with the given name, if it exists.
//
// A node in this context is a user, if one with the name exists.
func (*rootDir) Lookup(_ context.Context, name string) (fs.Node, error) {
	if strings.ContainsRune(name, '.') { // Usernames can't contain '.'
		return nil, fuse.ENOENT
	}
	if _, _, err := client.Users.Get(name); err == nil {
		return &userDir{user: name}, nil
	}
	// If it wasn't a user name, try it as an org name.
	if _, _, err := client.Organizations.Get(name); err == nil {
		return &userDir{user: name}, nil
	}
	return nil, fuse.ENOENT
}

// ReadDirAll returns an empty list, since we can't list all GitHub users.
func (*rootDir) ReadDirAll(context.Context) ([]fuse.Dirent, error) {
	// TODO: return users/orgs we have already fetched instead of nothing
	// at all.
	return nil, nil
}

// userDir serves directories containing a user/org's repos.
type userDir struct {
	user  string
	repos []string
	err   error
}

// getRepos populates the cache of user's repos if necessary.
func (d *userDir) getRepos() {
	if d.repos != nil {
		return
	}
	repos, resp, err := client.Repositories.List(d.user, nil)
	// Ignore 404s, it may just mean the user is an org.
	if err != nil && resp.StatusCode != http.StatusNotFound {
		d.err = err
		log.Println(err)
		return
	}
	for _, r := range repos {
		d.repos = append(d.repos, *r.Name)
	}

	// Also check if the repos-by-org API returns any repos; there seem to
	// be inconsistent results for orgs, e.g.:
	// https://api.github.com/users/google/repos vs.
	// https://api.github.com/orgs/google/repos
	byOrg, resp, err := client.Repositories.ListByOrg(d.user, nil)
	// Ignore 404s, it may just mean the org is only a user.
	if err != nil && resp.StatusCode != http.StatusNotFound {
		d.err = err
		log.Println(err)
		return
	}
	for _, r := range byOrg {
		d.repos = append(d.repos, *r.Name)
	}
}

// Attr states that a userDir represents a directory.
func (d *userDir) Attr(_ context.Context, attr *fuse.Attr) error {
	*attr = fuse.Attr{Mode: os.ModeDir | 0555}
	return nil
}

// Lookup returns a node with the given name, if it exists.
//
// A node in this context is a repo owned by the user/org.
func (d *userDir) Lookup(_ context.Context, name string) (fs.Node, error) {
	if strings.ContainsRune(name, '.') { // Repos can't contain '.'
		return nil, fuse.ENOENT
	}
	d.getRepos()
	if d.err != nil {
		return nil, fuse.ENOENT
	}
	for _, r := range d.repos {
		if name == r {
			return &repoDir{userDir: d, repo: r}, nil
		}
	}
	return nil, fuse.ENOENT
}

// ReadDirAll returns a list of user's repos.
func (d *userDir) ReadDirAll(context.Context) ([]fuse.Dirent, error) {
	d.getRepos()
	if d.err != nil {
		return nil, fuse.ENOENT
	}
	var ents []fuse.Dirent
	for _, r := range d.repos {
		ents = append(ents, fuse.Dirent{Name: r, Type: fuse.DT_Dir})
	}
	return ents, nil
}

// repoDir serves directories containing a repo's refs.
type repoDir struct {
	*userDir
	repo string
	refs map[string]bool
	err  error
}

// getRefs populates the cache of possible refs if necessary.
//
// TODO: the values of these refs may change if the FS is mounted long-term;
// periodically refresh the list of refs and release things under them.
func (d *repoDir) getRefs() {
	if d.refs != nil {
		return
	}
	d.refs = map[string]bool{}
	tags, _, err := client.Repositories.ListTags(d.user, d.repo, nil)
	if err != nil {
		d.err = err
		log.Println(err)
		return
	}
	for _, t := range tags {
		d.refs[*t.Name] = true
	}
	branches, _, err := client.Repositories.ListBranches(d.user, d.repo, nil)
	if err != nil {
		d.err = err
		log.Println(err)
		return
	}
	for _, b := range branches {
		d.refs[*b.Name] = true
	}
}

// Attr states that a repoDir is a directory.
func (d *repoDir) Attr(_ context.Context, attr *fuse.Attr) error {
	*attr = fuse.Attr{Mode: os.ModeDir | 0555}
	return nil
}

// Lookup returns a node with the given name, if it exists.
//
// A node in this context is a ref, if one with the name exists.
func (d *repoDir) Lookup(_ context.Context, name string) (fs.Node, error) {
	if strings.ContainsRune(name, '.') { // refs can't contain '.'
		return nil, fuse.ENOENT
	}
	d.getRefs()
	if d.err != nil {
		return nil, fuse.ENOENT
	}
	if d.refs[name] {
		return &contentDir{repoDir: d, ref: name}, nil
	}
	// Always return a contentDir, even if there isn't a branch/tag by that
	// name. This allows users to use a commit SHA as a directory name, and
	// further lookups will just use that SHA. If no commit exists with
	// that SHA, future failures will make that apparent.
	if !shaRE.MatchString(name) {
		// Only return a SHA dir if the name could possibly be a SHA.
		return nil, fuse.ENOENT
	}
	// TODO: actually look up whether the repo contains any commits with
	// the SHA.
	return &contentDir{repoDir: d, ref: name}, nil
}

// ReadDirAll returns a list of repo's refs.
func (d *repoDir) ReadDirAll(context.Context) ([]fuse.Dirent, error) {
	d.getRefs()
	if d.err != nil {
		return nil, fuse.ENOENT
	}
	var ents []fuse.Dirent
	for r, _ := range d.refs {
		ents = append(ents, fuse.Dirent{Name: r, Type: fuse.DT_Dir})
	}
	return ents, nil
}

// contentDir serves directories and files contained in the repo at a ref.
type contentDir struct {
	*repoDir
	ref, path   string
	files, dirs []string
}

// getContents populates the cache of contents belonging at this path in the
// repo at the ref if necessary.
//
// TODO: contents may change if the FS is mounted long-term (e.g., the parent
// ref "master" changes or is deleted); periodically refresh the contents and
// release things under them.
func (d *contentDir) getContents() {
	if d.files != nil || d.dirs != nil {
		return
	}
	_, contents, _, err := client.Repositories.GetContents(d.user, d.repo, d.path, &github.RepositoryContentGetOptions{d.ref})
	if err != nil {
		d.err = err
		log.Println(err)
		return
	}
	for _, c := range contents {
		if *c.Type == "file" {
			d.files = append(d.files, *c.Name)
		} else if *c.Type == "dir" {
			d.dirs = append(d.dirs, *c.Name)
		}
	}
}

// Attr states that a contentDir is a directory.
func (d *contentDir) Attr(_ context.Context, attr *fuse.Attr) error {
	*attr = fuse.Attr{Mode: os.ModeDir | 0555}
	return nil
}

// Lookup returns a node with the given name, if it exists.
//
// A node in this context may be either a further contentDir if the path points
// to a directory in the repo, or it may be a contentFile if it points to a
// file in the repo.
func (d *contentDir) Lookup(_ context.Context, name string) (fs.Node, error) {
	d.getContents()
	if d.err != nil {
		return nil, fuse.ENOENT
	}
	for _, f := range d.files {
		if name == f {
			return &contentFile{contentDir: d, filename: filepath.Join(d.path, name)}, nil
		}
	}
	for _, dr := range d.dirs {
		if name == dr {
			return &contentDir{repoDir: d.repoDir, ref: d.ref, path: filepath.Join(d.path, name)}, nil
		}
	}
	return nil, fuse.ENOENT
}

// ReadDirAll returns a list of directories and files in the repo at the ref.
func (d *contentDir) ReadDirAll(context.Context) ([]fuse.Dirent, error) {
	d.getContents()
	if d.err != nil {
		return nil, fuse.ENOENT
	}
	var ents []fuse.Dirent
	for _, d := range d.dirs {
		ents = append(ents, fuse.Dirent{Name: d, Type: fuse.DT_Dir})
	}
	for _, f := range d.files {
		ents = append(ents, fuse.Dirent{Name: f, Type: fuse.DT_File})
	}
	return ents, nil
}

// contentFile serves file contents for leaf-node files in a repo at a ref.
type contentFile struct {
	*contentDir // embed user/repo/ref/path
	filename    string
	content     []byte
}

// getFile populates the cache of file contents if necessary.
func (d *contentFile) getFile() {
	if d.content != nil {
		return
	}
	path := filepath.Join(d.path, d.filename)
	contents, _, _, err := client.Repositories.GetContents(d.user, d.repo, path, &github.RepositoryContentGetOptions{d.ref})
	if err != nil {
		d.err = err
		log.Println(err)
		return
	}
	if contents == nil || contents.Content == nil {
		d.err = errors.New("nil content")
		log.Println(err)
		return
	}
	if *contents.Encoding == "base64" {
		l := base64.StdEncoding.DecodedLen(len(*contents.Content))
		d.content = make([]byte, l)
		n, err := base64.StdEncoding.Decode(d.content, []byte(*contents.Content))
		if err != nil {
			d.err = err
			log.Println(err)
			return
		}
		d.content = d.content[0:n] // trim any padding
	} else {
		d.content = []byte(*contents.Content)
	}
}

// Attr states that contentFile is a file and provides its size.
func (d *contentFile) Attr(_ context.Context, attr *fuse.Attr) error {
	d.getFile()
	if d.err != nil {
		// It's a file, we just don't know its size.
		*attr = fuse.Attr{Mode: os.FileMode(0) | 0555}
	} else {
		*attr = fuse.Attr{Size: uint64(len(d.content)), Mode: os.FileMode(0) | 0555}
	}
	return nil
}

// ReadAll returns all of the file's contents.
func (d *contentFile) ReadAll(context.Context) ([]byte, error) {
	d.getFile()
	if d.err != nil {
		return nil, fuse.ENOENT
	}
	return d.content, nil
}

// Read responds with a possible subset of the file's contents.
func (d *contentFile) Read(_ context.Context, req *fuse.ReadRequest, resp *fuse.ReadResponse) error {
	d.getFile()
	if d.err != nil {
		return fuse.ENOENT
	}
	*resp = fuse.ReadResponse{
		Data: d.content[req.Offset : req.Offset+int64(req.Size)],
	}
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"fmt"
	twilio "github.com/carlosdp/twiliogo"
	"io"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"time"
)

var (
	client       twilio.Client
	twilioNumber string
)

func main() {
	port := os.Getenv("PORT")
	twilioNumber = os.Getenv("TWILIO_NUMBER")
	sid := os.Getenv("twilio_sid")
	auth_token := os.Getenv("twilio_auth")

	client = twilio.NewClient(sid, auth_token)

	http.HandleFunc("/twilio", handleRequestHand)

	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatal(err)
	}
}

func parseTwiloResponse(body io.Reader) url.Values {
	queryStringBytes, _ := ioutil.ReadAll(body)
	queryString := string(queryStringBytes)
	values, err := url.ParseQuery(queryString)
	if err != nil {
		log.Println(err)
	}
	return values
}

func handleRequestHand(w http.ResponseWriter, r *http.Request) {
	hand := NewHand()

	if _, err := w.Write([]byte(hand)); err != nil {
		w.Write(err)
		fmt.Println(err)
	}
}

func NewHand() string {
	deck := make([]int, 0, 52)

	for j := 0; j < 3; j++ {
		for i := 0; i < 11; i++ {
			deck = append(deck, i+1)
		}
	}

	for j := 0; j < 2; j++ {
		for i := 0; i < 6; i++ {
			deck = append(deck, i+12)
		}
	}

	for i := 0; i < 8; i++ {
		deck = append(deck, i+18)
	}

	dest := make([]int, len(deck))
	perm := rand.Perm(len(deck))
	for i, v := range perm {
		dest[v] = deck[i]
	}

	deck = dest

	rand.Seed(int64(time.Now().Nanosecond()))
	offset := 0
	var hand bytes.Buffer
	for i := 0; i < 5; i++ {
		index := rand.Intn(len(deck))
		card := strconv.Itoa(deck[index])
		hand.WriteString(card)
		hand.WriteString(" ")
		deck = append(deck[:index], deck[index+1:]...)

		if i == 1 {
			offset = len(hand.String())
		}
	}

	hand.WriteString("\r\n")
	for i := 0; i < offset; i++ {
		hand.WriteString(" ")
	}

	hand.WriteString(strconv.Itoa(deck[rand.Intn(len(deck))]))

	return hand.String()
}
<commit_msg>Dont write error back to page<commit_after>package main

import (
	"bytes"
	"fmt"
	twilio "github.com/carlosdp/twiliogo"
	"io"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"time"
)

var (
	client       twilio.Client
	twilioNumber string
)

func main() {
	port := os.Getenv("PORT")
	twilioNumber = os.Getenv("TWILIO_NUMBER")
	sid := os.Getenv("twilio_sid")
	auth_token := os.Getenv("twilio_auth")

	client = twilio.NewClient(sid, auth_token)

	http.HandleFunc("/twilio", handleRequestHand)

	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatal(err)
	}
}

func parseTwiloResponse(body io.Reader) url.Values {
	queryStringBytes, _ := ioutil.ReadAll(body)
	queryString := string(queryStringBytes)
	values, err := url.ParseQuery(queryString)
	if err != nil {
		log.Println(err)
	}
	return values
}

func handleRequestHand(w http.ResponseWriter, r *http.Request) {
	hand := NewHand()

	if _, err := w.Write([]byte(hand)); err != nil {
		fmt.Println(err)
	}
}

func NewHand() string {
	deck := make([]int, 0, 52)

	for j := 0; j < 3; j++ {
		for i := 0; i < 11; i++ {
			deck = append(deck, i+1)
		}
	}

	for j := 0; j < 2; j++ {
		for i := 0; i < 6; i++ {
			deck = append(deck, i+12)
		}
	}

	for i := 0; i < 8; i++ {
		deck = append(deck, i+18)
	}

	dest := make([]int, len(deck))
	perm := rand.Perm(len(deck))
	for i, v := range perm {
		dest[v] = deck[i]
	}

	deck = dest

	rand.Seed(int64(time.Now().Nanosecond()))
	offset := 0
	var hand bytes.Buffer
	for i := 0; i < 5; i++ {
		index := rand.Intn(len(deck))
		card := strconv.Itoa(deck[index])
		hand.WriteString(card)
		hand.WriteString(" ")
		deck = append(deck[:index], deck[index+1:]...)

		if i == 1 {
			offset = len(hand.String())
		}
	}

	hand.WriteString("\r\n")
	for i := 0; i < offset; i++ {
		hand.WriteString(" ")
	}

	hand.WriteString(strconv.Itoa(deck[rand.Intn(len(deck))]))

	return hand.String()
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"net/http"
	"os"
	"strings"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ecs"
)

var (
	clusterName = flag.String("c", "", "Cluster name to deploy to")
	repoName    = flag.String("i", "", "Container repo to pull from e.g. quay.io/username/reponame")
	appName     = flag.String("a", "", "Application name")
	environment = flag.String("e", "", "Application environment, e.g. production")
	sha         = flag.String("s", "", "Tag, usually short git SHA to deploy")
	region      = flag.String("r", "", "AWS region")
	webhook     = flag.String("w", "", "Webhook (slack) URL to post to")
	targetImage = flag.String("t", "", "Target image (overrides -s and -i)")
	debug       = flag.Bool("d", false, "enable Debug output")
)

func fail(s string) {
	fmt.Printf(s)
	webhookFunc(s)
	os.Exit(2)
}

func webhookFunc(s string) {
	if *webhook == "" {
		return
	}

	json, _ := json.Marshal(
		struct {
			Text     string `json:"text"`
			Username string `json:"username"`
		}{
			s,
			"GO ECS Deploy",
		},
	)

	reader := bytes.NewReader(json)
	http.Post(*webhook, "application/json", reader)
}

func main() {
	flag.Parse()

	if *clusterName == "" || *appName == "" || *environment == "" || *region == "" {
		flag.Usage()
		fail(fmt.Sprintf("Failed deployment %s : missing parameters\n", *appName))
	}

	if (*repoName == "" || *sha == "") && *targetImage == "" {
		flag.Usage()
		fail(fmt.Sprintf("Failed deployment %s : no repo name, sha or target image specified\n", *appName))
	}

	serviceName := *appName + "-" + *environment

	svc := ecs.New(session.New(), &aws.Config{Region: aws.String(*region)})

	if *targetImage == "" {
		fmt.Printf("Request to deploy sha: %s to %s at %s \n", *sha, *environment, *region)
	} else {
		fmt.Printf("Request to deploy target image: %s to %s at %s \n", *targetImage, *environment, *region)
	}
	fmt.Printf("Describing services for cluster %s and service %s \n", *clusterName, serviceName)

	serviceDesc, err :=
		svc.DescribeServices(
			&ecs.DescribeServicesInput{
				Cluster:  clusterName,
				Services: []*string{&serviceName},
			})
	if err != nil {
		fail(fmt.Sprintf("Failed: deployment %s \n`%s`", *appName, err.Error()))
	}

	if len(serviceDesc.Services) < 1 {
		msg := fmt.Sprintf("No service %s found on cluster %s", serviceName, *clusterName)
		fail("Failed: " + msg)
	}

	service := serviceDesc.Services[0]
	if serviceName != *service.ServiceName {
		msg := fmt.Sprintf("Found the wrong service when looking for %s found %s \n", serviceName, *service.ServiceName)
		fail("Failed: " + msg)
	}

	fmt.Printf("Found existing ARN %s for service %s \n", *service.ClusterArn, *service.ServiceName)

	taskDesc, err :=
		svc.DescribeTaskDefinition(
			&ecs.DescribeTaskDefinitionInput{
				TaskDefinition: service.TaskDefinition})
	if err != nil {
		fail(fmt.Sprintf("Failed: deployment %s \n`%s`", *appName, err.Error()))
	}

	if *debug {
		fmt.Printf("Current task description: \n%+v \n", taskDesc)
	}

	containerDef := taskDesc.TaskDefinition.ContainerDefinitions[0]
	oldImage := containerDef.Image
	{
		x := *targetImage
		if *targetImage == "" {
			x = fmt.Sprintf("%s:%s", *repoName, *sha)
		}
		containerDef.Image = &x
	}

	futureDef := &ecs.RegisterTaskDefinitionInput{
		ContainerDefinitions: taskDesc.TaskDefinition.ContainerDefinitions,
		Family:               taskDesc.TaskDefinition.Family,
		Volumes:              taskDesc.TaskDefinition.Volumes,
		NetworkMode:          taskDesc.TaskDefinition.NetworkMode,
		TaskRoleArn:          taskDesc.TaskDefinition.TaskRoleArn,
	}

	if *debug {
		fmt.Printf("Future task description: \n%+v \n", futureDef)
	}

	registerRes, err :=
		svc.RegisterTaskDefinition(futureDef)
	if err != nil {
		fail(fmt.Sprintf("Failed: deployment %s for %s to %s \n`%s`", *containerDef.Image, *appName, *clusterName, err.Error()))
	}

	newArn := registerRes.TaskDefinition.TaskDefinitionArn

	fmt.Printf("Registered new task for %s:%s \n", *sha, *newArn)

	// update service to use new definition
	_, err = svc.UpdateService(
		&ecs.UpdateServiceInput{
			Cluster:        clusterName,
			Service:        &serviceName,
			DesiredCount:   service.DesiredCount,
			TaskDefinition: newArn,
		})
	if err != nil {
		fail(fmt.Sprintf("Failed: deployment %s for %s to %s as %s \n`%s`", *containerDef.Image, *appName, *clusterName, *newArn, err.Error()))
	}

	slackMsg := fmt.Sprintf("Deployed %s for *%s* to *%s* as `%s`", *containerDef.Image, *appName, *clusterName, *newArn)

	// extract old image sha, and use it to generate a git compare URL
	if *oldImage != "" && *sha != "" {
		parts := strings.Split(*oldImage, ":")
		if len(parts) == 2 {
			// possibly a tagged image "def15c31-php5.5"
			parts = strings.Split(parts[1], "-")
			if gitURL, err := gitURL(parts[0], *sha); err == nil {
				slackMsg += " (<" + gitURL + "|diff>)"
			}
		}
	}
	webhookFunc(slackMsg)

	fmt.Printf("Updated %s service to use new ARN: %s \n", serviceName, *newArn)

}

// gitURL uses git since the program runs in many CI environments
func gitURL(startSHA string, endSHA string) (string, error) {
	var project string

	if travisSlug, ok := os.LookupEnv("TRAVIS_REPO_SLUG"); ok {
		project = travisSlug
	}

	if werckerOwner, ok := os.LookupEnv("WERCKER_GIT_OWNER"); ok {
		if werckerRepo, ok := os.LookupEnv("WERCKER_GIT_REPOSITORY"); ok {
			project = werckerOwner + "/" + werckerRepo
		}
	}

	if project == "" {
		return "", errors.New("nope")
	}

	url := "https://github.com/" + project + "/compare/" + startSHA + "..." + endSHA
	return url, nil
}
<commit_msg>Allow sending webhooks to multiple channels<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"net/http"
	"os"
	"strings"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/ecs"
)

type arrayFlag []string

func (flags *arrayFlag) String() string {
	return strings.Join(*flags, ",")
}

func (flags *arrayFlag) Set(value string) error {
	*flags = append(*flags, value)
	return nil
}

var (
	clusterName = flag.String("c", "", "Cluster name to deploy to")
	repoName = flag.String("i", "", "Container repo to pull from e.g. quay.io/username/reponame")
	appName = flag.String("a", "", "Application name")
	environment = flag.String("e", "", "Application environment, e.g. production")
	sha = flag.String("s", "", "Tag, usually short git SHA to deploy")
	region = flag.String("r", "", "AWS region")
	webhook = flag.String("w", "", "Webhook (slack) URL to post to")
	targetImage = flag.String("t", "", "Target image (overrides -s and -i)")
	debug = flag.Bool("d", false, "enable Debug output")
)

var channels arrayFlag

func fail(s string) {
	fmt.Printf(s)
	sendWebhooks(s)
	os.Exit(2)
}

func sendWebhook(message string, url *string, channel *string) {
	var request interface{}

	if (channel != nil) {
		request = struct {
			Text     string `json:"text"`
			Username string `json:"username"`
			Channel  string `json:"channel"`
		}{
			message,
			"GO ECS Deploy",
			*channel,
		}
	} else {
		request = struct {
			Text     string `json:"text"`
			Username string `json:"username"`
		}{
			message,
			"GO ECS Deploy",
		}
	}

	json, _ := json.Marshal(request)
	reader := bytes.NewReader(json)
	http.Post(*url, "application/json", reader)
}

func sendWebhooks(message string) {
	if (len(channels) > 0) {
		for _, channel := range channels {
			sendWebhook(message, webhook, &channel)
		}
	} else {
		sendWebhook(message, webhook, nil)
	}
}

func init() {
	flag.Var(&channels, "C", "Slack channels to post to (can be specified multiple times)")
}

func main() {
	if *clusterName == "" || *appName == "" || *environment == "" || *region == "" {
		flag.Usage()
		fail(fmt.Sprintf("Failed deployment %s : missing parameters\n", *appName))
	}

	if (*repoName == "" || *sha == "") && *targetImage == "" {
		flag.Usage()
		fail(fmt.Sprintf("Failed deployment %s : no repo name, sha or target image specified\n", *appName))
	}

	serviceName := *appName + "-" + *environment

	svc := ecs.New(session.New(), &aws.Config{Region: aws.String(*region)})

	if *targetImage == "" {
		fmt.Printf("Request to deploy sha: %s to %s at %s \n", *sha, *environment, *region)
	} else {
		fmt.Printf("Request to deploy target image: %s to %s at %s \n", *targetImage, *environment, *region)
	}
	fmt.Printf("Describing services for cluster %s and service %s \n", *clusterName, serviceName)

	serviceDesc, err :=
		svc.DescribeServices(
			&ecs.DescribeServicesInput{
				Cluster:  clusterName,
				Services: []*string{&serviceName},
			})
	if err != nil {
		fail(fmt.Sprintf("Failed: deployment %s \n`%s`", *appName, err.Error()))
	}

	if len(serviceDesc.Services) < 1 {
		msg := fmt.Sprintf("No service %s found on cluster %s", serviceName, *clusterName)
		fail("Failed: " + msg)
	}

	service := serviceDesc.Services[0]
	if serviceName != *service.ServiceName {
		msg := fmt.Sprintf("Found the wrong service when looking for %s found %s \n", serviceName, *service.ServiceName)
		fail("Failed: " + msg)
	}

	fmt.Printf("Found existing ARN %s for service %s \n", *service.ClusterArn, *service.ServiceName)

	taskDesc, err :=
		svc.DescribeTaskDefinition(
			&ecs.DescribeTaskDefinitionInput{
				TaskDefinition: service.TaskDefinition})
	if err != nil {
		fail(fmt.Sprintf("Failed: deployment %s \n`%s`", *appName, err.Error()))
	}

	if *debug {
		fmt.Printf("Current task description: \n%+v \n", taskDesc)
	}

	containerDef := taskDesc.TaskDefinition.ContainerDefinitions[0]
	oldImage := containerDef.Image
	{
		x := *targetImage
		if *targetImage == "" {
			x = fmt.Sprintf("%s:%s", *repoName, *sha)
		}
		containerDef.Image = &x
	}

	futureDef := &ecs.RegisterTaskDefinitionInput{
		ContainerDefinitions: taskDesc.TaskDefinition.ContainerDefinitions,
		Family:               taskDesc.TaskDefinition.Family,
		Volumes:              taskDesc.TaskDefinition.Volumes,
		NetworkMode:          taskDesc.TaskDefinition.NetworkMode,
		TaskRoleArn:          taskDesc.TaskDefinition.TaskRoleArn,
	}

	if *debug {
		fmt.Printf("Future task description: \n%+v \n", futureDef)
	}

	registerRes, err :=
		svc.RegisterTaskDefinition(futureDef)
	if err != nil {
		fail(fmt.Sprintf("Failed: deployment %s for %s to %s \n`%s`", *containerDef.Image, *appName, *clusterName, err.Error()))
	}

	newArn := registerRes.TaskDefinition.TaskDefinitionArn

	fmt.Printf("Registered new task for %s:%s \n", *sha, *newArn)

	// update service to use new definition
	_, err = svc.UpdateService(
		&ecs.UpdateServiceInput{
			Cluster:        clusterName,
			Service:        &serviceName,
			DesiredCount:   service.DesiredCount,
			TaskDefinition: newArn,
		})
	if err != nil {
		fail(fmt.Sprintf("Failed: deployment %s for %s to %s as %s \n`%s`", *containerDef.Image, *appName, *clusterName, *newArn, err.Error()))
	}

	slackMsg := fmt.Sprintf("Deployed %s for *%s* to *%s* as `%s`", *containerDef.Image, *appName, *clusterName, *newArn)

	// extract old image sha, and use it to generate a git compare URL
	if *oldImage != "" && *sha != "" {
		parts := strings.Split(*oldImage, ":")
		if len(parts) == 2 {
			// possibly a tagged image "def15c31-php5.5"
			parts = strings.Split(parts[1], "-")
			if gitURL, err := gitURL(parts[0], *sha); err == nil {
				slackMsg += " (<" + gitURL + "|diff>)"
			}
		}
	}
	sendWebhooks(slackMsg)

	fmt.Printf("Updated %s service to use new ARN: %s \n", serviceName, *newArn)

}

// gitURL uses git since the program runs in many CI environments
func gitURL(startSHA string, endSHA string) (string, error) {
	var project string

	if travisSlug, ok := os.LookupEnv("TRAVIS_REPO_SLUG"); ok {
		project = travisSlug
	}

	if werckerOwner, ok := os.LookupEnv("WERCKER_GIT_OWNER"); ok {
		if werckerRepo, ok := os.LookupEnv("WERCKER_GIT_REPOSITORY"); ok {
			project = werckerOwner + "/" + werckerRepo
		}
	}

	if project == "" {
		return "", errors.New("nope")
	}

	url := "https://github.com/" + project + "/compare/" + startSHA + "..." + endSHA
	return url, nil
}
<|endoftext|>


<commit_before>// Copyright © 2015-2018 Hilko Bengen <bengen@hilluzination.de>
// All rights reserved.
//
// Use of this source code is governed by the license that can be
// found in the LICENSE file.

package yara

/*
#include <yara.h>
*/
import "C"

func init() {
	_ = C.yr_initialize()
}

// Finalize releases all the resources allocated by the library. It should be
// called when your program is about to exit. Calling Finalize is not strictly
// required as the program is going to die anyways, but it's highly recommended
// because memory profiling tools can detect and report memory leaks if you
// don't. The recommended practice is calling it as a defered function in your
// program's main:
//  defer yara.Finalize()
func Finalize() {
	C.yr_finalize()
}
<commit_msg>Make Finalize() to return an error. Panic if YARA failed while being initialized.<commit_after>// Copyright © 2015-2018 Hilko Bengen <bengen@hilluzination.de>
// All rights reserved.
//
// Use of this source code is governed by the license that can be
// found in the LICENSE file.

package yara

/*
#include <yara.h>
*/
import "C"

func init() {
	if err := initialize(); err != nil {
		panic(err)
	}
}

// Prepares the library to be used.
func initialize() error {
	return newError(C.yr_initialize())
}

// Finalize releases all the resources allocated by the library. It should be
// called when your program is about to exit. Calling Finalize is not strictly
// required as the program is going to die anyways, but it's highly recommended
// because memory profiling tools can detect and report memory leaks if you
// don't. The recommended practice is calling it as a defered function in your
// program's main:
//  defer yara.Finalize()
func Finalize() error {
	return newError(C.yr_finalize())
}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"fmt"
	"math"
	"os"
	"path"
	"runtime"
	"strconv"
	"strings"
	"time"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"

	log "github.com/sirupsen/logrus"
	prefixed "github.com/x-cray/logrus-prefixed-formatter"
)

var (
	buildVersion = "v0.8.3-dev"
	buildCommit  = ""
	buildDate    = ""
)

var cfgFile string

var showVersion bool
var debug bool
var check bool

var dispatch *Dispatch

func main() {
	Execute()
}

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:    "dispatch",
	Short:  "A mail forwarding API service",
	Long:   `Run a webserver that provides an json api for emails`,
	PreRun: preRun,
	Run:    run,
}

// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	RootCmd.SetHelpTemplate(fmt.Sprintf("%s\nVersion:\n  github.com/gesquive/dispatch %s\n",
		RootCmd.HelpTemplate(), buildVersion))
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)

	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "",
		"Path to a specific config file (default \"./config.yml\")")
	RootCmd.PersistentFlags().StringP("log-file", "l", "",
		"Path to log file (default \"/var/log/dispatch.log\")")
	RootCmd.PersistentFlags().StringP("target-dir", "t", "",
		"Path to target configs (default \"/etc/dispatch/targets-enabled\")")
	RootCmd.PersistentFlags().BoolVar(&check, "check", false,
		"Check the config for errors and exit")

	RootCmd.PersistentFlags().BoolVar(&showVersion, "version", false,
		"Display the version info and exit")
	RootCmd.PersistentFlags().StringP("address", "a", "0.0.0.0",
		"The IP address to bind the web server too")
	RootCmd.PersistentFlags().IntP("port", "p", 2525,
		"The port to bind the webserver too")
	RootCmd.PersistentFlags().StringP("rate-limit", "r", "inf",
		"The rate limit at which to send emails in the format 'inf|<num>/<duration>'. "+
			"inf for infinite or 1/10s for 1 email per 10 seconds.")

	RootCmd.PersistentFlags().StringP("smtp-server", "x", "localhost",
		"The SMTP server to send email through")
	RootCmd.PersistentFlags().Uint32P("smtp-port", "o", 25,
		"The port to use for the SMTP server")
	RootCmd.PersistentFlags().StringP("smtp-username", "u", "",
		"Authenticate the SMTP server with this user")
	RootCmd.PersistentFlags().StringP("smtp-password", "w", "",
		"Authenticate the SMTP server with this password")

	RootCmd.PersistentFlags().BoolVarP(&debug, "debug", "D", false,
		"Include debug statements in log output")
	RootCmd.PersistentFlags().MarkHidden("debug")

	viper.SetEnvPrefix("dispatch")
	viper.AutomaticEnv()
	viper.BindEnv("config")
	viper.BindEnv("log_file")
	viper.BindEnv("target_dir")
	viper.BindEnv("address")
	viper.BindEnv("port")
	viper.BindEnv("rate_limit")
	viper.BindEnv("smtp_server")
	viper.BindEnv("smtp_port")
	viper.BindEnv("smtp_username")
	viper.BindEnv("smtp_password")

	viper.BindPFlag("config", RootCmd.PersistentFlags().Lookup("config"))
	viper.BindPFlag("log_file", RootCmd.PersistentFlags().Lookup("log-file"))
	viper.BindPFlag("target_dir", RootCmd.PersistentFlags().Lookup("target-dir"))
	viper.BindPFlag("web.address", RootCmd.PersistentFlags().Lookup("address"))
	viper.BindPFlag("web.port", RootCmd.PersistentFlags().Lookup("port"))
	viper.BindPFlag("rate_limit", RootCmd.PersistentFlags().Lookup("rate-limit"))
	viper.BindPFlag("smtp.server", RootCmd.PersistentFlags().Lookup("smtp-server"))
	viper.BindPFlag("smtp.port", RootCmd.PersistentFlags().Lookup("smtp-port"))
	viper.BindPFlag("smtp.username", RootCmd.PersistentFlags().Lookup("smtp-username"))
	viper.BindPFlag("smtp.password", RootCmd.PersistentFlags().Lookup("smtp-password"))

	viper.SetDefault("log_file", "/var/log/dispatch.log")
	viper.SetDefault("target_dir", "/etc/dispatch/targets-enabled")
	viper.SetDefault("web.address", "0.0.0.0")
	viper.SetDefault("web.port", 2525)
	viper.SetDefault("rate_limit", "inf")
	viper.SetDefault("smtp.server", "localhost")
	viper.SetDefault("smtp.port", 25)

	dotReplacer := strings.NewReplacer(".", "_")
	viper.SetEnvKeyReplacer(dotReplacer)
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	cfgFile := viper.GetString("config")
	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	} else {
		viper.SetConfigName("config")                 // name of config file (without extension)
		viper.AddConfigPath(".")                      // add current directory as first search path
		viper.AddConfigPath("$HOME/.config/dispatch") // add home directory to search path
		viper.AddConfigPath("/etc/dispatch")          // add etc to search path
	}

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err != nil {
		if !showVersion {
			if !strings.Contains(err.Error(), "Not Found") {
				fmt.Printf("Error opening config: %s\n", err)
			}
		}
	}
}

func preRun(cmd *cobra.Command, args []string) {
	if showVersion {
		fmt.Printf("github.com/gesquive/dispatch\n")
		fmt.Printf(" Version:    %s\n", buildVersion)
		if len(buildCommit) > 6 {
			fmt.Printf(" Git Commit: %s\n", buildCommit[:7])
		}
		if buildDate != "" {
			fmt.Printf(" Build Date: %s\n", buildDate)
		}
		fmt.Printf(" Go Version: %s\n", runtime.Version())
		fmt.Printf(" OS/Arch:    %s/%s\n", runtime.GOOS, runtime.GOARCH)
		os.Exit(0)
	}
}

func run(cmd *cobra.Command, args []string) {
	log.SetFormatter(&prefixed.TextFormatter{
		TimestampFormat: time.RFC3339,
	})

	if debug {
		log.SetLevel(log.DebugLevel)
	} else {
		log.SetLevel(log.InfoLevel)
	}

	logFilePath := viper.GetString("log_file")
	log.Debugf("config: log_file=%s", logFilePath)
	if strings.ToLower(logFilePath) == "stdout" || logFilePath == "-" || logFilePath == "" {
		log.SetOutput(os.Stdout)
	} else {
		logFilePath = getLogFilePath(logFilePath)
		logFile, err := os.OpenFile(logFilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			log.Fatalf("error opening log file=%v", err)
		}
		defer logFile.Close()
		log.SetOutput(logFile)
	}

	log.Infof("config: file=%s", viper.ConfigFileUsed())
	if viper.ConfigFileUsed() == "" {
		log.Fatal("No config file found.")
	}

	smtpSettings := SMTPSettings{
		viper.GetString("smtp.server"),
		viper.GetInt("smtp.port"),
		viper.GetString("smtp.username"),
		viper.GetString("smtp.password"),
	}
	log.Debugf("config: smtp={Host:%s Port:%d UserName:%s}", smtpSettings.Host,
		smtpSettings.Port, smtpSettings.UserName)

	targetsDir := viper.Get("target_dir").(string)
	log.Debugf("config: targets=%s", targetsDir)
	dispatch = NewDispatch(targetsDir, smtpSettings)

	address := viper.GetString("web.address")
	port := viper.GetInt("web.port")

	limitMax, limitTTL, err := getRateLimit(viper.GetString("rate-limit"))
	if err != nil {
		log.Fatalf("error parsing limit: %v", err)
	}

	if check {
		log.Debugf("config: webserver=%s:%d", address, port)
		log.Debugf("config: rate-limit=%d/%s", limitMax, limitTTL)
		log.Infof("Config file format checks out, exiting")
		if !debug {
			log.Infof("Use the --debug flag for more info")
		}
		os.Exit(0)
	}

	// finally, run the webserver
	server := NewServer(dispatch, limitMax, limitTTL)
	server.Run(fmt.Sprintf("%s:%d", address, port))
}

func getRateLimit(rateLimit string) (limitMax int64, limitTTL time.Duration, err error) {
	if rateLimit == "inf" {
		return math.MaxInt64, time.Nanosecond, nil
	}

	parts := strings.Split(rateLimit, "/")
	if len(parts) != 2 {
		msg := fmt.Sprintf("rate limit is not formatted properly - %v", rateLimit)
		return limitMax, limitTTL, errors.New(msg)
	}
	limitMax, err = strconv.ParseInt(parts[0], 10, 64)
	if err != nil {
		return
	}
	limitTTL, err = time.ParseDuration(parts[1])
	if err != nil {
		return
	}
	return
}

func getLogFilePath(defaultPath string) (logPath string) {
	fi, err := os.Stat(defaultPath)
	if err == nil && fi.IsDir() {
		logPath = path.Join(defaultPath, "dispatch.log")
	} else {
		logPath = defaultPath
	}
	return
}
<commit_msg>add version info to log output<commit_after>package main

import (
	"errors"
	"fmt"
	"math"
	"os"
	"path"
	"runtime"
	"strconv"
	"strings"
	"time"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"

	log "github.com/sirupsen/logrus"
	prefixed "github.com/x-cray/logrus-prefixed-formatter"
)

var (
	buildVersion = "v0.8.3-dev"
	buildCommit  = ""
	buildDate    = ""
)

var cfgFile string

var showVersion bool
var debug bool
var check bool

var dispatch *Dispatch

func main() {
	Execute()
}

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:    "dispatch",
	Short:  "A mail forwarding API service",
	Long:   `Run a webserver that provides an json api for emails`,
	PreRun: preRun,
	Run:    run,
}

// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	RootCmd.SetHelpTemplate(fmt.Sprintf("%s\nVersion:\n  github.com/gesquive/dispatch %s\n",
		RootCmd.HelpTemplate(), buildVersion))
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)

	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "",
		"Path to a specific config file (default \"./config.yml\")")
	RootCmd.PersistentFlags().StringP("log-file", "l", "",
		"Path to log file (default \"/var/log/dispatch.log\")")
	RootCmd.PersistentFlags().StringP("target-dir", "t", "",
		"Path to target configs (default \"/etc/dispatch/targets-enabled\")")
	RootCmd.PersistentFlags().BoolVar(&check, "check", false,
		"Check the config for errors and exit")

	RootCmd.PersistentFlags().BoolVar(&showVersion, "version", false,
		"Display the version info and exit")
	RootCmd.PersistentFlags().StringP("address", "a", "0.0.0.0",
		"The IP address to bind the web server too")
	RootCmd.PersistentFlags().IntP("port", "p", 2525,
		"The port to bind the webserver too")
	RootCmd.PersistentFlags().StringP("rate-limit", "r", "inf",
		"The rate limit at which to send emails in the format 'inf|<num>/<duration>'. "+
			"inf for infinite or 1/10s for 1 email per 10 seconds.")

	RootCmd.PersistentFlags().StringP("smtp-server", "x", "localhost",
		"The SMTP server to send email through")
	RootCmd.PersistentFlags().Uint32P("smtp-port", "o", 25,
		"The port to use for the SMTP server")
	RootCmd.PersistentFlags().StringP("smtp-username", "u", "",
		"Authenticate the SMTP server with this user")
	RootCmd.PersistentFlags().StringP("smtp-password", "w", "",
		"Authenticate the SMTP server with this password")

	RootCmd.PersistentFlags().BoolVarP(&debug, "debug", "D", false,
		"Include debug statements in log output")
	RootCmd.PersistentFlags().MarkHidden("debug")

	viper.SetEnvPrefix("dispatch")
	viper.AutomaticEnv()
	viper.BindEnv("config")
	viper.BindEnv("log_file")
	viper.BindEnv("target_dir")
	viper.BindEnv("address")
	viper.BindEnv("port")
	viper.BindEnv("rate_limit")
	viper.BindEnv("smtp_server")
	viper.BindEnv("smtp_port")
	viper.BindEnv("smtp_username")
	viper.BindEnv("smtp_password")

	viper.BindPFlag("config", RootCmd.PersistentFlags().Lookup("config"))
	viper.BindPFlag("log_file", RootCmd.PersistentFlags().Lookup("log-file"))
	viper.BindPFlag("target_dir", RootCmd.PersistentFlags().Lookup("target-dir"))
	viper.BindPFlag("web.address", RootCmd.PersistentFlags().Lookup("address"))
	viper.BindPFlag("web.port", RootCmd.PersistentFlags().Lookup("port"))
	viper.BindPFlag("rate_limit", RootCmd.PersistentFlags().Lookup("rate-limit"))
	viper.BindPFlag("smtp.server", RootCmd.PersistentFlags().Lookup("smtp-server"))
	viper.BindPFlag("smtp.port", RootCmd.PersistentFlags().Lookup("smtp-port"))
	viper.BindPFlag("smtp.username", RootCmd.PersistentFlags().Lookup("smtp-username"))
	viper.BindPFlag("smtp.password", RootCmd.PersistentFlags().Lookup("smtp-password"))

	viper.SetDefault("log_file", "/var/log/dispatch.log")
	viper.SetDefault("target_dir", "/etc/dispatch/targets-enabled")
	viper.SetDefault("web.address", "0.0.0.0")
	viper.SetDefault("web.port", 2525)
	viper.SetDefault("rate_limit", "inf")
	viper.SetDefault("smtp.server", "localhost")
	viper.SetDefault("smtp.port", 25)

	dotReplacer := strings.NewReplacer(".", "_")
	viper.SetEnvKeyReplacer(dotReplacer)
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	cfgFile := viper.GetString("config")
	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	} else {
		viper.SetConfigName("config")                 // name of config file (without extension)
		viper.AddConfigPath(".")                      // add current directory as first search path
		viper.AddConfigPath("$HOME/.config/dispatch") // add home directory to search path
		viper.AddConfigPath("/etc/dispatch")          // add etc to search path
	}

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err != nil {
		if !showVersion {
			if !strings.Contains(err.Error(), "Not Found") {
				fmt.Printf("Error opening config: %s\n", err)
			}
		}
	}
}

func preRun(cmd *cobra.Command, args []string) {
	if showVersion {
		fmt.Printf("github.com/gesquive/dispatch\n")
		fmt.Printf(" Version:    %s\n", buildVersion)
		if len(buildCommit) > 6 {
			fmt.Printf(" Git Commit: %s\n", buildCommit[:7])
		}
		if buildDate != "" {
			fmt.Printf(" Build Date: %s\n", buildDate)
		}
		fmt.Printf(" Go Version: %s\n", runtime.Version())
		fmt.Printf(" OS/Arch:    %s/%s\n", runtime.GOOS, runtime.GOARCH)
		os.Exit(0)
	}
}

func run(cmd *cobra.Command, args []string) {
	log.SetFormatter(&prefixed.TextFormatter{
		TimestampFormat: time.RFC3339,
	})

	if debug {
		log.SetLevel(log.DebugLevel)
	} else {
		log.SetLevel(log.InfoLevel)
	}

	log.Infof("running dispatch %s", buildVersion)
	if len(buildCommit) > 6 {
		log.Debugf("build: commit=%s", buildCommit[:7])
	}
	if buildDate != "" {
		log.Debugf("build: date=%s", buildDate)
	}
	log.Debugf("build: info=%s %s/%s", runtime.Version(), runtime.GOOS, runtime.GOARCH)

	logFilePath := viper.GetString("log_file")
	log.Debugf("config: log_file=%s", logFilePath)
	if strings.ToLower(logFilePath) == "stdout" || logFilePath == "-" || logFilePath == "" {
		log.SetOutput(os.Stdout)
	} else {
		logFilePath = getLogFilePath(logFilePath)
		logFile, err := os.OpenFile(logFilePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
		if err != nil {
			log.Fatalf("error opening log file=%v", err)
		}
		defer logFile.Close()
		log.SetOutput(logFile)
	}

	log.Infof("config: file=%s", viper.ConfigFileUsed())
	if viper.ConfigFileUsed() == "" {
		log.Fatal("No config file found.")
	}

	smtpSettings := SMTPSettings{
		viper.GetString("smtp.server"),
		viper.GetInt("smtp.port"),
		viper.GetString("smtp.username"),
		viper.GetString("smtp.password"),
	}
	log.Debugf("config: smtp={Host:%s Port:%d UserName:%s}", smtpSettings.Host,
		smtpSettings.Port, smtpSettings.UserName)

	targetsDir := viper.Get("target_dir").(string)
	log.Debugf("config: targets=%s", targetsDir)
	dispatch = NewDispatch(targetsDir, smtpSettings)

	address := viper.GetString("web.address")
	port := viper.GetInt("web.port")

	limitMax, limitTTL, err := getRateLimit(viper.GetString("rate-limit"))
	if err != nil {
		log.Fatalf("error parsing limit: %v", err)
	}

	if check {
		log.Debugf("config: webserver=%s:%d", address, port)
		log.Debugf("config: rate-limit=%d/%s", limitMax, limitTTL)
		log.Infof("Config file format checks out, exiting")
		if !debug {
			log.Infof("Use the --debug flag for more info")
		}
		os.Exit(0)
	}

	// finally, run the webserver
	server := NewServer(dispatch, limitMax, limitTTL)
	server.Run(fmt.Sprintf("%s:%d", address, port))
}

func getRateLimit(rateLimit string) (limitMax int64, limitTTL time.Duration, err error) {
	if rateLimit == "inf" {
		return math.MaxInt64, time.Nanosecond, nil
	}

	parts := strings.Split(rateLimit, "/")
	if len(parts) != 2 {
		msg := fmt.Sprintf("rate limit is not formatted properly - %v", rateLimit)
		return limitMax, limitTTL, errors.New(msg)
	}
	limitMax, err = strconv.ParseInt(parts[0], 10, 64)
	if err != nil {
		return
	}
	limitTTL, err = time.ParseDuration(parts[1])
	if err != nil {
		return
	}
	return
}

func getLogFilePath(defaultPath string) (logPath string) {
	fi, err := os.Stat(defaultPath)
	if err == nil && fi.IsDir() {
		logPath = path.Join(defaultPath, "dispatch.log")
	} else {
		logPath = defaultPath
	}
	return
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"

	"github.com/codegangsta/cli"
)

const (
	version = "0.2"
	usage   = `Open Container Initiative hypervisor-based runtime

runv is a command line client for running applications packaged according to
the Open Container Format (OCF) and is a compliant implementation of the
Open Container Initiative specification.  However, due to the difference
between hypervisors and containers, the following sections of OCF don't
apply to runV:
    Namespace
    Capability
    Device
    "linux" and "mount" fields in OCI specs are ignored

The current release of "runV" supports the following hypervisors:
    KVM (QEMU 2.0 or later)
    Xen (4.5 or later)
    VirtualBox (Mac OS X)

After creating a spec for your root filesystem, you can execute a container
in your shell by running:

    cd /mycontainer
    runv [ spec-file ]

or
    cd /mycontainer
    runv start [ spec-file ]

If not specified, the default value for the 'spec-file' is 'config.json'. `
)

func main() {
	app := cli.NewApp()
	app.Name = "runv"
	app.Usage = usage
	app.Version = version
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "driver",
			Value: "kvm",
			Usage: "hypervisor driver (supports: kvm xen vbox)",
		},
		cli.StringFlag{
			Name:  "kernel",
			Value: "./kernel",
			Usage: "kernel for the container",
		},
		cli.StringFlag{
			Name:  "initrd",
			Value: "./initrd",
			Usage: "runv-compatible initrd for the container",
		},
		cli.StringFlag{
			Name:  "vbox",
			Value: "./vbox",
			Usage: "runv-compatible boot ISO for the container for vbox driver",
		},
	}
	app.Commands = []cli.Command{
		startCommand,
	}
	// Default to 'start' is no command is specified
	app.Action = startCommand.Action
	if err := app.Run(os.Args); err != nil {
		fmt.Printf("%s\n", err.Error())
	}
}
<commit_msg>make sure default initrd file is consistent with README<commit_after>package main

import (
	"fmt"
	"os"

	"github.com/codegangsta/cli"
)

const (
	version = "0.2"
	usage   = `Open Container Initiative hypervisor-based runtime

runv is a command line client for running applications packaged according to
the Open Container Format (OCF) and is a compliant implementation of the
Open Container Initiative specification.  However, due to the difference
between hypervisors and containers, the following sections of OCF don't
apply to runV:
    Namespace
    Capability
    Device
    "linux" and "mount" fields in OCI specs are ignored

The current release of "runV" supports the following hypervisors:
    KVM (QEMU 2.0 or later)
    Xen (4.5 or later)
    VirtualBox (Mac OS X)

After creating a spec for your root filesystem, you can execute a container
in your shell by running:

    cd /mycontainer
    runv [ spec-file ]

or
    cd /mycontainer
    runv start [ spec-file ]

If not specified, the default value for the 'spec-file' is 'config.json'. `
)

func main() {
	app := cli.NewApp()
	app.Name = "runv"
	app.Usage = usage
	app.Version = version
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "driver",
			Value: "kvm",
			Usage: "hypervisor driver (supports: kvm xen vbox)",
		},
		cli.StringFlag{
			Name:  "kernel",
			Value: "./kernel",
			Usage: "kernel for the container",
		},
		cli.StringFlag{
			Name:  "initrd",
			Value: "./initrd.img",
			Usage: "runv-compatible initrd for the container",
		},
		cli.StringFlag{
			Name:  "vbox",
			Value: "./vbox",
			Usage: "runv-compatible boot ISO for the container for vbox driver",
		},
	}
	app.Commands = []cli.Command{
		startCommand,
	}
	// Default to 'start' is no command is specified
	app.Action = startCommand.Action
	if err := app.Run(os.Args); err != nil {
		fmt.Printf("%s\n", err.Error())
	}
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/url"
	"os"
	"strings"

	"github.com/lair-framework/api-server/client"
	"github.com/lair-framework/go-lair"
	"github.com/tomsteele/blacksheepwall/bsw"
)

const (
	version = "2.0.0"
	tool    = "blacksheepwall"
	usage   = `
Parses a blacksheepwall JSON file into a lair project.

Usage:
  drone-blacksheepwall [options] <id> <filename>
  export LAIR_ID=<id>; drone-blacksheepwall [options] <filename>
Options:
  -v              show version and exit
  -h              show usage and exit
  -k              allow insecure SSL connections
  -force-ports    disable data protection in the API server for excessive ports
  -tags           a comma separated list of tags to add to every host that is imported
`
)

func main() {
	showVersion := flag.Bool("v", false, "")
	insecureSSL := flag.Bool("k", false, "")
	forcePorts := flag.Bool("force-ports", false, "")
	tags := flag.String("tags", "", "")
	flag.Usage = func() {
		fmt.Println(usage)
	}
	flag.Parse()
	if *showVersion {
		log.Println(version)
		os.Exit(0)
	}
	lairURL := os.Getenv("LAIR_API_SERVER")
	if lairURL == "" {
		log.Fatal("Fatal: Missing LAIR_API_SERVER environment variable")
	}
	lairPID := os.Getenv("LAIR_ID")
	var filename string
	switch len(flag.Args()) {
	case 2:
		lairPID = flag.Arg(0)
		filename = flag.Arg(1)
	case 1:
		filename = flag.Arg(0)
	default:
		log.Fatal("Fatal: Missing required argument")
	}

	u, err := url.Parse(lairURL)
	if err != nil {
		log.Fatalf("Fatal: Error parsing LAIR_API_SERVER URL. Error %s", err.Error())
	}
	if u.User == nil {
		log.Fatal("Fatal: Missing username and/or password")
	}
	user := u.User.Username()
	pass, _ := u.User.Password()
	if user == "" || pass == "" {
		log.Fatal("Fatal: Missing username and/or password")
	}
	c, err := client.New(&client.COptions{
		User:               user,
		Password:           pass,
		Host:               u.Host,
		Scheme:             u.Scheme,
		InsecureSkipVerify: *insecureSSL,
	})
	if err != nil {
		log.Fatalf("Fatal: Error setting up client: Error %s", err.Error())
	}
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Fatalf("Fatal: Could not open file. Error %s", err.Error())
	}
	hostTags := []string{}
	if *tags != "" {
		hostTags = strings.Split(*tags, ",")
	}
	tagSet := map[string]bool{}
	bResults := bsw.Results{}
	if err := json.Unmarshal(data, &bResults); err != nil {
		log.Fatalf("Fatal: Could not parse JSON. Error %s", err.Error())
	}
	bNotFound := map[string]bool{}

	exproject, err := c.ExportProject(lairPID)
	if err != nil {
		log.Fatalf("Fatal: Unable to export project. Error %s", err.Error())
	}

	project := &lair.Project{
		ID:   lairPID,
		Tool: tool,
		Commands: []lair.Command{lair.Command{
			Tool: tool,
		}},
	}

	for _, result := range bResults {
		found := false
		for i := range exproject.Hosts {
			h := exproject.Hosts[i]
			if result.IP == h.IPv4 {
				exproject.Hosts[i].Hostnames = append(exproject.Hosts[i].Hostnames, result.Hostname)
				exproject.Hosts[i].LastModifiedBy = tool
				found = true
				if _, ok := tagSet[h.IPv4]; !ok {
					tagSet[h.IPv4] = true
					exproject.Hosts[i].Tags = append(exproject.Hosts[i].Tags, hostTags...)
				}
			}
			if !found {
				bNotFound[result.IP] = true
			}
		}
	}

	for _, h := range exproject.Hosts {
		project.Hosts = append(project.Hosts, lair.Host{
			IPv4:           h.IPv4,
			LongIPv4Addr:   h.LongIPv4Addr,
			IsFlagged:      h.IsFlagged,
			LastModifiedBy: h.LastModifiedBy,
			MAC:            h.MAC,
			OS:             h.OS,
			Status:         h.Status,
			StatusMessage:  h.StatusMessage,
			Tags:           hostTags,
			Hostnames:      h.Hostnames,
		})
	}

	res, err := c.ImportProject(&client.DOptions{ForcePorts: *forcePorts}, project)
	if err != nil {
		log.Fatalf("Fatal: Unable to import project. Error %s", err)
	}

	defer res.Body.Close()
	droneRes := &client.Response{}
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Fatalf("Fatal: Error %s", err.Error())
	}
	if err := json.Unmarshal(body, droneRes); err != nil {
		log.Fatalf("Fatal: Could not unmarshal JSON. Error %s", err.Error())
	}
	if droneRes.Status == "Error" {
		log.Fatalf("Fatal: Import failed. Error %s", droneRes.Message)
	}

	if len(bNotFound) > 0 {
		log.Println("Info: The following hosts had hostnames but could not be imported because they do not exist in lair")
	}
	for k := range bNotFound {
		fmt.Println(k)
	}
	log.Println("Success: Operation completed successfully")
}
<commit_msg>Fix found bug<commit_after>package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/url"
	"os"
	"strings"

	"github.com/lair-framework/api-server/client"
	"github.com/lair-framework/go-lair"
	"github.com/tomsteele/blacksheepwall/bsw"
)

const (
	version = "2.0.0"
	tool    = "blacksheepwall"
	usage   = `
Parses a blacksheepwall JSON file into a lair project.

Usage:
  drone-blacksheepwall [options] <id> <filename>
  export LAIR_ID=<id>; drone-blacksheepwall [options] <filename>
Options:
  -v              show version and exit
  -h              show usage and exit
  -k              allow insecure SSL connections
  -force-ports    disable data protection in the API server for excessive ports
  -tags           a comma separated list of tags to add to every host that is imported
`
)

func main() {
	showVersion := flag.Bool("v", false, "")
	insecureSSL := flag.Bool("k", false, "")
	forcePorts := flag.Bool("force-ports", false, "")
	tags := flag.String("tags", "", "")
	flag.Usage = func() {
		fmt.Println(usage)
	}
	flag.Parse()
	if *showVersion {
		log.Println(version)
		os.Exit(0)
	}
	lairURL := os.Getenv("LAIR_API_SERVER")
	if lairURL == "" {
		log.Fatal("Fatal: Missing LAIR_API_SERVER environment variable")
	}
	lairPID := os.Getenv("LAIR_ID")
	var filename string
	switch len(flag.Args()) {
	case 2:
		lairPID = flag.Arg(0)
		filename = flag.Arg(1)
	case 1:
		filename = flag.Arg(0)
	default:
		log.Fatal("Fatal: Missing required argument")
	}

	u, err := url.Parse(lairURL)
	if err != nil {
		log.Fatalf("Fatal: Error parsing LAIR_API_SERVER URL. Error %s", err.Error())
	}
	if u.User == nil {
		log.Fatal("Fatal: Missing username and/or password")
	}
	user := u.User.Username()
	pass, _ := u.User.Password()
	if user == "" || pass == "" {
		log.Fatal("Fatal: Missing username and/or password")
	}
	c, err := client.New(&client.COptions{
		User:               user,
		Password:           pass,
		Host:               u.Host,
		Scheme:             u.Scheme,
		InsecureSkipVerify: *insecureSSL,
	})
	if err != nil {
		log.Fatalf("Fatal: Error setting up client: Error %s", err.Error())
	}
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		log.Fatalf("Fatal: Could not open file. Error %s", err.Error())
	}
	hostTags := []string{}
	if *tags != "" {
		hostTags = strings.Split(*tags, ",")
	}
	tagSet := map[string]bool{}
	bResults := bsw.Results{}
	if err := json.Unmarshal(data, &bResults); err != nil {
		log.Fatalf("Fatal: Could not parse JSON. Error %s", err.Error())
	}
	bNotFound := map[string]bool{}

	exproject, err := c.ExportProject(lairPID)
	if err != nil {
		log.Fatalf("Fatal: Unable to export project. Error %s", err.Error())
	}

	project := &lair.Project{
		ID:   lairPID,
		Tool: tool,
		Commands: []lair.Command{lair.Command{
			Tool: tool,
		}},
	}

	for _, result := range bResults {
		found := false
		for i := range exproject.Hosts {
			h := exproject.Hosts[i]
			if result.IP == h.IPv4 {
				exproject.Hosts[i].Hostnames = append(exproject.Hosts[i].Hostnames, result.Hostname)
				exproject.Hosts[i].LastModifiedBy = tool
				found = true
				if _, ok := tagSet[h.IPv4]; !ok {
					tagSet[h.IPv4] = true
					exproject.Hosts[i].Tags = append(exproject.Hosts[i].Tags, hostTags...)
				}
			}
		}
		if !found {
			bNotFound[result.IP] = true
		}
	}

	for _, h := range exproject.Hosts {
		project.Hosts = append(project.Hosts, lair.Host{
			IPv4:           h.IPv4,
			LongIPv4Addr:   h.LongIPv4Addr,
			IsFlagged:      h.IsFlagged,
			LastModifiedBy: h.LastModifiedBy,
			MAC:            h.MAC,
			OS:             h.OS,
			Status:         h.Status,
			StatusMessage:  h.StatusMessage,
			Tags:           hostTags,
			Hostnames:      h.Hostnames,
		})
	}

	res, err := c.ImportProject(&client.DOptions{ForcePorts: *forcePorts}, project)
	if err != nil {
		log.Fatalf("Fatal: Unable to import project. Error %s", err)
	}

	defer res.Body.Close()
	droneRes := &client.Response{}
	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Fatalf("Fatal: Error %s", err.Error())
	}
	if err := json.Unmarshal(body, droneRes); err != nil {
		log.Fatalf("Fatal: Could not unmarshal JSON. Error %s", err.Error())
	}
	if droneRes.Status == "Error" {
		log.Fatalf("Fatal: Import failed. Error %s", droneRes.Message)
	}

	if len(bNotFound) > 0 {
		log.Println("Info: The following hosts had hostnames but could not be imported because they do not exist in lair")
	}
	for k := range bNotFound {
		fmt.Println(k)
	}
	log.Println("Success: Operation completed successfully")
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"errors"
	"net/http"
	"os"

	"github.com/rs/cors"
	"github.com/zenazn/goji"
	"github.com/zenazn/goji/web"

	"github.com/ckpt/backend-services/middleware"
	"github.com/ckpt/backend-services/players"
)

type appError struct {
	Error   error
	Message string
	Code    int
}

type appHandler func(web.C, http.ResponseWriter, *http.Request) *appError

func (fn appHandler) ServeHTTPC(c web.C, w http.ResponseWriter, r *http.Request) {
	if e := fn(c, w, r); e != nil {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		w.WriteHeader(e.Code)
		encoder := json.NewEncoder(w)
		encoder.Encode(map[string]string{"error": e.Error.Error() +
			" (" + e.Message + ")"})
	}
}

func login(c web.C, w http.ResponseWriter, r *http.Request) *appError {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	type LoginRequest struct {
		Username string
		Password string
	}

	loginReq := new(LoginRequest)
	decoder := json.NewDecoder(r.Body)
	if err := decoder.Decode(loginReq); err != nil {
		return &appError{err, "Invalid JSON", 400}
	}

	if !players.AuthUser(loginReq.Username, loginReq.Password) {
		return &appError{errors.New("Forbidden"), "Invalid username/password", 403}
	}

	authUser, err := players.UserByName(loginReq.Username)
	if err != nil {
		return &appError{err, "Failed to fetch user data", 500}
	}
	if authUser.Locked {
		return &appError{errors.New("Locked"), "User locked", 403}
	}
	encoder := json.NewEncoder(w)
	encoder.Encode(authUser)
	return nil
}

func main() {
	//
	// Event queue hadling
	//
	err := players.StartEventProcessor()
	if err != nil {
		println(err.Error)
		println("Could not initialize event queue. Exiting")
		os.Exit(1)
	}

	//
	// HTTP Serving
	//
	c := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
		AllowedHeaders: []string{"*"},
		AllowedMethods: []string{"GET", "PUT", "PATCH", "POST", "OPTIONS", "DELETE"},
	})
	goji.Use(c.Handler)
	goji.Use(middleware.TokenHandler)

	goji.Post("/login", appHandler(login))

	goji.Get("/players", appHandler(listAllPlayers))
	goji.Post("/players", appHandler(createNewPlayer))
	goji.Get("/players/quotes", appHandler(getAllPlayerQuotes))
	goji.Get("/players/:uuid", appHandler(getPlayer))
	goji.Put("/players/:uuid", appHandler(updatePlayer))
	goji.Get("/players/:uuid/profile", appHandler(getPlayerProfile))
	goji.Put("/players/:uuid/profile", appHandler(updatePlayerProfile))
	goji.Get("/players/:uuid/user", appHandler(getUserForPlayer))
	goji.Put("/players/:uuid/user", appHandler(setUserForPlayer))
	goji.Put("/players/:uuid/user/password", appHandler(setUserPassword))
	goji.Put("/players/:uuid/user/settings", appHandler(setUserSettings))
	goji.Get("/players/:uuid/debts", appHandler(showPlayerDebt))
	goji.Delete("/players/:uuid/debts", appHandler(resetPlayerDebts))
	goji.Get("/players/:uuid/credits", appHandler(showPlayerCredits))
	goji.Post("/players/:uuid/debts", appHandler(addPlayerDebt))
	goji.Delete("/players/:uuid/debts/:debtuuid", appHandler(settlePlayerDebt))

	goji.Post("/users", appHandler(createNewUser))

	goji.Get("/locations", appHandler(listAllLocations))
	goji.Post("/locations", appHandler(createNewLocation))
	goji.Get("/locations/:uuid", appHandler(getLocation))
	goji.Put("/locations/:uuid", appHandler(updateLocationProfile))
	goji.Patch("/locations/:uuid", appHandler(updateLocationProfile))
	goji.Post("/locations/:uuid/pictures", appHandler(addLocationPicture))

	goji.Get("/tournaments", appHandler(listAllTournaments))
	goji.Post("/tournaments", appHandler(createNewTournament))
	goji.Get("/tournaments/:uuid", appHandler(getTournament))
	goji.Put("/tournaments/:uuid", appHandler(updateTournamentInfo))
	goji.Patch("/tournaments/:uuid", appHandler(updateTournamentInfo))
	goji.Put("/tournaments/:uuid/played", appHandler(setTournamentPlayed))
	goji.Get("/tournaments/:uuid/result", appHandler(getTournamentResult))
	goji.Put("/tournaments/:uuid/result", appHandler(setTournamentResult))

	goji.Get("/seasons", appHandler(listAllSeasons))
	goji.Get("/seasons/stats", appHandler(getTotalStats))
	goji.Get("/seasons/standings", appHandler(getTotalStandings))
	goji.Get("/seasons/titles", appHandler(getTotalTitles))
	goji.Get("/seasons/:year/tournaments", appHandler(listTournamentsBySeason))
	goji.Get("/seasons/:year/standings", appHandler(getSeasonStandings))
	goji.Get("/seasons/:year/titles", appHandler(getSeasonTitles))
	goji.Get("/seasons/:year/stats", appHandler(getSeasonStats))

	goji.Get("/caterings", appHandler(listAllCaterings))
	goji.Post("/caterings", appHandler(createNewCatering))
	goji.Get("/caterings/:uuid", appHandler(getCatering))
	goji.Put("/caterings/:uuid", appHandler(updateCateringInfo))
	goji.Patch("/caterings/:uuid", appHandler(updateCateringInfo))
	goji.Post("/caterings/:uuid/votes", appHandler(addCateringVote))
	goji.Put("/caterings/:uuid/votes/:playeruuid", appHandler(updateCateringVote))

	goji.Get("/news", appHandler(listAllNews))
	goji.Get("/news/:uuid", appHandler(getNewsItem))
	goji.Patch("/news/:uuid", appHandler(updateNewsItem))
	goji.Post("/news", appHandler(createNewNewsItem))
	// TODO: Comments

	goji.Serve()
}
<commit_msg>Try to get more output when failing queue connection.<commit_after>package main

import (
	"encoding/json"
	"errors"
	"net/http"
	"os"
	"fmt"

	"github.com/rs/cors"
	"github.com/zenazn/goji"
	"github.com/zenazn/goji/web"

	"github.com/ckpt/backend-services/middleware"
	"github.com/ckpt/backend-services/players"
)

type appError struct {
	Error   error
	Message string
	Code    int
}

type appHandler func(web.C, http.ResponseWriter, *http.Request) *appError

func (fn appHandler) ServeHTTPC(c web.C, w http.ResponseWriter, r *http.Request) {
	if e := fn(c, w, r); e != nil {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		w.WriteHeader(e.Code)
		encoder := json.NewEncoder(w)
		encoder.Encode(map[string]string{"error": e.Error.Error() +
			" (" + e.Message + ")"})
	}
}

func login(c web.C, w http.ResponseWriter, r *http.Request) *appError {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	type LoginRequest struct {
		Username string
		Password string
	}

	loginReq := new(LoginRequest)
	decoder := json.NewDecoder(r.Body)
	if err := decoder.Decode(loginReq); err != nil {
		return &appError{err, "Invalid JSON", 400}
	}

	if !players.AuthUser(loginReq.Username, loginReq.Password) {
		return &appError{errors.New("Forbidden"), "Invalid username/password", 403}
	}

	authUser, err := players.UserByName(loginReq.Username)
	if err != nil {
		return &appError{err, "Failed to fetch user data", 500}
	}
	if authUser.Locked {
		return &appError{errors.New("Locked"), "User locked", 403}
	}
	encoder := json.NewEncoder(w)
	encoder.Encode(authUser)
	return nil
}

func main() {
	//
	// Event queue hadling
	//
	err := players.StartEventProcessor()
	if err != nil {
		fmt.Printf("%+v", err.Error)
		println("Could not initialize event queue. Exiting")
		os.Exit(1)
	}

	//
	// HTTP Serving
	//
	c := cors.New(cors.Options{
		AllowedOrigins: []string{"*"},
		AllowedHeaders: []string{"*"},
		AllowedMethods: []string{"GET", "PUT", "PATCH", "POST", "OPTIONS", "DELETE"},
	})
	goji.Use(c.Handler)
	goji.Use(middleware.TokenHandler)

	goji.Post("/login", appHandler(login))

	goji.Get("/players", appHandler(listAllPlayers))
	goji.Post("/players", appHandler(createNewPlayer))
	goji.Get("/players/quotes", appHandler(getAllPlayerQuotes))
	goji.Get("/players/:uuid", appHandler(getPlayer))
	goji.Put("/players/:uuid", appHandler(updatePlayer))
	goji.Get("/players/:uuid/profile", appHandler(getPlayerProfile))
	goji.Put("/players/:uuid/profile", appHandler(updatePlayerProfile))
	goji.Get("/players/:uuid/user", appHandler(getUserForPlayer))
	goji.Put("/players/:uuid/user", appHandler(setUserForPlayer))
	goji.Put("/players/:uuid/user/password", appHandler(setUserPassword))
	goji.Put("/players/:uuid/user/settings", appHandler(setUserSettings))
	goji.Get("/players/:uuid/debts", appHandler(showPlayerDebt))
	goji.Delete("/players/:uuid/debts", appHandler(resetPlayerDebts))
	goji.Get("/players/:uuid/credits", appHandler(showPlayerCredits))
	goji.Post("/players/:uuid/debts", appHandler(addPlayerDebt))
	goji.Delete("/players/:uuid/debts/:debtuuid", appHandler(settlePlayerDebt))

	goji.Post("/users", appHandler(createNewUser))

	goji.Get("/locations", appHandler(listAllLocations))
	goji.Post("/locations", appHandler(createNewLocation))
	goji.Get("/locations/:uuid", appHandler(getLocation))
	goji.Put("/locations/:uuid", appHandler(updateLocationProfile))
	goji.Patch("/locations/:uuid", appHandler(updateLocationProfile))
	goji.Post("/locations/:uuid/pictures", appHandler(addLocationPicture))

	goji.Get("/tournaments", appHandler(listAllTournaments))
	goji.Post("/tournaments", appHandler(createNewTournament))
	goji.Get("/tournaments/:uuid", appHandler(getTournament))
	goji.Put("/tournaments/:uuid", appHandler(updateTournamentInfo))
	goji.Patch("/tournaments/:uuid", appHandler(updateTournamentInfo))
	goji.Put("/tournaments/:uuid/played", appHandler(setTournamentPlayed))
	goji.Get("/tournaments/:uuid/result", appHandler(getTournamentResult))
	goji.Put("/tournaments/:uuid/result", appHandler(setTournamentResult))

	goji.Get("/seasons", appHandler(listAllSeasons))
	goji.Get("/seasons/stats", appHandler(getTotalStats))
	goji.Get("/seasons/standings", appHandler(getTotalStandings))
	goji.Get("/seasons/titles", appHandler(getTotalTitles))
	goji.Get("/seasons/:year/tournaments", appHandler(listTournamentsBySeason))
	goji.Get("/seasons/:year/standings", appHandler(getSeasonStandings))
	goji.Get("/seasons/:year/titles", appHandler(getSeasonTitles))
	goji.Get("/seasons/:year/stats", appHandler(getSeasonStats))

	goji.Get("/caterings", appHandler(listAllCaterings))
	goji.Post("/caterings", appHandler(createNewCatering))
	goji.Get("/caterings/:uuid", appHandler(getCatering))
	goji.Put("/caterings/:uuid", appHandler(updateCateringInfo))
	goji.Patch("/caterings/:uuid", appHandler(updateCateringInfo))
	goji.Post("/caterings/:uuid/votes", appHandler(addCateringVote))
	goji.Put("/caterings/:uuid/votes/:playeruuid", appHandler(updateCateringVote))

	goji.Get("/news", appHandler(listAllNews))
	goji.Get("/news/:uuid", appHandler(getNewsItem))
	goji.Patch("/news/:uuid", appHandler(updateNewsItem))
	goji.Post("/news", appHandler(createNewNewsItem))
	// TODO: Comments

	goji.Serve()
}
<|endoftext|>


<commit_before>package main

import (
	"os"

	"github.com/Sirupsen/logrus"
	"github.com/codegangsta/cli"
	"github.com/opencontainers/specs"
)

const (
	version = "0.3"
	usage   = `Open Container Initiative runtime

runc is a command line client for running applications packaged according to
the Open Container Format (OCF) and is a compliant implementation of the
Open Container Initiative specification.

runc integrates well with existing process supervisors to provide a production
container runtime environment for applications. It can be used with your
existing process monitoring tools and the container will be spawned as a
direct child of the process supervisor.

After creating config files for your root filesystem with runc, you can execute a
container in your shell by running:

    # cd /mycontainer
    # runc start [ -c spec-config-file ] [ -r runtime-config-file ]

If not specified, the default value for the 'spec-config-file' is 'config.json',
and the default value for the 'runtime-config-file' is 'runtime.json'.`
)

func main() {
	app := cli.NewApp()
	app.Name = "runc"
	app.Usage = usage
	app.Version = version
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "id",
			Value: getDefaultID(),
			Usage: "specify the ID to be used for the container",
		},
		cli.BoolFlag{
			Name:  "debug",
			Usage: "enable debug output for logging",
		},
		cli.StringFlag{
			Name:  "log",
			Usage: "set the log file path where internal debug information is written",
		},
		cli.StringFlag{
			Name:  "root",
			Value: specs.LinuxStateDirectory,
			Usage: "root directory for storage of container state (this should be located in tmpfs)",
		},
		cli.StringFlag{
			Name:  "criu",
			Value: "criu",
			Usage: "path to the criu binary used for checkpoint and restore",
		},
	}
	app.Commands = []cli.Command{
		startCommand,
		checkpointCommand,
		eventsCommand,
		restoreCommand,
		killCommand,
		specCommand,
		pauseCommand,
		resumeCommand,
		execCommand,
	}
	app.Before = func(context *cli.Context) error {
		if context.GlobalBool("debug") {
			logrus.SetLevel(logrus.DebugLevel)
		}
		if path := context.GlobalString("log"); path != "" {
			f, err := os.Create(path)
			if err != nil {
				return err
			}
			logrus.SetOutput(f)
		}
		return nil
	}
	if err := app.Run(os.Args); err != nil {
		logrus.Fatal(err)
	}
}
<commit_msg>Add ability to use json structured logging format.<commit_after>package main

import (
	"os"

	"github.com/Sirupsen/logrus"
	"github.com/codegangsta/cli"
	"github.com/opencontainers/specs"
)

const (
	version = "0.3"
	usage   = `Open Container Initiative runtime

runc is a command line client for running applications packaged according to
the Open Container Format (OCF) and is a compliant implementation of the
Open Container Initiative specification.

runc integrates well with existing process supervisors to provide a production
container runtime environment for applications. It can be used with your
existing process monitoring tools and the container will be spawned as a
direct child of the process supervisor.

After creating config files for your root filesystem with runc, you can execute a
container in your shell by running:

    # cd /mycontainer
    # runc start [ -c spec-config-file ] [ -r runtime-config-file ]

If not specified, the default value for the 'spec-config-file' is 'config.json',
and the default value for the 'runtime-config-file' is 'runtime.json'.`
)

func main() {
	app := cli.NewApp()
	app.Name = "runc"
	app.Usage = usage
	app.Version = version
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "id",
			Value: getDefaultID(),
			Usage: "specify the ID to be used for the container",
		},
		cli.BoolFlag{
			Name:  "debug",
			Usage: "enable debug output for logging",
		},
		cli.StringFlag{
			Name:  "log",
			Usage: "set the log file path where internal debug information is written",
		},
		cli.StringFlag{
			Name:  "log-format",
			Value: "text",
			Usage: "set the format used by logs ('text' (default), or 'json')",
		},
		cli.StringFlag{
			Name:  "root",
			Value: specs.LinuxStateDirectory,
			Usage: "root directory for storage of container state (this should be located in tmpfs)",
		},
		cli.StringFlag{
			Name:  "criu",
			Value: "criu",
			Usage: "path to the criu binary used for checkpoint and restore",
		},
	}
	app.Commands = []cli.Command{
		startCommand,
		checkpointCommand,
		eventsCommand,
		restoreCommand,
		killCommand,
		specCommand,
		pauseCommand,
		resumeCommand,
		execCommand,
	}
	app.Before = func(context *cli.Context) error {
		if context.GlobalBool("debug") {
			logrus.SetLevel(logrus.DebugLevel)
		}
		if path := context.GlobalString("log"); path != "" {
			f, err := os.Create(path)
			if err != nil {
				return err
			}
			logrus.SetOutput(f)
		}
		switch context.GlobalString("log-format") {
		case "text":
			// retain logrus's default.
		case "json":
			logrus.SetFormatter(new(logrus.JSONFormatter))
		default:
			logrus.Fatalf("unknown log-format %q", context.GlobalString("log-format"))
		}
		return nil
	}
	if err := app.Run(os.Args); err != nil {
		logrus.Fatal(err)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"github.com/kballard/dcpu16/dcpu"
	"github.com/kballard/dcpu16/dcpu/core"
	"github.com/kballard/termbox-go"
	"io/ioutil"
	"os"
)

var requestedRate dcpu.ClockRate = dcpu.DefaultClockRate
var printRate *bool = flag.Bool("printRate", false, "Print the effective clock rate at termination")
var screenRefreshRate dcpu.ClockRate = dcpu.DefaultScreenRefreshRate

func main() {
	// command-line flags
	flag.Var(&requestedRate, "rate", "Clock rate to run the machine at")
	flag.Var(&screenRefreshRate, "screenRefreshRate", "Clock rate to refresh the screen at")
	// update usage
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: %s [flags] program\n", os.Args[0])
		flag.PrintDefaults()
	}
	flag.Parse()
	if flag.NArg() != 1 {
		flag.Usage()
		os.Exit(2)
	}
	program := flag.Arg(0)
	data, err := ioutil.ReadFile(program)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	// Interpret the file as Words
	words := make([]core.Word, len(data)/2)
	for i := 0; i < len(data)/2; i++ {
		w := core.Word(data[i*2])<<8 + core.Word(data[i*2+1])
		words[i] = w
	}

	// Set up a machine
	machine := new(dcpu.Machine)
	machine.Video.RefreshRate = screenRefreshRate
	if err := machine.State.LoadProgram(words, 0); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	if err := machine.Start(requestedRate); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	var effectiveRate dcpu.ClockRate
	// now wait for the ^C key
	for {
		evt := termbox.PollEvent()
		if err := machine.HasError(); err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		if evt.Type == termbox.EventKey {
			if evt.Key == termbox.KeyCtrlC {
				effectiveRate = machine.EffectiveClockRate()
				if err := machine.Stop(); err != nil {
					fmt.Fprintln(os.Stderr, err)
					os.Exit(1)
				}
				break
			}
			// else pass it to the keyboard
			if evt.Ch == 0 {
				// it's a key constant
				key := evt.Key
				machine.Keyboard.RegisterKey(rune(key))
			} else {
				machine.Keyboard.RegisterKey(evt.Ch)
			}
		}
	}
	if *printRate {
		fmt.Printf("Effective clock rate: %s\n", effectiveRate)
	}
}
<commit_msg>Add a -littleEndian flag<commit_after>package main

import (
	"flag"
	"fmt"
	"github.com/kballard/dcpu16/dcpu"
	"github.com/kballard/dcpu16/dcpu/core"
	"github.com/kballard/termbox-go"
	"io/ioutil"
	"os"
)

var requestedRate dcpu.ClockRate = dcpu.DefaultClockRate
var printRate *bool = flag.Bool("printRate", false, "Print the effective clock rate at termination")
var screenRefreshRate dcpu.ClockRate = dcpu.DefaultScreenRefreshRate
var littleEndian *bool = flag.Bool("littleEndian", false, "Interpret the input file as little endian")

func main() {
	// command-line flags
	flag.Var(&requestedRate, "rate", "Clock rate to run the machine at")
	flag.Var(&screenRefreshRate, "screenRefreshRate", "Clock rate to refresh the screen at")
	// update usage
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: %s [flags] program\n", os.Args[0])
		flag.PrintDefaults()
	}
	flag.Parse()
	if flag.NArg() != 1 {
		flag.Usage()
		os.Exit(2)
	}
	program := flag.Arg(0)
	data, err := ioutil.ReadFile(program)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	// Interpret the file as Words
	words := make([]core.Word, len(data)/2)
	for i := 0; i < len(data)/2; i++ {
		b1, b2 := core.Word(data[i*2]), core.Word(data[i*2+1])
		var w core.Word
		if *littleEndian {
			w = b2<<8 + b1
		} else {
			w = b1<<8 + b2
		}
		words[i] = w
	}

	// Set up a machine
	machine := new(dcpu.Machine)
	machine.Video.RefreshRate = screenRefreshRate
	if err := machine.State.LoadProgram(words, 0); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	if err := machine.Start(requestedRate); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	var effectiveRate dcpu.ClockRate
	// now wait for the ^C key
	for {
		evt := termbox.PollEvent()
		if err := machine.HasError(); err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		if evt.Type == termbox.EventKey {
			if evt.Key == termbox.KeyCtrlC {
				effectiveRate = machine.EffectiveClockRate()
				if err := machine.Stop(); err != nil {
					fmt.Fprintln(os.Stderr, err)
					os.Exit(1)
				}
				break
			}
			// else pass it to the keyboard
			if evt.Ch == 0 {
				// it's a key constant
				key := evt.Key
				machine.Keyboard.RegisterKey(rune(key))
			} else {
				machine.Keyboard.RegisterKey(evt.Ch)
			}
		}
	}
	if *printRate {
		fmt.Printf("Effective clock rate: %s\n", effectiveRate)
	}
}
<|endoftext|>