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

package main

// TODOs:
// - Better regexp matching (support sed-like behavior).
// - Keep time from original archive.
// - Add tests.
// - Integrate with cp logic.

import (
	"archive/tar"
	"fmt"
	"io"
	"io/ioutil"
	"strings"

	"flag"

	"upspin.io/access"
	"upspin.io/errors"
	"upspin.io/path"
	"upspin.io/subcmd"
	"upspin.io/upspin"
)

func (s *State) tar(args ...string) {
	const help = `
Tar archives an Upspin tree into a local tar file, or with the
-extract flag, unpacks a local tar file into an Upspin tree.

When extracting, the -match and -replace flags cause the extracted
file to have any prefix that matches be replaced by substitute text.
Whether or not these flags are used, the destination path must
always be in Upspin.
`
	fs := flag.NewFlagSet("tar", flag.ExitOnError)
	extract := fs.Bool("extract", false, "extract from archive")
	match := fs.String("match", "", "extract from the archive only those pathnames that match the `prefix`")
	replace := fs.String("replace", "", "replace -match prefix with the replacement `text`")
	fs.Bool("v", false, "verbose output")
	s.ParseFlags(fs, args, help, "tar [-extract [-match prefix -replace substitution] ] upspin_directory local_file")
	if !*extract {
		if *match != "" || *replace != "" {
			usageAndExit(fs)
		}
		s.tarCommand(fs)
		return
	}
	s.untarCommand(fs)
}

// archiver implements archiving and unarchiving to/from Upspin tree and a local
// file system.
type archiver struct {
	// state holds the current upspin state.
	state *State

	// client is the Upspin client to use for read or write.
	client upspin.Client

	// prefixMatch and prefixReplace are used when unarchiving from an
	// archive when the destination path should be matched and replaced.
	// See flags match and replace.
	prefixMatch   string
	prefixReplace string

	verbose bool
}

func (s *State) tarCommand(fs *flag.FlagSet) {
	if fs.NArg() != 2 {
		usageAndExit(fs)
	}
	a, err := s.newArchiver(subcmd.BoolFlag(fs, "v"))
	if err != nil {
		s.Exit(err)
	}
	dir := s.GlobOneUpspinPath(fs.Arg(0))
	file := s.GlobOneLocal(fs.Arg(1))
	err = a.archive(dir, s.CreateLocal(file))
	if err != nil {
		s.Exit(err)
	}
}

func (s *State) untarCommand(fs *flag.FlagSet) {
	if fs.NArg() != 1 {
		usageAndExit(fs)
	}
	a, err := s.newArchiver(subcmd.BoolFlag(fs, "v"))
	if err != nil {
		s.Exit(err)
	}
	a.matchReplace(subcmd.StringFlag(fs, "match"), subcmd.StringFlag(fs, "replace"))
	err = a.unarchive(s.OpenLocal(s.GlobOneLocal(fs.Arg(0))))
	if err != nil {
		s.Exit(err)
	}
}

func (s *State) newArchiver(verbose bool) (*archiver, error) {
	return &archiver{
		state:   s,
		client:  s.Client,
		verbose: verbose,
	}, nil
}

func (a *archiver) matchReplace(match, replace string) {
	a.prefixMatch = match
	a.prefixReplace = replace
}

// archive walks the pathName and writes the contents to dst.
func (a *archiver) archive(pathName upspin.PathName, dst io.WriteCloser) error {
	tw := tar.NewWriter(dst)

	if err := a.doArchive(pathName, tw, dst); err != nil {
		return err
	}
	if err := tw.Close(); err != nil {
		return err
	}
	return dst.Close()
}

// doArchive is called by the archive method to walk subdirectories.
func (a *archiver) doArchive(pathName upspin.PathName, tw *tar.Writer, dst io.Writer) error {
	entries, err := a.client.Glob(string(path.Join(pathName, "*")))
	if err != nil {
		return err
	}
	for _, e := range entries {
		hdr := &tar.Header{
			Name:    string(e.Name),
			Mode:    0600,
			ModTime: e.Time.Go(),
		}
		if a.verbose {
			fmt.Fprintf(a.state.Stderr, "Archiving %q\n", e.Name)
		}
		switch {
		case e.IsDir():
			hdr.Typeflag = tar.TypeDir
			if err := tw.WriteHeader(hdr); err != nil {
				return err
			}
			// Recurse into this subdir.
			err = a.doArchive(e.Name, tw, dst)
			if err != nil {
				return err
			}
		case e.IsLink():
			hdr.Typeflag = tar.TypeSymlink
			hdr.Linkname = string(e.Link)
			if err := tw.WriteHeader(hdr); err != nil {
				return err
			}
		default:
			size, err := e.Size()
			if err != nil {
				return err
			}
			hdr.Typeflag = tar.TypeReg
			hdr.Size = size
			if err := tw.WriteHeader(hdr); err != nil {
				return err
			}
			if data, err := a.client.Get(e.Name); err != nil {
				return err
			} else if _, err := tw.Write(data); err != nil {
				return err
			}
		}
	}
	return nil
}

// unarchive reads an archive from src and restores it to its final location.
func (a *archiver) unarchive(src io.ReadCloser) error {
	defer src.Close()
	tr := tar.NewReader(src)

	// accessFiles keeps track of Access files' names and contents, since they're
	// unarchived last.
	type accessFiles struct {
		name     upspin.PathName
		contents []byte
	}

	var acc []accessFiles
	for {
		hdr, err := tr.Next()
		if err == io.EOF {
			break
		}
		if err != nil {
			return err
		}

		var name upspin.PathName
		// Adjust names if necessary.
		if a.prefixMatch != "" {
			idx := strings.Index(hdr.Name, a.prefixMatch)
			if idx == 0 {
				// Must be an exact prefix.
				// TODO: support a more general sed-like behavior?
				name = upspin.PathName(a.prefixReplace + hdr.Name[idx+len(a.prefixMatch):])
			} else {
				// Skip if it doesn't match.
				continue
			}
		} else {
			name = upspin.PathName(hdr.Name)
		}

		if a.verbose {
			fmt.Fprintf(a.state.Stderr, "Extracting %q into %q\n", hdr.Name, name)
		}

		switch hdr.Typeflag {
		case tar.TypeDir:
			_, err = a.client.MakeDirectory(name)
			if err != nil && !errors.Is(errors.Exist, err) {
				return err
			}
		case tar.TypeSymlink:
			_, err = a.client.PutLink(upspin.PathName(hdr.Linkname), name)
			if err != nil {
				return err
			}
		case tar.TypeReg:
			buf, err := ioutil.ReadAll(tr)
			if err != nil {
				return err
			}
			name := upspin.PathName(name)
			if access.IsAccessFile(name) {
				// Save Access files for later, to prevent
				// being locked out from restoring sub-entries.
				acc = append(acc, accessFiles{
					name:     name,
					contents: buf,
				})
				continue
			}
			_, err = a.client.Put(name, buf)
			if err != nil {
				return err
			}
		}
	}

	// Now extracts Access files.
	for _, af := range acc {
		_, err := a.client.Put(af.name, af.contents)
		if err != nil {
			return err
		}
	}

	return nil
}
<commit_msg>cmd/upspin: do not read whole files into memory in tar<commit_after>// Copyright 2016 The Upspin Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

// TODOs:
// - Better regexp matching (support sed-like behavior).
// - Keep time from original archive.
// - Add tests.
// - Integrate with cp logic.

import (
	"archive/tar"
	"fmt"
	"io"
	"io/ioutil"
	"strings"

	"flag"

	"upspin.io/access"
	"upspin.io/errors"
	"upspin.io/path"
	"upspin.io/subcmd"
	"upspin.io/upspin"
)

func (s *State) tar(args ...string) {
	const help = `
Tar archives an Upspin tree into a local tar file, or with the
-extract flag, unpacks a local tar file into an Upspin tree.

When extracting, the -match and -replace flags cause the extracted
file to have any prefix that matches be replaced by substitute text.
Whether or not these flags are used, the destination path must
always be in Upspin.
`
	fs := flag.NewFlagSet("tar", flag.ExitOnError)
	extract := fs.Bool("extract", false, "extract from archive")
	match := fs.String("match", "", "extract from the archive only those pathnames that match the `prefix`")
	replace := fs.String("replace", "", "replace -match prefix with the replacement `text`")
	fs.Bool("v", false, "verbose output")
	s.ParseFlags(fs, args, help, "tar [-extract [-match prefix -replace substitution] ] upspin_directory local_file")
	if !*extract {
		if *match != "" || *replace != "" {
			usageAndExit(fs)
		}
		s.tarCommand(fs)
		return
	}
	s.untarCommand(fs)
}

// archiver implements archiving and unarchiving to/from Upspin tree and a local
// file system.
type archiver struct {
	// state holds the current upspin state.
	state *State

	// client is the Upspin client to use for read or write.
	client upspin.Client

	// prefixMatch and prefixReplace are used when unarchiving from an
	// archive when the destination path should be matched and replaced.
	// See flags match and replace.
	prefixMatch   string
	prefixReplace string

	verbose bool
}

func (s *State) tarCommand(fs *flag.FlagSet) {
	if fs.NArg() != 2 {
		usageAndExit(fs)
	}
	a, err := s.newArchiver(subcmd.BoolFlag(fs, "v"))
	if err != nil {
		s.Exit(err)
	}
	dir := s.GlobOneUpspinPath(fs.Arg(0))
	file := s.GlobOneLocal(fs.Arg(1))
	err = a.archive(dir, s.CreateLocal(file))
	if err != nil {
		s.Exit(err)
	}
}

func (s *State) untarCommand(fs *flag.FlagSet) {
	if fs.NArg() != 1 {
		usageAndExit(fs)
	}
	a, err := s.newArchiver(subcmd.BoolFlag(fs, "v"))
	if err != nil {
		s.Exit(err)
	}
	a.matchReplace(subcmd.StringFlag(fs, "match"), subcmd.StringFlag(fs, "replace"))
	err = a.unarchive(s.OpenLocal(s.GlobOneLocal(fs.Arg(0))))
	if err != nil {
		s.Exit(err)
	}
}

func (s *State) newArchiver(verbose bool) (*archiver, error) {
	return &archiver{
		state:   s,
		client:  s.Client,
		verbose: verbose,
	}, nil
}

func (a *archiver) matchReplace(match, replace string) {
	a.prefixMatch = match
	a.prefixReplace = replace
}

// archive walks the pathName and writes the contents to dst.
func (a *archiver) archive(pathName upspin.PathName, dst io.WriteCloser) error {
	tw := tar.NewWriter(dst)

	if err := a.doArchive(pathName, tw, dst); err != nil {
		return err
	}
	if err := tw.Close(); err != nil {
		return err
	}
	return dst.Close()
}

// doArchive is called by the archive method to walk subdirectories.
func (a *archiver) doArchive(pathName upspin.PathName, tw *tar.Writer, dst io.Writer) error {
	entries, err := a.client.Glob(string(path.Join(pathName, "*")))
	if err != nil {
		return err
	}
	for _, e := range entries {
		hdr := &tar.Header{
			Name:    string(e.Name),
			Mode:    0600,
			ModTime: e.Time.Go(),
		}
		if a.verbose {
			fmt.Fprintf(a.state.Stderr, "Archiving %q\n", e.Name)
		}
		switch {
		case e.IsDir():
			hdr.Typeflag = tar.TypeDir
			if err := tw.WriteHeader(hdr); err != nil {
				return err
			}
			// Recurse into this subdir.
			err = a.doArchive(e.Name, tw, dst)
			if err != nil {
				return err
			}
		case e.IsLink():
			hdr.Typeflag = tar.TypeSymlink
			hdr.Linkname = string(e.Link)
			if err := tw.WriteHeader(hdr); err != nil {
				return err
			}
		default:
			size, err := e.Size()
			if err != nil {
				return err
			}
			hdr.Typeflag = tar.TypeReg
			hdr.Size = size
			if err := tw.WriteHeader(hdr); err != nil {
				return err
			}
			f, err := a.client.Open(e.Name)
			if err != nil {
				return err
			}
			_, err = io.Copy(tw, f)
			f.Close()
			if err != nil {
				return err
			}
		}
	}
	return nil
}

// unarchive reads an archive from src and restores it to its final location.
func (a *archiver) unarchive(src io.ReadCloser) error {
	defer src.Close()
	tr := tar.NewReader(src)

	// accessFiles keeps track of Access files' names and contents, since they're
	// unarchived last.
	type accessFiles struct {
		name     upspin.PathName
		contents []byte
	}

	var acc []accessFiles
	for {
		hdr, err := tr.Next()
		if err == io.EOF {
			break
		}
		if err != nil {
			return err
		}

		var name upspin.PathName
		// Adjust names if necessary.
		if a.prefixMatch != "" {
			idx := strings.Index(hdr.Name, a.prefixMatch)
			if idx == 0 {
				// Must be an exact prefix.
				// TODO: support a more general sed-like behavior?
				name = upspin.PathName(a.prefixReplace + hdr.Name[idx+len(a.prefixMatch):])
			} else {
				// Skip if it doesn't match.
				continue
			}
		} else {
			name = upspin.PathName(hdr.Name)
		}

		if a.verbose {
			fmt.Fprintf(a.state.Stderr, "Extracting %q into %q\n", hdr.Name, name)
		}

		switch hdr.Typeflag {
		case tar.TypeDir:
			_, err = a.client.MakeDirectory(name)
			if err != nil && !errors.Is(errors.Exist, err) {
				return err
			}
		case tar.TypeSymlink:
			_, err = a.client.PutLink(upspin.PathName(hdr.Linkname), name)
			if err != nil {
				return err
			}
		case tar.TypeReg:
			if access.IsAccessFile(name) {
				// Save Access files for later, to prevent
				// being locked out from restoring sub-entries.
				buf, err := ioutil.ReadAll(tr)
				if err != nil {
					return err
				}
				acc = append(acc, accessFiles{
					name:     name,
					contents: buf,
				})
				continue
			}
			f, err := a.client.Create(name)
			if err != nil {
				return err
			}
			if _, err := io.Copy(f, tr); err != nil {
				f.Close()
				a.client.Delete(name)
				return err
			}
			if err := f.Close(); err != nil {
				return err
			}
		}
	}

	// Now extract Access files.
	for _, af := range acc {
		_, err := a.client.Put(af.name, af.contents)
		if err != nil {
			return err
		}
	}

	return nil
}
<|endoftext|>


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

// Fmap parses flash maps.
//
// Synopsis:
//     fmap checksum [md5|sha1|sha256] FILE
//     fmap extract i FILE
//     fmap jget JSONFILE FILE
//     fmap jput JSONFILE FILE
//     fmap summary FILE
//     fmap usage FILE
//     fmap verify FILE
//
// Description:
//     checksum: Print a checksum using the given hash function.
//     extract:  Print the i-th area of the flash.
//     jget:     Write json representation of the fmap to JSONFILE.
//     jput:     Replace current fmap with json representation in JSONFILE.
//     summary:  Print a human readable summary.
//     usage:    Print human readable usage stats.
//     verify:   Return 1 if the flash map is invalid.
//
//     This implementation is based off of https://github.com/dhendrix/flashmap.
package main

import (
	"bytes"
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"encoding/json"
	"errors"
	"fmt"
	"hash"
	"io"
	"io/ioutil"
	"log"
	"os"
	"strconv"
	"text/template"

	fmap "github.com/u-root/u-root/cmds/fmap/lib"
)

var cmds = map[string]struct {
	nArgs     int
	parseFMap bool
	f         func(a cmdArgs) error
}{
	"checksum": {1, true, checksum},
	"extract":  {1, true, extract},
	"jget":     {1, true, jsonGet},
	"jput":     {1, false, jsonPut},
	"summary":  {0, true, summary},
	"usage":    {0, true, usage},
	"verify":   {0, true, verify},
}

type cmdArgs struct {
	args []string
	f    *fmap.FMap         // optional
	m    *fmap.FMapMetadata // optional
	r    io.ReadSeeker
}

var hashFuncs = map[string](func() hash.Hash){
	"md5":    md5.New,
	"sha1":   sha1.New,
	"sha256": sha256.New,
}

type jsonSchema struct {
	FMap     *fmap.FMap
	Metadata *fmap.FMapMetadata
}

// Print a checksum using the given hash function.
func checksum(a cmdArgs) error {
	if _, ok := hashFuncs[a.args[0]]; !ok {
		msg := "Not a valid hash function. Must be one of:"
		for k := range hashFuncs {
			msg += " " + k
		}
		return errors.New(msg)
	}

	checksum, err := a.f.Checksum(a.r, hashFuncs[a.args[0]]())
	if err != nil {
		return err
	}
	fmt.Printf("%x\n", checksum)
	return nil
}

// Print the i-th area of the flash.
func extract(a cmdArgs) error {
	i, err := strconv.Atoi(a.args[0])
	if err != nil {
		return err
	}
	areaReader, err := a.f.ReadArea(a.r, i)
	if err != nil {
		return err
	}
	_, err = io.Copy(os.Stdout, areaReader)
	if err != nil {
		return err
	}
	return nil
}

// Write json representation of the fmap to JSONFILE.
func jsonGet(a cmdArgs) error {
	data, err := json.MarshalIndent(jsonSchema{a.f, a.m}, "", "\t")
	if err != nil {
		return err
	}
	data = append(data, byte('\n'))
	if err := ioutil.WriteFile(a.args[0], data, 0666); err != nil {
		return err
	}
	return nil
}

// Replace current fmap with json representation in JSONFILE.
func jsonPut(a cmdArgs) error {
	r, err := os.OpenFile(a.args[0], os.O_RDWR, 0666)
	if err != nil {
		return err
	}
	defer r.Close()

	data, err := ioutil.ReadFile(a.args[0])
	if err != nil {
		return err
	}
	j := jsonSchema{}
	if err := json.Unmarshal(data, &j); err != nil {
		return err
	}
	return fmap.WriteFMap(r, j.FMap, j.Metadata)
}

// Print a human readable summary.
func summary(a cmdArgs) error {
	const desc = `Fmap found at {{printf "%#x" .Metadata.Start}}:
	Signature:  {{printf "%s" .Signature}}
	VerMajor:   {{.VerMajor}}
	VerMinor:   {{.VerMinor}}
	Base:       {{printf "%#x" .Base}}
	Size:       {{printf "%#x" .Size}}
	Name:       {{.Name}}
	NAreas:     {{.NAreas}}
{{- range $i, $v := .Areas}}
	Areas[{{$i}}]:
		Offset:  {{printf "%#x" $v.Offset}}
		Size:    {{printf "%#x" $v.Size}}
		Name:    {{$v.Name}}
		Flags:   {{printf "%#x" $v.Flags}} ({{FlagNames $v.Flags}})
{{- end}}
`
	t := template.Must(template.New("desc").
		Funcs(template.FuncMap{"FlagNames": fmap.FlagNames}).
		Parse(desc))
	// Combine the two structs to pass into template.
	combined := struct {
		*fmap.FMap
		Metadata *fmap.FMapMetadata
	}{a.f, a.m}
	if err := t.Execute(os.Stdout, combined); err != nil {
		return err
	}
	return nil
}

// Print human readable usage stats.
func usage(a cmdArgs) error {
	blockSize := 4 * 1024
	rowLength := 32

	buffer := make([]byte, blockSize)
	fullBlock := bytes.Repeat([]byte{0xff}, blockSize)
	zeroBlock := bytes.Repeat([]byte{0x00}, blockSize)

	fmt.Println("Legend: '.' - full (0xff), '0' - zero (0x00), '#' - mixed")

	if _, err := a.r.Seek(0, io.SeekStart); err != nil {
		return err
	}

	var numBlocks, numFull, numZero int
loop:
	for {
		fmt.Printf("%#08x: ", numBlocks*blockSize)
		for col := 0; col < rowLength; col++ {
			// Read next block.
			_, err := io.ReadFull(a.r, buffer)
			if err == io.EOF {
				fmt.Print("\n")
				break loop
			} else if err == io.ErrUnexpectedEOF {
				fmt.Printf("\nWarning: flash is not a multiple of %d", len(buffer))
				break loop
			} else if err != nil {
				return err
			}
			numBlocks++

			// Analyze block.
			if bytes.Equal(buffer, fullBlock) {
				numFull++
				fmt.Print(".")
			} else if bytes.Equal(buffer, zeroBlock) {
				numZero++
				fmt.Print("0")
			} else {
				fmt.Print("#")
			}
		}
		fmt.Print("\n")
	}

	// Print usage statistics.
	print := func(name string, n int) {
		fmt.Printf("%s %d (%.1f%%)\n", name, n,
			float32(n)/float32(numBlocks)*100)
	}
	print("Blocks:      ", numBlocks)
	print("Full (0xff): ", numFull)
	print("Empty (0x00):", numZero)
	print("Mixed:       ", numBlocks-numFull-numZero)
	return nil
}

// Return 1 if the flash map is invalid.
func verify(a cmdArgs) error {
	var err error
	for i, area := range a.f.Areas {
		if area.Offset+area.Size > a.f.Size {
			err = errors.New("Invalid flash map")
			log.Printf("Area %d is out of range", i)
		}
	}
	return err
}

func printUsage() {
	fmt.Printf("Usage: %s CMD [ARGS...] FILE\n", os.Args[0])
	fmt.Printf("CMD can be one of:\n")
	for k := range cmds {
		fmt.Printf("\t%s\n", k)
	}
	os.Exit(2)
}

func main() {
	// Validate args.
	if len(os.Args) <= 2 {
		printUsage()
	}
	cmd, ok := cmds[os.Args[1]]
	if !ok {
		log.Printf("Invalid command %#v\n", os.Args[1])
		printUsage()
	}
	if len(os.Args) != cmd.nArgs+3 {
		log.Printf("Expected %d arguments, got %d\n", cmd.nArgs+3, len(os.Args))
		printUsage()
	}

	// Args passed to the command.
	a := cmdArgs{
		args: os.Args[2 : len(os.Args)-1],
	}

	// Open file and read fmap, but only for specific commands.
	if cmd.parseFMap {
		// Open file.
		r, err := os.Open(os.Args[len(os.Args)-1])
		if err != nil {
			log.Fatal(err)
		}
		a.r = r
		defer r.Close()

		// Parse fmap.
		f, m, err := fmap.ReadFMap(r)
		if err != nil {
			log.Fatal(err)
		}
		a.f, a.m = f, m
	}

	// Execute command.
	if err := cmd.f(a); err != nil {
		log.Fatal(err)
	}
}
<commit_msg>Fix file writing mistake in jsonPut<commit_after>// Copyright 2017 the u-root Authors. All rights reserved
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Fmap parses flash maps.
//
// Synopsis:
//     fmap checksum [md5|sha1|sha256] FILE
//     fmap extract i FILE
//     fmap jget JSONFILE FILE
//     fmap jput JSONFILE FILE
//     fmap summary FILE
//     fmap usage FILE
//     fmap verify FILE
//
// Description:
//     checksum: Print a checksum using the given hash function.
//     extract:  Print the i-th area of the flash.
//     jget:     Write json representation of the fmap to JSONFILE.
//     jput:     Replace current fmap with json representation in JSONFILE.
//     summary:  Print a human readable summary.
//     usage:    Print human readable usage stats.
//     verify:   Return 1 if the flash map is invalid.
//
//     This implementation is based off of https://github.com/dhendrix/flashmap.
package main

import (
	"bytes"
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"encoding/json"
	"errors"
	"fmt"
	"hash"
	"io"
	"io/ioutil"
	"log"
	"os"
	"strconv"
	"text/template"

	fmap "github.com/u-root/u-root/cmds/fmap/lib"
)

var cmds = map[string]struct {
	nArgs     int
	parseFMap bool
	f         func(a cmdArgs) error
}{
	"checksum": {1, true, checksum},
	"extract":  {1, true, extract},
	"jget":     {1, true, jsonGet},
	"jput":     {1, false, jsonPut},
	"summary":  {0, true, summary},
	"usage":    {0, true, usage},
	"verify":   {0, true, verify},
}

type cmdArgs struct {
	args []string
	f    *fmap.FMap         // optional
	m    *fmap.FMapMetadata // optional
	r    io.ReadSeeker
}

var hashFuncs = map[string](func() hash.Hash){
	"md5":    md5.New,
	"sha1":   sha1.New,
	"sha256": sha256.New,
}

type jsonSchema struct {
	FMap     *fmap.FMap
	Metadata *fmap.FMapMetadata
}

// Print a checksum using the given hash function.
func checksum(a cmdArgs) error {
	if _, ok := hashFuncs[a.args[0]]; !ok {
		msg := "Not a valid hash function. Must be one of:"
		for k := range hashFuncs {
			msg += " " + k
		}
		return errors.New(msg)
	}

	checksum, err := a.f.Checksum(a.r, hashFuncs[a.args[0]]())
	if err != nil {
		return err
	}
	fmt.Printf("%x\n", checksum)
	return nil
}

// Print the i-th area of the flash.
func extract(a cmdArgs) error {
	i, err := strconv.Atoi(a.args[0])
	if err != nil {
		return err
	}
	areaReader, err := a.f.ReadArea(a.r, i)
	if err != nil {
		return err
	}
	_, err = io.Copy(os.Stdout, areaReader)
	if err != nil {
		return err
	}
	return nil
}

// Write json representation of the fmap to JSONFILE.
func jsonGet(a cmdArgs) error {
	data, err := json.MarshalIndent(jsonSchema{a.f, a.m}, "", "\t")
	if err != nil {
		return err
	}
	data = append(data, byte('\n'))
	if err := ioutil.WriteFile(a.args[0], data, 0666); err != nil {
		return err
	}
	return nil
}

// Replace current fmap with json representation in JSONFILE.
func jsonPut(a cmdArgs) error {
	r, err := os.OpenFile(os.Args[len(os.Args)-1], os.O_WRONLY, 0666)
	if err != nil {
		return err
	}
	defer r.Close()

	data, err := ioutil.ReadFile(a.args[0])
	if err != nil {
		return err
	}
	j := jsonSchema{}
	if err := json.Unmarshal(data, &j); err != nil {
		return err
	}
	return fmap.WriteFMap(r, j.FMap, j.Metadata)
}

// Print a human readable summary.
func summary(a cmdArgs) error {
	const desc = `Fmap found at {{printf "%#x" .Metadata.Start}}:
	Signature:  {{printf "%s" .Signature}}
	VerMajor:   {{.VerMajor}}
	VerMinor:   {{.VerMinor}}
	Base:       {{printf "%#x" .Base}}
	Size:       {{printf "%#x" .Size}}
	Name:       {{.Name}}
	NAreas:     {{.NAreas}}
{{- range $i, $v := .Areas}}
	Areas[{{$i}}]:
		Offset:  {{printf "%#x" $v.Offset}}
		Size:    {{printf "%#x" $v.Size}}
		Name:    {{$v.Name}}
		Flags:   {{printf "%#x" $v.Flags}} ({{FlagNames $v.Flags}})
{{- end}}
`
	t := template.Must(template.New("desc").
		Funcs(template.FuncMap{"FlagNames": fmap.FlagNames}).
		Parse(desc))
	// Combine the two structs to pass into template.
	combined := struct {
		*fmap.FMap
		Metadata *fmap.FMapMetadata
	}{a.f, a.m}
	if err := t.Execute(os.Stdout, combined); err != nil {
		return err
	}
	return nil
}

// Print human readable usage stats.
func usage(a cmdArgs) error {
	blockSize := 4 * 1024
	rowLength := 32

	buffer := make([]byte, blockSize)
	fullBlock := bytes.Repeat([]byte{0xff}, blockSize)
	zeroBlock := bytes.Repeat([]byte{0x00}, blockSize)

	fmt.Println("Legend: '.' - full (0xff), '0' - zero (0x00), '#' - mixed")

	if _, err := a.r.Seek(0, io.SeekStart); err != nil {
		return err
	}

	var numBlocks, numFull, numZero int
loop:
	for {
		fmt.Printf("%#08x: ", numBlocks*blockSize)
		for col := 0; col < rowLength; col++ {
			// Read next block.
			_, err := io.ReadFull(a.r, buffer)
			if err == io.EOF {
				fmt.Print("\n")
				break loop
			} else if err == io.ErrUnexpectedEOF {
				fmt.Printf("\nWarning: flash is not a multiple of %d", len(buffer))
				break loop
			} else if err != nil {
				return err
			}
			numBlocks++

			// Analyze block.
			if bytes.Equal(buffer, fullBlock) {
				numFull++
				fmt.Print(".")
			} else if bytes.Equal(buffer, zeroBlock) {
				numZero++
				fmt.Print("0")
			} else {
				fmt.Print("#")
			}
		}
		fmt.Print("\n")
	}

	// Print usage statistics.
	print := func(name string, n int) {
		fmt.Printf("%s %d (%.1f%%)\n", name, n,
			float32(n)/float32(numBlocks)*100)
	}
	print("Blocks:      ", numBlocks)
	print("Full (0xff): ", numFull)
	print("Empty (0x00):", numZero)
	print("Mixed:       ", numBlocks-numFull-numZero)
	return nil
}

// Return 1 if the flash map is invalid.
func verify(a cmdArgs) error {
	var err error
	for i, area := range a.f.Areas {
		if area.Offset+area.Size > a.f.Size {
			err = errors.New("Invalid flash map")
			log.Printf("Area %d is out of range", i)
		}
	}
	return err
}

func printUsage() {
	fmt.Printf("Usage: %s CMD [ARGS...] FILE\n", os.Args[0])
	fmt.Printf("CMD can be one of:\n")
	for k := range cmds {
		fmt.Printf("\t%s\n", k)
	}
	os.Exit(2)
}

func main() {
	// Validate args.
	if len(os.Args) <= 2 {
		printUsage()
	}
	cmd, ok := cmds[os.Args[1]]
	if !ok {
		log.Printf("Invalid command %#v\n", os.Args[1])
		printUsage()
	}
	if len(os.Args) != cmd.nArgs+3 {
		log.Printf("Expected %d arguments, got %d\n", cmd.nArgs+3, len(os.Args))
		printUsage()
	}

	// Args passed to the command.
	a := cmdArgs{
		args: os.Args[2 : len(os.Args)-1],
	}

	// Open file and read fmap, but only for specific commands.
	if cmd.parseFMap {
		// Open file.
		r, err := os.Open(os.Args[len(os.Args)-1])
		if err != nil {
			log.Fatal(err)
		}
		a.r = r
		defer r.Close()

		// Parse fmap.
		f, m, err := fmap.ReadFMap(r)
		if err != nil {
			log.Fatal(err)
		}
		a.f, a.m = f, m
	}

	// Execute command.
	if err := cmd.f(a); err != nil {
		log.Fatal(err)
	}
}
<|endoftext|>


<commit_before>package quest

import (
	"bytes"
	"log"
	"net/http"
	"net/url"
	"testing"

	. "github.com/go-libs/methods"

	mocha "github.com/smartystreets/goconvey/convey"
)

func TestMakeARequest(t *testing.T) {
	q := Request(GET, "http://httpbin.org/get")

	mocha.Convey("Should be making a Request", t, func() {
		mocha.So(q.Method, mocha.ShouldEqual, GET)
	})
}

func TestResponseHandling(t *testing.T) {
	queryParams := url.Values{}
	queryParams.Set("foo", "bar")
	queryParams.Set("name", "活力")

	mocha.Convey("QueryParameters, query string", t, func() {
		Request(GET, "http://httpbin.org/get").
			QueryParameters(&queryParams).
			Response(func(req *http.Request, res *http.Response, data *bytes.Buffer, err error) {
			mocha.So(req.URL.String(), mocha.ShouldEqual, "http://httpbin.org/get?foo=bar&name=%E6%B4%BB%E5%8A%9B")
		})
	})

	mocha.Convey("Parameters, ContentLength should equal to buffer length", t, func() {
		Request(POST, "http://httpbin.org/post").
			Parameters(queryParams).
			Response(func(req *http.Request, res *http.Response, data *bytes.Buffer, err error) {
			mocha.So(res.ContentLength, mocha.ShouldEqual, int64(data.Len()))
		})
	})

	parameters := map[string]interface{}{
		"foo": []int{1, 2, 3},
		"bar": map[string]string{"baz": "qux"},
	}

	type DataStruct struct {
		Headers map[string]string
		Origin  string
	}

	type DataStruct2 struct {
		Origin string
	}

	mocha.Convey("Response JSON", t, func() {
		Request(POST, "http://httpbin.org/post").
			Encoding("JSON").
			Parameters(parameters).
			ResponseJSON(func(req *http.Request, res *http.Response, data *DataStruct, e error) {
			mocha.Convey("Data - a pointer struct", func() {
				mocha.So(data, mocha.ShouldPointTo, data)
				mocha.So(data.Headers["Host"], mocha.ShouldEqual, "httpbin.org")
			})
		}).
			ResponseJSON(func(req *http.Request, res *http.Response, data DataStruct2, e error) {
			mocha.Convey("Data - a struct", func() {
				mocha.So(&data, mocha.ShouldNotPointTo, &DataStruct2{})
				mocha.So(data.Origin, mocha.ShouldNotBeNil)
			})
		}).
			// Nothing happend
			ResponseJSON(func(req *http.Request, res *http.Response, data DataStruct2, e error, g error) {
			log.Println("Nothing happend!")
		})
	})

	type PostParameters struct {
		Foo []int             `json:"foo,omitempty"`
		Bar map[string]string `json:"bar,omitempty"`
	}

	parameters2 := &PostParameters{
		Foo: []int{1, 2, 3},
		Bar: map[string]string{"baz": "qux"},
	}

	type DataStruct4 struct {
		Origin string
	}
	type DataStruct3 struct {
		Headers map[string]string
		Origin  string
		Json    PostParameters `json:"json,omitempty"`
	}

	mocha.Convey("Response JSON, using JSON decode", t, func() {
		Request(POST, "http://httpbin.org/post").
			Encoding("JSON").
			Parameters(parameters2).
			ResponseJSON(func(req *http.Request, res *http.Response, data DataStruct4, e error) {
			mocha.Convey("Using DataStruct4 JSON struct", func() {
				mocha.So(data.Origin, mocha.ShouldNotBeNil)
			})
		}).
			ResponseJSON(func(req *http.Request, res *http.Response, data *DataStruct3, e error) {
			mocha.Convey("Using DataStruct3 JSON struct", func() {
				mocha.So(&data.Json, mocha.ShouldResemble, parameters2)
			})
		})
	})

	mocha.Convey("Encoding Query Options", t, func() {
		type Options struct {
			Foo string `url:"foo"`
			Baz []int  `url:"baz"`
		}

		// http://httpbin.org/get
		Request(GET, "http://httpbin.org/get").
			QueryParameters(Options{"bar", []int{233, 377, 610}}).
			Response(func(req *http.Request, res *http.Response, data *bytes.Buffer, err error) {
			mocha.So(req.URL.String(), mocha.ShouldEqual, "http://httpbin.org/get?baz=233&baz=377&baz=610&foo=bar")
		})
	})
}

func TestDownload(t *testing.T) {
	mocha.Convey("Downloading file", t, func() {
		mocha.Convey("Downloading stream.log in progress", func() {
			Download(GET, "http://httpbin.org/bytes/1024", "tmp/stream.log").Progress(func(c, t, e int64) {
				log.Println(c, t, e)
				mocha.So(c, mocha.ShouldBeLessThanOrEqualTo, t)
			}).Do()
		})
		mocha.Convey("Downloading stream2.log in progress and invoke response handler", func() {
			var n int64
			Download(GET, "http://httpbin.org/bytes/10240", "tmp/stream2.log").Progress(func(c, t, e int64) {
				n = c
				log.Println(c, t, e)
				mocha.So(c, mocha.ShouldBeLessThanOrEqualTo, t)
			}).Response(func(req *http.Request, res *http.Response, data *bytes.Buffer, err error) {
				l := int64(data.Len())
				mocha.So(n, mocha.ShouldEqual, l)
				mocha.So(res.ContentLength, mocha.ShouldEqual, l)
			})
		})
	})
}

func TestUpload(t *testing.T) {
	mocha.Convey("Uploading file", t, func() {
		mocha.Convey("Uploading one file", func() {
			Upload(POST, "http://httpbin.org/post", map[string]string{"stream": "tmp/stream.log"}, nil).
				Progress(func(c, t, e int64) {
				log.Println(c, t, e)
				mocha.So(c, mocha.ShouldBeLessThanOrEqualTo, t)
			}).Do()
		})
		mocha.Convey("Uploading multi files", func() {
			Upload(POST, "http://httpbin.org/post", map[string]string{"stream": "tmp/stream.log", "stream2": "tmp/stream2.log"}, nil).
				Progress(func(c, t, e int64) {
				log.Println(c, t, e)
				mocha.So(c, mocha.ShouldBeLessThanOrEqualTo, t)
			}).Response(func(req *http.Request, res *http.Response, data *bytes.Buffer, err error) {
				l := int64(data.Len())
				mocha.So(res.ContentLength, mocha.ShouldEqual, l)
			})
		})
	})
}
<commit_msg>update<commit_after>package quest

import (
	"bytes"
	"log"
	"net/http"
	"net/url"
	"os"
	"testing"

	. "github.com/go-libs/methods"

	mocha "github.com/smartystreets/goconvey/convey"
)

func TestMakeARequest(t *testing.T) {
	q := Request(GET, "http://httpbin.org/get")

	mocha.Convey("Should be making a Request", t, func() {
		mocha.So(q.Method, mocha.ShouldEqual, GET)
	})
}

func TestResponseHandling(t *testing.T) {
	queryParams := url.Values{}
	queryParams.Set("foo", "bar")
	queryParams.Set("name", "活力")

	mocha.Convey("QueryParameters, query string", t, func() {
		Request(GET, "http://httpbin.org/get").
			QueryParameters(&queryParams).
			Response(func(req *http.Request, res *http.Response, data *bytes.Buffer, err error) {
			mocha.So(req.URL.String(), mocha.ShouldEqual, "http://httpbin.org/get?foo=bar&name=%E6%B4%BB%E5%8A%9B")
		})
	})

	mocha.Convey("Parameters, ContentLength should equal to buffer length", t, func() {
		Request(POST, "http://httpbin.org/post").
			Parameters(queryParams).
			Response(func(req *http.Request, res *http.Response, data *bytes.Buffer, err error) {
			mocha.So(res.ContentLength, mocha.ShouldEqual, int64(data.Len()))
		})
	})

	parameters := map[string]interface{}{
		"foo": []int{1, 2, 3},
		"bar": map[string]string{"baz": "qux"},
	}

	type DataStruct struct {
		Headers map[string]string
		Origin  string
	}

	type DataStruct2 struct {
		Origin string
	}

	mocha.Convey("Response JSON", t, func() {
		Request(POST, "http://httpbin.org/post").
			Encoding("JSON").
			Parameters(parameters).
			ResponseJSON(func(req *http.Request, res *http.Response, data *DataStruct, e error) {
			mocha.Convey("Data - a pointer struct", func() {
				mocha.So(data, mocha.ShouldPointTo, data)
				mocha.So(data.Headers["Host"], mocha.ShouldEqual, "httpbin.org")
			})
		}).
			ResponseJSON(func(req *http.Request, res *http.Response, data DataStruct2, e error) {
			mocha.Convey("Data - a struct", func() {
				mocha.So(&data, mocha.ShouldNotPointTo, &DataStruct2{})
				mocha.So(data.Origin, mocha.ShouldNotBeNil)
			})
		}).
			// Nothing happend
			ResponseJSON(func(req *http.Request, res *http.Response, data DataStruct2, e error, g error) {
			log.Println("Nothing happend!")
		})
	})

	type PostParameters struct {
		Foo []int             `json:"foo,omitempty"`
		Bar map[string]string `json:"bar,omitempty"`
	}

	parameters2 := &PostParameters{
		Foo: []int{1, 2, 3},
		Bar: map[string]string{"baz": "qux"},
	}

	type DataStruct4 struct {
		Origin string
	}
	type DataStruct3 struct {
		Headers map[string]string
		Origin  string
		Json    PostParameters `json:"json,omitempty"`
	}

	mocha.Convey("Response JSON, using JSON decode", t, func() {
		Request(POST, "http://httpbin.org/post").
			Encoding("JSON").
			Parameters(parameters2).
			ResponseJSON(func(req *http.Request, res *http.Response, data DataStruct4, e error) {
			mocha.Convey("Using DataStruct4 JSON struct", func() {
				mocha.So(data.Origin, mocha.ShouldNotBeNil)
			})
		}).
			ResponseJSON(func(req *http.Request, res *http.Response, data *DataStruct3, e error) {
			mocha.Convey("Using DataStruct3 JSON struct", func() {
				mocha.So(&data.Json, mocha.ShouldResemble, parameters2)
			})
		})
	})

	mocha.Convey("Encoding Query Options", t, func() {
		type Options struct {
			Foo string `url:"foo"`
			Baz []int  `url:"baz"`
		}

		// http://httpbin.org/get
		Request(GET, "http://httpbin.org/get").
			QueryParameters(Options{"bar", []int{233, 377, 610}}).
			Response(func(req *http.Request, res *http.Response, data *bytes.Buffer, err error) {
			mocha.So(req.URL.String(), mocha.ShouldEqual, "http://httpbin.org/get?baz=233&baz=377&baz=610&foo=bar")
		})
	})
}

func TestDownload(t *testing.T) {
	os.Mkdir("tmp", os.ModePerm)

	mocha.Convey("Downloading file", t, func() {
		mocha.Convey("Downloading stream.log in progress", func() {
			Download(GET, "http://httpbin.org/bytes/1024", "tmp/stream.log").
				Progress(func(c, t, e int64) {
				log.Println(c, t, e)
				mocha.So(c, mocha.ShouldBeLessThanOrEqualTo, t)
			}).Do()
		})
		mocha.Convey("Downloading stream2.log in progress and invoke response handler", func() {
			var n int64
			Download(GET, "http://httpbin.org/bytes/10240", "tmp/stream2.log").
				Progress(func(c, t, e int64) {
				n = c
				log.Println(c, t, e)
				mocha.So(c, mocha.ShouldBeLessThanOrEqualTo, t)
			}).Response(func(req *http.Request, res *http.Response, data *bytes.Buffer, err error) {
				l := int64(data.Len())
				mocha.So(n, mocha.ShouldEqual, l)
				mocha.So(res.ContentLength, mocha.ShouldEqual, l)
			})
		})
	})
}

func TestUpload(t *testing.T) {
	mocha.Convey("Uploading file", t, func() {
		mocha.Convey("Uploading one file", func() {
			Upload(POST, "http://httpbin.org/post", map[string]string{"stream": "tmp/stream.log"}, nil).
				Progress(func(c, t, e int64) {
				log.Println(c, t, e)
				mocha.So(c, mocha.ShouldBeLessThanOrEqualTo, t)
			}).Do()
		})
		mocha.Convey("Uploading multi files", func() {
			Upload(POST, "http://httpbin.org/post", map[string]string{"stream": "tmp/stream.log", "stream2": "tmp/stream2.log"}, nil).
				Progress(func(c, t, e int64) {
				log.Println(c, t, e)
				mocha.So(c, mocha.ShouldBeLessThanOrEqualTo, t)
			}).Response(func(req *http.Request, res *http.Response, data *bytes.Buffer, err error) {
				l := int64(data.Len())
				mocha.So(res.ContentLength, mocha.ShouldEqual, l)
			})
		})
	})
}
<|endoftext|>


<commit_before>package cluster

import (
	"errors"
	"math"
	"sort"
	"time"

	"github.com/Shopify/sarama"
	"github.com/samuel/go-zookeeper/zk"
)

var (
	DiscardCommit = errors.New("sarama: commit discarded")
	NoCheckout    = errors.New("sarama: not checkout")
)

// A ConsumerGroup operates on all partitions of a single topic. The goal is to ensure
// each topic message is consumed only once, no matter of the number of consumer instances within
// a cluster, as described in: http://kafka.apache.org/documentation.html#distributionimpl.
//
// The ConsumerGroup internally creates multiple Consumer instances. It uses Zookkeper
// and follows a simple consumer rebalancing algorithm which allows all the consumers
// in a group to come into consensus on which consumer is consuming which partitions. Each
// ConsumerGroup can 'claim' 0-n partitions and will consume their messages until another
// ConsumerGroup instance with the same name joins or leaves the cluster.
//
// Unlike stated in the Kafka documentation, consumer rebalancing is *only* triggered on each
// addition or removal of consumers within the same group, while the addition of broker nodes
// and/or partition *does currently not trigger* a rebalancing cycle.
type ConsumerGroup struct {
	id, name, topic string

	config *sarama.ConsumerConfig
	client *sarama.Client
	zoo    *ZK
	claims []PartitionConsumer

	zkchange <-chan zk.Event
	claimed  chan *PartitionConsumer
	listener chan *Notification

	checkout, force, stopper, done chan bool
}

// NewConsumerGroup creates a new consumer group for a given topic.
//
// You MUST call Close() on a consumer to avoid leaks, it will not be garbage-collected automatically when
// it passes out of scope (this is in addition to calling Close on the underlying client, which is still necessary).
func NewConsumerGroup(client *sarama.Client, zoo *ZK, name string, topic string, listener chan *Notification, config *sarama.ConsumerConfig) (group *ConsumerGroup, err error) {
	if config == nil {
		config = new(sarama.ConsumerConfig)
	}

	// Validate configuration
	if err = validateConsumerConfig(config); err != nil {
		return
	} else if topic == "" {
		return nil, sarama.ConfigurationError("Empty topic")
	} else if name == "" {
		return nil, sarama.ConfigurationError("Empty name")
	}

	// Register consumer group
	if err = zoo.RegisterGroup(name); err != nil {
		return
	}

	// Init struct
	group = &ConsumerGroup{
		id:    GUID.New(name),
		name:  name,
		topic: topic,

		config:   config,
		client:   client,
		zoo:      zoo,
		claims:   make([]PartitionConsumer, 0),
		listener: listener,

		stopper:  make(chan bool),
		done:     make(chan bool),
		checkout: make(chan bool),
		force:    make(chan bool),
		claimed:  make(chan *PartitionConsumer),
	}

	// Register itself with zookeeper
	if err = zoo.RegisterConsumer(group.name, group.id, group.topic); err != nil {
		return nil, err
	}

	go group.signalLoop()
	return group, nil
}

// Checkout applies a callback function to a single partition consumer.
// The latest consumer offset is automatically comitted to zookeeper if successful.
// The callback may return a DiscardCommit error to skip the commit silently.
// Returns an error if any, but may also return a NoCheckout error to indicate
// that no partition was available. You should add an artificial delay keep your CPU cool.
func (cg *ConsumerGroup) Checkout(callback func(*PartitionConsumer) error) error {
	cg.checkout <- true
	claimed := <-cg.claimed

	if claimed == nil {
		return NoCheckout
	}

	err := callback(claimed)
	if err == DiscardCommit {
		err = nil
	} else if err == nil && claimed.offset > 0 {
		err = cg.Commit(claimed.partition, claimed.offset+1)
	}
	return err
}

// Process retrieves a bulk of events and applies a callback.
// The latest consumer offset is automatically comitted to zookeeper if successful.
// The callback may return a DiscardCommit error to skip the commit silently.
// Returns an error if any, but may also return a NoCheckout error to indicate
// that no partition was available. You should add an artificial delay keep your CPU cool.
func (cg *ConsumerGroup) Process(callback func(*EventBatch) error) error {
	return cg.Checkout(func(pc *PartitionConsumer) error {
		if batch := pc.Fetch(); batch != nil {

			// Try to reset offset on OffsetOutOfRange errors
			if batch.offsetIsOutOfRange() {
				if err := cg.Commit(pc.partition, 0); err != nil {
					return err
				}
				cg.force <- true
				batch.Events = batch.Events[:1]
			}

			return callback(batch)
		}
		return nil
	})
}

// Commit manually commits an offset for a partition
func (cg *ConsumerGroup) Commit(partition int32, offset int64) error {
	return cg.zoo.Commit(cg.name, cg.topic, partition, offset)
}

// Offset manually retrives an offset for a partition
func (cg *ConsumerGroup) Offset(partition int32) (int64, error) {
	return cg.zoo.Offset(cg.name, cg.topic, partition)
}

// Claims returns the claimed partitions
func (cg *ConsumerGroup) Claims() []int32 {
	res := make([]int32, 0, len(cg.claims))
	for _, claim := range cg.claims {
		res = append(res, claim.partition)
	}
	return res
}

// Close closes the consumer group
func (cg *ConsumerGroup) Close() error {
	close(cg.stopper)
	<-cg.done
	return nil
}

// Background signal loop
func (cg *ConsumerGroup) signalLoop() {
	for {
		// If we have no zk handle, rebalance
		if cg.zkchange == nil {
			if err := cg.rebalance(); err != nil && cg.listener != nil {
				cg.listener <- &Notification{Type: REBALANCE_ERROR, Src: cg, Err: err}
			}
		}

		// If rebalance failed, check if we had a stop signal, then try again
		if cg.zkchange == nil {
			select {
			case <-cg.stopper:
				cg.stop()
				return
			case <-time.After(time.Millisecond):
				// Continue
			}
			continue
		}

		// If rebalance worked, wait for a stop signal or a zookeeper change or a fetch-request
		select {
		case <-cg.stopper:
			cg.stop()
			return
		case <-cg.force:
			cg.zkchange = nil
		case <-cg.zkchange:
			cg.zkchange = nil
		case <-cg.checkout:
			cg.claimed <- cg.nextConsumer()
		}
	}
}

/**********************************************************************
 * PRIVATE
 **********************************************************************/

// Stops the consumer group
func (cg *ConsumerGroup) stop() {
	cg.releaseClaims()
	close(cg.done)
}

// Checkout a claimed partition consumer
func (cg *ConsumerGroup) nextConsumer() *PartitionConsumer {
	if len(cg.claims) < 1 {
		return nil
	}

	shift := cg.claims[0]
	cg.claims = append(cg.claims[1:], shift)
	return &shift
}

// Start a rebalance cycle
func (cg *ConsumerGroup) rebalance() (err error) {
	var cids []string
	var pids []int32

	if cg.listener != nil {
		cg.listener <- &Notification{Type: REBALANCE_START, Src: cg}
	}

	// Fetch a list of consumers and listen for changes
	if cids, cg.zkchange, err = cg.zoo.Consumers(cg.name); err != nil {
		cg.zkchange = nil
		return
	}

	// Fetch a list of partition IDs
	if pids, err = cg.client.Partitions(cg.topic); err != nil {
		cg.zkchange = nil
		return
	}

	// Get leaders for each partition ID
	parts := make(PartitionSlice, len(pids))
	for i, pid := range pids {
		var broker *sarama.Broker
		if broker, err = cg.client.Leader(cg.topic, pid); err != nil {
			cg.zkchange = nil
			return
		}
		defer broker.Close()
		parts[i] = Partition{Id: pid, Addr: broker.Addr()}
	}

	if err = cg.makeClaims(cids, parts); err != nil {
		cg.zkchange = nil
		cg.releaseClaims()
		return
	}
	return
}

func (cg *ConsumerGroup) makeClaims(cids []string, parts PartitionSlice) error {
	cg.releaseClaims()

	for _, part := range cg.claimRange(cids, parts) {
		pc, err := NewPartitionConsumer(cg, part.Id)
		if err != nil {
			return err
		}

		err = cg.zoo.Claim(cg.name, cg.topic, pc.partition, cg.id)
		if err != nil {
			return err
		}

		cg.claims = append(cg.claims, *pc)
	}

	if cg.listener != nil {
		cg.listener <- &Notification{Type: REBALANCE_OK, Src: cg}
	}
	return nil
}

// Determine the partititons dumber to claim
func (cg *ConsumerGroup) claimRange(cids []string, parts PartitionSlice) PartitionSlice {
	sort.Strings(cids)
	sort.Sort(parts)

	cpos := sort.SearchStrings(cids, cg.id)
	clen := len(cids)
	plen := len(parts)
	if cpos >= clen || cpos >= plen {
		return make(PartitionSlice, 0)
	}

	step := int(math.Ceil(float64(plen) / float64(clen)))
	if step < 1 {
		step = 1
	}

	last := (cpos + 1) * step
	if last > plen {
		last = plen
	}
	return parts[cpos*step : last]
}

// Releases all claims
func (cg *ConsumerGroup) releaseClaims() {
	for _, pc := range cg.claims {
		pc.Close()
		cg.zoo.Release(cg.name, cg.topic, pc.partition, cg.id)
	}
	cg.claims = cg.claims[:0]
}

// Validate consumer config, maybe sarama can expose a public ConsumerConfig.Validate() one day
func validateConsumerConfig(config *sarama.ConsumerConfig) error {
	if config.DefaultFetchSize < 0 {
		return sarama.ConfigurationError("Invalid DefaultFetchSize")
	} else if config.DefaultFetchSize == 0 {
		config.DefaultFetchSize = 1024
	}

	if config.MinFetchSize < 0 {
		return sarama.ConfigurationError("Invalid MinFetchSize")
	} else if config.MinFetchSize == 0 {
		config.MinFetchSize = 1
	}

	if config.MaxWaitTime <= 0 {
		return sarama.ConfigurationError("Invalid MaxWaitTime")
	} else if config.MaxWaitTime < 100 {
		sarama.Logger.Println("ConsumerConfig.MaxWaitTime is very low, which can cause high CPU and network usage. See sarama documentation for details.")
	}

	if config.MaxMessageSize < 0 {
		return sarama.ConfigurationError("Invalid MaxMessageSize")
	} else if config.EventBufferSize < 0 {
		return sarama.ConfigurationError("Invalid EventBufferSize")
	}

	return nil
}
<commit_msg>Expose topic & name<commit_after>package cluster

import (
	"errors"
	"math"
	"sort"
	"time"

	"github.com/Shopify/sarama"
	"github.com/samuel/go-zookeeper/zk"
)

var (
	DiscardCommit = errors.New("sarama: commit discarded")
	NoCheckout    = errors.New("sarama: not checkout")
)

// A ConsumerGroup operates on all partitions of a single topic. The goal is to ensure
// each topic message is consumed only once, no matter of the number of consumer instances within
// a cluster, as described in: http://kafka.apache.org/documentation.html#distributionimpl.
//
// The ConsumerGroup internally creates multiple Consumer instances. It uses Zookkeper
// and follows a simple consumer rebalancing algorithm which allows all the consumers
// in a group to come into consensus on which consumer is consuming which partitions. Each
// ConsumerGroup can 'claim' 0-n partitions and will consume their messages until another
// ConsumerGroup instance with the same name joins or leaves the cluster.
//
// Unlike stated in the Kafka documentation, consumer rebalancing is *only* triggered on each
// addition or removal of consumers within the same group, while the addition of broker nodes
// and/or partition *does currently not trigger* a rebalancing cycle.
type ConsumerGroup struct {
	id, name, topic string

	config *sarama.ConsumerConfig
	client *sarama.Client
	zoo    *ZK
	claims []PartitionConsumer

	zkchange <-chan zk.Event
	claimed  chan *PartitionConsumer
	listener chan *Notification

	checkout, force, stopper, done chan bool
}

// NewConsumerGroup creates a new consumer group for a given topic.
//
// You MUST call Close() on a consumer to avoid leaks, it will not be garbage-collected automatically when
// it passes out of scope (this is in addition to calling Close on the underlying client, which is still necessary).
func NewConsumerGroup(client *sarama.Client, zoo *ZK, name string, topic string, listener chan *Notification, config *sarama.ConsumerConfig) (group *ConsumerGroup, err error) {
	if config == nil {
		config = new(sarama.ConsumerConfig)
	}

	// Validate configuration
	if err = validateConsumerConfig(config); err != nil {
		return
	} else if topic == "" {
		return nil, sarama.ConfigurationError("Empty topic")
	} else if name == "" {
		return nil, sarama.ConfigurationError("Empty name")
	}

	// Register consumer group
	if err = zoo.RegisterGroup(name); err != nil {
		return
	}

	// Init struct
	group = &ConsumerGroup{
		id:    GUID.New(name),
		name:  name,
		topic: topic,

		config:   config,
		client:   client,
		zoo:      zoo,
		claims:   make([]PartitionConsumer, 0),
		listener: listener,

		stopper:  make(chan bool),
		done:     make(chan bool),
		checkout: make(chan bool),
		force:    make(chan bool),
		claimed:  make(chan *PartitionConsumer),
	}

	// Register itself with zookeeper
	if err = zoo.RegisterConsumer(group.name, group.id, group.topic); err != nil {
		return nil, err
	}

	go group.signalLoop()
	return group, nil
}

// Name exposes the group name
func (cg *ConsumerGroup) Name() string {
	return cg.name
}

// Topic exposes the group topic
func (cg *ConsumerGroup) Topic() string {
	return cg.topic
}

// Checkout applies a callback function to a single partition consumer.
// The latest consumer offset is automatically comitted to zookeeper if successful.
// The callback may return a DiscardCommit error to skip the commit silently.
// Returns an error if any, but may also return a NoCheckout error to indicate
// that no partition was available. You should add an artificial delay keep your CPU cool.
func (cg *ConsumerGroup) Checkout(callback func(*PartitionConsumer) error) error {
	cg.checkout <- true
	claimed := <-cg.claimed

	if claimed == nil {
		return NoCheckout
	}

	err := callback(claimed)
	if err == DiscardCommit {
		err = nil
	} else if err == nil && claimed.offset > 0 {
		err = cg.Commit(claimed.partition, claimed.offset+1)
	}
	return err
}

// Process retrieves a bulk of events and applies a callback.
// The latest consumer offset is automatically comitted to zookeeper if successful.
// The callback may return a DiscardCommit error to skip the commit silently.
// Returns an error if any, but may also return a NoCheckout error to indicate
// that no partition was available. You should add an artificial delay keep your CPU cool.
func (cg *ConsumerGroup) Process(callback func(*EventBatch) error) error {
	return cg.Checkout(func(pc *PartitionConsumer) error {
		if batch := pc.Fetch(); batch != nil {

			// Try to reset offset on OffsetOutOfRange errors
			if batch.offsetIsOutOfRange() {
				if err := cg.Commit(pc.partition, 0); err != nil {
					return err
				}
				cg.force <- true
				batch.Events = batch.Events[:1]
			}

			return callback(batch)
		}
		return nil
	})
}

// Commit manually commits an offset for a partition
func (cg *ConsumerGroup) Commit(partition int32, offset int64) error {
	return cg.zoo.Commit(cg.name, cg.topic, partition, offset)
}

// Offset manually retrives an offset for a partition
func (cg *ConsumerGroup) Offset(partition int32) (int64, error) {
	return cg.zoo.Offset(cg.name, cg.topic, partition)
}

// Claims returns the claimed partitions
func (cg *ConsumerGroup) Claims() []int32 {
	res := make([]int32, 0, len(cg.claims))
	for _, claim := range cg.claims {
		res = append(res, claim.partition)
	}
	return res
}

// Close closes the consumer group
func (cg *ConsumerGroup) Close() error {
	close(cg.stopper)
	<-cg.done
	return nil
}

// Background signal loop
func (cg *ConsumerGroup) signalLoop() {
	for {
		// If we have no zk handle, rebalance
		if cg.zkchange == nil {
			if err := cg.rebalance(); err != nil && cg.listener != nil {
				cg.listener <- &Notification{Type: REBALANCE_ERROR, Src: cg, Err: err}
			}
		}

		// If rebalance failed, check if we had a stop signal, then try again
		if cg.zkchange == nil {
			select {
			case <-cg.stopper:
				cg.stop()
				return
			case <-time.After(time.Millisecond):
				// Continue
			}
			continue
		}

		// If rebalance worked, wait for a stop signal or a zookeeper change or a fetch-request
		select {
		case <-cg.stopper:
			cg.stop()
			return
		case <-cg.force:
			cg.zkchange = nil
		case <-cg.zkchange:
			cg.zkchange = nil
		case <-cg.checkout:
			cg.claimed <- cg.nextConsumer()
		}
	}
}

/**********************************************************************
 * PRIVATE
 **********************************************************************/

// Stops the consumer group
func (cg *ConsumerGroup) stop() {
	cg.releaseClaims()
	close(cg.done)
}

// Checkout a claimed partition consumer
func (cg *ConsumerGroup) nextConsumer() *PartitionConsumer {
	if len(cg.claims) < 1 {
		return nil
	}

	shift := cg.claims[0]
	cg.claims = append(cg.claims[1:], shift)
	return &shift
}

// Start a rebalance cycle
func (cg *ConsumerGroup) rebalance() (err error) {
	var cids []string
	var pids []int32

	if cg.listener != nil {
		cg.listener <- &Notification{Type: REBALANCE_START, Src: cg}
	}

	// Fetch a list of consumers and listen for changes
	if cids, cg.zkchange, err = cg.zoo.Consumers(cg.name); err != nil {
		cg.zkchange = nil
		return
	}

	// Fetch a list of partition IDs
	if pids, err = cg.client.Partitions(cg.topic); err != nil {
		cg.zkchange = nil
		return
	}

	// Get leaders for each partition ID
	parts := make(PartitionSlice, len(pids))
	for i, pid := range pids {
		var broker *sarama.Broker
		if broker, err = cg.client.Leader(cg.topic, pid); err != nil {
			cg.zkchange = nil
			return
		}
		defer broker.Close()
		parts[i] = Partition{Id: pid, Addr: broker.Addr()}
	}

	if err = cg.makeClaims(cids, parts); err != nil {
		cg.zkchange = nil
		cg.releaseClaims()
		return
	}
	return
}

func (cg *ConsumerGroup) makeClaims(cids []string, parts PartitionSlice) error {
	cg.releaseClaims()

	for _, part := range cg.claimRange(cids, parts) {
		pc, err := NewPartitionConsumer(cg, part.Id)
		if err != nil {
			return err
		}

		err = cg.zoo.Claim(cg.name, cg.topic, pc.partition, cg.id)
		if err != nil {
			return err
		}

		cg.claims = append(cg.claims, *pc)
	}

	if cg.listener != nil {
		cg.listener <- &Notification{Type: REBALANCE_OK, Src: cg}
	}
	return nil
}

// Determine the partititons dumber to claim
func (cg *ConsumerGroup) claimRange(cids []string, parts PartitionSlice) PartitionSlice {
	sort.Strings(cids)
	sort.Sort(parts)

	cpos := sort.SearchStrings(cids, cg.id)
	clen := len(cids)
	plen := len(parts)
	if cpos >= clen || cpos >= plen {
		return make(PartitionSlice, 0)
	}

	step := int(math.Ceil(float64(plen) / float64(clen)))
	if step < 1 {
		step = 1
	}

	last := (cpos + 1) * step
	if last > plen {
		last = plen
	}
	return parts[cpos*step : last]
}

// Releases all claims
func (cg *ConsumerGroup) releaseClaims() {
	for _, pc := range cg.claims {
		pc.Close()
		cg.zoo.Release(cg.name, cg.topic, pc.partition, cg.id)
	}
	cg.claims = cg.claims[:0]
}

// Validate consumer config, maybe sarama can expose a public ConsumerConfig.Validate() one day
func validateConsumerConfig(config *sarama.ConsumerConfig) error {
	if config.DefaultFetchSize < 0 {
		return sarama.ConfigurationError("Invalid DefaultFetchSize")
	} else if config.DefaultFetchSize == 0 {
		config.DefaultFetchSize = 1024
	}

	if config.MinFetchSize < 0 {
		return sarama.ConfigurationError("Invalid MinFetchSize")
	} else if config.MinFetchSize == 0 {
		config.MinFetchSize = 1
	}

	if config.MaxWaitTime <= 0 {
		return sarama.ConfigurationError("Invalid MaxWaitTime")
	} else if config.MaxWaitTime < 100 {
		sarama.Logger.Println("ConsumerConfig.MaxWaitTime is very low, which can cause high CPU and network usage. See sarama documentation for details.")
	}

	if config.MaxMessageSize < 0 {
		return sarama.ConfigurationError("Invalid MaxMessageSize")
	} else if config.EventBufferSize < 0 {
		return sarama.ConfigurationError("Invalid EventBufferSize")
	}

	return nil
}
<|endoftext|>


<commit_before>package run

import (
	"bytes"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/jteeuwen/go-bindata"
)

const (
	// tmp folder prefix
	testDirPrefix = "gentmpl_"

	// base template directory
	baseTemplateDir = "tmpl"
)

var templates = map[string][]string{
	"flat":    {"flat/footer.tmpl", "flat/header.tmpl", "flat/page1.tmpl", "flat/page2and3.tmpl"},
	"inhbase": {"inheritance/base.tmpl"},
	"inh1":    {"inhbase", "inheritance/content1.tmpl"},
	"inh2":    {"inhbase", "inheritance/content2.tmpl"},
}
var pages = map[string]struct {
	Template string
	Base     string
}{
	"Pag1": {"flat", "page-1"},
	"Pag2": {"flat", "page-2"},
	"Pag3": {"flat", "page-3"},
	"Inh1": {"inh1", ""},
	"Inh2": {"inh2", ""},
}

var results = map[string]string{
	"Pag1": "Page 1",
	"Pag2": "Page 2",
	"Pag3": "Page 3",
	"Inh1": "content 1",
	"Inh2": "content 2",
}

var fileinfos = []struct {
	path    string
	content string
}{
	{"flat/header.tmpl", `{{define "header"}}<html><head></head><body>{{end}}`},
	{"flat/footer.tmpl", `{{define "footer"}}</body></html>{{end}}`},
	{"flat/page1.tmpl", `{{define "page-1"}}{{template "header"}}Page 1{{template "footer"}}{{end}}`},
	{"flat/page2and3.tmpl", `{{define "page-2"}}{{template "header"}}Page 2{{template "footer"}}{{end}}{{define "page-3"}}{{template "header"}}Page 3{{template "footer"}}{{end}}`},
	{"inheritance/base.tmpl", `<html><head></head><body>{{template "content" .}}</body></html>`},
	{"inheritance/content1.tmpl", `{{define "content"}}content 1{{end}}`},
	{"inheritance/content2.tmpl", `{{define "content"}}content 2{{end}}`},
}

func writeFile(fullpath, content string) error {
	folder := filepath.Dir(fullpath)
	if err := os.MkdirAll(folder, 0777); err != nil {
		return err
	}
	if err := ioutil.WriteFile(fullpath, []byte(content), 0666); err != nil {
		return err
	}
	return nil
}

func errorLike(err error, msg string) bool {
	return strings.Contains(err.Error(), msg)
}

// create a tmp dir with the template files
// returns the name of the created folder
func setupDirTemplates() string {
	// creates a tmp root directory
	tmpdir, err := ioutil.TempDir("", testDirPrefix)
	if err != nil {
		panic(err)
	}
	// creates the templates files
	for _, fi := range fileinfos {
		out := filepath.Join(tmpdir, baseTemplateDir, fi.path)
		if err := writeFile(out, fi.content); err != nil {
			panic(err)
		}
	}
	// return the name of the tmp root directory
	return tmpdir
}

func TestCheck(t *testing.T) {
	var (
		ctx *Context
		err error
	)

	checkErr := func(err error, testCase, errLike string) {
		if err == nil {
			t.Errorf("%s: expected error like %q; no error found", testCase, errLike)
		}
		if !errorLike(err, errLike) {
			t.Errorf("%s: expected error like %q; found error %q", testCase, errLike, err.Error())
		}
	}

	// test no pages
	ctx = &Context{}
	err = ctx.Check()
	checkErr(err, "no pages", "No pages found")

	// test page without a template
	ctx = &Context{
		Pages: map[string]struct {
			Template string
			Base     string
		}{
			"Pag": {},
		},
	}
	err = ctx.Check()
	checkErr(err, "page with no template", "Page must have a template")

	// test template's page not found
	tmpl := map[string][]string{}
	for _, key := range []string{"flat", "inh1"} {
		tmpl[key] = templates[key]
	}
	ctx = &Context{Pages: pages, Templates: tmpl}
	err = ctx.Check()
	checkErr(err, "no template", "Template not found for page")

	// test cyclic templates
	ctx = &Context{
		Pages: map[string]struct {
			Template string
			Base     string
		}{
			"Pag": {"t1", ""},
		},
		Templates: map[string][]string{
			"t1": {"p1", "t2"},
			"t2": {"p2", "t1"},
		},
	}
	err = ctx.Check()
	checkErr(err, "cyclic templates", "Found invalid cyclic template")

}

func TestWritePackage(t *testing.T) {
	ctx := &Context{Pages: pages, Templates: templates}
	w := new(bytes.Buffer)
	err := ctx.WritePackage(w)
	if err != nil {
		t.Errorf(err.Error())
	}
}

func TestWriteConfig(t *testing.T) {
	ctx := &Context{Pages: pages, Templates: templates}
	w := new(bytes.Buffer)
	err := ctx.WriteConfig(w)
	if err != nil {
		t.Errorf(err.Error())
	}
}
func ctx2str(ctx *Context) string {
	var b bytes.Buffer
	writeBool := func(x bool) {
		ch := '0'
		if x {
			ch = '1'
		}
		b.WriteRune(ch)
	}
	writeSep := func() { b.WriteRune('-') }

	b.WriteString("as")
	writeBool(strings.ToLower(ctx.AssetManager) == "go-bindata")

	writeSep()
	b.WriteString("nc")
	writeBool(ctx.NoCache)

	writeSep()
	b.WriteString("fm")
	writeBool(ctx.FuncMap != "")

	//writeSep()
	//b.WriteString("nf")
	//writeBool(ctx.NoGoFormat)

	return b.String()

}

func writeBindata(out string, ctx *Context) error {
	c := bindata.NewConfig()
	c.Debug = ctx.NoCache
	c.Output = out
	c.Prefix = filepath.Clean(filepath.Join(filepath.Dir(out), "..", baseTemplateDir))
	c.Package = "main"
	c.Input = []bindata.InputConfig{
		bindata.InputConfig{
			Path:      c.Prefix,
			Recursive: true,
		},
	}

	return bindata.Translate(c)
}
func writeMain(out string, ctx *Context) error {
	const text = `package main

import (
	"fmt"
	"os"
)

func main(){
	var page PageEnum = PageInh1
	wr := os.Stdout

	if err := page.Execute(wr, nil); err != nil {
		fmt.Print(err)
	}
}
`
	return writeFile(out, text)

}

func TestAll(t *testing.T) {

	// setup
	tmpdir := setupDirTemplates()
	ctx := &Context{
		PackageName:     "main",
		TemplateBaseDir: filepath.Join("..", baseTemplateDir),
		Pages:           pages,
		Templates:       templates,
	}

	buf := new(bytes.Buffer)

	for _, nocache := range []bool{false, true} {
		ctx.NoCache = nocache

		for _, assetmngr := range []string{"", "go-bindata"} {
			ctx.AssetManager = assetmngr

			for _, funcmap := range []string{"", "funcMap"} {
				ctx.FuncMap = funcmap

				folder := ctx2str(ctx)

				// template.go
				out := filepath.Join(tmpdir, folder, "templates.go")
				buf.Reset()
				err := ctx.WritePackage(buf)
				if err == nil {
					err = writeFile(out, buf.String())
				}
				if err != nil {
					t.Errorf("%s/template %s", folder, err.Error())
				}

				// bindata.go
				if assetmngr != "" {
					out = filepath.Join(tmpdir, folder, "bindata.go")
					err = writeBindata(out, ctx)
					if err != nil {
						t.Errorf("%s/bindata %s", folder, err.Error())
					}
				}

				// main.go
				out = filepath.Join(tmpdir, folder, "main.go")
				err = writeMain(out, ctx)
				if err != nil {
					t.Errorf("%s/main %s", folder, err.Error())
				}
			}
		}
	}
	// clean up
	//defer os.RemoveAll(tmpdir)
}
<commit_msg>fix TestAll example<commit_after>package run

import (
	"bytes"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"

	"github.com/jteeuwen/go-bindata"
)

const (
	// tmp folder prefix
	testDirPrefix = "gentmpl_"

	// base template directory
	baseTemplateDir = "tmpl"
)

var templates = map[string][]string{
	"flat":    {"flat/footer.tmpl", "flat/header.tmpl", "flat/page1.tmpl", "flat/page2and3.tmpl"},
	"inhbase": {"inheritance/base.tmpl"},
	"inh1":    {"inhbase", "inheritance/content1.tmpl"},
	"inh2":    {"inhbase", "inheritance/content2.tmpl"},
}
var pages = map[string]struct {
	Template string
	Base     string
}{
	"Pag1": {"flat", "page-1"},
	"Pag2": {"flat", "page-2"},
	"Pag3": {"flat", "page-3"},
	"Inh1": {"inh1", ""},
	"Inh2": {"inh2", ""},
}

var results = map[string]string{
	"Pag1": "Page 1",
	"Pag2": "Page 2",
	"Pag3": "Page 3",
	"Inh1": "content 1",
	"Inh2": "content 2",
}

var fileinfos = []struct {
	path    string
	content string
}{
	{"flat/header.tmpl", `{{define "header"}}<html><head></head><body>{{end}}`},
	{"flat/footer.tmpl", `{{define "footer"}}</body></html>{{end}}`},
	{"flat/page1.tmpl", `{{define "page-1"}}{{template "header"}}Page 1{{template "footer"}}{{end}}`},
	{"flat/page2and3.tmpl", `{{define "page-2"}}{{template "header"}}Page 2{{template "footer"}}{{end}}{{define "page-3"}}{{template "header"}}Page 3{{template "footer"}}{{end}}`},
	{"inheritance/base.tmpl", `<html><head></head><body>{{template "content" .}}</body></html>`},
	{"inheritance/content1.tmpl", `{{define "content"}}content 1{{end}}`},
	{"inheritance/content2.tmpl", `{{define "content"}}content 2{{end}}`},
}

func writeFile(fullpath, content string) error {
	folder := filepath.Dir(fullpath)
	if err := os.MkdirAll(folder, 0777); err != nil {
		return err
	}
	if err := ioutil.WriteFile(fullpath, []byte(content), 0666); err != nil {
		return err
	}
	return nil
}

func errorLike(err error, msg string) bool {
	return strings.Contains(err.Error(), msg)
}

// create a tmp dir with the template files
// returns the name of the created folder
func setupDirTemplates() string {
	// creates a tmp root directory
	tmpdir, err := ioutil.TempDir("", testDirPrefix)
	if err != nil {
		panic(err)
	}
	// creates the templates files
	for _, fi := range fileinfos {
		out := filepath.Join(tmpdir, baseTemplateDir, fi.path)
		if err := writeFile(out, fi.content); err != nil {
			panic(err)
		}
	}
	// return the name of the tmp root directory
	return tmpdir
}

func TestCheck(t *testing.T) {
	var (
		ctx *Context
		err error
	)

	checkErr := func(err error, testCase, errLike string) {
		if err == nil {
			t.Errorf("%s: expected error like %q; no error found", testCase, errLike)
		}
		if !errorLike(err, errLike) {
			t.Errorf("%s: expected error like %q; found error %q", testCase, errLike, err.Error())
		}
	}

	// test no pages
	ctx = &Context{}
	err = ctx.Check()
	checkErr(err, "no pages", "No pages found")

	// test page without a template
	ctx = &Context{
		Pages: map[string]struct {
			Template string
			Base     string
		}{
			"Pag": {},
		},
	}
	err = ctx.Check()
	checkErr(err, "page with no template", "Page must have a template")

	// test template's page not found
	tmpl := map[string][]string{}
	for _, key := range []string{"flat", "inh1"} {
		tmpl[key] = templates[key]
	}
	ctx = &Context{Pages: pages, Templates: tmpl}
	err = ctx.Check()
	checkErr(err, "no template", "Template not found for page")

	// test cyclic templates
	ctx = &Context{
		Pages: map[string]struct {
			Template string
			Base     string
		}{
			"Pag": {"t1", ""},
		},
		Templates: map[string][]string{
			"t1": {"p1", "t2"},
			"t2": {"p2", "t1"},
		},
	}
	err = ctx.Check()
	checkErr(err, "cyclic templates", "Found invalid cyclic template")

}

func TestWritePackage(t *testing.T) {
	ctx := &Context{Pages: pages, Templates: templates}
	w := new(bytes.Buffer)
	err := ctx.WritePackage(w)
	if err != nil {
		t.Errorf(err.Error())
	}
}

func TestWriteConfig(t *testing.T) {
	ctx := &Context{Pages: pages, Templates: templates}
	w := new(bytes.Buffer)
	err := ctx.WriteConfig(w)
	if err != nil {
		t.Errorf(err.Error())
	}
}
func ctx2str(ctx *Context) string {
	var b bytes.Buffer
	writeBool := func(x bool) {
		ch := '0'
		if x {
			ch = '1'
		}
		b.WriteRune(ch)
	}
	writeSep := func() { b.WriteRune('-') }

	b.WriteString("as")
	writeBool(strings.ToLower(ctx.AssetManager) == "go-bindata")

	writeSep()
	b.WriteString("nc")
	writeBool(ctx.NoCache)

	writeSep()
	b.WriteString("fm")
	writeBool(ctx.FuncMap != "")

	//writeSep()
	//b.WriteString("nf")
	//writeBool(ctx.NoGoFormat)

	return b.String()

}

func writeBindata(out string, ctx *Context) error {
	c := bindata.NewConfig()
	c.Debug = ctx.NoCache
	c.Output = out
	c.Prefix = filepath.Clean(filepath.Join(filepath.Dir(out), "..", baseTemplateDir))
	c.Package = "main"
	c.Input = []bindata.InputConfig{
		bindata.InputConfig{
			Path:      c.Prefix,
			Recursive: true,
		},
	}

	return bindata.Translate(c)
}
func writeMain(out string, ctx *Context) error {
	const text = `package main

import (
	"fmt"
	"os"
)

func main(){
	var page PageEnum = PageInh1
	wr := os.Stdout

	if err := page.Execute(wr, nil); err != nil {
		fmt.Print(err)
	}
}
`
	return writeFile(out, text)

}

func writeFuncmap(out string, ctx *Context) error {
	const text = `package %s

import "html/template"

var %s = template.FuncMap{}
`
	return writeFile(out, fmt.Sprintf(text, ctx.PackageName, ctx.FuncMap))

}

func execMain(dir string) (string, error) {
	var out []byte
	var err error

	//cmdline := fmt.Sprintf("go run %s", filepath.Join(dir, "*.go"))
	cmdline := fmt.Sprintf("cd %s && go run *.go", dir)

	cmd := exec.Command("sh", "-c", cmdline)
	out, err = cmd.CombinedOutput()
	sout := string(out)

	if err != nil {
		return "", errors.New(sout)
	}

	return sout, nil
}

func TestAll(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping TestAll in short mode")
	}

	// setup
	tmpdir := setupDirTemplates()
	ctx := &Context{
		PackageName:     "main",
		TemplateBaseDir: filepath.Join("..", baseTemplateDir),
		Pages:           pages,
		Templates:       templates,
	}

	buf := new(bytes.Buffer)

	for _, nocache := range []bool{false, true} {
		ctx.NoCache = nocache

		for _, assetmngr := range []string{"", "go-bindata"} {
			ctx.AssetManager = assetmngr

			for _, funcmap := range []string{"", "funcMap"} {
				ctx.FuncMap = funcmap

				folder := ctx2str(ctx)

				// template.go
				out := filepath.Join(tmpdir, folder, "templates.go")
				buf.Reset()
				err := ctx.WritePackage(buf)
				if err == nil {
					err = writeFile(out, buf.String())
				}
				if err != nil {
					t.Errorf("%s/template %s", folder, err.Error())
				}

				// bindata.go
				if ctx.FuncMap != "" {
					out = filepath.Join(tmpdir, folder, "funcmap.go")
					err = writeFuncmap(out, ctx)
					if err != nil {
						t.Errorf("%s/funcmap %s", folder, err.Error())
					}
				}

				// bindata.go
				if assetmngr != "" {
					out = filepath.Join(tmpdir, folder, "bindata.go")
					err = writeBindata(out, ctx)
					if err != nil {
						t.Errorf("%s/bindata %s", folder, err.Error())
					}
				}
				// main.go
				out = filepath.Join(tmpdir, folder, "main.go")
				err = writeMain(out, ctx)
				if err != nil {
					t.Errorf("%s/main %s", folder, err.Error())
				}

				// exec main
				if _, err := execMain(filepath.Join(tmpdir, folder)); err != nil {
					t.Errorf("%s/exec %s", folder, err.Error())
				}

			}
		}
	}
	// clean up
	//defer os.RemoveAll(tmpdir)
}
<|endoftext|>


<commit_before>package manager

import (
	"context"
	"time"

	"github.com/golang/protobuf/ptypes/empty"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"github.com/datawire/ambassador/pkg/dlog"
	"github.com/datawire/telepresence2/pkg/rpc"
)

type Manager struct {
	rpc.UnimplementedManagerServer

	state *State
}

type wall struct{}

func (wall) Now() time.Time {
	return time.Now()
}

func NewManager(ctx context.Context) *Manager {
	return &Manager{state: NewState(ctx, wall{})}
}

func (*Manager) Version(context.Context, *empty.Empty) (*rpc.VersionInfo2, error) {
	return &rpc.VersionInfo2{Version: "VERSION"}, nil
}

func (m *Manager) ArriveAsClient(ctx context.Context, client *rpc.ClientInfo) (*rpc.SessionInfo, error) {
	dlog.Debug(ctx, "ArriveAsClient called")

	if val := validateClient(client); val != "" {
		return nil, status.Errorf(codes.InvalidArgument, val)
	}

	sessionID := m.state.AddClient(client)

	return &rpc.SessionInfo{SessionId: sessionID}, nil
}

func (m *Manager) ArriveAsAgent(ctx context.Context, agent *rpc.AgentInfo) (*rpc.SessionInfo, error) {
	dlog.Debug(ctx, "ArriveAsAgent called")

	if val := validateAgent(agent); val != "" {
		return nil, status.Errorf(codes.InvalidArgument, val)
	}

	sessionID := m.state.AddAgent(agent)

	return &rpc.SessionInfo{SessionId: sessionID}, nil
}

func (m *Manager) Remain(ctx context.Context, session *rpc.SessionInfo) (*empty.Empty, error) {
	dlog.Debug(ctx, "Remain called")

	if ok := m.state.Mark(session.SessionId); !ok {
		return nil, status.Errorf(codes.NotFound, "Session %q not found", session.SessionId)
	}

	return &empty.Empty{}, nil
}

func (m *Manager) Depart(ctx context.Context, session *rpc.SessionInfo) (*empty.Empty, error) {
	dlog.Debug(ctx, "Depart called")

	m.state.Remove(session.SessionId)

	return &empty.Empty{}, nil
}

// FIXME Unimplemented
func (m *Manager) WatchAgents(session *rpc.SessionInfo, stream rpc.Manager_WatchAgentsServer) error {
	ctx := stream.Context()
	sessionID := session.SessionId

	dlog.Debug(ctx, "WatchAgents called", sessionID)

	var answerFunc func() []*rpc.AgentInfo

	entry := m.state.Get(sessionID)

	switch /* item := */ entry.Item().(type) {
	case *rpc.ClientInfo:
		// FIXME implement this
		// client := item
		answerFunc = func() []*rpc.AgentInfo {
			return []*rpc.AgentInfo{}
		}
	default:
		return status.Errorf(codes.NotFound, "Client session %q not found", session.SessionId)
	}

	sessionCtx := entry.Context()
	changed := m.state.agentWatches.Subscribe(sessionID)

	for {
		res := &rpc.AgentInfoSnapshot{Agents: answerFunc()}

		if err := stream.Send(res); err != nil {
			return err
		}

		select {
		case <-changed:
			// It's time to send another message
		case <-ctx.Done():
			return nil
		case <-sessionCtx.Done():
			return nil
		}
	}
}

// FIXME Unimplemented
func (m *Manager) WatchIntercepts(session *rpc.SessionInfo, stream rpc.Manager_WatchInterceptsServer) error {
	ctx := stream.Context()
	sessionID := session.SessionId

	dlog.Debug(ctx, "WatchIntercepts called", sessionID)

	var answerFunc func() []*rpc.InterceptInfo

	entry := m.state.Get(sessionID)

	switch /* item := */ entry.Item().(type) {
	case *rpc.ClientInfo:
		// FIXME implement this
		// client := item
		answerFunc = func() []*rpc.InterceptInfo {
			return []*rpc.InterceptInfo{}
		}
	case *rpc.AgentInfo:
		// FIXME implement this
		// agent := item
		answerFunc = func() []*rpc.InterceptInfo {
			return []*rpc.InterceptInfo{}
		}
	default:
		return status.Errorf(codes.NotFound, "Session %q not found", session.SessionId)
	}

	sessionCtx := entry.Context()
	changed := m.state.interceptWatches.Subscribe(sessionID)

	for {
		res := &rpc.InterceptInfoSnapshot{Intercepts: answerFunc()}

		if err := stream.Send(res); err != nil {
			return err
		}

		select {
		case <-changed:
			// It's time to send another message
		case <-ctx.Done():
			return nil
		case <-sessionCtx.Done():
			return nil
		}
	}
}

func (m *Manager) CreateIntercept(context.Context, *rpc.CreateInterceptRequest) (*rpc.InterceptInfo, error) {
	return nil, status.Errorf(codes.Unimplemented, "method CreateIntercept not implemented")
}

func (m *Manager) RemoveIntercept(context.Context, *rpc.RemoveInterceptRequest2) (*empty.Empty, error) {
	return nil, status.Errorf(codes.Unimplemented, "method RemoveIntercept not implemented")
}
<commit_msg>manager: Implement watching Agents<commit_after>package manager

import (
	"context"
	"time"

	"github.com/golang/protobuf/ptypes/empty"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"

	"github.com/datawire/ambassador/pkg/dlog"
	"github.com/datawire/telepresence2/pkg/rpc"
)

type Manager struct {
	rpc.UnimplementedManagerServer

	state *State
}

type wall struct{}

func (wall) Now() time.Time {
	return time.Now()
}

func NewManager(ctx context.Context) *Manager {
	return &Manager{state: NewState(ctx, wall{})}
}

func (*Manager) Version(context.Context, *empty.Empty) (*rpc.VersionInfo2, error) {
	return &rpc.VersionInfo2{Version: "VERSION"}, nil
}

func (m *Manager) ArriveAsClient(ctx context.Context, client *rpc.ClientInfo) (*rpc.SessionInfo, error) {
	dlog.Debug(ctx, "ArriveAsClient called")

	if val := validateClient(client); val != "" {
		return nil, status.Errorf(codes.InvalidArgument, val)
	}

	sessionID := m.state.AddClient(client)

	return &rpc.SessionInfo{SessionId: sessionID}, nil
}

func (m *Manager) ArriveAsAgent(ctx context.Context, agent *rpc.AgentInfo) (*rpc.SessionInfo, error) {
	dlog.Debug(ctx, "ArriveAsAgent called")

	if val := validateAgent(agent); val != "" {
		return nil, status.Errorf(codes.InvalidArgument, val)
	}

	sessionID := m.state.AddAgent(agent)

	return &rpc.SessionInfo{SessionId: sessionID}, nil
}

func (m *Manager) Remain(ctx context.Context, session *rpc.SessionInfo) (*empty.Empty, error) {
	dlog.Debug(ctx, "Remain called")

	if ok := m.state.Mark(session.SessionId); !ok {
		return nil, status.Errorf(codes.NotFound, "Session %q not found", session.SessionId)
	}

	return &empty.Empty{}, nil
}

func (m *Manager) Depart(ctx context.Context, session *rpc.SessionInfo) (*empty.Empty, error) {
	dlog.Debug(ctx, "Depart called")

	m.state.Remove(session.SessionId)

	return &empty.Empty{}, nil
}

// FIXME Unimplemented
func (m *Manager) WatchAgents(session *rpc.SessionInfo, stream rpc.Manager_WatchAgentsServer) error {
	ctx := stream.Context()
	sessionID := session.SessionId

	dlog.Debug(ctx, "WatchAgents called", sessionID)

	if !m.state.HasClient(sessionID) {
		return status.Errorf(codes.NotFound, "Client session %q not found", session.SessionId)
	}

	entry := m.state.Get(sessionID)
	sessionCtx := entry.Context()
	changed := m.state.agentWatches.Subscribe(sessionID)

	for {
		// FIXME This will loop over the presence list looking for agents for
		// every single watcher. How inefficient!
		res := &rpc.AgentInfoSnapshot{Agents: m.state.GetAgents()}

		if err := stream.Send(res); err != nil {
			return err
		}

		select {
		case <-changed:
			// It's time to send another message. Loop.
		case <-ctx.Done():
			// Manager is shutting down.
			return nil
		case <-sessionCtx.Done():
			// Manager believes this session has ended.
			return nil
		}
	}
}

// FIXME Unimplemented
func (m *Manager) WatchIntercepts(session *rpc.SessionInfo, stream rpc.Manager_WatchInterceptsServer) error {
	ctx := stream.Context()
	sessionID := session.SessionId

	dlog.Debug(ctx, "WatchIntercepts called", sessionID)

	var answerFunc func() []*rpc.InterceptInfo

	entry := m.state.Get(sessionID)

	switch /* item := */ entry.Item().(type) {
	case *rpc.ClientInfo:
		// FIXME implement this
		// client := item
		answerFunc = func() []*rpc.InterceptInfo {
			return []*rpc.InterceptInfo{}
		}
	case *rpc.AgentInfo:
		// FIXME implement this
		// agent := item
		answerFunc = func() []*rpc.InterceptInfo {
			return []*rpc.InterceptInfo{}
		}
	default:
		return status.Errorf(codes.NotFound, "Session %q not found", session.SessionId)
	}

	sessionCtx := entry.Context()
	changed := m.state.interceptWatches.Subscribe(sessionID)

	for {
		res := &rpc.InterceptInfoSnapshot{Intercepts: answerFunc()}

		if err := stream.Send(res); err != nil {
			return err
		}

		select {
		case <-changed:
			// It's time to send another message. Loop.
		case <-ctx.Done():
			// Manager is shutting down.
			return nil
		case <-sessionCtx.Done():
			// Manager believes this session has ended.
			return nil
		}
	}
}

func (m *Manager) CreateIntercept(context.Context, *rpc.CreateInterceptRequest) (*rpc.InterceptInfo, error) {
	return nil, status.Errorf(codes.Unimplemented, "method CreateIntercept not implemented")
}

func (m *Manager) RemoveIntercept(context.Context, *rpc.RemoveInterceptRequest2) (*empty.Empty, error) {
	return nil, status.Errorf(codes.Unimplemented, "method RemoveIntercept not implemented")
}
<|endoftext|>