<commit_before>package mail

import (
	"bytes"
	"fmt"
	"github.com/sloonz/go-mime-message"
	"github.com/sloonz/go-qprintable"
	"io"
	"net/smtp"
	"os"
)

type Address struct {
	Email string
	Name  string
}

type Message struct {
	From          Address
	To            []Address
	Subject       string
	HTMLBody      string
	PlaintextBody string
	Files         *AttachmentList
}

func NewMessage() *Message {
	m := &Message{}
	m.Files = NewAttachmentList()
	return m
}

func (m *Message) AddRecipient(to Address) {
	if m.To == nil {
		m.To = make([]Address, 0)
	}
	m.To = append(m.To, to)
}

type SMTP struct {
	Auth    smtp.Auth
	Address string
}

func NewSMTP(auth smtp.Auth, address string) *SMTP {
	return &SMTP{auth, address}
}

func (s *SMTP) SubmitHTML(fromEmail, fromName, toEmail, toName, subject, htmlBody string, files *AttachmentList) (int, error) {
	m := NewMessage()
	m.From.Name = fromName
	m.From.Email = fromEmail
	m.AddRecipient(Address{toEmail, toName})
	m.HTMLBody = htmlBody
	m.Files = files
	m.Subject = subject
	return s.submit(m)
}

func (s *SMTP) SubmitPlaintext(fromEmail, fromName, toEmail, toName, subject, plainBody string, files *AttachmentList) (int, error) {
	m := NewMessage()
	m.From.Name = fromName
	m.From.Email = fromEmail
	m.AddRecipient(Address{toEmail, toName})
	m.PlaintextBody = plainBody
	m.Files = files
	m.Subject = subject
	return s.submit(m)
}

func (s *SMTP) SubmitMixed(fromEmail, fromName, toEmail, toName, subject, plainBody string, htmlBody string, files *AttachmentList) (int, error) {
	m := NewMessage()
	m.From.Name = fromName
	m.From.Email = fromEmail
	m.AddRecipient(Address{toEmail, toName})
	m.HTMLBody = htmlBody
	m.PlaintextBody = plainBody
	m.Files = files
	m.Subject = subject
	return s.submit(m)
}

func (s *SMTP) submit(msg *Message) (int, error) {
	//var buffer bytes.Buffer
	bmarker := newBoundary()
	multipartmessage := message.NewMultipartMessage("mixed", bmarker)

	multipartmessage.SetHeader("From", fmt.Sprintf("%s <%s>", message.EncodeWord(msg.From.Name), msg.From.Email))
	multipartmessage.SetHeader("Return-Path", fmt.Sprintf("<%s>", msg.From.Email))
	// TO
	var tol bytes.Buffer
	for i := 0; i < len(msg.To); i++ {
		if i > 0 {
			tol.WriteString(", ")
		}
		tol.WriteString(message.EncodeWord(msg.To[i].Name))
		tol.WriteString(" <")
		tol.WriteString(msg.To[i].Email)
		tol.WriteString(">")
	}
	multipartmessage.SetHeader("To", tol.String())
	// SUBJECT
	multipartmessage.SetHeader("Subject", message.EncodeWord(msg.Subject))
	//// MIME-Version
	multipartmessage.SetHeader("MIME-Version", "1.0")
	//// [END] [HEADERS]

	if len(msg.HTMLBody) > 0 && len(msg.PlaintextBody) > 0 {
		alternatives := message.NewMultipartMessage("alternative", newBoundary())
		hbits := new(bytes.Buffer)
		tbits := new(bytes.Buffer)
		hbits.WriteString(msg.HTMLBody)
		tbits.WriteString(msg.PlaintextBody)
		hmsg := message.NewTextMessage(qprintable.UnixTextEncoding, hbits)
		hmsg.SetHeader("Content-Type", "text/html; charset=UTF-8")
		tmsg := message.NewTextMessage(qprintable.UnixTextEncoding, tbits)
		tmsg.SetHeader("Content-Type", "text/plain; charset=UTF-8")
		multipartmessage.AddPart(&alternatives.Message)
	} else if len(msg.HTMLBody) > 0 {
		hbits := new(bytes.Buffer)
		hbits.WriteString(msg.HTMLBody)
		hmsg := message.NewTextMessage(qprintable.UnixTextEncoding, hbits)
		hmsg.SetHeader("Content-Type", "text/html; charset=UTF-8")
		multipartmessage.AddPart(hmsg)
	} else if len(msg.PlaintextBody) > 0 {
		tbits := new(bytes.Buffer)
		tbits.WriteString(msg.PlaintextBody)
		tmsg := message.NewTextMessage(qprintable.UnixTextEncoding, tbits)
		tmsg.SetHeader("Content-Type", "text/plain; charset=UTF-8")
		multipartmessage.AddPart(tmsg)
	}

	tols := make([]string, len(msg.To))
	for k, v := range msg.To {
		tols[k] = v.Email
	}
	//
	if msg.Files == nil {
		goto Submit
	}
	if msg.Files.Count() < 1 {
		goto Submit
	}

	for curItem := msg.Files.First(); curItem != nil; curItem = curItem.Next() {
		if len(curItem.Value.Path) > 0 && curItem.Value.File == nil {
			curItem.Value.File, _ = os.Open(curItem.Value.Path)
			//TODO: treat this error
		}
		msg00 := message.NewBinaryMessage(curItem.Value.File)
		msg00.SetHeader("Content-Type", fmt.Sprintf("%v; name=\"%v\"", curItem.Value.MimeType, message.EncodeWord(curItem.Value.Name)))
		msg00.SetHeader("Content-Disposition", fmt.Sprintf("attachment; filename=\"%v\"", message.EncodeWord(curItem.Value.Name)))
		multipartmessage.AddPart(msg00)
	}

Submit:
	buffer := new(bytes.Buffer)
	written, _ := io.Copy(buffer, multipartmessage)
	//TODO: replace smtp.Send with a buffer receiver sender for SMTP
	return int(written), smtp.SendMail(s.Address, s.Auth, msg.From.Email, tols, buffer.Bytes())
}
<commit_msg>streaming data instead of using byte slice<commit_after>package mail

import (
	"bytes"
	"fmt"
	"github.com/gabstv/golib/smtp2"
	"github.com/sloonz/go-mime-message"
	"github.com/sloonz/go-qprintable"
	"net/smtp"
	"os"
)

type Address struct {
	Email string
	Name  string
}

type Message struct {
	From          Address
	To            []Address
	Subject       string
	HTMLBody      string
	PlaintextBody string
	Files         *AttachmentList
}

func NewMessage() *Message {
	m := &Message{}
	m.Files = NewAttachmentList()
	return m
}

func (m *Message) AddRecipient(to Address) {
	if m.To == nil {
		m.To = make([]Address, 0)
	}
	m.To = append(m.To, to)
}

type SMTP struct {
	Auth    smtp.Auth
	Address string
}

func NewSMTP(auth smtp.Auth, address string) *SMTP {
	return &SMTP{auth, address}
}

func (s *SMTP) SubmitHTML(fromEmail, fromName, toEmail, toName, subject, htmlBody string, files *AttachmentList) (int, error) {
	m := NewMessage()
	m.From.Name = fromName
	m.From.Email = fromEmail
	m.AddRecipient(Address{toEmail, toName})
	m.HTMLBody = htmlBody
	m.Files = files
	m.Subject = subject
	return s.submit(m)
}

func (s *SMTP) SubmitPlaintext(fromEmail, fromName, toEmail, toName, subject, plainBody string, files *AttachmentList) (int, error) {
	m := NewMessage()
	m.From.Name = fromName
	m.From.Email = fromEmail
	m.AddRecipient(Address{toEmail, toName})
	m.PlaintextBody = plainBody
	m.Files = files
	m.Subject = subject
	return s.submit(m)
}

func (s *SMTP) SubmitMixed(fromEmail, fromName, toEmail, toName, subject, plainBody string, htmlBody string, files *AttachmentList) (int, error) {
	m := NewMessage()
	m.From.Name = fromName
	m.From.Email = fromEmail
	m.AddRecipient(Address{toEmail, toName})
	m.HTMLBody = htmlBody
	m.PlaintextBody = plainBody
	m.Files = files
	m.Subject = subject
	return s.submit(m)
}

func (s *SMTP) submit(msg *Message) (int, error) {
	//var buffer bytes.Buffer
	bmarker := newBoundary()
	multipartmessage := message.NewMultipartMessage("mixed", bmarker)

	multipartmessage.SetHeader("From", fmt.Sprintf("%s <%s>", message.EncodeWord(msg.From.Name), msg.From.Email))
	multipartmessage.SetHeader("Return-Path", fmt.Sprintf("<%s>", msg.From.Email))
	// TO
	var tol bytes.Buffer
	for i := 0; i < len(msg.To); i++ {
		if i > 0 {
			tol.WriteString(", ")
		}
		tol.WriteString(message.EncodeWord(msg.To[i].Name))
		tol.WriteString(" <")
		tol.WriteString(msg.To[i].Email)
		tol.WriteString(">")
	}
	multipartmessage.SetHeader("To", tol.String())
	// SUBJECT
	multipartmessage.SetHeader("Subject", message.EncodeWord(msg.Subject))
	//// MIME-Version
	multipartmessage.SetHeader("MIME-Version", "1.0")
	//// [END] [HEADERS]

	if len(msg.HTMLBody) > 0 && len(msg.PlaintextBody) > 0 {
		alternatives := message.NewMultipartMessage("alternative", newBoundary())
		hbits := new(bytes.Buffer)
		tbits := new(bytes.Buffer)
		hbits.WriteString(msg.HTMLBody)
		tbits.WriteString(msg.PlaintextBody)
		hmsg := message.NewTextMessage(qprintable.UnixTextEncoding, hbits)
		hmsg.SetHeader("Content-Type", "text/html; charset=UTF-8")
		tmsg := message.NewTextMessage(qprintable.UnixTextEncoding, tbits)
		tmsg.SetHeader("Content-Type", "text/plain; charset=UTF-8")
		multipartmessage.AddPart(&alternatives.Message)
	} else if len(msg.HTMLBody) > 0 {
		hbits := new(bytes.Buffer)
		hbits.WriteString(msg.HTMLBody)
		hmsg := message.NewTextMessage(qprintable.UnixTextEncoding, hbits)
		hmsg.SetHeader("Content-Type", "text/html; charset=UTF-8")
		multipartmessage.AddPart(hmsg)
	} else if len(msg.PlaintextBody) > 0 {
		tbits := new(bytes.Buffer)
		tbits.WriteString(msg.PlaintextBody)
		tmsg := message.NewTextMessage(qprintable.UnixTextEncoding, tbits)
		tmsg.SetHeader("Content-Type", "text/plain; charset=UTF-8")
		multipartmessage.AddPart(tmsg)
	}

	tols := make([]string, len(msg.To))
	for k, v := range msg.To {
		tols[k] = v.Email
	}
	//
	if msg.Files == nil {
		goto Submit
	}
	if msg.Files.Count() < 1 {
		goto Submit
	}

	for curItem := msg.Files.First(); curItem != nil; curItem = curItem.Next() {
		if len(curItem.Value.Path) > 0 && curItem.Value.File == nil {
			curItem.Value.File, _ = os.Open(curItem.Value.Path)
			//TODO: treat this error
		}
		msg00 := message.NewBinaryMessage(curItem.Value.File)
		msg00.SetHeader("Content-Type", fmt.Sprintf("%v; name=\"%v\"", curItem.Value.MimeType, message.EncodeWord(curItem.Value.Name)))
		msg00.SetHeader("Content-Disposition", fmt.Sprintf("attachment; filename=\"%v\"", message.EncodeWord(curItem.Value.Name)))
		multipartmessage.AddPart(msg00)
	}

Submit:
	return 1024 * 1024, smtp2.SendMail(s.Address, s.Auth, msg.From.Email, tols, multipartmessage)
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"io"
	"os"
	"os/signal"
	"path/filepath"
	"strings"
	"syscall"

	"v2ray.com/core"
	"v2ray.com/core/common/log"
	//"net/http"
	//_ "net/http/pprof"
)

var (
	configFile string
	version    = flag.Bool("version", false, "Show current version of V2Ray.")
	test       = flag.Bool("test", false, "Test config file only, without launching V2Ray server.")
	format     = flag.String("format", "json", "Format of input file.")
)

func init() {
	defaultConfigFile := ""
	workingDir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err == nil {
		defaultConfigFile = filepath.Join(workingDir, "config.json")
	}
	flag.StringVar(&configFile, "config", defaultConfigFile, "Config file for this Point server.")
}

func GetConfigFormat() core.ConfigFormat {
	switch strings.ToLower(*format) {
	case "json":
		return core.ConfigFormat_JSON
	case "pb", "protobuf":
		return core.ConfigFormat_Protobuf
	default:
		return core.ConfigFormat_JSON
	}
}

func startV2Ray() *core.Point {
	if len(configFile) == 0 {
		log.Error("Config file is not set.")
		return nil
	}
	var configInput io.Reader
	if configFile == "stdin:" {
		configInput = os.Stdin
	} else {
		fixedFile := os.ExpandEnv(configFile)
		file, err := os.Open(fixedFile)
		if err != nil {
			log.Error("Config file not readable: ", err)
			return nil
		}
		defer file.Close()
		configInput = file
	}
	config, err := core.LoadConfig(GetConfigFormat(), configInput)
	if err != nil {
		log.Error("Failed to read config file (", configFile, "): ", configFile, err)
		return nil
	}

	vPoint, err := core.NewPoint(config)
	if err != nil {
		log.Error("Failed to create Point server: ", err)
		return nil
	}

	if *test {
		fmt.Println("Configuration OK.")
		return nil
	}

	err = vPoint.Start()
	if err != nil {
		log.Error("Error starting Point server: ", err)
		return nil
	}

	return vPoint
}

func main() {
	flag.Parse()

	core.PrintVersion()

	if *version {
		return
	}

	//go func() {
	//	http.ListenAndServe(":6060", nil)
	//}()

	if point := startV2Ray(); point != nil {
		osSignals := make(chan os.Signal, 1)
		signal.Notify(osSignals, os.Interrupt, os.Kill, syscall.SIGTERM)

		<-osSignals
		point.Close()
	}
	log.Close()
}
<commit_msg>remove unused code<commit_after>package main

import (
	"flag"
	"fmt"
	"io"
	"os"
	"os/signal"
	"path/filepath"
	"strings"
	"syscall"

	"v2ray.com/core"
	"v2ray.com/core/common/log"
)

var (
	configFile string
	version    = flag.Bool("version", false, "Show current version of V2Ray.")
	test       = flag.Bool("test", false, "Test config file only, without launching V2Ray server.")
	format     = flag.String("format", "json", "Format of input file.")
)

func init() {
	defaultConfigFile := ""
	workingDir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err == nil {
		defaultConfigFile = filepath.Join(workingDir, "config.json")
	}
	flag.StringVar(&configFile, "config", defaultConfigFile, "Config file for this Point server.")
}

func GetConfigFormat() core.ConfigFormat {
	switch strings.ToLower(*format) {
	case "json":
		return core.ConfigFormat_JSON
	case "pb", "protobuf":
		return core.ConfigFormat_Protobuf
	default:
		return core.ConfigFormat_JSON
	}
}

func startV2Ray() *core.Point {
	if len(configFile) == 0 {
		log.Error("Config file is not set.")
		return nil
	}
	var configInput io.Reader
	if configFile == "stdin:" {
		configInput = os.Stdin
	} else {
		fixedFile := os.ExpandEnv(configFile)
		file, err := os.Open(fixedFile)
		if err != nil {
			log.Error("Config file not readable: ", err)
			return nil
		}
		defer file.Close()
		configInput = file
	}
	config, err := core.LoadConfig(GetConfigFormat(), configInput)
	if err != nil {
		log.Error("Failed to read config file (", configFile, "): ", configFile, err)
		return nil
	}

	vPoint, err := core.NewPoint(config)
	if err != nil {
		log.Error("Failed to create Point server: ", err)
		return nil
	}

	if *test {
		fmt.Println("Configuration OK.")
		return nil
	}

	err = vPoint.Start()
	if err != nil {
		log.Error("Error starting Point server: ", err)
		return nil
	}

	return vPoint
}

func main() {
	flag.Parse()

	core.PrintVersion()

	if *version {
		return
	}

	if point := startV2Ray(); point != nil {
		osSignals := make(chan os.Signal, 1)
		signal.Notify(osSignals, os.Interrupt, os.Kill, syscall.SIGTERM)

		<-osSignals
		point.Close()
	}
	log.Close()
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/couchbaselabs/logg"
	"github.com/tleyden/checkerlution"
	cbot "github.com/tleyden/checkers-bot"
	ng "github.com/tleyden/neurgo"
	nv "github.com/tleyden/neurvolve"
	"math"
	"time"
)

func init() {
	logg.LogKeys["MAIN"] = true
	logg.LogKeys["DEBUG"] = true
	logg.LogKeys["NODE_PRE_SEND"] = true
	logg.LogKeys["NODE_POST_SEND"] = true
	logg.LogKeys["NODE_POST_RECV"] = true
	logg.LogKeys["NODE_STATE"] = true
	ng.SeedRandom()
}

func main() {

	// create a checkerlution instance just to create a cortex (kludgy)
	thinker := &checkerlution.Checkerlution{}
	thinker.SetMode(checkerlution.TRAINING_MODE)
	thinker.CreateNeurgoCortex()
	// thinker.LoadNeurgoCortex("/Users/traun/tmp/checkerlution-1381908895.json")
	cortex := thinker.Cortex()

	// setup the scape
	team, syncGatewayUrl, feedType := cbot.ParseCmdLine()
	scape := &checkerlution.CheckerlutionScape{}
	scape.SetThinker(thinker)
	scape.SetSyncGatewayUrl(syncGatewayUrl)
	scape.SetFeedType(feedType)
	scape.SetTeam(team)

	// create a stochastic hill climber
	shc := &nv.StochasticHillClimber{
		FitnessThreshold:           150,
		MaxIterationsBeforeRestart: 5,
		MaxAttempts:                5,
		WeightSaturationRange:      []float64{-2 * math.Pi, 2 * math.Pi},
	}
	cortexTrained, succeeded := shc.Train(cortex, scape)
	if succeeded {
		logg.LogTo("MAIN", "Training succeeded")
	} else {
		logg.LogTo("MAIN", "Training Failed")
	}

	filename := fmt.Sprintf("/tmp/checkerlution-%v.json", time.Now().Unix())
	logg.LogTo("MAIN", "Dumping latest cortex to %v", filename)
	cortexTrained.MarshalJSONToFile(filename)

}
<commit_msg>1. put command line flags into a struct.  2. logging related cleanup<commit_after>package main

import (
	"fmt"
	"github.com/couchbaselabs/logg"
	"github.com/tleyden/checkerlution"
	cbot "github.com/tleyden/checkers-bot"
	ng "github.com/tleyden/neurgo"
	nv "github.com/tleyden/neurvolve"
	"math"
	"time"
)

func init() {
	logg.LogKeys["MAIN"] = true
	logg.LogKeys["DEBUG"] = false
	logg.LogKeys["NEURGO"] = false
	logg.LogKeys["NODE_PRE_SEND"] = false
	logg.LogKeys["NODE_POST_SEND"] = false
	logg.LogKeys["NODE_POST_RECV"] = false
	logg.LogKeys["NODE_STATE"] = false
	ng.SeedRandom()
}

func main() {

	// create a checkerlution instance just to create a cortex (kludgy)
	thinker := &checkerlution.Checkerlution{}
	thinker.SetMode(checkerlution.TRAINING_MODE)
	// thinker.CreateNeurgoCortex()
	thinker.LoadNeurgoCortex("/Users/traun/tmp/checkerlution-1381908895.json")
	cortex := thinker.Cortex()

	// setup the scape
	checkersBotFlags := cbot.ParseCmdLine()
	scape := &checkerlution.CheckerlutionScape{}
	scape.SetThinker(thinker)
	scape.SetSyncGatewayUrl(checkersBotFlags.SyncGatewayUrl)
	scape.SetFeedType(checkersBotFlags.FeedType)
	scape.SetTeam(checkersBotFlags.Team)

	// create a stochastic hill climber
	shc := &nv.StochasticHillClimber{
		FitnessThreshold:           150,
		MaxIterationsBeforeRestart: 5,
		MaxAttempts:                5,
		WeightSaturationRange:      []float64{-2 * math.Pi, 2 * math.Pi},
	}
	cortexTrained, succeeded := shc.Train(cortex, scape)
	if succeeded {
		logg.LogTo("MAIN", "Training succeeded")
	} else {
		logg.LogTo("MAIN", "Training Failed")
	}

	filename := fmt.Sprintf("/tmp/checkerlution-%v.json", time.Now().Unix())
	logg.LogTo("MAIN", "Saving Cortex to %v", filename)
	cortexTrained.MarshalJSONToFile(filename)

}
<|endoftext|>


<commit_before>package quota_manager

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

	"code.cloudfoundry.org/lager"
)

type AUFSDiffSizer struct {
	AUFSDiffPathFinder AUFSDiffPathFinder
}

func (a *AUFSDiffSizer) DiffSize(logger lager.Logger, containerRootFSPath string) (uint64, error) {
	_, err := os.Stat(containerRootFSPath)
	if os.IsNotExist(err) {
		return 0, fmt.Errorf("get usage: %s", err)
	}

	log := logger.Session("diff-size", lager.Data{"path": containerRootFSPath})
	log.Info("start")

	command := fmt.Sprintf("df -B 1 %s | tail -n1 | awk -v N=3 '{print $N}'", a.AUFSDiffPathFinder.GetDiffLayerPath((containerRootFSPath)))
	outbytes, err := exec.Command("sh", "-c", command).CombinedOutput()
	if err != nil {
		log.Error("df-failed", err)
		return 0, fmt.Errorf("get usage: df: %s, %s", err, string(outbytes))
	}

	var bytesUsed uint64
	if _, err := fmt.Sscanf(string(outbytes), "%d", &bytesUsed); err != nil {
		log.Error("scanf-failed", err, lager.Data{"out": string(outbytes)})
		return 0, nil
	}

	log.Info("finished", lager.Data{"bytes": bytesUsed})
	return bytesUsed, nil
}
<commit_msg>Make shed less chatty<commit_after>package quota_manager

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

	"code.cloudfoundry.org/lager"
)

type AUFSDiffSizer struct {
	AUFSDiffPathFinder AUFSDiffPathFinder
}

func (a *AUFSDiffSizer) DiffSize(logger lager.Logger, containerRootFSPath string) (uint64, error) {
	_, err := os.Stat(containerRootFSPath)
	if os.IsNotExist(err) {
		return 0, fmt.Errorf("get usage: %s", err)
	}

	log := logger.Session("diff-size", lager.Data{"path": containerRootFSPath})
	log.Debug("start")

	command := fmt.Sprintf("df -B 1 %s | tail -n1 | awk -v N=3 '{print $N}'", a.AUFSDiffPathFinder.GetDiffLayerPath((containerRootFSPath)))
	outbytes, err := exec.Command("sh", "-c", command).CombinedOutput()
	if err != nil {
		log.Error("df-failed", err)
		return 0, fmt.Errorf("get usage: df: %s, %s", err, string(outbytes))
	}

	var bytesUsed uint64
	if _, err := fmt.Sscanf(string(outbytes), "%d", &bytesUsed); err != nil {
		log.Error("scanf-failed", err, lager.Data{"out": string(outbytes)})
		return 0, nil
	}

	log.Debug("finished", lager.Data{"bytes": bytesUsed})
	return bytesUsed, nil
}
<|endoftext|>


<commit_before>// +build integration,!no-etcd

package integration

import (
	"io/ioutil"
	"testing"

	kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	kapierror "github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/fields"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"

	authorizationapi "github.com/openshift/origin/pkg/authorization/api"
	"github.com/openshift/origin/pkg/client"
	"github.com/openshift/origin/pkg/cmd/server/admin"
	"github.com/openshift/origin/pkg/cmd/server/etcd"
	"github.com/openshift/origin/pkg/cmd/server/origin"
	"github.com/openshift/origin/pkg/cmd/util/tokencmd"
	testutil "github.com/openshift/origin/test/util"
)

func TestBootstrapPolicyAuthenticatedUsersAgainstOpenshiftNamespace(t *testing.T) {
	_, clusterAdminKubeConfig, err := testutil.StartTestMaster()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	valerieClientConfig := *clusterAdminClientConfig
	valerieClientConfig.Username = ""
	valerieClientConfig.Password = ""
	valerieClientConfig.BearerToken = ""
	valerieClientConfig.CertFile = ""
	valerieClientConfig.KeyFile = ""
	valerieClientConfig.CertData = nil
	valerieClientConfig.KeyData = nil

	accessToken, err := tokencmd.RequestToken(&valerieClientConfig, nil, "valerie", "security!")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	valerieClientConfig.BearerToken = accessToken
	valerieOpenshiftClient, err := client.New(&valerieClientConfig)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	openshiftSharedResourcesNamespace := "openshift"

	if _, err := valerieOpenshiftClient.Templates(openshiftSharedResourcesNamespace).List(labels.Everything(), fields.Everything()); err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if _, err := valerieOpenshiftClient.Templates(kapi.NamespaceDefault).List(labels.Everything(), fields.Everything()); err == nil || !kapierror.IsForbidden(err) {
		t.Errorf("unexpected error: %v", err)
	}

	if _, err := valerieOpenshiftClient.ImageStreams(openshiftSharedResourcesNamespace).List(labels.Everything(), fields.Everything()); err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if _, err := valerieOpenshiftClient.ImageStreams(kapi.NamespaceDefault).List(labels.Everything(), fields.Everything()); err == nil || !kapierror.IsForbidden(err) {
		t.Errorf("unexpected error: %v", err)
	}

	if _, err := valerieOpenshiftClient.ImageStreamTags(openshiftSharedResourcesNamespace).Get("name", "tag"); !kapierror.IsNotFound(err) {
		t.Errorf("unexpected error: %v", err)
	}
	if _, err := valerieOpenshiftClient.ImageStreamTags(kapi.NamespaceDefault).Get("name", "tag"); err == nil || !kapierror.IsForbidden(err) {
		t.Errorf("unexpected error: %v", err)
	}
}

func TestBootstrapPolicyOverwritePolicyCommand(t *testing.T) {
	masterConfig, clusterAdminKubeConfig, err := testutil.StartTestMaster()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	client, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	if err := client.ClusterPolicies().Delete(authorizationapi.PolicyName); err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	if _, err := client.ClusterPolicies().List(labels.Everything(), fields.Everything()); err == nil || !kapierror.IsForbidden(err) {
		t.Errorf("unexpected error: %v", err)
	}

	etcdClient, err := etcd.GetAndTestEtcdClient(masterConfig.EtcdClientInfo)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	etcdHelper, err := origin.NewEtcdHelper(etcdClient, masterConfig.EtcdStorageConfig.OpenShiftStorageVersion, masterConfig.EtcdStorageConfig.OpenShiftStoragePrefix)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	if err := admin.OverwriteBootstrapPolicy(etcdHelper, masterConfig.PolicyConfig.BootstrapPolicyFile, admin.CreateBootstrapPolicyFileFullCommand, true, ioutil.Discard); err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	if _, err := client.ClusterPolicies().List(labels.Everything(), fields.Everything()); err != nil {
		t.Errorf("unexpected error: %v", err)
	}
}

func TestBootstrapPolicySelfSubjectAccessReviews(t *testing.T) {
	_, clusterAdminKubeConfig, err := testutil.StartTestMaster()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	valerieClientConfig := *clusterAdminClientConfig
	valerieClientConfig.Username = ""
	valerieClientConfig.Password = ""
	valerieClientConfig.BearerToken = ""
	valerieClientConfig.CertFile = ""
	valerieClientConfig.KeyFile = ""
	valerieClientConfig.CertData = nil
	valerieClientConfig.KeyData = nil

	accessToken, err := tokencmd.RequestToken(&valerieClientConfig, nil, "valerie", "security!")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	valerieClientConfig.BearerToken = accessToken
	valerieOpenshiftClient, err := client.New(&valerieClientConfig)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	// can I get a subjectaccessreview on myself even if I have no rights to do it generally
	askCanICreatePolicyBindings := &authorizationapi.SubjectAccessReview{Verb: "create", Resource: "policybindings"}
	subjectAccessReviewTest{
		clientInterface: valerieOpenshiftClient.SubjectAccessReviews("openshift"),
		review:          askCanICreatePolicyBindings,
		response: authorizationapi.SubjectAccessReviewResponse{
			Allowed:   false,
			Reason:    "denied by default",
			Namespace: "openshift",
		},
	}.run(t)

	// I shouldn't be allowed to ask whether someone else can perform an action
	askCanClusterAdminsCreateProject := &authorizationapi.SubjectAccessReview{Groups: util.NewStringSet("system:cluster-admins"), Verb: "create", Resource: "projects"}
	subjectAccessReviewTest{
		clientInterface: valerieOpenshiftClient.SubjectAccessReviews("openshift"),
		review:          askCanClusterAdminsCreateProject,
		err:             "cannot ",
	}.run(t)

}
<commit_msg>Deflake integration test for overwrite policy<commit_after>// +build integration,!no-etcd

package integration

import (
	"io/ioutil"
	"testing"
	"time"

	kapi "github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	kapierror "github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/fields"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util/wait"

	authorizationapi "github.com/openshift/origin/pkg/authorization/api"
	"github.com/openshift/origin/pkg/client"
	"github.com/openshift/origin/pkg/cmd/server/admin"
	"github.com/openshift/origin/pkg/cmd/server/etcd"
	"github.com/openshift/origin/pkg/cmd/server/origin"
	"github.com/openshift/origin/pkg/cmd/util/tokencmd"
	testutil "github.com/openshift/origin/test/util"
)

func TestBootstrapPolicyAuthenticatedUsersAgainstOpenshiftNamespace(t *testing.T) {
	_, clusterAdminKubeConfig, err := testutil.StartTestMaster()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	valerieClientConfig := *clusterAdminClientConfig
	valerieClientConfig.Username = ""
	valerieClientConfig.Password = ""
	valerieClientConfig.BearerToken = ""
	valerieClientConfig.CertFile = ""
	valerieClientConfig.KeyFile = ""
	valerieClientConfig.CertData = nil
	valerieClientConfig.KeyData = nil

	accessToken, err := tokencmd.RequestToken(&valerieClientConfig, nil, "valerie", "security!")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	valerieClientConfig.BearerToken = accessToken
	valerieOpenshiftClient, err := client.New(&valerieClientConfig)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	openshiftSharedResourcesNamespace := "openshift"

	if _, err := valerieOpenshiftClient.Templates(openshiftSharedResourcesNamespace).List(labels.Everything(), fields.Everything()); err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if _, err := valerieOpenshiftClient.Templates(kapi.NamespaceDefault).List(labels.Everything(), fields.Everything()); err == nil || !kapierror.IsForbidden(err) {
		t.Errorf("unexpected error: %v", err)
	}

	if _, err := valerieOpenshiftClient.ImageStreams(openshiftSharedResourcesNamespace).List(labels.Everything(), fields.Everything()); err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if _, err := valerieOpenshiftClient.ImageStreams(kapi.NamespaceDefault).List(labels.Everything(), fields.Everything()); err == nil || !kapierror.IsForbidden(err) {
		t.Errorf("unexpected error: %v", err)
	}

	if _, err := valerieOpenshiftClient.ImageStreamTags(openshiftSharedResourcesNamespace).Get("name", "tag"); !kapierror.IsNotFound(err) {
		t.Errorf("unexpected error: %v", err)
	}
	if _, err := valerieOpenshiftClient.ImageStreamTags(kapi.NamespaceDefault).Get("name", "tag"); err == nil || !kapierror.IsForbidden(err) {
		t.Errorf("unexpected error: %v", err)
	}
}

func TestBootstrapPolicyOverwritePolicyCommand(t *testing.T) {
	masterConfig, clusterAdminKubeConfig, err := testutil.StartTestMaster()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	client, err := testutil.GetClusterAdminClient(clusterAdminKubeConfig)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	if err := client.ClusterPolicies().Delete(authorizationapi.PolicyName); err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	// after the policy is deleted, we must wait for it to be cleared from the policy cache
	err = wait.Poll(10*time.Millisecond, 10*time.Second, func() (bool, error) {
		_, err := client.ClusterPolicies().List(labels.Everything(), fields.Everything())
		if err == nil {
			return false, nil
		}
		if !kapierror.IsForbidden(err) {
			t.Errorf("unexpected error: %v", err)
		}
		return true, nil
	})
	if err != nil {
		t.Errorf("timeout: %v", err)
	}

	etcdClient, err := etcd.GetAndTestEtcdClient(masterConfig.EtcdClientInfo)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	etcdHelper, err := origin.NewEtcdHelper(etcdClient, masterConfig.EtcdStorageConfig.OpenShiftStorageVersion, masterConfig.EtcdStorageConfig.OpenShiftStoragePrefix)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	if err := admin.OverwriteBootstrapPolicy(etcdHelper, masterConfig.PolicyConfig.BootstrapPolicyFile, admin.CreateBootstrapPolicyFileFullCommand, true, ioutil.Discard); err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	if _, err := client.ClusterPolicies().List(labels.Everything(), fields.Everything()); err != nil {
		t.Errorf("unexpected error: %v", err)
	}
}

func TestBootstrapPolicySelfSubjectAccessReviews(t *testing.T) {
	_, clusterAdminKubeConfig, err := testutil.StartTestMaster()
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	clusterAdminClientConfig, err := testutil.GetClusterAdminClientConfig(clusterAdminKubeConfig)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	valerieClientConfig := *clusterAdminClientConfig
	valerieClientConfig.Username = ""
	valerieClientConfig.Password = ""
	valerieClientConfig.BearerToken = ""
	valerieClientConfig.CertFile = ""
	valerieClientConfig.KeyFile = ""
	valerieClientConfig.CertData = nil
	valerieClientConfig.KeyData = nil

	accessToken, err := tokencmd.RequestToken(&valerieClientConfig, nil, "valerie", "security!")
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	valerieClientConfig.BearerToken = accessToken
	valerieOpenshiftClient, err := client.New(&valerieClientConfig)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	// can I get a subjectaccessreview on myself even if I have no rights to do it generally
	askCanICreatePolicyBindings := &authorizationapi.SubjectAccessReview{Verb: "create", Resource: "policybindings"}
	subjectAccessReviewTest{
		clientInterface: valerieOpenshiftClient.SubjectAccessReviews("openshift"),
		review:          askCanICreatePolicyBindings,
		response: authorizationapi.SubjectAccessReviewResponse{
			Allowed:   false,
			Reason:    "denied by default",
			Namespace: "openshift",
		},
	}.run(t)

	// I shouldn't be allowed to ask whether someone else can perform an action
	askCanClusterAdminsCreateProject := &authorizationapi.SubjectAccessReview{Groups: util.NewStringSet("system:cluster-admins"), Verb: "create", Resource: "projects"}
	subjectAccessReviewTest{
		clientInterface: valerieOpenshiftClient.SubjectAccessReviews("openshift"),
		review:          askCanClusterAdminsCreateProject,
		err:             "cannot ",
	}.run(t)

}
<|endoftext|>


<commit_before>package main
<commit_msg>Update main_test.go<commit_after>package main

// Coming very soon!
<|endoftext|>


<commit_before>package sample

import (
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
	"time"
	"fmt"
	"reflect"
)

type Person struct {
	ID        bson.ObjectId `bson:"_id,omitempty"`
	Name      string
	Phone     string
	Timestamp time.Time
}

var (
	IsDrop = true
)

func GetResult() string {
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		panic(err)
	}
	defer session.Close()
	session.SetMode(mgo.Monotonic, true)

	// Drop Database
	if IsDrop {
		err = session.DB("test").DropDatabase()
		if err != nil {
			panic(err)
		}
	}

	// Collection People
	c := session.DB("test").C("people")

	// Index
	index := mgo.Index{
		Key:        []string{"name", "phone"},
		Unique:     true,
		DropDups:   true,
		Background: true,
		Sparse:     true,
	}
	err = c.EnsureIndex(index)
	if err != nil {
		panic(err)
	}

	// Insert Datas
	err = c.Insert(&Person{Name: "Ale", Phone: "+55 53 1234 4321", Timestamp: time.Now()},
		&Person{Name: "Cla", Phone: "+66 33 1234 5678", Timestamp: time.Now()})
	if err != nil {
		panic(err)
	}

	result := Person{}
	err = c.Find(bson.M{"name": "Ale"}).Select(bson.M{"phone": 0}).One(&result)
	if err != nil {
		panic(err)
	}
	return fmt.Sprintf("%v", reflect.ValueOf(&result).Elem().Field(1))
}<commit_msg>Update sample.go<commit_after>package sample

import (
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
	"time"
	"fmt"
	"reflect"
)

type Person struct {
	ID        bson.ObjectId `bson:"_id,omitempty"`
	Name      string
	Phone     string
	Timestamp time.Time
}

var (
	IsDrop = true
)

func GetResult() string {
	session, err := mgo.Dial("127.0.0.1")
	if err != nil {
		panic(err)
	}
	defer session.Close()
	session.SetMode(mgo.Monotonic, true)

	// Drop Database
	if IsDrop {
		err = session.DB("test").DropDatabase()
		if err != nil {
			panic(err)
		}
	}

	// Collection People
	c := session.DB("test").C("people")

	// Index
	index := mgo.Index{
		Key:        []string{"name", "phone"},
		Unique:     true,
		DropDups:   true,
		Background: true,
		Sparse:     true,
	}
	err = c.EnsureIndex(index)
	if err != nil {
		panic(err)
	}

	// Insert Datas
	err = c.Insert(&Person{Name: "Alen", Phone: "+55 53 1234 4321", Timestamp: time.Now()},
		&Person{Name: "Cla", Phone: "+66 33 1234 5678", Timestamp: time.Now()})
	if err != nil {
		panic(err)
	}

	result := Person{}
	err = c.Find(bson.M{"name": "Alen"}).Select(bson.M{"phone": 0}).One(&result)
	if err != nil {
		panic(err)
	}
	return fmt.Sprintf("%v", reflect.ValueOf(&result).Elem().Field(1))
}
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package tchannel

import (
	"sync"

	"golang.org/x/net/context"
)

// A Handler is an object that can be registered with a Channel to process
// incoming calls for a given service and operation
type Handler interface {
	// Handles an incoming call for service
	Handle(ctx context.Context, call *InboundCall)
}

// A HandlerFunc is an adapter to allow the use of ordering functions as
// Channel handlers.  If f is a function with the appropriate signature,
// HandlerFunc(f) is a Hander object that calls f
type HandlerFunc func(ctx context.Context, call *InboundCall)

// Handle calls f(ctx, call)
func (f HandlerFunc) Handle(ctx context.Context, call *InboundCall) { f(ctx, call) }

// Manages handlers
type handlerMap struct {
	mut      sync.RWMutex
	handlers map[string]map[string]Handler
}

// Registers a handler
func (hmap *handlerMap) register(h Handler, serviceName, operation string) {
	hmap.mut.Lock()
	defer hmap.mut.Unlock()

	if hmap.handlers == nil {
		hmap.handlers = make(map[string]map[string]Handler)
	}

	operations := hmap.handlers[serviceName]
	if operations == nil {
		operations = make(map[string]Handler)
		hmap.handlers[serviceName] = operations
	}

	operations[operation] = h
}

// Finds the handler matching the given service and operation.  See https://github.com/golang/go/issues/3512
// for the reason that operation is []byte instead of a string
func (hmap *handlerMap) find(serviceName string, operation []byte) Handler {
	hmap.mut.RLock()
	handler := hmap.handlers[serviceName][string(operation)]
	hmap.mut.RUnlock()

	return handler
}
<commit_msg>Embed mutex in handlerMap<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

package tchannel

import (
	"sync"

	"golang.org/x/net/context"
)

// A Handler is an object that can be registered with a Channel to process
// incoming calls for a given service and operation
type Handler interface {
	// Handles an incoming call for service
	Handle(ctx context.Context, call *InboundCall)
}

// A HandlerFunc is an adapter to allow the use of ordering functions as
// Channel handlers.  If f is a function with the appropriate signature,
// HandlerFunc(f) is a Hander object that calls f
type HandlerFunc func(ctx context.Context, call *InboundCall)

// Handle calls f(ctx, call)
func (f HandlerFunc) Handle(ctx context.Context, call *InboundCall) { f(ctx, call) }

// Manages handlers
type handlerMap struct {
	sync.RWMutex

	handlers map[string]map[string]Handler
}

// Registers a handler
func (hmap *handlerMap) register(h Handler, serviceName, operation string) {
	hmap.Lock()
	defer hmap.Unlock()

	if hmap.handlers == nil {
		hmap.handlers = make(map[string]map[string]Handler)
	}

	operations := hmap.handlers[serviceName]
	if operations == nil {
		operations = make(map[string]Handler)
		hmap.handlers[serviceName] = operations
	}

	operations[operation] = h
}

// Finds the handler matching the given service and operation.  See https://github.com/golang/go/issues/3512
// for the reason that operation is []byte instead of a string
func (hmap *handlerMap) find(serviceName string, operation []byte) Handler {
	hmap.RLock()
	handler := hmap.handlers[serviceName][string(operation)]
	hmap.RUnlock()

	return handler
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"fmt"
	"html"
	"io"
	"io/ioutil"
	"net/http"

	"github.com/gorilla/mux"
)

func Index(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}

func TodoIndex(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)

	if err := json.NewEncoder(w).Encode(todos); err != nil {
		panic(err)
	}
}

func TodoShow(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	todoID := vars["todoID"]
	fmt.Fprintln(w, "Todo show:", todoID)
}

func TodoCreate(w http.ResponseWriter, r *http.Request) {
	var todo Todo
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
	if err != nil {
		panic(err)
	}
	if err := r.Body.Close(); err != nil {
		panic(err)
	}
	if err := json.Unmarshal(body, &todo); err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(422) // unprocessable entity
		if err := json.NewEncoder(w).Encode(err); err != nil {
			panic(err)
		}
	}

	t := RepoCreateTodo(&todo)
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusCreated)
	if err := json.NewEncoder(w).Encode(t); err != nil {
		panic(err)
	}
}

func TodoCreateMany(w http.ResponseWriter, r *http.Request) {
	// Request body should conform to a JSON API format.
	var newTodos = make(map[string]TodosToAdd)
	// var newTodos TodosToAdd
	var response []Todo
	dec := json.NewDecoder(r.Body)

	if err := dec.Decode(&newTodos); err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(422) // unprocessable entity
		if err := json.NewEncoder(w).Encode(err); err != nil {
			panic(err)
		}
	}

	for _, todo := range newTodos["data"].Todos {
		t := RepoCreateTodo(&todo)
		response = append(response, t)
	}

	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusCreated)
	if err := json.NewEncoder(w).Encode(response); err != nil {
		panic(err)
	}
}
<commit_msg>Format responses.<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"html"
	"io"
	"io/ioutil"
	"net/http"

	"github.com/gorilla/mux"
)

func Index(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello, %q", html.EscapeString(r.URL.Path))
}

func TodoIndex(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)

	m := make(map[string]interface{})
	m["data"] = todos

	if err := json.NewEncoder(w).Encode(m); err != nil {
		panic(err)
	}
}

func TodoShow(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	todoID := vars["todoID"]
	fmt.Fprintln(w, "Todo show:", todoID)
}

func TodoCreate(w http.ResponseWriter, r *http.Request) {
	var req = make(map[string]Todo)
	// b := io.LimitReader(r.Body, 1048567)
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
	if err != nil {
		panic(err)
	}
	if err := r.Body.Close(); err != nil {
		panic(err)
	}
	if err := json.Unmarshal(body, &req); err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(422) // unprocessable entity
		if err := json.NewEncoder(w).Encode(err); err != nil {
			panic(err)
		}
	}

	newTodo := req["data"]
	t := RepoCreateTodo(&newTodo)
	res := map[string]Todo{"data": t}
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusCreated)
	if err := json.NewEncoder(w).Encode(res); err != nil {
		panic(err)
	}
}

func TodoCreateMany(w http.ResponseWriter, r *http.Request) {
	// Request body should conform to a JSON API format.
	var newTodos = make(map[string]TodosToAdd)
	// var newTodos TodosToAdd
	var response []Todo
	dec := json.NewDecoder(r.Body)

	if err := dec.Decode(&newTodos); err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(422) // unprocessable entity
		if err := json.NewEncoder(w).Encode(err); err != nil {
			panic(err)
		}
	}

	for _, todo := range newTodos["data"].Todos {
		t := RepoCreateTodo(&todo)
		response = append(response, t)
	}

	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusCreated)
	if err := json.NewEncoder(w).Encode(response); err != nil {
		panic(err)
	}
}
<|endoftext|>


<commit_before>package main

/*
 * Copyright 2014 Albert P. Tobey <atobey@datastax.com> @AlTobey
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * main.go: http server application for cassandra-summit-cfp-review
 *
 */

import (
	"encoding/json"
	"fmt"
	"github.com/gocql/gocql"
	"github.com/gorilla/mux"
	"log"
	"net/http"
	"time"
)

func RootHandler(w http.ResponseWriter, r *http.Request) {
	// check for auth but ignore the result: this will initialize
	// the cookie on page load
	checkAuth(w, r)
	http.ServeFile(w, r, "./public/index.html")
}

func AbstractsHandler(w http.ResponseWriter, r *http.Request) {
	if !checkAuth(w, r) {
		return
	}

	a := Abstract{}
	dec := json.NewDecoder(r.Body)
	err := dec.Decode(&a)

	switch r.Method {
	case "GET":
		alist, err := ListAbstracts(cass)
		if err != nil {
			http.Error(w, fmt.Sprintf("Failed to list abstracts: %s", err), 500)
		}
		jsonOut(w, r, alist)
		return
	case "PUT":
		if err != nil {
			http.Error(w, fmt.Sprintf("AbstractsHandler/PUT invalid json data: %s", err), 500)
		}

		a.Id = gocql.TimeUUID()
		a.Created = time.Now()
	case "PATCH":
		if err != nil {
			http.Error(w, fmt.Sprintf("AbstractsHandler/PATCH invalid json data: %s", err), 500)
		}
	default:
		http.Error(w, fmt.Sprintf("method '%s' not implemented", r.Method), 500)
		return
	}

	// bare minimum input checking
	if a.Title == "" || a.Body == "" || len(a.Attrs) == 0 || len(a.Authors) == 0 {
		http.Error(w, "required field missing", 500)
		return
	}

	err = a.Save(cass)
	if err != nil {
		http.Error(w, fmt.Sprintf("AbstractsHandler/PUT a.Save() failed: %s", err), 500)
	}

	jsonOut(w, r, a)
}

func AbstractHandler(w http.ResponseWriter, r *http.Request) {
	if !checkAuth(w, r) {
		return
	}

	vars := mux.Vars(r)
	id, err := gocql.ParseUUID(vars["id"])
	if err != nil {
		http.Error(w, fmt.Sprintf("could not parse uuid: '%s'", err), 500)
	}
	a, _ := GetAbstract(cass, id)
	jsonOut(w, r, a)
}

func ScoreUpdateHandler(w http.ResponseWriter, r *http.Request) {
	if !checkAuth(w, r) {
		return
	}
	scores := make(ScoreUpdates, 7)
	dec := json.NewDecoder(r.Body)
	err := dec.Decode(&scores)
	if err != nil {
		log.Printf("invalid score update json: %s\n", err)
		http.Error(w, fmt.Sprintf("invalid score update json: %s", err), 500)
	}

	err = scores.Save(cass)
	if err != nil {
		log.Printf("score update failed: %s\n", err)
		http.Error(w, fmt.Sprintf("score update failed: %s", err), 500)
	}

	jsonOut(w, r, scores)
}

// returns the email string if authenticated (via persona), it won't
// be there at all if the user didn't authenticate
func checkAuth(w http.ResponseWriter, r *http.Request) bool {
	log.Println("checkAuth()")
	sess, err := store.Get(r, sessCookie)
	if err != nil {
		http.Error(w, fmt.Sprintf("failed to read cookie: %s\n", err), 400)
		return false
	}

	if sess.IsNew {
		log.Printf("Saving session ID '%s' to Cassandra.\n", sess.ID)
		sess.Save(r, w)
	}

	if sess.Values["email"] != nil {
		email := sess.Values["email"].(string)
		log.Printf("sess.Values[email]: '%s'\n", sess.Values["email"])
		if email != "" {
			return true
		}
	}

	return false
}
<commit_msg>Log errors along with 500's<commit_after>package main

/*
 * Copyright 2014 Albert P. Tobey <atobey@datastax.com> @AlTobey
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * main.go: http server application for cassandra-summit-cfp-review
 *
 */

import (
	"encoding/json"
	"fmt"
	"github.com/gocql/gocql"
	"github.com/gorilla/mux"
	"log"
	"net/http"
	"time"
)

func RootHandler(w http.ResponseWriter, r *http.Request) {
	// check for auth but ignore the result: this will initialize
	// the cookie on page load
	checkAuth(w, r)
	http.ServeFile(w, r, "./public/index.html")
}

func AbstractsHandler(w http.ResponseWriter, r *http.Request) {
	if !checkAuth(w, r) {
		return
	}

	a := Abstract{}
	dec := json.NewDecoder(r.Body)
	err := dec.Decode(&a)

	switch r.Method {
	case "GET":
		alist, err := ListAbstracts(cass)
		if err != nil {
			http.Error(w, fmt.Sprintf("Failed to list abstracts: %s", err), 500)
		}
		jsonOut(w, r, alist)
		return
	case "PUT":
		if err != nil {
			log.Printf("AbstractsHandler/PUT invalid json data: %s", err)
			http.Error(w, fmt.Sprintf("AbstractsHandler/PUT invalid json data: %s", err), 500)
		}

		a.Id = gocql.TimeUUID()
		a.Created = time.Now()
	case "PATCH":
		if err != nil {
			log.Printf("AbstractsHandler/PATCH invalid json data: %s", err)
			http.Error(w, fmt.Sprintf("AbstractsHandler/PATCH invalid json data: %s", err), 500)
		}
	default:
		http.Error(w, fmt.Sprintf("method '%s' not implemented", r.Method), 500)
		return
	}

	// bare minimum input checking
	if a.Title == "" || a.Body == "" || len(a.Attrs) == 0 || len(a.Authors) == 0 {
		log.Printf("AbstractsHandle required field missing")
		http.Error(w, "required field missing", 500)
		return
	}

	err = a.Save(cass)
	if err != nil {
		http.Error(w, fmt.Sprintf("AbstractsHandler/PUT a.Save() failed: %s", err), 500)
	}

	jsonOut(w, r, a)
}

func AbstractHandler(w http.ResponseWriter, r *http.Request) {
	if !checkAuth(w, r) {
		return
	}

	vars := mux.Vars(r)
	id, err := gocql.ParseUUID(vars["id"])
	if err != nil {
		http.Error(w, fmt.Sprintf("could not parse uuid: '%s'", err), 500)
	}
	a, _ := GetAbstract(cass, id)
	jsonOut(w, r, a)
}

func ScoreUpdateHandler(w http.ResponseWriter, r *http.Request) {
	if !checkAuth(w, r) {
		return
	}
	scores := make(ScoreUpdates, 7)
	dec := json.NewDecoder(r.Body)
	err := dec.Decode(&scores)
	if err != nil {
		log.Printf("invalid score update json: %s\n", err)
		http.Error(w, fmt.Sprintf("invalid score update json: %s", err), 500)
	}

	err = scores.Save(cass)
	if err != nil {
		log.Printf("score update failed: %s\n", err)
		http.Error(w, fmt.Sprintf("score update failed: %s", err), 500)
	}

	jsonOut(w, r, scores)
}

// returns the email string if authenticated (via persona), it won't
// be there at all if the user didn't authenticate
func checkAuth(w http.ResponseWriter, r *http.Request) bool {
	log.Println("checkAuth()")
	sess, err := store.Get(r, sessCookie)
	if err != nil {
		http.Error(w, fmt.Sprintf("failed to read cookie: %s\n", err), 400)
		return false
	}

	if sess.IsNew {
		log.Printf("Saving session ID '%s' to Cassandra.\n", sess.ID)
		sess.Save(r, w)
	}

	if sess.Values["email"] != nil {
		email := sess.Values["email"].(string)
		log.Printf("sess.Values[email]: '%s'\n", sess.Values["email"])
		if email != "" {
			return true
		}
	}

	return false
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/zenazn/goji"

	"log"
	"net/http"
	"os"
)

// serveStatic makes sure that if Chinchilla is running for development
// purposes, it serves static content from /static
// simple function with side-effects
func serveStatic() {
	buildMode := os.Getenv("chinchilla")
	switch buildMode {
	case "development", "":
		log.Println(info("Enabling static file serving dir: %s", "static/"))
		goji.Handle("/", http.FileServer(http.Dir("static")))
	case "production":
		return
	default:
		return
	}
}
<commit_msg>implemted goji handler for development purposes, serving files in /static when not hitting any /api/*<commit_after>package main

import (
	"github.com/zenazn/goji"
	"github.com/zenazn/goji/web"

	"log"
	"net/http"
	"os"
	"strings"
)

// ReverseStringPattern is a simple struct keeping the raw string
// and the prefix to skip in requests
type ReverseStringPattern struct {
	raw    string
	prefix string
}

// prefix returns "" so goji doesn't ever skip the matching function
func (s ReverseStringPattern) Prefix() string {
	return ""
}
func (s ReverseStringPattern) Match(r *http.Request, c *web.C) bool {
	path := r.URL.Path
	return !strings.HasPrefix(path, s.prefix)
}
func (s ReverseStringPattern) Run(r *http.Request, c *web.C) {}

func NewReverseStringPattern(s string) ReverseStringPattern {
	var prefix string = s
	if strings.HasSuffix(s, "*") {
		prefix = s[:len(s)-1]
	}
	return ReverseStringPattern{raw: s, prefix: prefix}
}

// serveStatic makes sure that if running for development
// purposes, it serves static content from /static
func serveStatic() {
	buildMode := os.Getenv("chinchilla")
	switch buildMode {
	case "development", "":
		log.Println(info("Enabling static file serving dir: %s", "static/"))
		reverseApiPattern := NewReverseStringPattern("/api/*")
		goji.Handle(reverseApiPattern, http.FileServer(http.Dir("static")))
	case "production":
		return
	default:
		return
	}
}
<|endoftext|>


<commit_before>package gnosis

// package file will contain MarkdownHandler and RawHandler to handle incoming requests
// Whole thing needs to be written

import (
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"regexp"

	"github.com/JackKnifed/blackfriday"
)

var fileFilter = regexp.MustCompile("^(/([a-zA-Z0-9_ /]+/)?)([a-zA-Z0-9_ ]+)?(\\.)?([a-zA-Z0-9_ ]+)?")

func RawHandler(responsePipe http.ResponseWriter, request *http.Request) {
	var err error

	filteredRequest := wikiFilter.FindStringSubmatch(request.URL.Path)
	config := GetConfig()

	if filteredRequest == nil {
		log.Printf("null request improperly routed to wiki handler %s", request.URL.Path, config.Mainserver.Prefix)
		http.Error(responsePipe, "Request not allowed", 403)
	}

	if filteredRequest[1] != config.Mainserver.Prefix {
		log.Printf("request %s was improperly routed to wiki handler %s", request.URL.Path, config.Mainserver.Prefix)
		http.Error(responsePipe, err.Error(), 500)
	}

	contents, err := ioutil.ReadFile(config.Mainserver.Prefix + filteredRequest[2] + ".md")
	if err != nil {
		log.Printf("request %s points to an bad file target sent to server %s", request.URL.Path, config.Mainserver.Prefix)
		http.Error(responsePipe, err.Error(), 403)
	}

	_, err = responsePipe.Write([]byte(contents))
	if err != nil {
		http.Error(responsePipe, err.Error(), 500)
	}
}

const (
	bodyHtmlFlags = 0 |
		blackfriday.HTML_USE_XHTML |
		blackfriday.HTML_USE_SMARTYPANTS |
		blackfriday.HTML_SMARTYPANTS_FRACTIONS |
		blackfriday.HTML_SMARTYPANTS_LATEX_DASHES

	bodyExtensions = 0 |
		blackfriday.EXTENSION_NO_INTRA_EMPHASIS |
		blackfriday.EXTENSION_TABLES |
		blackfriday.EXTENSION_FENCED_CODE |
		blackfriday.EXTENSION_AUTOLINK |
		blackfriday.EXTENSION_STRIKETHROUGH |
		blackfriday.EXTENSION_SPACE_HEADERS |
		blackfriday.EXTENSION_AUTO_HEADER_IDS |
		blackfriday.EXTENSION_TITLEBLOCK

	tocHtmlFlags = 0 |
		blackfriday.HTML_USE_XHTML |
		blackfriday.HTML_SMARTYPANTS_FRACTIONS |
		blackfriday.HTML_SMARTYPANTS_LATEX_DASHES |
		blackfriday.HTML_TOC |
		blackfriday.HTML_OMIT_CONTENTS

	tocExtensions = 0 |
		blackfriday.EXTENSION_NO_INTRA_EMPHASIS |
		blackfriday.EXTENSION_TABLES |
		blackfriday.EXTENSION_FENCED_CODE |
		blackfriday.EXTENSION_AUTOLINK |
		blackfriday.EXTENSION_STRIKETHROUGH |
		blackfriday.EXTENSION_SPACE_HEADERS |
		blackfriday.EXTENSION_AUTO_HEADER_IDS |
		blackfriday.EXTENSION_TITLEBLOCK
)

type WikiPage struct {
	Title string
	ToC   template.HTML
	Body  template.HTML
}

var templates = template.Must(template.ParseFiles("wiki.html"))

var wikiFilter = regexp.MustCompile("^(/([a-zA-Z0-9_ /]+/)?)([a-zA-Z0-9_ ]+)$")

func bodyParseMarkdown(input []byte) []byte {
	// set up the HTML renderer
	renderer := blackfriday.HtmlRenderer(bodyHtmlFlags, "", "")
	return blackfriday.Markdown(input, renderer, bodyExtensions)
}

func tocParseMarkdown(input []byte) []byte {
	// set up the HTML renderer
	renderer := blackfriday.HtmlRenderer(tocHtmlFlags, "", "")
	return blackfriday.Markdown(input, renderer, tocExtensions)
}

func MarkdownHandler(responsePipe http.ResponseWriter, request *http.Request) {
	var err error

	filteredRequest := wikiFilter.FindStringSubmatch(request.URL.Path)

	config := GetConfig()
	if filteredRequest == nil {
		log.Printf("null request [ %s ] improperly routed to wiki handler [ %s ]", request.URL.Path, config.Mainserver.Prefix)
		http.Error(responsePipe, "Request not allowed", 403)
	} else {
		if filteredRequest[1] != config.Mainserver.Prefix {
			log.Printf("request %s was improperly routed to wiki handler %s", request.URL.Path, config.Mainserver.Prefix)
			http.Error(responsePipe, err.Error(), 500)
		}

		contents, err := ioutil.ReadFile(config.Mainserver.Path + filteredRequest[3] + ".md")
		if err != nil {
			log.Printf("request [ %s ] points to an bad file target [ %s ]sent to server %s", request.URL.Path, filteredRequest[3], config.Mainserver.Prefix)
			http.Error(responsePipe, err.Error(), 403)
		}
		// parse any markdown in the input
		body := template.HTML(bodyParseMarkdown(contents))

		toc := template.HTML(tocParseMarkdown(contents))

		response := WikiPage{Title: filteredRequest[3], ToC: toc, Body: body}
		err = templates.ExecuteTemplate(responsePipe, "wiki.html", response)
		if err != nil {
			http.Error(responsePipe, err.Error(), 500)
		}
	}
}

// Generate a Markdown Handler Function
func ConfiguredMarkdownHandler(responsePipe http.ResponseWriter, request *http.Request, serverConfig ServerSection) http.HandlerFunc {

	return func(resposePipe http.ResponseWriter, request *http.Request) {

		var err error

		// break up the request parameters - for reference, regex is listed below
		filteredRequest := wikiFilter.FindStringSubmatch(request.URL.Path)

		// if there are no matches, the regex ovbiously didn't match up
		if filteredRequest == nil {
			log.Printf("null request [ %s ] improperly routed to wiki handler [ %s ]", request.URL.Path, serverConfig.Prefix)
			http.Error(responsePipe, "Request not allowed", 403)
		} else {
			if filteredRequest[1] != serverConfig.Prefix {
				log.Printf("request %s was improperly routed to wiki handler %s", request.URL.Path, serverConfig.Prefix)
				http.Error(responsePipe, err.Error(), 500)
			}

			contents, err := ioutil.ReadFile(serverConfig.Path + filteredRequest[3] + ".md")
			if err != nil {
				log.Printf("request [ %s ] points to an bad file target [ %s ]sent to server %s", request.URL.Path, filteredRequest[3], serverConfig.Prefix)
				http.Error(responsePipe, err.Error(), 404)
			}
			// parse any markdown in the input
			body := template.HTML(bodyParseMarkdown(contents))

			toc := template.HTML(tocParseMarkdown(contents))

			response := WikiPage{Title: filteredRequest[3], ToC: toc, Body: body}
			err = templates.ExecuteTemplate(responsePipe, serverConfig.Template, response)
			if err != nil {
				http.Error(responsePipe, err.Error(), 500)
			}
		}
	}
}

func makeHandler(handlerConfig ServerSection)) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		switch handlerConfig.ServerType {
			case "markdown":
				ConfiguredMarkdownHandler(w, r, handlerConfig)
			case "raw":
				ConfiguredRawHandler(w, r, handlerConfig)
			default:
				log.printf("Bad server type [%s]", handlerConfig.ServerType)
		}
	}
}

/*
func GenerateRawHandler(responsePipe http.ResponseWriter, request *http.Request, serverConfig ServerSection) {
	return func(responsePipe http.responseWriter, request *http.Request) {
		var err error

		filteredRequest := wikiFilter.FindStringSubmatch(request.URL.Path)

		if filteredRequest == nil {
			log.Printf("null request improperly routed to wiki handler %s", request.URL.Path, config.Mainserver.Prefix)
			http.Error(responsePipe, "Request not allowed", 403)
		}

		if filteredRequest[1] != config.Mainserver.Prefix {
			log.Printf("request %s was improperly routed to wiki handler %s", request.URL.Path, config.Mainserver.Prefix)
			http.Error(responsePipe, err.Error(), 500)
		}

		contents, err := ioutil.ReadFile(config.Mainserver.Prefix + filteredRequest[2] + ".md")
		if err != nil {
			log.Printf("request %s points to an bad file target sent to server %s", request.URL.Path, config.Mainserver.Prefix)
			http.Error(responsePipe, err.Error(), 403)
		}

		_, err = responsePipe.Write([]byte(contents))
		if err != nil {
			http.Error(responsePipe, err.Error(), 500)
		}
	}
}
*/
<commit_msg>the package compiles, but for some reason pages aren't being loaded?<commit_after>package gnosis

// package file will contain MarkdownHandler and RawHandler to handle incoming requests
// Whole thing needs to be written

import (
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"regexp"

	"github.com/JackKnifed/blackfriday"
)

var fileFilter = regexp.MustCompile("^(/([a-zA-Z0-9_ /]+/)?)([a-zA-Z0-9_ ]+)?(\\.)?([a-zA-Z0-9_ ]+)?")

func RawHandler(responsePipe http.ResponseWriter, request *http.Request) {
	var err error

	filteredRequest := wikiFilter.FindStringSubmatch(request.URL.Path)
	config := GetConfig()

	if filteredRequest == nil {
		log.Printf("null request improperly routed to wiki handler %s", request.URL.Path, config.Mainserver.Prefix)
		http.Error(responsePipe, "Request not allowed", 403)
	}

	if filteredRequest[1] != config.Mainserver.Prefix {
		log.Printf("request %s was improperly routed to wiki handler %s", request.URL.Path, config.Mainserver.Prefix)
		http.Error(responsePipe, err.Error(), 500)
	}

	contents, err := ioutil.ReadFile(config.Mainserver.Prefix + filteredRequest[2] + ".md")
	if err != nil {
		log.Printf("request %s points to an bad file target sent to server %s", request.URL.Path, config.Mainserver.Prefix)
		http.Error(responsePipe, err.Error(), 403)
	}

	_, err = responsePipe.Write([]byte(contents))
	if err != nil {
		http.Error(responsePipe, err.Error(), 500)
	}
}

const (
	bodyHtmlFlags = 0 |
		blackfriday.HTML_USE_XHTML |
		blackfriday.HTML_USE_SMARTYPANTS |
		blackfriday.HTML_SMARTYPANTS_FRACTIONS |
		blackfriday.HTML_SMARTYPANTS_LATEX_DASHES

	bodyExtensions = 0 |
		blackfriday.EXTENSION_NO_INTRA_EMPHASIS |
		blackfriday.EXTENSION_TABLES |
		blackfriday.EXTENSION_FENCED_CODE |
		blackfriday.EXTENSION_AUTOLINK |
		blackfriday.EXTENSION_STRIKETHROUGH |
		blackfriday.EXTENSION_SPACE_HEADERS |
		blackfriday.EXTENSION_AUTO_HEADER_IDS |
		blackfriday.EXTENSION_TITLEBLOCK

	tocHtmlFlags = 0 |
		blackfriday.HTML_USE_XHTML |
		blackfriday.HTML_SMARTYPANTS_FRACTIONS |
		blackfriday.HTML_SMARTYPANTS_LATEX_DASHES |
		blackfriday.HTML_TOC |
		blackfriday.HTML_OMIT_CONTENTS

	tocExtensions = 0 |
		blackfriday.EXTENSION_NO_INTRA_EMPHASIS |
		blackfriday.EXTENSION_TABLES |
		blackfriday.EXTENSION_FENCED_CODE |
		blackfriday.EXTENSION_AUTOLINK |
		blackfriday.EXTENSION_STRIKETHROUGH |
		blackfriday.EXTENSION_SPACE_HEADERS |
		blackfriday.EXTENSION_AUTO_HEADER_IDS |
		blackfriday.EXTENSION_TITLEBLOCK
)

type WikiPage struct {
	Title string
	ToC   template.HTML
	Body  template.HTML
}

var templates = template.Must(template.ParseFiles("wiki.html"))

var wikiFilter = regexp.MustCompile("^(/([a-zA-Z0-9_ /]+/)?)([a-zA-Z0-9_ ]+)$")

func bodyParseMarkdown(input []byte) []byte {
	// set up the HTML renderer
	renderer := blackfriday.HtmlRenderer(bodyHtmlFlags, "", "")
	return blackfriday.Markdown(input, renderer, bodyExtensions)
}

func tocParseMarkdown(input []byte) []byte {
	// set up the HTML renderer
	renderer := blackfriday.HtmlRenderer(tocHtmlFlags, "", "")
	return blackfriday.Markdown(input, renderer, tocExtensions)
}

func MarkdownHandler(responsePipe http.ResponseWriter, request *http.Request) {
	var err error

	filteredRequest := wikiFilter.FindStringSubmatch(request.URL.Path)

	config := GetConfig()
	if filteredRequest == nil {
		log.Printf("null request [ %s ] improperly routed to wiki handler [ %s ]", request.URL.Path, config.Mainserver.Prefix)
		http.Error(responsePipe, "Request not allowed", 403)
	} else {
		if filteredRequest[1] != config.Mainserver.Prefix {
			log.Printf("request %s was improperly routed to wiki handler %s", request.URL.Path, config.Mainserver.Prefix)
			http.Error(responsePipe, err.Error(), 500)
		}

		contents, err := ioutil.ReadFile(config.Mainserver.Path + filteredRequest[3] + ".md")
		if err != nil {
			log.Printf("request [ %s ] points to an bad file target [ %s ]sent to server %s", request.URL.Path, filteredRequest[3], config.Mainserver.Prefix)
			http.Error(responsePipe, err.Error(), 403)
		}
		// parse any markdown in the input
		body := template.HTML(bodyParseMarkdown(contents))

		toc := template.HTML(tocParseMarkdown(contents))

		response := WikiPage{Title: filteredRequest[3], ToC: toc, Body: body}
		err = templates.ExecuteTemplate(responsePipe, "wiki.html", response)
		if err != nil {
			http.Error(responsePipe, err.Error(), 500)
		}
	}
}

// Generate a Markdown Handler Function
func ConfiguredMarkdownHandler(responsePipe http.ResponseWriter, request *http.Request, serverConfig ServerSection) http.HandlerFunc {

	return func(resposePipe http.ResponseWriter, request *http.Request) {

		var err error

		// break up the request parameters - for reference, regex is listed below
		filteredRequest := wikiFilter.FindStringSubmatch(request.URL.Path)

		// if there are no matches, the regex ovbiously didn't match up
		if filteredRequest == nil {
			log.Printf("null request [ %s ] improperly routed to wiki handler [ %s ]", request.URL.Path, serverConfig.Prefix)
			http.Error(responsePipe, "Request not allowed", 403)
		} else {
			if filteredRequest[1] != serverConfig.Prefix {
				log.Printf("request %s was improperly routed to wiki handler %s", request.URL.Path, serverConfig.Prefix)
				http.Error(responsePipe, err.Error(), 500)
			}

			contents, err := ioutil.ReadFile(serverConfig.Path + filteredRequest[3] + ".md")
			if err != nil {
				log.Printf("request [ %s ] points to an bad file target [ %s ]sent to server %s", request.URL.Path, filteredRequest[3], serverConfig.Prefix)
				http.Error(responsePipe, err.Error(), 404)
			}
			// parse any markdown in the input
			body := template.HTML(bodyParseMarkdown(contents))

			toc := template.HTML(tocParseMarkdown(contents))

			response := WikiPage{Title: filteredRequest[3], ToC: toc, Body: body}
			err = templates.ExecuteTemplate(responsePipe, serverConfig.Template, response)
			if err != nil {
				http.Error(responsePipe, err.Error(), 500)
			}
		}
	}
}

func MakeHandler(handlerConfig ServerSection) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		switch handlerConfig.ServerType {
		case "markdown":
			ConfiguredMarkdownHandler(w, r, handlerConfig)
			//		case "raw":
			//			ConfiguredRawHandler(w, r, handlerConfig)
		default:
			log.Printf("Bad server type [%s]", handlerConfig.ServerType)
		}
	}
}

/*
func GenerateRawHandler(responsePipe http.ResponseWriter, request *http.Request, serverConfig ServerSection) {
	return func(responsePipe http.responseWriter, request *http.Request) {
		var err error

		filteredRequest := wikiFilter.FindStringSubmatch(request.URL.Path)

		if filteredRequest == nil {
			log.Printf("null request improperly routed to wiki handler %s", request.URL.Path, config.Mainserver.Prefix)
			http.Error(responsePipe, "Request not allowed", 403)
		}

		if filteredRequest[1] != config.Mainserver.Prefix {
			log.Printf("request %s was improperly routed to wiki handler %s", request.URL.Path, config.Mainserver.Prefix)
			http.Error(responsePipe, err.Error(), 500)
		}

		contents, err := ioutil.ReadFile(config.Mainserver.Prefix + filteredRequest[2] + ".md")
		if err != nil {
			log.Printf("request %s points to an bad file target sent to server %s", request.URL.Path, config.Mainserver.Prefix)
			http.Error(responsePipe, err.Error(), 403)
		}

		_, err = responsePipe.Write([]byte(contents))
		if err != nil {
			http.Error(responsePipe, err.Error(), 500)
		}
	}
}
*/
<|endoftext|>


<commit_before>// Package preprocessor provides a basic source code preprocessor, emulating
// the C preprocessor.
package preprocessor

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"strings"
)

// A Preprocessor processes directives in source code to perform certain
// actions before any other processing stages occur.
type Preprocessor struct {
	s       *bufio.Scanner
	defines map[string]string

	// Define is a function which indicates how "#define" directives should
	// be handled.
	//
	// This function will be invoked with the name of a preprocessor constant
	// and its value.  The appropriate name and value should be returned to
	// register them with the Preprocessor.  If an error is returned by Define,
	// Preprocessor.Process is halted and the error is returned.
	//
	// If nil, the name and value are left unchanged and registered with the
	// Preprocessor.
	Define func(name string, value string) (outName string, outValue string, err error)

	// Include is a function which indicates how "#include" directives should
	// be handled.
	//
	// This function will be invoked with the name of a source file for
	// inclusion in the code.  The source code of the file should be returned
	// to replace the include directive with the source code.  If an error is
	// returned by Include, Preprocessor.Process is halted and the error is
	// returned.
	//
	// If nil, name attempts to open a file in the filesystem, returning its
	// contents for inclusion in the output source code.
	Include func(name string) (src []byte, err error)
}

// New creates a new Preprocessor using the input io.Reader.
func New(r io.Reader) *Preprocessor {
	return &Preprocessor{
		s:       bufio.NewScanner(r),
		defines: make(map[string]string, 0),

		Define: func(name string, value string) (string, string, error) {
			return name, value, nil
		},

		Include: ioutil.ReadFile,
	}
}

var (
	bufDefine  = []byte("#define")
	bufInclude = []byte("#include")
)

// Process invokes the Preprocessor, handling directives as necessary, and
// returning the modified source code.
func (p *Preprocessor) Process() ([]byte, error) {
	var src []byte
	for p.s.Scan() {
		b := p.s.Bytes()
		switch {
		case bytes.HasPrefix(b, bufDefine):
			// Syntax:
			//   - #define FOO_BITS 8
			//   - #define FOO_BAR "foo bar"
			f := bytes.Fields(b)
			if len(f) < 3 {
				return nil, fmt.Errorf("invalid define preprocessor directive: %q", string(b))
			}

			name := string(f[1])
			// TODO(mdlayher): don't mangle spaces in define value
			value := string(bytes.Join(f[2:], []byte(" ")))

			outName, outValue, err := p.Define(name, value)
			if err != nil {
				return nil, fmt.Errorf("preprocessor error while defining %q as %q: %v", outName, outValue, err)
			}

			p.defines[outName] = outValue
		case bytes.HasPrefix(b, bufInclude):
			// Syntax:
			//   - #include "foo.p4"
			//   - #include "foo/bar.p4"
			f := bytes.Fields(b)
			if len(f) != 2 {
				return nil, fmt.Errorf("invalid include preprocessor directive: %q", string(b))
			}

			name := strings.Trim(string(f[1]), `"`)
			inc, err := p.Include(name)
			if err != nil {
				return nil, fmt.Errorf("preprocessor error while including %q: %v", name, err)
			}

			src = append(src, inc...)
		default:
			for k, v := range p.defines {
				b = bytes.Replace(b, []byte(k), []byte(v), -1)
			}

			// bufio.Scanner removes trailing newlines so we need to put it back
			src = append(src, append(b, '\n')...)
		}
	}

	if err := p.s.Err(); err != nil {
		return nil, err
	}

	return src, nil
}
<commit_msg>preprocessor: make define and include docs more truthful<commit_after>// Package preprocessor provides a basic source code preprocessor, emulating
// the C preprocessor.
package preprocessor

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"strings"
)

// A Preprocessor processes directives in source code to perform certain
// actions before any other processing stages occur.
type Preprocessor struct {
	// Define is a function which indicates how "#define" directives should
	// be handled.
	//
	// This function will be invoked with the name of a preprocessor constant
	// and its value.  The appropriate name and value should be returned to
	// register them with the Preprocessor.  If an error is returned by Define,
	// Preprocessor.Process is halted and the error is returned.
	//
	// If nil, the name and value are left unchanged and registered with the
	// Preprocessor.
	Define func(name string, value string) (outName string, outValue string, err error)

	// Include is a function which indicates how "#include" directives should
	// be handled.
	//
	// This function will be invoked with the name of a source file for
	// inclusion in the code.  The source code of the file should be returned
	// to replace the include directive with the source code.  If an error is
	// returned by Include, Preprocessor.Process is halted and the error is
	// returned.
	//
	// If nil, name attempts to open a file in the filesystem, returning its
	// contents for inclusion in the output source code.
	Include func(name string) (src []byte, err error)

	s       *bufio.Scanner
	defines map[string]string
}

// New creates a new Preprocessor using the input io.Reader.
func New(r io.Reader) *Preprocessor {
	return &Preprocessor{
		s:       bufio.NewScanner(r),
		defines: make(map[string]string, 0),
	}
}

var (
	bufDefine  = []byte("#define")
	bufInclude = []byte("#include")
)

// Process invokes the Preprocessor, handling directives as necessary, and
// returning the modified source code.
func (p *Preprocessor) Process() ([]byte, error) {
	var src []byte
	for p.s.Scan() {
		b := p.s.Bytes()
		switch {
		case bytes.HasPrefix(b, bufDefine):
			// Syntax:
			//   - #define FOO_BITS 8
			//   - #define FOO_BAR "foo bar"
			f := bytes.Fields(b)
			if len(f) < 3 {
				return nil, fmt.Errorf("invalid define preprocessor directive: %q", string(b))
			}

			name := string(f[1])
			// TODO(mdlayher): don't mangle spaces in define value
			value := string(bytes.Join(f[2:], []byte(" ")))

			define := p.Define
			if define == nil {
				define = defineNoChanges
			}

			outName, outValue, err := define(name, value)
			if err != nil {
				return nil, fmt.Errorf("preprocessor error while defining %q as %q: %v", outName, outValue, err)
			}

			p.defines[outName] = outValue
		case bytes.HasPrefix(b, bufInclude):
			// Syntax:
			//   - #include "foo.p4"
			//   - #include "foo/bar.p4"
			f := bytes.Fields(b)
			if len(f) != 2 {
				return nil, fmt.Errorf("invalid include preprocessor directive: %q", string(b))
			}

			include := p.Include
			if include == nil {
				include = ioutil.ReadFile
			}

			name := strings.Trim(string(f[1]), `"`)
			inc, err := include(name)
			if err != nil {
				return nil, fmt.Errorf("preprocessor error while including %q: %v", name, err)
			}

			src = append(src, inc...)
		default:
			for k, v := range p.defines {
				b = bytes.Replace(b, []byte(k), []byte(v), -1)
			}

			// bufio.Scanner removes trailing newlines so we need to put it back
			src = append(src, append(b, '\n')...)
		}
	}

	if err := p.s.Err(); err != nil {
		return nil, err
	}

	return src, nil
}

// defineNoChanges is the default Preprocessor.Define function.
func defineNoChanges(name string, value string) (string, string, error) {
	return name, value, nil
}
<|endoftext|>


<commit_before>package main

import (
	`errors`
	`fmt`
	`github.com/brandentimm/harvestd/plugin`
	`github.com/brandentimm/harvestd/plugin/nfs`
	`os`
	`time`
)

func readWithTimeout(reaper plugin.Reaper, p []byte, timeout int64) (n int, err error) {
	readChan := make(chan int, 1)

	go func() {
		bytesRead, readError := reaper.Read(p)
		if readError != nil {
			readChan <- 0
		}
		readChan <- bytesRead
	}()

	select {
	case bytesRead := <-readChan:
		if bytesRead == 0 {
			return 0, errors.New(`Error reading.`)
		}
		return bytesRead, nil
	case <-time.After(time.Duration(timeout) * time.Second):
		return 0, errors.New(`Read timeout`)
	}
}

func main() {

	nfsPlugin, err := nfs.Init()
	if err != nil {
		fmt.Fprintf(os.Stdout, `Failed to initialize NFS plugin.`)
		os.Exit(1)
	}
	fmt.Fprintf(os.Stdout, `Plugin loaded: %s`, string(nfsPlugin.Name))

	var nfsReadBytes []byte = []byte(`nfs reader in`)
	readBytes, err := readWithTimeout(nfsPlugin, nfsReadBytes, 5)
	if readBytes == 0 {
		fmt.Fprintf(os.Stdout, `Error reading, %s`, err)
		os.Exit(1)
	}
	fmt.Fprintf(os.Stdout, `Read %d bytes : %s`, readBytes, string(nfsReadBytes))
	os.Exit(0)
}
<commit_msg>Changed readWithTimeout to take an io.Reader instead of plugin.Reaper<commit_after>package main

import (
	`errors`
	`fmt`
	`github.com/brandentimm/harvestd/plugin/nfs`
	`io`
	`os`
	`time`
)

func readWithTimeout(reader io.Reader, p []byte, timeout int64) (n int, err error) {
	readChan := make(chan int, 1)

	go func() {
		bytesRead, readError := reader.Read(p)
		if readError != nil {
			readChan <- 0
		}
		readChan <- bytesRead
	}()

	select {
	case bytesRead := <-readChan:
		if bytesRead == 0 {
			return 0, errors.New(`Error reading.`)
		}
		return bytesRead, nil
	case <-time.After(time.Duration(timeout) * time.Second):
		return 0, errors.New(`Read timeout`)
	}
}

func main() {

	nfsPlugin, err := nfs.Init()
	if err != nil {
		fmt.Fprintf(os.Stdout, `Failed to initialize NFS plugin.`)
		os.Exit(1)
	}
	fmt.Fprintf(os.Stdout, `Plugin loaded: %s`, string(nfsPlugin.Name))

	var nfsReadBytes []byte = []byte(`nfs reader in`)
	readBytes, err := readWithTimeout(nfsPlugin, nfsReadBytes, 5)
	if readBytes == 0 {
		fmt.Fprintf(os.Stdout, `Error reading, %s`, err)
		os.Exit(1)
	}
	fmt.Fprintf(os.Stdout, `Read %d bytes : %s`, readBytes, string(nfsReadBytes))
	os.Exit(0)
}
<|endoftext|>


<commit_before>package main

import (
	"strings"
	"testing"
	"time"

	"github.com/BotBotMe/botbot-bot/common"
)

const (
	SERVER_PORT = "60667"
	TEST_MSG    = "q: Something new"
)

func GetQueueLength(queue *common.MockQueue) int {
	queue.RLock()
	q := queue.Got["q"]
	queue.RUnlock()
	return len(q)
}

// A serious integration test for BotBot.
// This covers BotBot, the IRC code, and the dispatcher.
func TestBotBotIRC(t *testing.T) {

	// Create a mock storage with configuration in it
	storage := common.NewMockStorage(SERVER_PORT)

	// Create a mock queue to gather BotBot output
	queue := common.NewMockQueue()

	// Start a Mock IRC server, and gather writes to it
	server := common.NewMockIRCServer(TEST_MSG, SERVER_PORT)
	go server.Run(t)

	// Run BotBot
	botbot := NewBotBot(storage, queue)
	go botbot.listen("testcmds")
	go botbot.mainLoop()
	waitForServer(server, 5)

	// Test sending a reply - should probably be separate test
	queue.ReadChannel <- "WRITE 1 #unit I am a plugin response"
	waitForServer(server, 6)

	queue.RLock()
	q := queue.Got["q"]
	queue.RUnlock()

	checkContains(q, TEST_MSG, t)

	// Check IRC server expectations

	if server.GotLength() != 6 {
		t.Fatal("Expected exactly 6 IRC messages from the bot. Got ", server.GotLength())
	}

	expect := []string{"PING", "USER", "NICK", "NickServ", "JOIN", "PRIVMSG"}
	for i := 0; i < 5; i++ {
		if !strings.Contains(string(server.Got[i]), expect[i]) {
			t.Error("Line ", i, " did not contain ", expect[i], ". It is: ", server.Got[i])
		}
	}

	// test shutdown - should probably be separate test

	botbot.shutdown()

	tries := 0
	for GetQueueLength(queue) < 4 && tries < 20 {
		time.Sleep(100 * time.Millisecond)
		tries++
	}

	queue.RLock()
	checkContains(queue.Got["q"], "SHUTDOWN", t)
	queue.RUnlock()
}

// Block until len(target.Get) is at least val, or timeout
func waitForServer(target *common.MockIRCServer, val int) {

	tries := 0
	for target.GotLength() < val && tries < 60 {
		time.Sleep(200 * time.Millisecond)
		tries++
	}
}

// Check that "val" is in one of the strings in "arr". t.Error if not.
func checkContains(arr []string, val string, t *testing.T) {

	isFound := false
	for _, item := range arr {
		if strings.Contains(item, val) {
			isFound = true
			break
		}
	}
	if !isFound {
		t.Error("Queue did not get a message containing:", val)
	}
}
<commit_msg>Increate the number of tries before belling out<commit_after>package main

import (
	"strings"
	"testing"
	"time"

	"github.com/BotBotMe/botbot-bot/common"
)

const (
	SERVER_PORT = "60667"
	TEST_MSG    = "q: Something new"
)

func GetQueueLength(queue *common.MockQueue) int {
	queue.RLock()
	q := queue.Got["q"]
	queue.RUnlock()
	return len(q)
}

// A serious integration test for BotBot.
// This covers BotBot, the IRC code, and the dispatcher.
func TestBotBotIRC(t *testing.T) {

	// Create a mock storage with configuration in it
	storage := common.NewMockStorage(SERVER_PORT)

	// Create a mock queue to gather BotBot output
	queue := common.NewMockQueue()

	// Start a Mock IRC server, and gather writes to it
	server := common.NewMockIRCServer(TEST_MSG, SERVER_PORT)
	go server.Run(t)

	// Run BotBot
	botbot := NewBotBot(storage, queue)
	go botbot.listen("testcmds")
	go botbot.mainLoop()
	waitForServer(server, 5)

	// Test sending a reply - should probably be separate test
	queue.ReadChannel <- "WRITE 1 #unit I am a plugin response"
	waitForServer(server, 6)

	queue.RLock()
	q := queue.Got["q"]
	queue.RUnlock()

	checkContains(q, TEST_MSG, t)

	// Check IRC server expectations

	if server.GotLength() != 6 {
		t.Fatal("Expected exactly 6 IRC messages from the bot. Got ", server.GotLength())
	}

	expect := []string{"PING", "USER", "NICK", "NickServ", "JOIN", "PRIVMSG"}
	for i := 0; i < 5; i++ {
		if !strings.Contains(string(server.Got[i]), expect[i]) {
			t.Error("Line ", i, " did not contain ", expect[i], ". It is: ", server.Got[i])
		}
	}

	// test shutdown - should probably be separate test

	botbot.shutdown()

	tries := 0
	for GetQueueLength(queue) < 4 && tries < 100 {
		time.Sleep(50 * time.Millisecond)
		tries++
	}

	queue.RLock()
	checkContains(queue.Got["q"], "SHUTDOWN", t)
	queue.RUnlock()
}

// Block until len(target.Get) is at least val, or timeout
func waitForServer(target *common.MockIRCServer, val int) {

	tries := 0
	for target.GotLength() < val && tries < 100 {
		time.Sleep(50 * time.Millisecond)
		tries++
	}
}

// Check that "val" is in one of the strings in "arr". t.Error if not.
func checkContains(arr []string, val string, t *testing.T) {

	isFound := false
	for _, item := range arr {
		if strings.Contains(item, val) {
			isFound = true
			break
		}
	}
	if !isFound {
		t.Error("Queue did not get a message containing:", val)
	}
}
<|endoftext|>


<commit_before>package config

import (
	"os"
	"testing"
	"time"

	"github.com/asobti/kube-monkey/config/param"
	"github.com/bouk/monkey"
	"github.com/golang/glog"
	"github.com/spf13/viper"
	"github.com/stretchr/testify/suite"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type ConfigTestSuite struct {
	suite.Suite
}

func (s *ConfigTestSuite) SetupTest() {
	viper.Reset()
	SetDefaults()
}

func (s *ConfigTestSuite) TestSetDefaults() {

	s.True(viper.GetBool(param.DryRun))
	s.Equal("America/Los_Angeles", viper.GetString(param.Timezone))
	s.Equal(8, viper.GetInt(param.RunHour))
	s.Equal(10, viper.GetInt(param.StartHour))
	s.Equal(16, viper.GetInt(param.EndHour))
	s.Equal(int64(5), viper.GetInt64(param.GracePeriodSec))
	s.Equal([]string{metav1.NamespaceSystem}, viper.GetStringSlice(param.BlacklistedNamespaces))
	s.Equal([]string{metav1.NamespaceDefault}, viper.GetStringSlice(param.WhitelistedNamespaces))
	s.False(viper.GetBool(param.DebugEnabled))
	s.Equal(viper.GetInt(param.DebugScheduleDelay), 30)
	s.False(viper.GetBool(param.DebugForceShouldKill))
	s.False(viper.GetBool(param.DebugScheduleImmediateKill))

}

func (s *ConfigTestSuite) TestDryRun() {
	viper.Set(param.DryRun, false)
	s.False(DryRun())
	viper.Set(param.DryRun, true)
	s.True(DryRun())
}

func (s *ConfigTestSuite) TestTimezone() {
	viper.Set(param.Timezone, "nolnexistent")

	// avoid Exit(255) on glog.Fatal
	monkey.Patch(glog.Fatal, func(a ...interface{}) {
		s.Equal(a[0], "cannot find nolnexistent in zip file "+os.Getenv("GOROOT")+"/lib/time/zoneinfo.zip")
	})
	defer func() { monkey.Unpatch(glog.Fatal) }()
	s.Equal((*time.Location)(nil), Timezone())
	viper.Set(param.Timezone, "UTC")
	s.Equal(Timezone().String(), "UTC")
}

func (s *ConfigTestSuite) TestRunHour() {
	viper.Set(param.RunHour, 11)
	s.Equal(11, RunHour())
}

func (s *ConfigTestSuite) TestStartHour() {
	viper.Set(param.StartHour, 10)
	s.Equal(10, StartHour())
}

func (s *ConfigTestSuite) TestEndHour() {
	viper.Set(param.EndHour, 9)
	s.Equal(9, EndHour())
}

func (s *ConfigTestSuite) TestGracePeriodSeconds() {
	g := int64(100)
	viper.Set(param.GracePeriodSec, 100)
	s.Equal(&g, GracePeriodSeconds())
}

func (s *ConfigTestSuite) TestBlacklistedNamespaces() {
	blns := []string{"namespace1", "namespace2"}
	viper.Set(param.BlacklistedNamespaces, blns)
	ns := BlacklistedNamespaces()
	s.Len(ns, len(blns))
	for _, v := range blns {
		s.Contains(ns, v)
	}
}

func (s *ConfigTestSuite) TestWhitelistedNamespaces() {
	wlns := []string{"namespace1", "namespace2"}
	viper.Set(param.WhitelistedNamespaces, wlns)
	ns := WhitelistedNamespaces()
	s.Len(ns, len(wlns))
	for _, v := range wlns {
		s.Contains(ns, v)
	}
}

func (s *ConfigTestSuite) TestBlacklistEnabled() {
	s.True(BlacklistEnabled())
	viper.Set(param.BlacklistedNamespaces, []string{metav1.NamespaceNone})
	s.False(BlacklistEnabled())
}

func (s *ConfigTestSuite) TestWhitelistEnabled() {
	s.True(WhitelistEnabled())
	viper.Set(param.WhitelistedNamespaces, []string{metav1.NamespaceAll})
	s.False(WhitelistEnabled())
}

func (s *ConfigTestSuite) TestClusterrAPIServerHost() {
	host, enabled := ClusterAPIServerHost()
	s.False(enabled)
	s.Empty(host)
	viper.Set(param.ClusterAPIServerHost, "Host")
	host, enabled = ClusterAPIServerHost()
	s.True(enabled)
	s.Equal("Host", host)
}

func (s *ConfigTestSuite) TestDebugEnabled() {
	viper.Set(param.DebugEnabled, true)
	s.True(DebugEnabled())
}

func (s *ConfigTestSuite) TestDebugScheduleDelay() {
	viper.Set(param.DebugScheduleDelay, 10)
	s.Equal(10*time.Second, DebugScheduleDelay())
}
func (s *ConfigTestSuite) TestDebugForceShouldKill() {
	viper.Set(param.DebugForceShouldKill, true)
	s.True(DebugForceShouldKill())
}

func (s *ConfigTestSuite) TestDebugInmediateKill() {
	viper.Set(param.DebugScheduleImmediateKill, true)
	s.True(DebugScheduleImmediateKill())
}

func TestSuite(t *testing.T) {
	suite.Run(t, new(ConfigTestSuite))
}
<commit_msg>Change assertion in TestTimezon to contains<commit_after>package config

import (
	"testing"
	"time"

	"github.com/asobti/kube-monkey/config/param"
	"github.com/bouk/monkey"
	"github.com/golang/glog"
	"github.com/spf13/viper"
	"github.com/stretchr/testify/suite"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type ConfigTestSuite struct {
	suite.Suite
}

func (s *ConfigTestSuite) SetupTest() {
	viper.Reset()
	SetDefaults()
}

func (s *ConfigTestSuite) TestSetDefaults() {

	s.True(viper.GetBool(param.DryRun))
	s.Equal("America/Los_Angeles", viper.GetString(param.Timezone))
	s.Equal(8, viper.GetInt(param.RunHour))
	s.Equal(10, viper.GetInt(param.StartHour))
	s.Equal(16, viper.GetInt(param.EndHour))
	s.Equal(int64(5), viper.GetInt64(param.GracePeriodSec))
	s.Equal([]string{metav1.NamespaceSystem}, viper.GetStringSlice(param.BlacklistedNamespaces))
	s.Equal([]string{metav1.NamespaceDefault}, viper.GetStringSlice(param.WhitelistedNamespaces))
	s.False(viper.GetBool(param.DebugEnabled))
	s.Equal(viper.GetInt(param.DebugScheduleDelay), 30)
	s.False(viper.GetBool(param.DebugForceShouldKill))
	s.False(viper.GetBool(param.DebugScheduleImmediateKill))

}

func (s *ConfigTestSuite) TestDryRun() {
	viper.Set(param.DryRun, false)
	s.False(DryRun())
	viper.Set(param.DryRun, true)
	s.True(DryRun())
}

func (s *ConfigTestSuite) TestTimezone() {
	viper.Set(param.Timezone, "nolnexistent")

	// avoid Exit(255) on glog.Fatal
	monkey.Patch(glog.Fatal, func(a ...interface{}) {
		s.Contains(a[0], "cannot find nolnexistent in zip file")
	})
	defer func() { monkey.Unpatch(glog.Fatal) }()
	s.Equal((*time.Location)(nil), Timezone())
	viper.Set(param.Timezone, "UTC")
	s.Equal(Timezone().String(), "UTC")
}

func (s *ConfigTestSuite) TestRunHour() {
	viper.Set(param.RunHour, 11)
	s.Equal(11, RunHour())
}

func (s *ConfigTestSuite) TestStartHour() {
	viper.Set(param.StartHour, 10)
	s.Equal(10, StartHour())
}

func (s *ConfigTestSuite) TestEndHour() {
	viper.Set(param.EndHour, 9)
	s.Equal(9, EndHour())
}

func (s *ConfigTestSuite) TestGracePeriodSeconds() {
	g := int64(100)
	viper.Set(param.GracePeriodSec, 100)
	s.Equal(&g, GracePeriodSeconds())
}

func (s *ConfigTestSuite) TestBlacklistedNamespaces() {
	blns := []string{"namespace1", "namespace2"}
	viper.Set(param.BlacklistedNamespaces, blns)
	ns := BlacklistedNamespaces()
	s.Len(ns, len(blns))
	for _, v := range blns {
		s.Contains(ns, v)
	}
}

func (s *ConfigTestSuite) TestWhitelistedNamespaces() {
	wlns := []string{"namespace1", "namespace2"}
	viper.Set(param.WhitelistedNamespaces, wlns)
	ns := WhitelistedNamespaces()
	s.Len(ns, len(wlns))
	for _, v := range wlns {
		s.Contains(ns, v)
	}
}

func (s *ConfigTestSuite) TestBlacklistEnabled() {
	s.True(BlacklistEnabled())
	viper.Set(param.BlacklistedNamespaces, []string{metav1.NamespaceNone})
	s.False(BlacklistEnabled())
}

func (s *ConfigTestSuite) TestWhitelistEnabled() {
	s.True(WhitelistEnabled())
	viper.Set(param.WhitelistedNamespaces, []string{metav1.NamespaceAll})
	s.False(WhitelistEnabled())
}

func (s *ConfigTestSuite) TestClusterrAPIServerHost() {
	host, enabled := ClusterAPIServerHost()
	s.False(enabled)
	s.Empty(host)
	viper.Set(param.ClusterAPIServerHost, "Host")
	host, enabled = ClusterAPIServerHost()
	s.True(enabled)
	s.Equal("Host", host)
}

func (s *ConfigTestSuite) TestDebugEnabled() {
	viper.Set(param.DebugEnabled, true)
	s.True(DebugEnabled())
}

func (s *ConfigTestSuite) TestDebugScheduleDelay() {
	viper.Set(param.DebugScheduleDelay, 10)
	s.Equal(10*time.Second, DebugScheduleDelay())
}
func (s *ConfigTestSuite) TestDebugForceShouldKill() {
	viper.Set(param.DebugForceShouldKill, true)
	s.True(DebugForceShouldKill())
}

func (s *ConfigTestSuite) TestDebugInmediateKill() {
	viper.Set(param.DebugScheduleImmediateKill, true)
	s.True(DebugScheduleImmediateKill())
}

func TestSuite(t *testing.T) {
	suite.Run(t, new(ConfigTestSuite))
}
<|endoftext|>