<commit_before>package haaasd

import (
	"bytes"
	"errors"
	"fmt"
	log "github.com/Sirupsen/logrus"
	"io/ioutil"
	"os"
	"os/exec"
	"time"
)

func NewHaproxy(properties *Config, application string, platform string, version string) *Haproxy {
	if version == "" {
		version = "1.4.22"
	}
	return &Haproxy{
		Application: application,
		Platform:    platform,
		properties:  properties,
		Version:     version,
	}
}

type Haproxy struct {
	Application string
	Platform    string
	Version     string
	properties  *Config
	State       int
}

const (
	SUCCESS int = iota
	UNCHANGED int = iota
	ERR_SYSLOG int = iota
	ERR_CONF int = iota
	ERR_RELOAD int = iota
)

// ApplyConfiguration write the new configuration and reload
// A rollback is called on failure
func (hap *Haproxy) ApplyConfiguration(data *EventMessage) (int, error) {
	hap.createSkeleton(data.Correlationid)

	newConf := data.Conf
	path := hap.confPath()

	// Check conf diff
	oldConf, err := ioutil.ReadFile(path)

	if err != nil {
		log.WithFields(log.Fields{
			"correlationId" : data.Correlationid,
			"path": path,
		}).Error("Cannot read old configuration")
		return ERR_CONF, err
	}
	if log.GetLevel() == log.DebugLevel {
		hap.dumpConfiguration(hap.NewDebugPath(), newConf, data)
	}
	if bytes.Equal(oldConf, newConf) {
		log.WithFields(log.Fields{
			"correlationId": data.Correlationid,
			"application": data.Application,
			"plateform":   data.Platform,
		}).Info("Ignore unchanged configuration")
		return UNCHANGED, nil
	}

	// Archive previous configuration
	archivePath := hap.confArchivePath()
	os.Rename(path, archivePath)
	log.WithFields(
		log.Fields{
			"correlationId": data.Correlationid,
			"application": data.Application,
			"plateform":   data.Platform,
			"archivePath": archivePath,
		}).Info("Old configuration saved")
	err = ioutil.WriteFile(path, newConf, 0644)
	if err != nil {
		return ERR_CONF, err
	}
	log.WithField("path", path).Info("New configuration written")

	// Reload haproxy
	err = hap.reload(data.Correlationid)
	if err != nil {
		log.WithFields(log.Fields{
			"application": data.Application,
			"plateform":   data.Platform,
		}).WithError(err).Error("Reload failed")
		hap.dumpConfiguration(hap.NewErrorPath(), newConf, data)
		err = hap.rollback(data.Correlationid)
		return ERR_RELOAD, err
	}
	// Write syslog fragment
	fragmentPath := hap.syslogFragmentPath()
	err = ioutil.WriteFile(fragmentPath, data.SyslogFragment, 0644)
	if err != nil {
		log.WithFields(log.Fields{
			"application": data.Application,
			"plateform":   data.Platform,
		}).WithError(err).Error("Failed to write syslog fragment")
		// TODO Should we rollback on syslog error ?
		return ERR_SYSLOG, err
	}

	return SUCCESS, nil
}

// dumpConfiguration dumps the new configuration file with context for debugging purpose
func (hap *Haproxy) dumpConfiguration(filename string, newConf []byte, data *EventMessage) {

	f, err2 := os.Create(filename)
	defer f.Close()
	if err2 == nil {
		f.WriteString("================================================================\n")
		f.WriteString(fmt.Sprintf("application: %s\n", data.Application))
		f.WriteString(fmt.Sprintf("platform: %s\n", data.Platform))
		f.WriteString(fmt.Sprintf("correlationid: %s\n", data.Correlationid))
		f.WriteString("================================================================\n")
		f.Write(newConf)
		f.Sync()

		log.WithFields(log.Fields{
			"correlationId": data.Correlationid,
			"filename": filename,
			"application": data.Application,
			"platform": data.Platform,
		}).Info("Dump configuration")
	}
}

// confPath give the path of the configuration file given an application context
// It returns the absolute path to the file
func (hap *Haproxy) confPath() string {
	baseDir := hap.properties.HapHome + "/" + hap.Application + "/Config"
	os.MkdirAll(baseDir, 0755)
	return baseDir + "/hap" + hap.Application + hap.Platform + ".conf"
}

// confPath give the path of the archived configuration file given an application context
func (hap *Haproxy) confArchivePath() string {
	baseDir := hap.properties.HapHome + "/" + hap.Application + "/version-1"
	// It returns the absolute path to the file
	os.MkdirAll(baseDir, 0755)
	return baseDir + "/hap" + hap.Application + hap.Platform + ".conf"
}

// NewErrorPath gives a unique path the error file given the hap context
// It returns the full path to the file
func (hap *Haproxy) NewErrorPath() string {
	baseDir := hap.properties.HapHome + "/" + hap.Application + "/errors"
	os.MkdirAll(baseDir, 0755)
	prefix := time.Now().Format("20060102150405")
	return baseDir + "/" + prefix + "_" + hap.Application + hap.Platform + ".log"
}

func (hap *Haproxy) NewDebugPath() string {
	baseDir := hap.properties.HapHome + "/" + hap.Application + "/dump"
	os.MkdirAll(baseDir, 0755)
	prefix := time.Now().Format("20060102150405")
	return baseDir + "/" + prefix + "_" + hap.Application + hap.Platform + ".log"
}

// reload calls external shell script to reload haproxy
// It returns error if the reload fails
func (hap *Haproxy) reload(correlationId string) error {

	reloadScript := hap.getReloadScript()
	cmd, err := exec.Command("sh", reloadScript, "reload", "-y").Output()
	if err != nil {
		log.WithError(err).Error("Error reloading")
	}
	log.WithFields(log.Fields{
		"correlationId" : correlationId,
		"application": hap.Application,
		"platform": hap.Platform,
		"reloadScript": reloadScript,
	}).WithField("cmd", cmd).Debug("Reload succeeded")
	return err
}

// rollbac reverts configuration files and call for reload
func (hap *Haproxy) rollback(correlationId string) error {
	lastConf := hap.confArchivePath()
	if _, err := os.Stat(lastConf); os.IsNotExist(err) {
		return errors.New("No configuration file to rollback")
	}
	os.Rename(lastConf, hap.confPath())
	hap.reload(correlationId)
	return nil
}

// createSkeleton creates the directory tree for a new haproxy context
func (hap *Haproxy) createSkeleton(correlationId string) error {
	baseDir := hap.properties.HapHome + "/" + hap.Application

	createDirectory(correlationId, baseDir + "/Config")
	createDirectory(correlationId, baseDir + "/logs/" + hap.Application + hap.Platform)
	createDirectory(correlationId, baseDir + "/scripts")
	createDirectory(correlationId, baseDir + "/version-1")

	updateSymlink(correlationId, hap.getHapctlFilename(), hap.getReloadScript())
	updateSymlink(correlationId, hap.getHapBinary(), baseDir + "/Config/haproxy")

	log.WithFields(log.Fields{
		"correlationId" : correlationId,
		"dir": baseDir,
	}).Info("Skeleton created")

	return nil
}

// confPath give the path of the configuration file given an application context
// It returns the absolute path to the file
func (hap *Haproxy) syslogFragmentPath() string {
	baseDir := hap.properties.HapHome + "/SYSLOG/Config/syslog.conf.d"
	os.MkdirAll(baseDir, 0755)
	return baseDir + "/syslog" + hap.Application + hap.Platform + ".conf"
}

// updateSymlink create or update a symlink
func updateSymlink(correlationId, oldname string, newname string) {
	if _, err := os.Stat(newname); err == nil {
		os.Remove(newname)
	}
	err := os.Symlink(oldname, newname)
	if err != nil {
		log.WithError(err).WithFields(log.Fields{
			"correlationId" : correlationId,
			"path": newname,
		}).Error("Failed to create symlink")
	}
}

// createDirectory recursively creates directory if it doesn't exists
func createDirectory(correlationId string, dir string) {
	if _, err := os.Stat(dir); os.IsNotExist(err) {
		err := os.MkdirAll(dir, 0755)
		if err != nil {
			log.WithError(err).WithFields(log.Fields{
				"correlationId" : correlationId,
				"dir": dir,
			}).Error("Failed to create")
		} else {
			log.WithFields(log.Fields{
				"correlationId" : correlationId,
				"dir": dir,
			}).Info("Directory created")
		}
	}
}

// getHapctlFilename return the path to the vsc hapctl shell script
// This script is provided
func (hap *Haproxy) getHapctlFilename() string {
	return "/HOME/uxwadm/scripts/hapctl_unif"
}

// getReloadScript calculates reload script path given the hap context
// It returns the full script path
func (hap *Haproxy) getReloadScript() string {
	return fmt.Sprintf("%s/%s/scripts/hapctl%s%s", hap.properties.HapHome, hap.Application, hap.Application, hap.Platform)
}

// getHapBinary calculates the haproxy binary to use given the expected version
// It returns the full path to the haproxy binary
func (hap *Haproxy) getHapBinary() string {
	return fmt.Sprintf("/export/product/haproxy/product/%s/bin/haproxy", hap.Version)
}
<commit_msg>Update logs<commit_after>package haaasd

import (
	"bytes"
	"errors"
	"fmt"
	log "github.com/Sirupsen/logrus"
	"io/ioutil"
	"os"
	"os/exec"
	"time"
)

func NewHaproxy(properties *Config, application string, platform string, version string) *Haproxy {
	if version == "" {
		version = "1.4.22"
	}
	return &Haproxy{
		Application: application,
		Platform:    platform,
		properties:  properties,
		Version:     version,
	}
}

type Haproxy struct {
	Application string
	Platform    string
	Version     string
	properties  *Config
	State       int
}

const (
	SUCCESS int = iota
	UNCHANGED int = iota
	ERR_SYSLOG int = iota
	ERR_CONF int = iota
	ERR_RELOAD int = iota
)

// ApplyConfiguration write the new configuration and reload
// A rollback is called on failure
func (hap *Haproxy) ApplyConfiguration(data *EventMessage) (int, error) {
	hap.createSkeleton(data.Correlationid)

	newConf := data.Conf
	path := hap.confPath()

	// Check conf diff
	oldConf, err := ioutil.ReadFile(path)

	if err != nil {
		log.WithFields(log.Fields{
			"correlationId" : data.Correlationid,
			"path": path,
		}).Error("Cannot read old configuration")
		return ERR_CONF, err
	}
	if log.GetLevel() == log.DebugLevel {
		hap.dumpConfiguration(hap.NewDebugPath(), newConf, data)
	}
	if bytes.Equal(oldConf, newConf) {
		log.WithFields(log.Fields{
			"correlationId": data.Correlationid,
			"application": data.Application,
			"plateform":   data.Platform,
		}).Info("Unchanged configuration")
		return UNCHANGED, nil
	}

	// Archive previous configuration
	archivePath := hap.confArchivePath()
	os.Rename(path, archivePath)
	log.WithFields(
		log.Fields{
			"correlationId": data.Correlationid,
			"application": data.Application,
			"plateform":   data.Platform,
			"archivePath": archivePath,
		}).Info("Old configuration saved")
	err = ioutil.WriteFile(path, newConf, 0644)
	if err != nil {
		return ERR_CONF, err
	}
	log.WithField("path", path).Info("New configuration written")

	// Reload haproxy
	err = hap.reload(data.Correlationid)
	if err != nil {
		log.WithFields(log.Fields{
			"application": data.Application,
			"plateform":   data.Platform,
		}).WithError(err).Error("Reload failed")
		hap.dumpConfiguration(hap.NewErrorPath(), newConf, data)
		err = hap.rollback(data.Correlationid)
		return ERR_RELOAD, err
	}
	// Write syslog fragment
	fragmentPath := hap.syslogFragmentPath()
	err = ioutil.WriteFile(fragmentPath, data.SyslogFragment, 0644)
	if err != nil {
		log.WithFields(log.Fields{
			"application": data.Application,
			"plateform":   data.Platform,
		}).WithError(err).Error("Failed to write syslog fragment")
		// TODO Should we rollback on syslog error ?
		return ERR_SYSLOG, err
	}

	return SUCCESS, nil
}

// dumpConfiguration dumps the new configuration file with context for debugging purpose
func (hap *Haproxy) dumpConfiguration(filename string, newConf []byte, data *EventMessage) {

	f, err2 := os.Create(filename)
	defer f.Close()
	if err2 == nil {
		f.WriteString("================================================================\n")
		f.WriteString(fmt.Sprintf("application: %s\n", data.Application))
		f.WriteString(fmt.Sprintf("platform: %s\n", data.Platform))
		f.WriteString(fmt.Sprintf("correlationid: %s\n", data.Correlationid))
		f.WriteString("================================================================\n")
		f.Write(newConf)
		f.Sync()

		log.WithFields(log.Fields{
			"correlationId": data.Correlationid,
			"filename": filename,
			"application": data.Application,
			"platform": data.Platform,
		}).Info("Dump configuration")
	}
}

// confPath give the path of the configuration file given an application context
// It returns the absolute path to the file
func (hap *Haproxy) confPath() string {
	baseDir := hap.properties.HapHome + "/" + hap.Application + "/Config"
	os.MkdirAll(baseDir, 0755)
	return baseDir + "/hap" + hap.Application + hap.Platform + ".conf"
}

// confPath give the path of the archived configuration file given an application context
func (hap *Haproxy) confArchivePath() string {
	baseDir := hap.properties.HapHome + "/" + hap.Application + "/version-1"
	// It returns the absolute path to the file
	os.MkdirAll(baseDir, 0755)
	return baseDir + "/hap" + hap.Application + hap.Platform + ".conf"
}

// NewErrorPath gives a unique path the error file given the hap context
// It returns the full path to the file
func (hap *Haproxy) NewErrorPath() string {
	baseDir := hap.properties.HapHome + "/" + hap.Application + "/errors"
	os.MkdirAll(baseDir, 0755)
	prefix := time.Now().Format("20060102150405")
	return baseDir + "/" + prefix + "_" + hap.Application + hap.Platform + ".log"
}

func (hap *Haproxy) NewDebugPath() string {
	baseDir := hap.properties.HapHome + "/" + hap.Application + "/dump"
	os.MkdirAll(baseDir, 0755)
	prefix := time.Now().Format("20060102150405")
	return baseDir + "/" + prefix + "_" + hap.Application + hap.Platform + ".log"
}

// reload calls external shell script to reload haproxy
// It returns error if the reload fails
func (hap *Haproxy) reload(correlationId string) error {

	reloadScript := hap.getReloadScript()
	cmd, err := exec.Command("sh", reloadScript, "reload", "-y").Output()
	if err != nil {
		log.WithError(err).Error("Error reloading")
	}
	log.WithFields(log.Fields{
		"correlationId" : correlationId,
		"application": hap.Application,
		"platform": hap.Platform,
		"reloadScript": reloadScript,
	}).WithField("cmd", cmd).Debug("Reload succeeded")
	return err
}

// rollbac reverts configuration files and call for reload
func (hap *Haproxy) rollback(correlationId string) error {
	lastConf := hap.confArchivePath()
	if _, err := os.Stat(lastConf); os.IsNotExist(err) {
		return errors.New("No configuration file to rollback")
	}
	os.Rename(lastConf, hap.confPath())
	hap.reload(correlationId)
	return nil
}

// createSkeleton creates the directory tree for a new haproxy context
func (hap *Haproxy) createSkeleton(correlationId string) error {
	baseDir := hap.properties.HapHome + "/" + hap.Application

	createDirectory(correlationId, baseDir + "/Config")
	createDirectory(correlationId, baseDir + "/logs/" + hap.Application + hap.Platform)
	createDirectory(correlationId, baseDir + "/scripts")
	createDirectory(correlationId, baseDir + "/version-1")

	updateSymlink(correlationId, hap.getHapctlFilename(), hap.getReloadScript())
	updateSymlink(correlationId, hap.getHapBinary(), baseDir + "/Config/haproxy")

	return nil
}

// confPath give the path of the configuration file given an application context
// It returns the absolute path to the file
func (hap *Haproxy) syslogFragmentPath() string {
	baseDir := hap.properties.HapHome + "/SYSLOG/Config/syslog.conf.d"
	os.MkdirAll(baseDir, 0755)
	return baseDir + "/syslog" + hap.Application + hap.Platform + ".conf"
}

// updateSymlink create or update a symlink
func updateSymlink(correlationId, oldname string, newname string) {
	if _, err := os.Stat(newname); err == nil {
		os.Remove(newname)
	}
	err := os.Symlink(oldname, newname)
	if err != nil {
		log.WithError(err).WithFields(log.Fields{
			"correlationId" : correlationId,
			"path": newname,
		}).Error("Symlink failed")
	} else {
		log.WithFields(log.Fields{
			"correlationId" : correlationId,
			"path": newname,
		}).Info("Symlink created")
	}
}

// createDirectory recursively creates directory if it doesn't exists
func createDirectory(correlationId string, dir string) {
	if _, err := os.Stat(dir); os.IsNotExist(err) {
		err := os.MkdirAll(dir, 0755)
		if err != nil {
			log.WithError(err).WithFields(log.Fields{
				"correlationId" : correlationId,
				"dir": dir,
			}).Error("Failed to create")
		} else {
			log.WithFields(log.Fields{
				"correlationId" : correlationId,
				"dir": dir,
			}).Info("Directory created")
		}
	}
}

// getHapctlFilename return the path to the vsc hapctl shell script
// This script is provided
func (hap *Haproxy) getHapctlFilename() string {
	return "/HOME/uxwadm/scripts/hapctl_unif"
}

// getReloadScript calculates reload script path given the hap context
// It returns the full script path
func (hap *Haproxy) getReloadScript() string {
	return fmt.Sprintf("%s/%s/scripts/hapctl%s%s", hap.properties.HapHome, hap.Application, hap.Application, hap.Platform)
}

// getHapBinary calculates the haproxy binary to use given the expected version
// It returns the full path to the haproxy binary
func (hap *Haproxy) getHapBinary() string {
	return fmt.Sprintf("/export/product/haproxy/product/%s/bin/haproxy", hap.Version)
}
<|endoftext|>


<commit_before>package multiaddr

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"strings"
)

// multiaddr is the data structure representing a Multiaddr
type multiaddr struct {
	bytes []byte
}

// NewMultiaddr parses and validates an input string, returning a *Multiaddr
func NewMultiaddr(s string) (a Multiaddr, err error) {
	defer func() {
		if e := recover(); e != nil {
			log.Printf("Panic in NewMultiaddr on input %q: %s", s, e)
			err = fmt.Errorf("%v", e)
		}
	}()
	b, err := stringToBytes(s)
	if err != nil {
		return nil, err
	}
	return &multiaddr{bytes: b}, nil
}

// NewMultiaddrBytes initializes a Multiaddr from a byte representation.
// It validates it as an input string.
func NewMultiaddrBytes(b []byte) (a Multiaddr, err error) {
	defer func() {
		if e := recover(); e != nil {
			log.Printf("Panic in NewMultiaddrBytes on input %q: %s", b, e)
			err = fmt.Errorf("%v", e)
		}
	}()

	if err := validateBytes(b); err != nil {
		return nil, err
	}

	return &multiaddr{bytes: b}, nil
}

// Equal tests whether two multiaddrs are equal
func (m *multiaddr) Equal(m2 Multiaddr) bool {
	return bytes.Equal(m.bytes, m2.Bytes())
}

// Bytes returns the []byte representation of this Multiaddr
//
// Do not modify the returned buffer, it may be shared.
func (m *multiaddr) Bytes() []byte {
	return m.bytes
}

// String returns the string representation of a Multiaddr
func (m *multiaddr) String() string {
	s, err := bytesToString(m.bytes)
	if err != nil {
		panic(fmt.Errorf("multiaddr failed to convert back to string. corrupted? %s", err))
	}
	return s
}

func (m *multiaddr) MarshalBinary() ([]byte, error) {
	return m.Bytes(), nil
}

func (m *multiaddr) UnmarshalBinary(data []byte) error {
	new, err := NewMultiaddrBytes(data)
	if err != nil {
		return err
	}
	*m = *(new.(*multiaddr))
	return nil
}

func (m *multiaddr) MarshalText() ([]byte, error) {
	return []byte(m.String()), nil
}

func (m *multiaddr) UnmarshalText(data []byte) error {
	new, err := NewMultiaddr(string(data))
	if err != nil {
		return err
	}
	*m = *(new.(*multiaddr))
	return nil
}

func (m *multiaddr) MarshalJSON() ([]byte, error) {
	return json.Marshal(m.String())
}

func (m *multiaddr) UnmarshalJSON(data []byte) error {
	var v string
	if err := json.Unmarshal(data, &v); err != nil {
		return err
	}
	new, err := NewMultiaddr(v)
	*m = *(new.(*multiaddr))
	return err
}

// Protocols returns the list of protocols this Multiaddr has.
// will panic in case we access bytes incorrectly.
func (m *multiaddr) Protocols() []Protocol {
	ps := make([]Protocol, 0, 8)
	b := m.bytes
	for len(b) > 0 {
		code, n, err := ReadVarintCode(b)
		if err != nil {
			panic(err)
		}

		p := ProtocolWithCode(code)
		if p.Code == 0 {
			// this is a panic (and not returning err) because this should've been
			// caught on constructing the Multiaddr
			panic(fmt.Errorf("no protocol with code %d", b[0]))
		}
		ps = append(ps, p)
		b = b[n:]

		n, size, err := sizeForAddr(p, b)
		if err != nil {
			panic(err)
		}

		b = b[n+size:]
	}
	return ps
}

// Encapsulate wraps a given Multiaddr, returning the resulting joined Multiaddr
func (m *multiaddr) Encapsulate(o Multiaddr) Multiaddr {
	mb := m.bytes
	ob := o.Bytes()

	b := make([]byte, len(mb)+len(ob))
	copy(b, mb)
	copy(b[len(mb):], ob)
	return &multiaddr{bytes: b}
}

// Decapsulate unwraps Multiaddr up until the given Multiaddr is found.
func (m *multiaddr) Decapsulate(o Multiaddr) Multiaddr {
	s1 := m.String()
	s2 := o.String()
	i := strings.LastIndex(s1, s2)
	if i < 0 {
		// if multiaddr not contained, returns a copy.
		cpy := make([]byte, len(m.bytes))
		copy(cpy, m.bytes)
		return &multiaddr{bytes: cpy}
	}

	if i == 0 {
		return nil
	}

	ma, err := NewMultiaddr(s1[:i])
	if err != nil {
		panic("Multiaddr.Decapsulate incorrect byte boundaries.")
	}
	return ma
}

var ErrProtocolNotFound = fmt.Errorf("protocol not found in multiaddr")

func (m *multiaddr) ValueForProtocol(code int) (value string, err error) {
	err = ErrProtocolNotFound
	ForEach(m, func(c Component) bool {
		if c.Protocol().Code == code {
			value = c.Value()
			err = nil
			return false
		}
		return true
	})
	return
}

// FilterAddrs is a filter that removes certain addresses, according to the given filters.
// If all filters return true, the address is kept.
func FilterAddrs(a []Multiaddr, filters ...func(Multiaddr) bool) []Multiaddr {
	b := make([]Multiaddr, 0, len(a))
	for _, addr := range a {
		good := true
		for _, filter := range filters {
			good = good && filter(addr)
		}
		if good {
			b = append(b, addr)
		}
	}
	return b
}
<commit_msg>optimize FilterAddrs implementation<commit_after>package multiaddr

import (
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"strings"
)

// multiaddr is the data structure representing a Multiaddr
type multiaddr struct {
	bytes []byte
}

// NewMultiaddr parses and validates an input string, returning a *Multiaddr
func NewMultiaddr(s string) (a Multiaddr, err error) {
	defer func() {
		if e := recover(); e != nil {
			log.Printf("Panic in NewMultiaddr on input %q: %s", s, e)
			err = fmt.Errorf("%v", e)
		}
	}()
	b, err := stringToBytes(s)
	if err != nil {
		return nil, err
	}
	return &multiaddr{bytes: b}, nil
}

// NewMultiaddrBytes initializes a Multiaddr from a byte representation.
// It validates it as an input string.
func NewMultiaddrBytes(b []byte) (a Multiaddr, err error) {
	defer func() {
		if e := recover(); e != nil {
			log.Printf("Panic in NewMultiaddrBytes on input %q: %s", b, e)
			err = fmt.Errorf("%v", e)
		}
	}()

	if err := validateBytes(b); err != nil {
		return nil, err
	}

	return &multiaddr{bytes: b}, nil
}

// Equal tests whether two multiaddrs are equal
func (m *multiaddr) Equal(m2 Multiaddr) bool {
	return bytes.Equal(m.bytes, m2.Bytes())
}

// Bytes returns the []byte representation of this Multiaddr
//
// Do not modify the returned buffer, it may be shared.
func (m *multiaddr) Bytes() []byte {
	return m.bytes
}

// String returns the string representation of a Multiaddr
func (m *multiaddr) String() string {
	s, err := bytesToString(m.bytes)
	if err != nil {
		panic(fmt.Errorf("multiaddr failed to convert back to string. corrupted? %s", err))
	}
	return s
}

func (m *multiaddr) MarshalBinary() ([]byte, error) {
	return m.Bytes(), nil
}

func (m *multiaddr) UnmarshalBinary(data []byte) error {
	new, err := NewMultiaddrBytes(data)
	if err != nil {
		return err
	}
	*m = *(new.(*multiaddr))
	return nil
}

func (m *multiaddr) MarshalText() ([]byte, error) {
	return []byte(m.String()), nil
}

func (m *multiaddr) UnmarshalText(data []byte) error {
	new, err := NewMultiaddr(string(data))
	if err != nil {
		return err
	}
	*m = *(new.(*multiaddr))
	return nil
}

func (m *multiaddr) MarshalJSON() ([]byte, error) {
	return json.Marshal(m.String())
}

func (m *multiaddr) UnmarshalJSON(data []byte) error {
	var v string
	if err := json.Unmarshal(data, &v); err != nil {
		return err
	}
	new, err := NewMultiaddr(v)
	*m = *(new.(*multiaddr))
	return err
}

// Protocols returns the list of protocols this Multiaddr has.
// will panic in case we access bytes incorrectly.
func (m *multiaddr) Protocols() []Protocol {
	ps := make([]Protocol, 0, 8)
	b := m.bytes
	for len(b) > 0 {
		code, n, err := ReadVarintCode(b)
		if err != nil {
			panic(err)
		}

		p := ProtocolWithCode(code)
		if p.Code == 0 {
			// this is a panic (and not returning err) because this should've been
			// caught on constructing the Multiaddr
			panic(fmt.Errorf("no protocol with code %d", b[0]))
		}
		ps = append(ps, p)
		b = b[n:]

		n, size, err := sizeForAddr(p, b)
		if err != nil {
			panic(err)
		}

		b = b[n+size:]
	}
	return ps
}

// Encapsulate wraps a given Multiaddr, returning the resulting joined Multiaddr
func (m *multiaddr) Encapsulate(o Multiaddr) Multiaddr {
	mb := m.bytes
	ob := o.Bytes()

	b := make([]byte, len(mb)+len(ob))
	copy(b, mb)
	copy(b[len(mb):], ob)
	return &multiaddr{bytes: b}
}

// Decapsulate unwraps Multiaddr up until the given Multiaddr is found.
func (m *multiaddr) Decapsulate(o Multiaddr) Multiaddr {
	s1 := m.String()
	s2 := o.String()
	i := strings.LastIndex(s1, s2)
	if i < 0 {
		// if multiaddr not contained, returns a copy.
		cpy := make([]byte, len(m.bytes))
		copy(cpy, m.bytes)
		return &multiaddr{bytes: cpy}
	}

	if i == 0 {
		return nil
	}

	ma, err := NewMultiaddr(s1[:i])
	if err != nil {
		panic("Multiaddr.Decapsulate incorrect byte boundaries.")
	}
	return ma
}

var ErrProtocolNotFound = fmt.Errorf("protocol not found in multiaddr")

func (m *multiaddr) ValueForProtocol(code int) (value string, err error) {
	err = ErrProtocolNotFound
	ForEach(m, func(c Component) bool {
		if c.Protocol().Code == code {
			value = c.Value()
			err = nil
			return false
		}
		return true
	})
	return
}

// FilterAddrs is a filter that removes certain addresses, according to the given filters.
// If all filters return true, the address is kept.
func FilterAddrs(a []Multiaddr, filters ...func(Multiaddr) bool) []Multiaddr {
	b := make([]Multiaddr, 0, len(a))
addrloop:
	for _, addr := range a {
		for _, filter := range filters {
			if !filter(addr) {
				continue addrloop
			}
		}
		b = append(b, addr)
	}
	return b
}
<|endoftext|>


<commit_before>package multipass

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/json"
	"encoding/pem"
	"errors"
	"fmt"
	"log"
	"net/http"
	"net/url"
	"path"
	"strings"
	"time"

	"github.com/mholt/caddy/caddyhttp/httpserver"

	jose "gopkg.in/square/go-jose.v1"
)

var ErrInvalidToken error = errors.New("invalid token")

type Auth struct {
	*Config
	Next httpserver.Handler
}

type Rule struct {
	Basepath  string
	Expires   time.Duration
	Resources []string
	Handles   []string

	SMTPAddr, SMTPUser, SMTPPass string
	MailFrom, MailTmpl           string
}

type Config struct {
	Resources []string
	Basepath  string
	SiteAddr  string
	Expires   time.Duration

	sender     Sender
	authorizer Authorizer
	signer     jose.Signer
	key        *rsa.PrivateKey
}

func ConfigFromRule(r Rule) (*Config, error) {
	config, err := NewConfig()
	if err != nil {
		return nil, err
	}
	if len(r.Resources) > 0 {
		config.Resources = r.Resources
	}
	if len(r.Basepath) > 0 {
		config.Basepath = r.Basepath
	}
	if r.Expires > 0 {
		config.Expires = r.Expires
	}

	smtpAddr := "localhost:25"
	if len(r.SMTPAddr) > 0 {
		smtpAddr = r.SMTPAddr
	}
	mailTmpl := emailTemplate
	if len(r.MailTmpl) > 0 {
		mailTmpl = r.MailTmpl
	}
	config.sender = NewMailSender(smtpAddr, nil, r.MailFrom, mailTmpl)

	authorizer := &EmailAuthorizer{list: []string{}}
	for _, handle := range r.Handles {
		authorizer.Add(handle)
	}
	config.authorizer = authorizer

	return config, nil
}

func NewConfig() (*Config, error) {
	pk, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, err
	}
	signer, err := jose.NewSigner(jose.PS512, pk)
	if err != nil {
		return nil, err
	}
	return &Config{
		Resources: []string{"/"},
		Basepath:  "/",
		Expires:   time.Hour * 24,
		key:       pk,
		signer:    signer,
	}, nil
}

// Claims are part of the JSON web token
type Claims struct {
	Handle    string   `json:"handle"`
	Resources []string `json:"resources"`
	Expires   int64    `json:"exp"`
}

func (c *Config) AccessToken(handle string) (tokenStr string, err error) {
	exp := time.Now().Add(c.Expires)
	claims := &Claims{
		Handle:    handle,
		Resources: c.Resources,
		Expires:   exp.Unix(),
	}
	payload, err := json.Marshal(claims)
	if err != nil {
		return "", err
	}
	jws, err := c.signer.Sign(payload)
	if err != nil {
		return "", err
	}

	return jws.CompactSerialize()
}

func (c *Config) LoginURL(u url.URL, tokenStr string) url.URL {
	u.Path = path.Join(c.Basepath, "login")
	v := url.Values{}
	v.Set("token", tokenStr)
	u.RawQuery = v.Encode()

	return u
}

func loginHandler(w http.ResponseWriter, r *http.Request, c *Config) (int, error) {
	if r.Method == "POST" {
		r.ParseForm()
		handle := r.PostForm.Get("handle")
		if len(handle) == 0 {
			loc := path.Join(c.Basepath, "login")
			http.Redirect(w, r, loc, http.StatusSeeOther)
			return http.StatusSeeOther, nil
		}
		switch c.authorizer.IsAuthorized(handle) {
		case true:
			token, err := c.AccessToken(handle)
			if err != nil {
				log.Print(err)
			}
			siteURL, err := url.Parse(c.SiteAddr)
			if err != nil {
				log.Fatal(err)
			}
			loginURL := c.LoginURL(*siteURL, token)
			if err := c.sender.Send(handle, loginURL.String()); err != nil {
				log.Print(err)
			}
		}
		w.Header().Add("Content-Type", "text/html; charset=utf-8")
		w.Write([]byte("A login link has been sent to user with handle " + handle + " if your handle is authorized"))
		return http.StatusOK, nil
	}
	if r.Method == "GET" {
		if tokenStr := r.URL.Query().Get("token"); len(tokenStr) > 0 {
			cookie := &http.Cookie{
				Name:  "jwt_token",
				Value: tokenStr,
				Path:  "/",
			}
			http.SetCookie(w, cookie)
			r.URL.Path = ""
			r.URL.RawQuery = ""
			http.Redirect(w, r, r.URL.String(), http.StatusSeeOther)
			return http.StatusSeeOther, nil
		}
		w.Header().Add("Content-Type", "text/html; charset=utf-8")
		w.Write([]byte("<form action=" + r.URL.Path + " method=POST><input type=text name=handle /><input type=submit></form>"))
		return http.StatusOK, nil
	}
	return http.StatusMethodNotAllowed, nil
}

func loginformHandler(w http.ResponseWriter, r *http.Request, c *Config) (int, error) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.Write([]byte(`

<form action="` + path.Join(c.Basepath, "/login") + `" method=POST>
<input type=hidden name=url value="` + r.URL.String() + `"/>
<input type=text name=handle />
<input type=submit>
</form>
`))
	return http.StatusOK, nil
}

func signoutHandler(w http.ResponseWriter, r *http.Request, c *Config) (int, error) {
	if cookie, err := r.Cookie("jwt_token"); err == nil {
		cookie.Expires = time.Now().AddDate(-1, 0, 0)
		cookie.MaxAge = -1
		cookie.Path = "/"
		http.SetCookie(w, cookie)
	}
	loc := path.Join(c.Basepath, "login")
	http.Redirect(w, r, loc, http.StatusSeeOther)
	return http.StatusSeeOther, nil
}

func publickeyHandler(w http.ResponseWriter, r *http.Request, c *Config) (int, error) {
	data, err := x509.MarshalPKIXPublicKey(c.key.PublicKey)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	block := &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: data,
	}
	if err := pem.Encode(w, block); err != nil {
		return http.StatusInternalServerError, err
	}
	w.Header().Set("Content-Type", "application/pkix-cert")
	return http.StatusOK, nil
}

func tokenHandler(w http.ResponseWriter, r *http.Request, c *Config) (int, error) {
	// Extract token from HTTP header, query parameter or cookie
	tokenStr, err := extractToken(r)
	if err != nil {
		return http.StatusUnauthorized, ErrInvalidToken
	}
	var claims *Claims
	if claims, err = validateToken(tokenStr, c.key.PublicKey); err != nil {
		return http.StatusUnauthorized, ErrInvalidToken
	}
	// Authorize handle claim
	if ok := c.authorizer.IsAuthorized(claims.Handle); !ok {
		return http.StatusUnauthorized, ErrInvalidToken
	}
	// Verify path claim
	var match bool
	for _, path := range claims.Resources {
		if httpserver.Path(r.URL.Path).Matches(path) {
			match = true
			continue
		}
	}
	if !match {
		return http.StatusUnauthorized, ErrInvalidToken
	}
	return http.StatusOK, nil
}

func (a *Auth) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	c := a.Config
	var pathMatch bool
	for _, path := range c.Resources {
		if httpserver.Path(r.URL.Path).Matches(path) {
			pathMatch = true
			continue
		}
	}
	if !pathMatch {
		return a.Next.ServeHTTP(w, r)
	}

	switch r.URL.Path {
	case path.Join(c.Basepath, "pub.cer"):
		return publickeyHandler(w, r, c)
	case path.Join(c.Basepath, "login"):
		return loginHandler(w, r, c)
	case path.Join(c.Basepath, "signout"):
		return signoutHandler(w, r, c)
	default:
		if code, err := tokenHandler(w, r, c); err != nil {
			w.WriteHeader(code)
			return loginformHandler(w, r, c)
		}
	}
	return a.Next.ServeHTTP(w, r)
}

// extractToken returns the JWT token embedded in the given request.
// JWT tokens can be embedded in the header prefixed with "Bearer ", with a
// "token" key query parameter or a cookie named "jwt_token".
func extractToken(r *http.Request) (string, error) {
	//from header
	if h := r.Header.Get("Authorization"); strings.HasPrefix(h, "Bearer ") {
		if len(h) > 7 {
			return h[7:], nil
		}
	}

	//from query parameter
	if token := r.URL.Query().Get("token"); len(token) > 0 {
		return token, nil
	}

	//from cookie
	if cookie, err := r.Cookie("jwt_token"); err == nil {
		return cookie.Value, nil
	}

	return "", fmt.Errorf("no token found")
}

func validateToken(token string, key rsa.PublicKey) (*Claims, error) {
	claims := &Claims{}

	// Verify token signature
	payload, err := verifyToken(token, key)
	if err != nil {
		return nil, err
	}
	// Unmarshal token claims
	if err := json.Unmarshal(payload, claims); err != nil {
		return nil, err
	}
	// Verify expire claim
	if time.Unix(claims.Expires, 0).Before(time.Now()) {
		return nil, errors.New("Token expired")
	}
	return claims, nil
}

func verifyToken(token string, key rsa.PublicKey) ([]byte, error) {
	var data []byte

	obj, err := jose.ParseSigned(token)
	if err != nil {
		return data, err
	}
	data, err = obj.Verify(&key)
	if err != nil {
		return data, err
	}
	return data, nil
}
<commit_msg>Fix wrong content-type for public key handler<commit_after>package multipass

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/json"
	"encoding/pem"
	"errors"
	"fmt"
	"log"
	"net/http"
	"net/url"
	"path"
	"strings"
	"time"

	"github.com/mholt/caddy/caddyhttp/httpserver"

	jose "gopkg.in/square/go-jose.v1"
)

var ErrInvalidToken error = errors.New("invalid token")

type Auth struct {
	*Config
	Next httpserver.Handler
}

type Rule struct {
	Basepath  string
	Expires   time.Duration
	Resources []string
	Handles   []string

	SMTPAddr, SMTPUser, SMTPPass string
	MailFrom, MailTmpl           string
}

type Config struct {
	Resources []string
	Basepath  string
	SiteAddr  string
	Expires   time.Duration

	sender     Sender
	authorizer Authorizer
	signer     jose.Signer
	key        *rsa.PrivateKey
}

func ConfigFromRule(r Rule) (*Config, error) {
	config, err := NewConfig()
	if err != nil {
		return nil, err
	}
	if len(r.Resources) > 0 {
		config.Resources = r.Resources
	}
	if len(r.Basepath) > 0 {
		config.Basepath = r.Basepath
	}
	if r.Expires > 0 {
		config.Expires = r.Expires
	}

	smtpAddr := "localhost:25"
	if len(r.SMTPAddr) > 0 {
		smtpAddr = r.SMTPAddr
	}
	mailTmpl := emailTemplate
	if len(r.MailTmpl) > 0 {
		mailTmpl = r.MailTmpl
	}
	config.sender = NewMailSender(smtpAddr, nil, r.MailFrom, mailTmpl)

	authorizer := &EmailAuthorizer{list: []string{}}
	for _, handle := range r.Handles {
		authorizer.Add(handle)
	}
	config.authorizer = authorizer

	return config, nil
}

func NewConfig() (*Config, error) {
	pk, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		return nil, err
	}
	signer, err := jose.NewSigner(jose.PS512, pk)
	if err != nil {
		return nil, err
	}
	return &Config{
		Resources: []string{"/"},
		Basepath:  "/",
		Expires:   time.Hour * 24,
		key:       pk,
		signer:    signer,
	}, nil
}

// Claims are part of the JSON web token
type Claims struct {
	Handle    string   `json:"handle"`
	Resources []string `json:"resources"`
	Expires   int64    `json:"exp"`
}

func (c *Config) AccessToken(handle string) (tokenStr string, err error) {
	exp := time.Now().Add(c.Expires)
	claims := &Claims{
		Handle:    handle,
		Resources: c.Resources,
		Expires:   exp.Unix(),
	}
	payload, err := json.Marshal(claims)
	if err != nil {
		return "", err
	}
	jws, err := c.signer.Sign(payload)
	if err != nil {
		return "", err
	}

	return jws.CompactSerialize()
}

func (c *Config) LoginURL(u url.URL, tokenStr string) url.URL {
	u.Path = path.Join(c.Basepath, "login")
	v := url.Values{}
	v.Set("token", tokenStr)
	u.RawQuery = v.Encode()

	return u
}

func loginHandler(w http.ResponseWriter, r *http.Request, c *Config) (int, error) {
	if r.Method == "POST" {
		r.ParseForm()
		handle := r.PostForm.Get("handle")
		if len(handle) == 0 {
			loc := path.Join(c.Basepath, "login")
			http.Redirect(w, r, loc, http.StatusSeeOther)
			return http.StatusSeeOther, nil
		}
		switch c.authorizer.IsAuthorized(handle) {
		case true:
			token, err := c.AccessToken(handle)
			if err != nil {
				log.Print(err)
			}
			siteURL, err := url.Parse(c.SiteAddr)
			if err != nil {
				log.Fatal(err)
			}
			loginURL := c.LoginURL(*siteURL, token)
			if err := c.sender.Send(handle, loginURL.String()); err != nil {
				log.Print(err)
			}
		}
		w.Header().Add("Content-Type", "text/html; charset=utf-8")
		w.Write([]byte("A login link has been sent to user with handle " + handle + " if your handle is authorized"))
		return http.StatusOK, nil
	}
	if r.Method == "GET" {
		if tokenStr := r.URL.Query().Get("token"); len(tokenStr) > 0 {
			cookie := &http.Cookie{
				Name:  "jwt_token",
				Value: tokenStr,
				Path:  "/",
			}
			http.SetCookie(w, cookie)
			r.URL.Path = ""
			r.URL.RawQuery = ""
			http.Redirect(w, r, r.URL.String(), http.StatusSeeOther)
			return http.StatusSeeOther, nil
		}
		w.Header().Add("Content-Type", "text/html; charset=utf-8")
		w.Write([]byte("<form action=" + r.URL.Path + " method=POST><input type=text name=handle /><input type=submit></form>"))
		return http.StatusOK, nil
	}
	return http.StatusMethodNotAllowed, nil
}

func loginformHandler(w http.ResponseWriter, r *http.Request, c *Config) (int, error) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.Write([]byte(`

<form action="` + path.Join(c.Basepath, "/login") + `" method=POST>
<input type=hidden name=url value="` + r.URL.String() + `"/>
<input type=text name=handle />
<input type=submit>
</form>
`))
	return http.StatusOK, nil
}

func signoutHandler(w http.ResponseWriter, r *http.Request, c *Config) (int, error) {
	if cookie, err := r.Cookie("jwt_token"); err == nil {
		cookie.Expires = time.Now().AddDate(-1, 0, 0)
		cookie.MaxAge = -1
		cookie.Path = "/"
		http.SetCookie(w, cookie)
	}
	loc := path.Join(c.Basepath, "login")
	http.Redirect(w, r, loc, http.StatusSeeOther)
	return http.StatusSeeOther, nil
}

func publickeyHandler(w http.ResponseWriter, r *http.Request, c *Config) (int, error) {
	data, err := x509.MarshalPKIXPublicKey(&c.key.PublicKey)
	if err != nil {
		return http.StatusInternalServerError, err
	}
	block := &pem.Block{
		Type:  "PUBLIC KEY",
		Bytes: data,
	}
	w.Header().Set("Content-Type", "application/pkix-cert")
	if err := pem.Encode(w, block); err != nil {
		return http.StatusInternalServerError, err
	}
	return http.StatusOK, nil
}

func tokenHandler(w http.ResponseWriter, r *http.Request, c *Config) (int, error) {
	// Extract token from HTTP header, query parameter or cookie
	tokenStr, err := extractToken(r)
	if err != nil {
		return http.StatusUnauthorized, ErrInvalidToken
	}
	var claims *Claims
	if claims, err = validateToken(tokenStr, c.key.PublicKey); err != nil {
		return http.StatusUnauthorized, ErrInvalidToken
	}
	// Authorize handle claim
	if ok := c.authorizer.IsAuthorized(claims.Handle); !ok {
		return http.StatusUnauthorized, ErrInvalidToken
	}
	// Verify path claim
	var match bool
	for _, path := range claims.Resources {
		if httpserver.Path(r.URL.Path).Matches(path) {
			match = true
			continue
		}
	}
	if !match {
		return http.StatusUnauthorized, ErrInvalidToken
	}
	return http.StatusOK, nil
}

func (a *Auth) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	c := a.Config
	var pathMatch bool
	for _, path := range c.Resources {
		if httpserver.Path(r.URL.Path).Matches(path) {
			pathMatch = true
			continue
		}
	}
	if !pathMatch {
		return a.Next.ServeHTTP(w, r)
	}

	switch r.URL.Path {
	case path.Join(c.Basepath, "pub.cer"):
		return publickeyHandler(w, r, c)
	case path.Join(c.Basepath, "login"):
		return loginHandler(w, r, c)
	case path.Join(c.Basepath, "signout"):
		return signoutHandler(w, r, c)
	default:
		if code, err := tokenHandler(w, r, c); err != nil {
			w.WriteHeader(code)
			return loginformHandler(w, r, c)
		}
	}
	return a.Next.ServeHTTP(w, r)
}

// extractToken returns the JWT token embedded in the given request.
// JWT tokens can be embedded in the header prefixed with "Bearer ", with a
// "token" key query parameter or a cookie named "jwt_token".
func extractToken(r *http.Request) (string, error) {
	//from header
	if h := r.Header.Get("Authorization"); strings.HasPrefix(h, "Bearer ") {
		if len(h) > 7 {
			return h[7:], nil
		}
	}

	//from query parameter
	if token := r.URL.Query().Get("token"); len(token) > 0 {
		return token, nil
	}

	//from cookie
	if cookie, err := r.Cookie("jwt_token"); err == nil {
		return cookie.Value, nil
	}

	return "", fmt.Errorf("no token found")
}

func validateToken(token string, key rsa.PublicKey) (*Claims, error) {
	claims := &Claims{}

	// Verify token signature
	payload, err := verifyToken(token, key)
	if err != nil {
		return nil, err
	}
	// Unmarshal token claims
	if err := json.Unmarshal(payload, claims); err != nil {
		return nil, err
	}
	// Verify expire claim
	if time.Unix(claims.Expires, 0).Before(time.Now()) {
		return nil, errors.New("Token expired")
	}
	return claims, nil
}

func verifyToken(token string, key rsa.PublicKey) ([]byte, error) {
	var data []byte

	obj, err := jose.ParseSigned(token)
	if err != nil {
		return data, err
	}
	data, err = obj.Verify(&key)
	if err != nil {
		return data, err
	}
	return data, nil
}
<|endoftext|>


<commit_before>package main

import (
    "bytes"
    "flag"
    "fmt"
    "io"
    "log"
    "net/http"
    "strings"
    //"runtime"
)

var downstreams []string

func forward_request(downstream string, in_req http.Request, body io.Reader) (resp *http.Response, err error) {
    client := &http.Client{}

    // Clone incoming request
    out_url := "http://" + downstream + in_req.URL.Path
    if in_req.URL.RawQuery != "" {
        out_url += "?" + in_req.URL.RawQuery;
    }
    req, _ := http.NewRequest(in_req.Method, out_url, body)
    for h, vv := range in_req.Header {
        for _, v := range vv {
            req.Header.Add(h, v)
        }
    }
    req.ContentLength = in_req.ContentLength

    resp, err = client.Do(req) // TODO need to close r.Body, see http://golang.org/pkg/net/http/#Client.Do
    if err != nil {
        log.Fatal("Request ", req.URL.Path, " to downstream ", downstream, " failed ", err)
        return
    }
    return
}

func handler(w http.ResponseWriter, r *http.Request) {
    log.Println("Received request", r.URL.Path, r.URL.RawQuery)

    // Read the body, make it available for all the downstreams
    clength := r.ContentLength
    var raw_body []byte

    if clength != 0 {
        body_part := make([]byte, clength)
        n, err := r.Body.Read(body_part)
        if err == nil {
            raw_body = body_part[:n]
        }
        r.Body.Close()
    }

    for _, downstream := range downstreams[1:] {
        go forward_request(downstream, *r, bytes.NewReader(raw_body))
    }

    resp, err := forward_request(downstreams[0], *r, bytes.NewReader(raw_body))
    if err == nil {
        io.Copy(w, resp.Body)
        resp.Body.Close()
    } else {
        w.WriteHeader(503)
    }
}

func main() {
    var port = flag.Int("port", 8080, "port to listen on")
    var downstreams_raw = flag.String("downstreams", "localhost:8090,localhost:8091", "list of downstreams in 'host:port' format, separated by comma")
    flag.Parse()

    downstreams = strings.Split(*downstreams_raw, ",")

    http.HandleFunc("/", handler)
    port_string := fmt.Sprintf(":%d", *port)
    log.Println("Listening on port", port_string)
    http.ListenAndServe(port_string, nil)
}

<commit_msg>Fix Body leaks once and for all.<commit_after>package main

import (
    "bytes"
    "flag"
    "fmt"
    "io"
    "log"
    "net/http"
    "strings"
    //"runtime"
)

var downstreams []string

// Forward *in_req* to specified *downstream*, with *body* (when POST is handled)
// if *close_body* is true - close the body before returning
func forward_request(downstream string, in_req http.Request, body io.Reader, close_body bool) (resp *http.Response, err error) {
    client := &http.Client{}

    // Clone incoming request
    out_url := "http://" + downstream + in_req.URL.Path
    if in_req.URL.RawQuery != "" {
        out_url += "?" + in_req.URL.RawQuery;
    }
    req, _ := http.NewRequest(in_req.Method, out_url, body)
    for h, vv := range in_req.Header {
        for _, v := range vv {
            req.Header.Add(h, v)
        }
    }
    req.ContentLength = in_req.ContentLength

    resp, err = client.Do(req) // TODO need to close r.Body, see http://golang.org/pkg/net/http/#Client.Do
    if err != nil {
        log.Fatal("Request ", req.URL.Path, " to downstream ", downstream, " failed ", err)
        return
    }
    if close_body {
        resp.Body.Close()
    }
    return
}

func handler(w http.ResponseWriter, r *http.Request) {
    log.Println("Received request", r.URL.Path, r.URL.RawQuery)

    // Read the body, make it available for all the downstreams
    clength := r.ContentLength
    var raw_body []byte

    if clength != 0 {
        body_part := make([]byte, clength)
        n, err := r.Body.Read(body_part)
        if err == nil {
            raw_body = body_part[:n]
        }
        r.Body.Close()
    }

    for _, downstream := range downstreams[1:] {
        go forward_request(downstream, *r, bytes.NewReader(raw_body), true)
    }

    resp, err := forward_request(downstreams[0], *r, bytes.NewReader(raw_body), false)
    if err == nil {
        io.Copy(w, resp.Body)
        resp.Body.Close()
    } else {
        w.WriteHeader(503)
    }
}

func main() {
    var port = flag.Int("port", 8080, "port to listen on")
    var downstreams_raw = flag.String("downstreams", "localhost:8090,localhost:8091", "list of downstreams in 'host:port' format, separated by comma")
    flag.Parse()

    downstreams = strings.Split(*downstreams_raw, ",")

    http.HandleFunc("/", handler)
    port_string := fmt.Sprintf(":%d", *port)
    log.Println("Listening on port", port_string)
    http.ListenAndServe(port_string, nil)
}

<|endoftext|>


<commit_before>package quasar

import (
	"testing"
	"time"
)

func sendLogEntries(l *logger, allSent chan bool) {
	time.Sleep(time.Millisecond * time.Duration(100))
	l.updateSent(nil, 0, nil, nil)
	l.updateReceived(nil, nil)
	l.updateSuccess(nil, nil)
	l.updateFail(nil, nil)
	l.eventPublished(nil, nil)
	l.eventReceived(nil, nil)
	l.eventDeliver(nil, nil)
	l.eventDropDuplicate(nil, nil)
	l.eventDropTTL(nil, nil)
	l.eventRouteDirect(nil, nil, nil)
	l.eventRouteWell(nil, nil, nil)
	l.eventRouteRandom(nil, nil, nil)
	time.Sleep(time.Millisecond * time.Duration(100))
	allSent <- true
}

func setReceived(b *bool, t *testing.T) {
	if *b == true {
		t.Errorf("Unexpected extra log!")
	}
	*b = true
}

func TestLogging(t *testing.T) {

	l := newLogger()
	allSent := make(chan bool)
	go sendLogEntries(l, allSent)

	rUpdatesSent := false
	rUpdatesReceived := false
	rUpdatesSuccess := false
	rUpdatesFail := false
	rEventsPublished := false
	rEventsReceived := false
	rEventsDeliver := false
	rEventsDropDuplicate := false
	rEventsDropTTL := false
	rEventsRouteDirect := false
	rEventsRouteWell := false
	rEventsRouteRandom := false

	exitLoop := false
	for !exitLoop {
		select {
		case <-l.updatesSent:
			setReceived(&rUpdatesSent, t)
		case <-l.updatesReceived:
			setReceived(&rUpdatesReceived, t)
		case <-l.updatesSuccess:
			setReceived(&rUpdatesSuccess, t)
		case <-l.updatesFail:
			setReceived(&rUpdatesFail, t)
		case <-l.eventsPublished:
			setReceived(&rEventsPublished, t)
		case <-l.eventsReceived:
			setReceived(&rEventsReceived, t)
		case <-l.eventsDeliver:
			setReceived(&rEventsDeliver, t)
		case <-l.eventsDropDuplicate:
			setReceived(&rEventsDropDuplicate, t)
		case <-l.eventsDropTTL:
			setReceived(&rEventsDropTTL, t)
		case <-l.eventsRouteDirect:
			setReceived(&rEventsRouteDirect, t)
		case <-l.eventsRouteWell:
			setReceived(&rEventsRouteWell, t)
		case <-l.eventsRouteRandom:
			setReceived(&rEventsRouteRandom, t)
		case <-allSent:
			exitLoop = true
		}
	}

	if !(rUpdatesSent && rUpdatesReceived &&
		rUpdatesSuccess && rUpdatesFail &&
		rEventsPublished && rEventsReceived &&
		rEventsDeliver && rEventsDropDuplicate &&
		rEventsDropTTL && rEventsRouteDirect &&
		rEventsRouteWell && rEventsRouteRandom) {
		t.Errorf("Missing log event!")
	}
}
<commit_msg>simplified logging tests even more<commit_after>package quasar

import (
	"testing"
	"time"
)

func sendUpdateLogEntries(l *logger, allSent chan bool) {
	time.Sleep(time.Millisecond * time.Duration(100))
	l.updateSent(nil, 0, nil, nil)
	l.updateReceived(nil, nil)
	l.updateSuccess(nil, nil)
	l.updateFail(nil, nil)
	time.Sleep(time.Millisecond * time.Duration(100))
	allSent <- true
}

func sendEventLogEntries(l *logger, allSent chan bool) {
	time.Sleep(time.Millisecond * time.Duration(100))
	l.eventPublished(nil, nil)
	l.eventReceived(nil, nil)
	l.eventDeliver(nil, nil)
	l.eventDropDuplicate(nil, nil)
	l.eventDropTTL(nil, nil)
	l.eventRouteDirect(nil, nil, nil)
	l.eventRouteWell(nil, nil, nil)
	l.eventRouteRandom(nil, nil, nil)
	time.Sleep(time.Millisecond * time.Duration(100))
	allSent <- true
}

func setReceived(b *bool, t *testing.T) {
	if *b == true {
		t.Errorf("Unexpected extra log!")
	}
	*b = true
}

func TestUpdateLogging(t *testing.T) {

	l := newLogger()
	allSent := make(chan bool)
	go sendUpdateLogEntries(l, allSent)

	sent := false
	received := false
	success := false
	fail := false

	exitLoop := false
	for !exitLoop {
		select {
		case <-l.updatesSent:
			setReceived(&sent, t)
		case <-l.updatesReceived:
			setReceived(&received, t)
		case <-l.updatesSuccess:
			setReceived(&success, t)
		case <-l.updatesFail:
			setReceived(&fail, t)
		case <-allSent:
			exitLoop = true
		}
	}

	if !(sent && received && success && fail) {
		t.Errorf("Missing log event!")
	}
}

func collectEventLogs(published *bool, received *bool, deliver *bool,
	dropDuplicate *bool, dropTTL *bool, routeDirect *bool,
	routeWell *bool, routeRandom *bool, allSent chan bool,
	l *logger, t *testing.T) {
	exitLoop := false
	for !exitLoop {
		select {
		case <-l.eventsPublished:
			setReceived(published, t)
		case <-l.eventsReceived:
			setReceived(received, t)
		case <-l.eventsDeliver:
			setReceived(deliver, t)
		case <-l.eventsDropDuplicate:
			setReceived(dropDuplicate, t)
		case <-l.eventsDropTTL:
			setReceived(dropTTL, t)
		case <-l.eventsRouteDirect:
			setReceived(routeDirect, t)
		case <-l.eventsRouteWell:
			setReceived(routeWell, t)
		case <-l.eventsRouteRandom:
			setReceived(routeRandom, t)
		case <-allSent:
			exitLoop = true
		}
	}
}

func TestEventLogging(t *testing.T) {

	l := newLogger()
	allSent := make(chan bool)
	go sendEventLogEntries(l, allSent)

	published := false
	received := false
	deliver := false
	dropDuplicate := false
	dropTTL := false
	routeDirect := false
	routeWell := false
	routeRandom := false
	collectEventLogs(&published, &received, &deliver, &dropDuplicate,
		&dropTTL, &routeDirect, &routeWell, &routeRandom, allSent, l, t)
	if !(published && received &&
		deliver && dropDuplicate &&
		dropTTL && routeDirect &&
		routeWell && routeRandom) {
		t.Errorf("Missing log event!")
	}
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"flag"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"strings"
)

type handler struct {
	dest url.URL
}

var rewriter *strings.Replacer

func (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	du := h.dest
	du.Path = req.URL.Path
	du.RawQuery = req.URL.RawQuery
	req.URL = &du
	req.RequestURI = ""

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	defer res.Body.Close()

	for k, v := range res.Header {
		res.Header[k] = v
	}
	w.WriteHeader(res.StatusCode)

	io.Copy(w, rewriteJson(res.Body, rewriter.Replace))
}

func initRewrite(conf string) {
	f, err := os.Open(conf)
	if err != nil {
		log.Fatalf("Error opening %v: %v", conf, err)
	}
	defer f.Close()
	d := json.NewDecoder(f)
	m := map[string]string{}
	err = d.Decode(&m)
	if err != nil {
		log.Fatalf("Error parsing %v: %v", conf, err)
	}

	params := []string{}
	for k, v := range m {
		params = append(params, k, v)
	}

	rewriter = strings.NewReplacer(params...)
}

func main() {
	bindAddr := flag.String("bind", ":7081", "Address to listen")
	rewriteConf := flag.String("rewriteconf", "/dev/null",
		"Path to json rewrite rules")

	flag.Parse()

	if flag.NArg() != 1 {
		log.Fatalf("Where to, sir?")
	}

	initRewrite(*rewriteConf)

	u, err := url.Parse(flag.Arg(0))
	if err != nil {
		log.Fatalf("Error parsing url: %v", err)
	}

	log.Fatal(http.ListenAndServe(*bindAddr, &handler{*u}))
}
<commit_msg>Special case "" instead of working with /dev/null<commit_after>package main

import (
	"encoding/json"
	"flag"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"strings"
)

type handler struct {
	dest url.URL
}

var rewriter *strings.Replacer

func (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	du := h.dest
	du.Path = req.URL.Path
	du.RawQuery = req.URL.RawQuery
	req.URL = &du
	req.RequestURI = ""

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	defer res.Body.Close()

	for k, v := range res.Header {
		res.Header[k] = v
	}
	w.WriteHeader(res.StatusCode)

	io.Copy(w, rewriteJson(res.Body, rewriter.Replace))
}

func initRewrite(conf string) {
	if conf == "" {
		rewriter = strings.NewReplacer()
		return
	}

	f, err := os.Open(conf)
	if err != nil {
		log.Fatalf("Error opening %v: %v", conf, err)
	}
	defer f.Close()
	d := json.NewDecoder(f)
	m := map[string]string{}
	err = d.Decode(&m)
	if err != nil {
		log.Fatalf("Error parsing %v: %v", conf, err)
	}

	params := []string{}
	for k, v := range m {
		params = append(params, k, v)
	}

	rewriter = strings.NewReplacer(params...)
}

func main() {
	bindAddr := flag.String("bind", ":7081", "Address to listen")
	rewriteConf := flag.String("rewriteconf", "",
		"Path to json rewrite rules")

	flag.Parse()

	if flag.NArg() != 1 {
		log.Fatalf("Where to, sir?")
	}

	initRewrite(*rewriteConf)

	u, err := url.Parse(flag.Arg(0))
	if err != nil {
		log.Fatalf("Error parsing url: %v", err)
	}

	log.Fatal(http.ListenAndServe(*bindAddr, &handler{*u}))
}
<|endoftext|>


<commit_before>package logging_test

import (
	"../logging"
	"testing"
)

func Example() {
	logging.L.SetLogFile("")
	logging.L.Info(map[string]string{"key 1": "value 1", "key2": "value2"}, "Hello World %s\t{%d}", "An\targument", 1234)
	// output (wrapped for display):
	// 2014-03-04T21:48:45.925788398Z  INFO    Hello World An argument [1234]  {"app":"logging.test","file":"logging_test.go",
	// "function":"logging_test.TestOutput","host":"kenf-linux","key 1":"value 1","key2":"value2","line":"10",
	// "message":"Hello World An argument [1234]","pid":"5992","severity":"INFO","timestamp":"2014-03-04T21:48:45.925788398Z"}
}

// test basic logging functionality
func TestLogger(t *testing.T) {
	err := logging.L.SetLogFile("/dev/null")
	if err != nil {
		t.Errorf("Could not set log file: %s", err)
	}
	// turn off Fatal logging so that we don't crash the process
	logging.L.SetOutput(true, true, true, true, true, false)
	err = logging.L.Debug(nil, "Hello %s", "World", "Extra")
	if err != nil {
		t.Errorf("Log write error: %s", err)
	}
	err = logging.L.Info(nil, "Hello %s", "World")
	if err != nil {
		t.Errorf("Log write error: %s", err)
	}
	err = logging.L.Error(nil, "Hello")
	if err != nil {
		t.Errorf("Log write error: %s", err)
	}
	err = logging.L.Warning(nil, "{Hello %s\t%d}", "World", 1234)
	if err != nil {
		t.Errorf("Log write error: %s", err)
	}
	err = logging.L.Critical(nil, "Hello %s\t%d", "World", 1234)
	if err != nil {
		t.Errorf("Log write error: %s", err)
	}
	err = logging.L.Fatal(map[string]string{"key 1": "value 1", "key2": "value2"}, "")
	if err != nil {
		t.Errorf("Log write error: %s", err)
	}
}

// benchmark logging calls that write to /dev/null
func BenchmarkNullLogger(b *testing.B) {
	logging.L.SetLogFile("/dev/null")
	for i := 0; i < b.N; i++ {
		logging.L.Info(map[string]string{"key 1": "value 1", "key2": "value2"}, "Hello World %s\t{%d}", "An\targument", 1234)
	}
}

// benchmark logging calls that write to a file
func BenchmarkFileLogger(b *testing.B) {
	logging.L.SetLogFile("./benchmark.log")
	for i := 0; i < b.N; i++ {
		logging.L.Info(map[string]string{"key 1": "value 1", "key2": "value2"}, "Hello World %s\t{%d}", "An\targument", 1234)
	}
}

// benchmark logging calls that don't actually do anything; tests map setup
func BenchmarkStubbedLogger(b *testing.B) {
	logging.L.SetOutput(false, false, false, false, false, false)
	for i := 0; i < b.N; i++ {
		logging.L.Info(map[string]string{"key 1": "value 1", "key2": "value2"}, "Hello World %s\t{%d}", "An\targument", 1234)
	}
}
<commit_msg>Fix import path for logging_test<commit_after>package logging_test

import (
	"github.com/Syncbak-Git/logging"
	"testing"
)

func Example() {
	logging.L.SetLogFile("")
	logging.L.Info(map[string]string{"key 1": "value 1", "key2": "value2"}, "Hello World %s\t{%d}", "An\targument", 1234)
	// output (wrapped for display):
	// 2014-03-04T21:48:45.925788398Z  INFO    Hello World An argument [1234]  {"app":"logging.test","file":"logging_test.go",
	// "function":"logging_test.TestOutput","host":"kenf-linux","key 1":"value 1","key2":"value2","line":"10",
	// "message":"Hello World An argument [1234]","pid":"5992","severity":"INFO","timestamp":"2014-03-04T21:48:45.925788398Z"}
}

// test basic logging functionality
func TestLogger(t *testing.T) {
	err := logging.L.SetLogFile("/dev/null")
	if err != nil {
		t.Errorf("Could not set log file: %s", err)
	}
	// turn off Fatal logging so that we don't crash the process
	logging.L.SetOutput(true, true, true, true, true, false)
	err = logging.L.Debug(nil, "Hello %s", "World", "Extra")
	if err != nil {
		t.Errorf("Log write error: %s", err)
	}
	err = logging.L.Info(nil, "Hello %s", "World")
	if err != nil {
		t.Errorf("Log write error: %s", err)
	}
	err = logging.L.Error(nil, "Hello")
	if err != nil {
		t.Errorf("Log write error: %s", err)
	}
	err = logging.L.Warning(nil, "{Hello %s\t%d}", "World", 1234)
	if err != nil {
		t.Errorf("Log write error: %s", err)
	}
	err = logging.L.Critical(nil, "Hello %s\t%d", "World", 1234)
	if err != nil {
		t.Errorf("Log write error: %s", err)
	}
	err = logging.L.Fatal(map[string]string{"key 1": "value 1", "key2": "value2"}, "")
	if err != nil {
		t.Errorf("Log write error: %s", err)
	}
}

// benchmark logging calls that write to /dev/null
func BenchmarkNullLogger(b *testing.B) {
	logging.L.SetLogFile("/dev/null")
	for i := 0; i < b.N; i++ {
		logging.L.Info(map[string]string{"key 1": "value 1", "key2": "value2"}, "Hello World %s\t{%d}", "An\targument", 1234)
	}
}

// benchmark logging calls that write to a file
func BenchmarkFileLogger(b *testing.B) {
	logging.L.SetLogFile("./benchmark.log")
	for i := 0; i < b.N; i++ {
		logging.L.Info(map[string]string{"key 1": "value 1", "key2": "value2"}, "Hello World %s\t{%d}", "An\targument", 1234)
	}
}

// benchmark logging calls that don't actually do anything; tests map setup
func BenchmarkStubbedLogger(b *testing.B) {
	logging.L.SetOutput(false, false, false, false, false, false)
	for i := 0; i < b.N; i++ {
		logging.L.Info(map[string]string{"key 1": "value 1", "key2": "value2"}, "Hello World %s\t{%d}", "An\targument", 1234)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"io"
	"net/http"
)

// Type covering `bool` to add more explanatory power than using bools
// directly to report whether a request was satisfied or not.
type RequestStatus bool

const Success RequestStatus = true
const Failure RequestStatus = false

// HTTP Status response OK
const STATUS_OK int = 200

/**
 * Send a POST request to the Bundle Inserter on the /insert route
 * to request that data for a url be inserted into Freenet.
 * @param bundleData - The content produced by the bundler server to insert into Freenet
 * @return Success if the request was sent successfully, otherwise Failure
 */
func InsertFreenet(bundleData []byte) RequestStatus {
	reader := bytes.NewReader(bundleData)
	insertUrl := Configuration.BundleInserter + "/insert"
	request, err1 := http.NewRequest("POST", insertUrl, reader)
	if err1 != nil {
		fmt.Println("Insert error")
		fmt.Println(err1)
		return Failure
	}
	request.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	response, err2 := client.Do(request)
	if err2 != nil {
		fmt.Println("Insert error")
		fmt.Println(err2)
		return Failure
	}
	defer response.Body.Close()
	if response.StatusCode != STATUS_OK {
		fmt.Println("Insert error")
		fmt.Printf("Status code %d\n", response.StatusCode)
		return Failure
	}
	return Success
}

/**
 * Retrieve a bundle for a site from the Bundle Server by sending a GET
 * request to /?url=<base64(url)>
 * @param url - The URL of the page to have bundled.
 */
func GetBundle(url string) ([]byte, RequestStatus) {
	b64Url := base64.StdEncoding.EncodeToString([]byte(url))
	bundleUrl := Configuration.BundleServer + "/?url=" + b64Url
	response, err := http.Get(bundleUrl)
	if err != nil || response == nil || response.StatusCode != STATUS_OK {
		fmt.Printf("In GetBundle err = %s, status = %d\n", err.Error(), response.StatusCode)
		return nil, Failure
	}
	output := make([]byte, MAX_BUNDLE_SIZE)
	bytesRead, readErr := response.Body.Read(output)
	// We will frequently get an EOF error reading to the end of the body,
	// however the content of the body will be read into `output`.
	if readErr != nil && readErr != io.EOF {
		return nil, Failure
	}
	defer response.Body.Close()
	if bytesRead == 0 {
		return nil, Failure
	}
	return output[:bytesRead], Success
}
<commit_msg>Do not print the bundle but do print actually descriptive info<commit_after>package main

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
)

// Type covering `bool` to add more explanatory power than using bools
// directly to report whether a request was satisfied or not.
type RequestStatus bool

const Success RequestStatus = true
const Failure RequestStatus = false

// HTTP Status response OK
const STATUS_OK int = 200

/**
 * Send a POST request to the Bundle Inserter on the /insert route
 * to request that data for a url be inserted into Freenet.
 * @param bundleData - The content produced by the bundler server to insert into Freenet
 * @return Success if the request was sent successfully, otherwise Failure
 */
func InsertFreenet(bundleData []byte) RequestStatus {
	fmt.Println("Going to POST to " + Configuration.BundleInserter + "/insert")
	reader := bytes.NewReader(bundleData)
	insertUrl := Configuration.BundleInserter + "/insert"
	request, err1 := http.NewRequest("POST", insertUrl, reader)
	if err1 != nil {
		fmt.Println("Insert error")
		fmt.Println(err1)
		return Failure
	}
	request.Header.Set("Content-Type", "application/json")
	client := &http.Client{}
	response, err2 := client.Do(request)
	if err2 != nil {
		fmt.Println("Insert error")
		fmt.Println(err2)
		return Failure
	}
	defer response.Body.Close()
	if response.StatusCode != STATUS_OK {
		fmt.Println("Insert error")
		fmt.Printf("Status code %d\n", response.StatusCode)
		return Failure
	}
	readBytes, _ := ioutil.ReadAll(response.Body)
	fmt.Println("Response from bundle inserter")
	fmt.Println(string(readBytes))
	return Success
}

/**
 * Retrieve a bundle for a site from the Bundle Server by sending a GET
 * request to /?url=<base64(url)>
 * @param url - The URL of the page to have bundled.
 */
func GetBundle(url string) ([]byte, RequestStatus) {
	b64Url := base64.StdEncoding.EncodeToString([]byte(url))
	bundleUrl := Configuration.BundleServer + "/?url=" + b64Url
	response, err := http.Get(bundleUrl)
	if err != nil || response == nil || response.StatusCode != STATUS_OK {
		fmt.Printf("In GetBundle err = %s, status = %d\n", err.Error(), response.StatusCode)
		return nil, Failure
	}
	output := make([]byte, MAX_BUNDLE_SIZE)
	bytesRead, readErr := response.Body.Read(output)
	// We will frequently get an EOF error reading to the end of the body,
	// however the content of the body will be read into `output`.
	if readErr != nil && readErr != io.EOF {
		return nil, Failure
	}
	defer response.Body.Close()
	if bytesRead == 0 {
		return nil, Failure
	}
	return output[:bytesRead], Success
}
<|endoftext|>


<commit_before>package main

import (
	"runtime"
	"testing"

	"github.com/hashicorp/go-syslog"
	"github.com/hashicorp/logutils"
)

func TestSyslogFilter(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.SkipNow()
	}
	l, err := gsyslog.NewLogger(gsyslog.LOG_NOTICE, "LOCAL0", "consul-template")
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	filt := NewLogFilter()
	filt.MinLevel = logutils.LogLevel("INFO")

	s := &SyslogWrapper{l, filt}
	n, err := s.Write([]byte("[INFO] test"))
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if n == 0 {
		t.Fatalf("should have logged")
	}

	n, err = s.Write([]byte("[DEBUG] test"))
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if n != 0 {
		t.Fatalf("should not have logged")
	}
}
<commit_msg>Do not run syslog test on Travis<commit_after>package main

import (
	"os"
	"runtime"
	"testing"

	"github.com/hashicorp/go-syslog"
	"github.com/hashicorp/logutils"
)

func TestSyslogFilter(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.SkipNow()
	}

	// Travis does not support syslog for some reason
	if travis := os.Getenv("TRAVIS"); travis != "" {
		t.SkipNow()
	}

	l, err := gsyslog.NewLogger(gsyslog.LOG_NOTICE, "LOCAL0", "consul-template")
	if err != nil {
		t.Fatalf("err: %s", err)
	}

	filt := NewLogFilter()
	filt.MinLevel = logutils.LogLevel("INFO")

	s := &SyslogWrapper{l, filt}
	n, err := s.Write([]byte("[INFO] test"))
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if n == 0 {
		t.Fatalf("should have logged")
	}

	n, err = s.Write([]byte("[DEBUG] test"))
	if err != nil {
		t.Fatalf("err: %s", err)
	}
	if n != 0 {
		t.Fatalf("should not have logged")
	}
}
<|endoftext|>


<commit_before>package logical

import (
	"fmt"
)

// Auth is the resulting authentication information that is part of
// Response for credential backends.
type Auth struct {
	// ClientToken is the token that is generated for the authentication.
	// This will be filled in by Vault core when an auth structure is
	// returned. Setting this manually will have no effect.
	ClientToken string

	// Policies is the list of policies that the authenticated user
	// is associated with.
	Policies []string

	// Metadata is used to attach arbitrary string-type metadata to
	// an authenticated user. This metadata will be outputted into the
	// audit log.
	Metadata map[string]string
}

func (a *Auth) GoString() string {
	return fmt.Sprintf("*%#v", *a)
}
<commit_msg>logical: adding lease to auth<commit_after>package logical

import (
	"fmt"
	"time"
)

// Auth is the resulting authentication information that is part of
// Response for credential backends.
type Auth struct {
	// ClientToken is the token that is generated for the authentication.
	// This will be filled in by Vault core when an auth structure is
	// returned. Setting this manually will have no effect.
	ClientToken string

	// Policies is the list of policies that the authenticated user
	// is associated with.
	Policies []string

	// Metadata is used to attach arbitrary string-type metadata to
	// an authenticated user. This metadata will be outputted into the
	// audit log.
	Metadata map[string]string

	// Lease is the duration that this token is valid for. Vault
	// will automatically revoke it after the duration + grace period.
	Lease            time.Duration
	LeaseGracePeriod time.Duration
}

func (a *Auth) GoString() string {
	return fmt.Sprintf("*%#v", *a)
}
<|endoftext|>


<commit_before>package space

import (
	"fmt"
	"strings"

	. "github.com/cloudfoundry/cli/cf/i18n"
	"github.com/cloudfoundry/cli/cf/models"

	"github.com/cloudfoundry/cli/cf/api/space_quotas"
	"github.com/cloudfoundry/cli/cf/command_metadata"
	"github.com/cloudfoundry/cli/cf/configuration/core_config"
	"github.com/cloudfoundry/cli/cf/formatters"
	"github.com/cloudfoundry/cli/cf/requirements"
	"github.com/cloudfoundry/cli/cf/terminal"
	"github.com/codegangsta/cli"
)

type ShowSpace struct {
	ui        terminal.UI
	config    core_config.Reader
	spaceReq  requirements.SpaceRequirement
	quotaRepo space_quotas.SpaceQuotaRepository
}

func NewShowSpace(ui terminal.UI, config core_config.Reader, quotaRepo space_quotas.SpaceQuotaRepository) (cmd *ShowSpace) {
	cmd = new(ShowSpace)
	cmd.ui = ui
	cmd.config = config
	cmd.quotaRepo = quotaRepo
	return
}

func (cmd *ShowSpace) Metadata() command_metadata.CommandMetadata {
	return command_metadata.CommandMetadata{
		Name:        "space",
		Description: T("Show space info"),
		Usage:       T("CF_NAME space SPACE"),
	}
}

func (cmd *ShowSpace) GetRequirements(requirementsFactory requirements.Factory, c *cli.Context) (reqs []requirements.Requirement, err error) {
	if len(c.Args()) != 1 {
		cmd.ui.FailWithUsage(c)
	}

	cmd.spaceReq = requirementsFactory.NewSpaceRequirement(c.Args()[0])
	reqs = []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		requirementsFactory.NewTargetedOrgRequirement(),
		cmd.spaceReq,
	}
	return
}

func (cmd *ShowSpace) Run(c *cli.Context) {
	space := cmd.spaceReq.GetSpace()
	cmd.ui.Say(T("Getting info for space {{.TargetSpace}} in org {{.OrgName}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"TargetSpace": terminal.EntityNameColor(space.Name),
			"OrgName":     terminal.EntityNameColor(space.Organization.Name),
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))

	quotaString := cmd.quotaString(space)

	cmd.ui.Ok()
	cmd.ui.Say("")
	cmd.ui.Say(terminal.EntityNameColor(space.Name) + ":")

	table := terminal.NewTable(cmd.ui, []string{"", "", ""})
	table.Add("", T("Org:"), terminal.EntityNameColor(space.Organization.Name))

	apps := []string{}
	for _, app := range space.Applications {
		apps = append(apps, terminal.EntityNameColor(app.Name))
	}
	table.Add("", T("Apps:"), strings.Join(apps, ", "))

	domains := []string{}
	for _, domain := range space.Domains {
		domains = append(domains, terminal.EntityNameColor(domain.Name))
	}
	table.Add("", T("Domains:"), strings.Join(domains, ", "))

	services := []string{}
	for _, service := range space.ServiceInstances {
		services = append(services, terminal.EntityNameColor(service.Name))
	}
	table.Add("", T("Services:"), strings.Join(services, ", "))

	securityGroups := []string{}
	for _, group := range space.SecurityGroups {
		securityGroups = append(securityGroups, terminal.EntityNameColor(group.Name))
	}
	table.Add("", T("Security Groups:"), strings.Join(securityGroups, ", "))

	table.Add("", T("Space Quota:"), quotaString)

	table.Print()
}

func (cmd *ShowSpace) quotaString(space models.Space) string {
	var instance_memory string

	if space.SpaceQuotaGuid == "" {
		return ""
	}

	quota, err := cmd.quotaRepo.FindByGuid(space.SpaceQuotaGuid)
	if err != nil {
		cmd.ui.Failed(err.Error())
		return ""
	}

	if quota.InstanceMemoryLimit == -1 {
		instance_memory = "-1"
	} else {
		instance_memory = formatters.ByteSize(quota.InstanceMemoryLimit * formatters.MEGABYTE)
	}
	memory := formatters.ByteSize(quota.MemoryLimit * formatters.MEGABYTE)

	spaceQuota := fmt.Sprintf("%s (%s memory limit, %s instance memory limit, %d routes, %d services, paid services %s)", quota.Name, memory, instance_memory, quota.RoutesLimit, quota.ServicesLimit, formatters.Allowed(quota.NonBasicServicesAllowed))
	//	spaceQuota := fmt.Sprintf(T("{{.QuotaName}} ({{.MemoryLimit}} memory limit, {{.InstanceMemoryLimit}} instance memory limit, {{.RoutesLimit}} routes, {{.ServicesLimit}} services, paid services {{.NonBasicServicesAllowed}})",
	//		map[string]interface{}{
	//			"QuotaName":               quota.Name,
	//			"MemoryLimit":             memory,
	//			"InstanceMemoryLimit":     instance_memory,
	//			"RoutesLimit":             quota.RoutesLimit,
	//			"ServicesLimit":           quota.ServicesLimit,
	//			"NonBasicServicesAllowed": formatters.Allowed(quota.NonBasicServicesAllowed)}))

	return spaceQuota
}
<commit_msg>Remove space from command `cf space ...` between space and table.<commit_after>package space

import (
	"fmt"
	"strings"

	. "github.com/cloudfoundry/cli/cf/i18n"
	"github.com/cloudfoundry/cli/cf/models"

	"github.com/cloudfoundry/cli/cf/api/space_quotas"
	"github.com/cloudfoundry/cli/cf/command_metadata"
	"github.com/cloudfoundry/cli/cf/configuration/core_config"
	"github.com/cloudfoundry/cli/cf/formatters"
	"github.com/cloudfoundry/cli/cf/requirements"
	"github.com/cloudfoundry/cli/cf/terminal"
	"github.com/codegangsta/cli"
)

type ShowSpace struct {
	ui        terminal.UI
	config    core_config.Reader
	spaceReq  requirements.SpaceRequirement
	quotaRepo space_quotas.SpaceQuotaRepository
}

func NewShowSpace(ui terminal.UI, config core_config.Reader, quotaRepo space_quotas.SpaceQuotaRepository) (cmd *ShowSpace) {
	cmd = new(ShowSpace)
	cmd.ui = ui
	cmd.config = config
	cmd.quotaRepo = quotaRepo
	return
}

func (cmd *ShowSpace) Metadata() command_metadata.CommandMetadata {
	return command_metadata.CommandMetadata{
		Name:        "space",
		Description: T("Show space info"),
		Usage:       T("CF_NAME space SPACE"),
	}
}

func (cmd *ShowSpace) GetRequirements(requirementsFactory requirements.Factory, c *cli.Context) (reqs []requirements.Requirement, err error) {
	if len(c.Args()) != 1 {
		cmd.ui.FailWithUsage(c)
	}

	cmd.spaceReq = requirementsFactory.NewSpaceRequirement(c.Args()[0])
	reqs = []requirements.Requirement{
		requirementsFactory.NewLoginRequirement(),
		requirementsFactory.NewTargetedOrgRequirement(),
		cmd.spaceReq,
	}
	return
}

func (cmd *ShowSpace) Run(c *cli.Context) {
	space := cmd.spaceReq.GetSpace()
	cmd.ui.Say(T("Getting info for space {{.TargetSpace}} in org {{.OrgName}} as {{.CurrentUser}}...",
		map[string]interface{}{
			"TargetSpace": terminal.EntityNameColor(space.Name),
			"OrgName":     terminal.EntityNameColor(space.Organization.Name),
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))

	quotaString := cmd.quotaString(space)

	cmd.ui.Ok()
	cmd.ui.Say("")
	table := terminal.NewTable(cmd.ui, []string{terminal.EntityNameColor(space.Name), "", ""})
	table.Add("", T("Org:"), terminal.EntityNameColor(space.Organization.Name))

	apps := []string{}
	for _, app := range space.Applications {
		apps = append(apps, terminal.EntityNameColor(app.Name))
	}
	table.Add("", T("Apps:"), strings.Join(apps, ", "))

	domains := []string{}
	for _, domain := range space.Domains {
		domains = append(domains, terminal.EntityNameColor(domain.Name))
	}
	table.Add("", T("Domains:"), strings.Join(domains, ", "))

	services := []string{}
	for _, service := range space.ServiceInstances {
		services = append(services, terminal.EntityNameColor(service.Name))
	}
	table.Add("", T("Services:"), strings.Join(services, ", "))

	securityGroups := []string{}
	for _, group := range space.SecurityGroups {
		securityGroups = append(securityGroups, terminal.EntityNameColor(group.Name))
	}
	table.Add("", T("Security Groups:"), strings.Join(securityGroups, ", "))

	table.Add("", T("Space Quota:"), quotaString)

	table.Print()
}

func (cmd *ShowSpace) quotaString(space models.Space) string {
	var instance_memory string

	if space.SpaceQuotaGuid == "" {
		return ""
	}

	quota, err := cmd.quotaRepo.FindByGuid(space.SpaceQuotaGuid)
	if err != nil {
		cmd.ui.Failed(err.Error())
		return ""
	}

	if quota.InstanceMemoryLimit == -1 {
		instance_memory = "-1"
	} else {
		instance_memory = formatters.ByteSize(quota.InstanceMemoryLimit * formatters.MEGABYTE)
	}
	memory := formatters.ByteSize(quota.MemoryLimit * formatters.MEGABYTE)

	spaceQuota := fmt.Sprintf("%s (%s memory limit, %s instance memory limit, %d routes, %d services, paid services %s)", quota.Name, memory, instance_memory, quota.RoutesLimit, quota.ServicesLimit, formatters.Allowed(quota.NonBasicServicesAllowed))
	//	spaceQuota := fmt.Sprintf(T("{{.QuotaName}} ({{.MemoryLimit}} memory limit, {{.InstanceMemoryLimit}} instance memory limit, {{.RoutesLimit}} routes, {{.ServicesLimit}} services, paid services {{.NonBasicServicesAllowed}})",
	//		map[string]interface{}{
	//			"QuotaName":               quota.Name,
	//			"MemoryLimit":             memory,
	//			"InstanceMemoryLimit":     instance_memory,
	//			"RoutesLimit":             quota.RoutesLimit,
	//			"ServicesLimit":           quota.ServicesLimit,
	//			"NonBasicServicesAllowed": formatters.Allowed(quota.NonBasicServicesAllowed)}))

	return spaceQuota
}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"fmt"
	"strconv"

	"github.com/hyperledger/fabric/core/chaincode/shim"
)

// SimpleChaincode implementation
type SimpleChaincode struct {
}

func (t *SimpleChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
	var err error

	if len(args) == 0 {
		return nil, errors.New("Incorrect number of arguments. At least one Meter's name is required.")
	}

	for _,name := range args {
		if len(name) == 0{
			continue
		}
		err = stub.PutState(name, []byte(strconv.Itoa(0)));
		if err != nil {
			return nil, errors.New("Meter cannot be created")
		}
	}

	return nil, nil
}

// Deletes an entity from state
func (t *SimpleChaincode) settle(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
	//var err error
	var key string
	var val, total int

	//exchange_rate = 13;

	var keys []string
	var values []int
	total = 0;

	for i := 1; i < 2; i++ {
		key = strconv.Itoa(i)
		value, err := stub.GetState(key)
		if err != nil {
			continue
		}
		if value == nil {
			continue
		}
		val, _ = strconv.Atoi(string(value))
		total = total + 1;
		keys = append(keys, key)
		values = append(values, val)

	}
	for index,name := range keys {
		if(values[index] < 0){
			//amount = values[index]*-1*exchange_rate;
			stub.QueryChaincode("2780b7463c57f343a9e107854c4b53150018cdd8fd74ca970c028de6bfa707f6e9f6cf2b20f0af4fdd04d2167651eb29c7bfabf19e6a93ae2aff65f55202d0e6", "change", []string{"10"})
		}
		name = name + "";
		//err = stub.PutState(name, []byte(strconv.Itoa(0)));
		//if err != nil {
		//	return nil, errors.New("Meter cannot be updated")
		//}
	}

	return []byte(" total: " + strconv.Itoa(total)), nil
}

func (t *SimpleChaincode) Invoke(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {

	if function == "settle" {
		return t.settle(stub, args)
	}

	if function != "report" {
		return nil, errors.New("Unimplemented '" + function + "' invoked")
	}

	var name string    // Entities
	var val int // Asset holdings
	var err error

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2")
	}

	name = args[0]
	val, _ = strconv.Atoi(string(args[1]))

	err = stub.PutState(name, []byte(strconv.Itoa(val)))

	if err != nil {
		return nil, err
	}

	return nil, nil
}

// Query callback representing the query of a chaincode
func (t *SimpleChaincode) Query(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {

	if function == "settle" {
		return t.settle(stub, args)
	}

	if function != "querybalance" {
		return nil, errors.New("Invalid query function name. Expecting \"querybalance\"")
	}
	var name string // Entities
	var err error

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting name of the Meter to query")
	}

	name = args[0]

	// Get the state from the ledger
	value, err := stub.GetState(name)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get state for " + name + "\"}"
		return nil, errors.New(jsonResp)
	}

	if value == nil {
		jsonResp := "{\"Error\":\"Nil amount for Meter" + name + "\"}"
		return nil, errors.New(jsonResp)
	}

	jsonResp := "{\"Name\":\"" + name + "\",\"Amount\":\"" + string(value) + "\"}"
	fmt.Printf("Query Response:%s\n", jsonResp)
	return value, nil
}

func main() {
	err := shim.Start(new(SimpleChaincode))
	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}
<commit_msg>updated chain code name.<commit_after>package main

import (
	"errors"
	"fmt"
	"strconv"

	"github.com/hyperledger/fabric/core/chaincode/shim"
)

// SimpleChaincode implementation
type SimpleChaincode struct {
}

func (t *SimpleChaincode) Init(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {
	var err error

	if len(args) == 0 {
		return nil, errors.New("Incorrect number of arguments. At least one Meter's name is required.")
	}

	for _,name := range args {
		if len(name) == 0{
			continue
		}
		err = stub.PutState(name, []byte(strconv.Itoa(0)));
		if err != nil {
			return nil, errors.New("Meter cannot be created")
		}
	}

	return nil, nil
}

// Deletes an entity from state
func (t *SimpleChaincode) settle(stub *shim.ChaincodeStub, args []string) ([]byte, error) {
	//var err error
	var key string
	var val, total int

	//exchange_rate = 13;

	var keys []string
	var values []int
	total = 0;

	for i := 1; i < 2; i++ {
		key = strconv.Itoa(i)
		value, err := stub.GetState(key)
		if err != nil {
			continue
		}
		if value == nil {
			continue
		}
		val, _ = strconv.Atoi(string(value))
		total = total + 1;
		keys = append(keys, key)
		values = append(values, val)

	}
	for index,name := range keys {
		if(values[index] < 0){
			//amount = values[index]*-1*exchange_rate;
			stub.QueryChaincode("github.com/olegabu/decentralized-energy-utility/chaincode/settle", "change", []string{"10"})
		}
		name = name + "";
		//err = stub.PutState(name, []byte(strconv.Itoa(0)));
		//if err != nil {
		//	return nil, errors.New("Meter cannot be updated")
		//}
	}

	return []byte(" total: " + strconv.Itoa(total)), nil
}

func (t *SimpleChaincode) Invoke(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {

	if function == "settle" {
		return t.settle(stub, args)
	}

	if function != "report" {
		return nil, errors.New("Unimplemented '" + function + "' invoked")
	}

	var name string    // Entities
	var val int // Asset holdings
	var err error

	if len(args) != 2 {
		return nil, errors.New("Incorrect number of arguments. Expecting 2")
	}

	name = args[0]
	val, _ = strconv.Atoi(string(args[1]))

	err = stub.PutState(name, []byte(strconv.Itoa(val)))

	if err != nil {
		return nil, err
	}

	return nil, nil
}

// Query callback representing the query of a chaincode
func (t *SimpleChaincode) Query(stub *shim.ChaincodeStub, function string, args []string) ([]byte, error) {

	if function == "settle" {
		return t.settle(stub, args)
	}

	if function != "querybalance" {
		return nil, errors.New("Invalid query function name. Expecting \"querybalance\"")
	}
	var name string // Entities
	var err error

	if len(args) != 1 {
		return nil, errors.New("Incorrect number of arguments. Expecting name of the Meter to query")
	}

	name = args[0]

	// Get the state from the ledger
	value, err := stub.GetState(name)
	if err != nil {
		jsonResp := "{\"Error\":\"Failed to get state for " + name + "\"}"
		return nil, errors.New(jsonResp)
	}

	if value == nil {
		jsonResp := "{\"Error\":\"Nil amount for Meter" + name + "\"}"
		return nil, errors.New(jsonResp)
	}

	jsonResp := "{\"Name\":\"" + name + "\",\"Amount\":\"" + string(value) + "\"}"
	fmt.Printf("Query Response:%s\n", jsonResp)
	return value, nil
}

func main() {
	err := shim.Start(new(SimpleChaincode))
	if err != nil {
		fmt.Printf("Error starting Simple chaincode: %s", err)
	}
}
<|endoftext|>


<commit_before>package lru

import (
	"fmt"
	"testing"
)

func TestNewInMemory(t *testing.T) {
	c := NewInMemory(3)
	if err := c.Put("foo", "bar"); err != nil {
		t.Fatal(err)
	}
	if v, err := c.Get("foo"); err != nil || fmt.Sprint(v) != "bar" {
		t.Fatal(err)
	}
}
<commit_msg>lru: test eviction<commit_after>package lru

import (
	"fmt"
	"testing"
)

func TestNewInMemory(t *testing.T) {
	c := NewInMemory(3)
	if err := c.Put("foo", "bar"); err != nil {
		t.Fatal(err)
	}
	if err := c.Put("foo1", "bar"); err != nil {
		t.Fatal(err)
	}
	if err := c.Put("foo2", "bar"); err != nil {
		t.Fatal(err)
	}
	if err := c.Put("foo3", "bar"); err != nil {
		t.Fatal(err)
	}
	if v, err := c.Get("foo3"); err != nil || fmt.Sprint(v) != "bar" {
		t.Fatal(err)
	}
	if _, err := c.Get("foo"); err != ErrKeyNotFound {
		t.Fatalf("expected eviction with %v, got %v", ErrKeyNotFound, err)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"flag"
	"github.com/cloudson/gitql/parser"
	"github.com/cloudson/gitql/runtime"
	"github.com/cloudson/gitql/semantical"
	"path/filepath"
)

func main() {

	query := flag.String("q", "", "The Query to search")
	pathString := flag.String("p", ".", "The (optional) path to run gitql")
	version := flag.Bool("v", false, "The version of gitql")
	flag.Parse()

	if *version {
		// @todo refactor to dynamic value
		fmt.Println("Gitql 1.0.0")
		return
	}

  if *query == "" {
    flag.Usage()
    return
  }

	path, errFile := filepath.Abs(*pathString)

	if errFile != nil {
		panic(errFile)
	}

	parser.New(*query)
	ast, errGit := parser.AST()
	if errGit != nil {
		panic(errGit)
	}
	ast.Path = &path
	errGit = semantical.Analysis(ast)
	if errGit != nil {
		panic(errGit)
	}

	runtime.Run(ast)
}
<commit_msg>Add exit code<commit_after>package main

import (
	"fmt"
	"flag"
	"github.com/cloudson/gitql/parser"
	"github.com/cloudson/gitql/runtime"
	"github.com/cloudson/gitql/semantical"
	"path/filepath"
	"os"
)

func main() {

	query := flag.String("q", "", "The Query to search")
	pathString := flag.String("p", ".", "The (optional) path to run gitql")
	version := flag.Bool("v", false, "The version of gitql")
	flag.Parse()

	if *version {
		// @todo refactor to dynamic value
		fmt.Println("Gitql 1.0.0")
		os.Exit(0)
	}

  if *query == "" {
    flag.Usage()
    os.Exit(1)
  }

	path, errFile := filepath.Abs(*pathString)

	if errFile != nil {
		panic(errFile)
	}

	parser.New(*query)
	ast, errGit := parser.AST()
	if errGit != nil {
		panic(errGit)
	}
	ast.Path = &path
	errGit = semantical.Analysis(ast)
	if errGit != nil {
		panic(errGit)
	}

	runtime.Run(ast)
}
<|endoftext|>