<commit_before>package main

import "github.com/jpki/myna/libmyna"

import (
	"crypto/x509"
	_ "errors"
	"fmt"
	"github.com/mattn/go-gtk/gdkpixbuf"
	"github.com/mattn/go-gtk/glib"
	"github.com/mattn/go-gtk/gtk"
	"github.com/urfave/cli"
	"os"
	"strings"
)

func main() {
	app := cli.NewApp()
	app.Name = "mynag"
	app.Usage = "マイナクライアント(GUI)"
	app.Author = "HAMANO Tsukasa"
	app.Email = "hamano@osstech.co.jp"
	app.Version = libmyna.Version
	app.Action = mynag
	app.Flags = []cli.Flag{
		cli.BoolFlag{
			Name:  "debug, d",
			Usage: "詳細出力",
		},
	}
	app.Run(os.Args)
}

func mynag(c *cli.Context) error {
	gtk.Init(&os.Args)
	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetPosition(gtk.WIN_POS_CENTER)
	window.SetTitle(c.App.Usage)
	window.SetIconName("application-certificate")
	window.Connect("destroy", func(ctx *glib.CallbackContext) {
		gtk.MainQuit()
	})

	// create menu
	menu := gtk.NewMenuBar()
	menuHelp := gtk.NewMenuItemWithMnemonic("Menu")
	menu.Append(menuHelp)

	menuSub := gtk.NewMenu()
	menuHelp.SetSubmenu(menuSub)
	menuItemAbout := gtk.NewMenuItemWithMnemonic("About")
	menuItemAbout.Connect("activate", onAbout, c)
	menuSub.Append(menuItemAbout)

	menuItemQuit := gtk.NewMenuItemWithMnemonic("Quit")
	menuItemQuit.Connect("activate", onQuit, c)
	menuSub.Append(menuItemQuit)

	// create button box
	boxButton := gtk.NewVBox(false, 1)
	buttonTest := gtk.NewToggleButtonWithLabel("動作確認")
	buttonTest.Clicked(onTest, c)
	boxButton.Add(buttonTest)

	buttonCardInfo := gtk.NewToggleButtonWithLabel("券面事項確認")
	buttonCardInfo.Clicked(onCardInfo, c)
	boxButton.Add(buttonCardInfo)

	buttonShowCert := gtk.NewToggleButtonWithLabel("証明書表示")
	buttonShowCert.Clicked(onShowCert, c)
	boxButton.Add(buttonShowCert)

	buttonSign := gtk.NewToggleButtonWithLabel("署名")
	buttonSign.Clicked(onSign, c)
	boxButton.Add(buttonSign)

	buttonPinStatus := gtk.NewToggleButtonWithLabel("PINステータス")
	buttonPinStatus.Clicked(onPinStatus, c)
	boxButton.Add(buttonPinStatus)

	// create hbox
	hbox := gtk.NewHBox(false, 1)
	//dir, _ := filepath.Split(os.Args[0])
	//imagefile := filepath.Join(dir, "usagi.png")
	//imageLogo := gtk.NewImageFromFile(imagefile)
	imageData, _ := Asset("usagi.png")
	imageBuf, _ := gdkpixbuf.NewPixbufFromData(imageData)
	imageLogo := gtk.NewImageFromPixbuf(imageBuf)
	hbox.Add(imageLogo)
	hbox.Add(boxButton)

	// create main box
	boxMain := gtk.NewVBox(false, 1)
	boxMain.PackStart(menu, false, false, 0)
	boxMain.Add(hbox)

	window.Add(boxMain)
	//window.SetSizeRequest(400, 400)
	window.ShowAll()
	gtk.Main()
	return nil
}

func onAbout(ctx *glib.CallbackContext) {
	c := ctx.Data().(*cli.Context)
	dialog := gtk.NewAboutDialog()
	dialog.SetName("About")
	dialog.SetProgramName(c.App.Name)
	dialog.SetAuthors([]string{c.App.Author})
	//dialog.SetLicense("ライセンス")
	dialog.SetWrapLicense(true)
	dialog.Run()
	dialog.Destroy()
}

func onQuit(ctx *glib.CallbackContext) {
	_ = ctx.Data().(*cli.Context)
	gtk.MainQuit()
}

func showErrorMsg(msg string) {
	dialog := gtk.NewMessageDialog(
		nil,
		gtk.DIALOG_MODAL,
		gtk.MESSAGE_INFO,
		gtk.BUTTONS_OK,
		msg)
	dialog.Response(func() {
		dialog.Destroy()
	})
	dialog.Run()
}

func showMsg(msg string) {
	dialog := gtk.NewMessageDialog(
		nil,
		gtk.DIALOG_MODAL,
		gtk.MESSAGE_INFO,
		gtk.BUTTONS_OK,
		msg)
	dialog.Response(func() {
		dialog.Destroy()
	})
	dialog.Run()
}

func onTest(ctx *glib.CallbackContext) {
	c := ctx.Data().(*cli.Context)
	err := libmyna.CheckCard(c)
	var msg string
	if err != nil {
		msg = err.Error()
	} else {
		msg = "正常です。"
	}
	showErrorMsg(msg)
}

func popupPrompt(title string) string {
	dialog := gtk.NewDialog()
	dialog.SetTitle(title)
	vbox := dialog.GetVBox()
	label := gtk.NewLabel(title)
	vbox.Add(label)
	pinEntry := gtk.NewEntry()
	pinEntry.SetVisibility(false)
	pinEntry.Connect("activate", func() {
		dialog.Hide()
		dialog.Response(gtk.RESPONSE_OK)
	})
	vbox.Add(pinEntry)
	dialog.AddButton(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
	dialog.AddButton(gtk.STOCK_OK, gtk.RESPONSE_OK)
	dialog.SetDefaultResponse(gtk.RESPONSE_OK)
	dialog.ShowAll()
	res := dialog.Run()
	pin := pinEntry.GetText()
	dialog.Destroy()
	if res == gtk.RESPONSE_OK {
		return pin
	} else {
		return ""
	}
}

func popupPinPrompt() string {
	return popupPrompt("暗証番号(4桁)")
}

func popupPasswordPrompt() string {
	pass := popupPrompt("署名用パスワード(6-16桁)")
	if len(pass) < 6 || 16 < len(pass) {
		showErrorMsg("署名用パスワード(6-16桁)を入力してください。")
		return ""
	}
	return strings.ToUpper(pass)
}

func onCardInfo(ctx *glib.CallbackContext) {
	c := ctx.Data().(*cli.Context)
	err := libmyna.CheckCard(c)
	if err != nil {
		showErrorMsg(err.Error())
		return
	}
	pin := popupPinPrompt()
	if pin == "" {
		return
	}
	info, _ := libmyna.GetCardInfo(c, pin)
	var msg string
	msg += fmt.Sprintf("個人番号: %s\n", info["number"])
	msg += fmt.Sprintf("氏名:     %s\n", info["name"])
	msg += fmt.Sprintf("住所:     %s\n", info["address"])
	msg += fmt.Sprintf("生年月日: %s\n", info["birth"])
	msg += fmt.Sprintf("性別:     %s", info["sex"])
	showMsg(msg)
}

func onPinStatus(ctx *glib.CallbackContext) {
	c := ctx.Data().(*cli.Context)
	status, _ := libmyna.GetPinStatus(c)
	var msg string
	msg += fmt.Sprintf("認証用PIN: のこり%d回\n", status["auth"])
	msg += fmt.Sprintf("署名用PIN: のこり%d回\n", status["sign"])
	msg += fmt.Sprintf("券面入力補助PIN: のこり%d回\n", status["card"])
	msg += fmt.Sprintf("謎のPIN1: のこり%d回\n", status["unknown1"])
	msg += fmt.Sprintf("謎のPIN2: のこり%d回", status["unknown2"])
	showMsg(msg)
}

func onShowCert(ctx *glib.CallbackContext) {
	c := ctx.Data().(*cli.Context)
	rc := selectCert()
	var title string
	var ef string
	var pin string
	switch rc {
	case 0:
		// キャンセル
		return
	case 1:
		title = "認証用証明書"
		ef = "00 0A"
	case 2:
		title = "署名用証明書"
		ef = "00 01"
		pin = popupPasswordPrompt()
		if pin == "" {
			return
		}
	case 3:
		title = "認証用CA証明書"
		ef = "00 0B"
	case 4:
		title = "署名用CA証明書"
		ef = "00 02"
	}
	cert, err := libmyna.GetCert(c, ef, pin)
	if err != nil {
		showErrorMsg(err.Error())
		return
	}
	popupCertDialog(title, cert)
}

func popupCertDialog(title string, cert *x509.Certificate) {
	dialog := gtk.NewDialog()
	defer dialog.Destroy()
	dialog.SetTitle(title)
	vbox := dialog.GetVBox()

	vbox.PackStart(gtk.NewLabel("Subject: "), false, false, 10)
	subjectEntry := gtk.NewEntry()
	subjectEntry.SetText(libmyna.Name2String(cert.Subject))
	subjectEntry.SetWidthChars(64)
	vbox.PackStart(subjectEntry, false, false, 10)
	vbox.PackStart(gtk.NewLabel("Issuer: "), false, false, 10)
	issuerEntry := gtk.NewEntry()
	issuerEntry.SetText(libmyna.Name2String(cert.Issuer))
	issuerEntry.SetWidthChars(64)
	vbox.PackStart(issuerEntry, false, false, 10)
	dialog.AddButton(gtk.STOCK_OK, gtk.RESPONSE_OK)
	dialog.ShowAll()
	dialog.Run()
}

func selectCert() int {
	dialog := gtk.NewDialog()
	defer dialog.Destroy()
	dialog.SetTitle("証明書選択")
	vbox := dialog.GetVBox()
	radio1 := gtk.NewRadioButtonWithLabel(nil, "認証用証明書")
	radio2 := gtk.NewRadioButtonWithLabel(radio1.GetGroup(), "署名用証明書")
	radio3 := gtk.NewRadioButtonWithLabel(radio1.GetGroup(), "認証用CA証明書")
	radio4 := gtk.NewRadioButtonWithLabel(radio1.GetGroup(), "署名用CA証明書")

	vbox.PackStart(radio1, false, false, 10)
	vbox.PackStart(radio2, false, false, 10)
	vbox.PackStart(radio3, false, false, 10)
	vbox.PackStart(radio4, false, false, 10)

	dialog.AddButton(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
	dialog.AddButton(gtk.STOCK_OK, gtk.RESPONSE_OK)
	dialog.SetDefaultResponse(gtk.RESPONSE_OK)
	dialog.ShowAll()
	res := dialog.Run()
	if res == gtk.RESPONSE_OK {
		if radio1.GetActive() {
			return 1
		} else if radio2.GetActive() {
			return 2
		} else if radio3.GetActive() {
			return 3
		} else if radio4.GetActive() {
			return 4
		} else {
			return 0
		}
	} else {
		return 0
	}
}

func onSign(ctx *glib.CallbackContext) {
	//c := ctx.Data().(*cli.Context)
	showErrorMsg("署名")
}
<commit_msg>ファイル選択UI<commit_after>package main

import "github.com/jpki/myna/libmyna"

import (
	"crypto/x509"
	_ "errors"
	"fmt"
	"github.com/mattn/go-gtk/gdkpixbuf"
	"github.com/mattn/go-gtk/glib"
	"github.com/mattn/go-gtk/gtk"
	"github.com/urfave/cli"
	"os"
	"strings"
)

func main() {
	app := cli.NewApp()
	app.Name = "mynag"
	app.Usage = "マイナクライアント(GUI)"
	app.Author = "HAMANO Tsukasa"
	app.Email = "hamano@osstech.co.jp"
	app.Version = libmyna.Version
	app.Action = mynag
	app.Flags = []cli.Flag{
		cli.BoolFlag{
			Name:  "debug, d",
			Usage: "詳細出力",
		},
	}
	app.Run(os.Args)
}

func mynag(c *cli.Context) error {
	gtk.Init(&os.Args)
	window := gtk.NewWindow(gtk.WINDOW_TOPLEVEL)
	window.SetPosition(gtk.WIN_POS_CENTER)
	window.SetTitle(c.App.Usage)
	window.SetIconName("application-certificate")
	window.Connect("destroy", func(ctx *glib.CallbackContext) {
		gtk.MainQuit()
	})

	// create menu
	menu := gtk.NewMenuBar()
	menuHelp := gtk.NewMenuItemWithMnemonic("Menu")
	menu.Append(menuHelp)

	menuSub := gtk.NewMenu()
	menuHelp.SetSubmenu(menuSub)
	menuItemAbout := gtk.NewMenuItemWithMnemonic("About")
	menuItemAbout.Connect("activate", onAbout, c)
	menuSub.Append(menuItemAbout)

	menuItemQuit := gtk.NewMenuItemWithMnemonic("Quit")
	menuItemQuit.Connect("activate", onQuit, c)
	menuSub.Append(menuItemQuit)

	// create button box
	boxButton := gtk.NewVBox(false, 1)
	buttonTest := gtk.NewButtonWithLabel("動作確認")
	buttonTest.Clicked(onTest, c)
	boxButton.Add(buttonTest)

	buttonCardInfo := gtk.NewButtonWithLabel("券面事項確認")
	buttonCardInfo.Clicked(onCardInfo, c)
	boxButton.Add(buttonCardInfo)

	buttonShowCert := gtk.NewButtonWithLabel("証明書表示")
	buttonShowCert.Clicked(onShowCert, c)
	boxButton.Add(buttonShowCert)

	buttonSign := gtk.NewButtonWithLabel("署名")
	buttonSign.Clicked(onSign, c)
	boxButton.Add(buttonSign)

	buttonPinStatus := gtk.NewButtonWithLabel("PINステータス")
	buttonPinStatus.Clicked(onPinStatus, c)
	boxButton.Add(buttonPinStatus)

	// create hbox
	hbox := gtk.NewHBox(false, 1)
	//dir, _ := filepath.Split(os.Args[0])
	//imagefile := filepath.Join(dir, "usagi.png")
	//imageLogo := gtk.NewImageFromFile(imagefile)
	imageData, _ := Asset("usagi.png")
	imageBuf, _ := gdkpixbuf.NewPixbufFromData(imageData)
	imageLogo := gtk.NewImageFromPixbuf(imageBuf)
	hbox.Add(imageLogo)
	hbox.Add(boxButton)

	// create main box
	boxMain := gtk.NewVBox(false, 1)
	boxMain.PackStart(menu, false, false, 0)
	boxMain.Add(hbox)

	window.Add(boxMain)
	//window.SetSizeRequest(400, 400)
	window.ShowAll()
	gtk.Main()
	return nil
}

func onAbout(ctx *glib.CallbackContext) {
	c := ctx.Data().(*cli.Context)
	dialog := gtk.NewAboutDialog()
	dialog.SetName("About")
	dialog.SetProgramName(c.App.Name)
	dialog.SetAuthors([]string{c.App.Author})
	//dialog.SetLicense("ライセンス")
	dialog.SetWrapLicense(true)
	dialog.Run()
	dialog.Destroy()
}

func onQuit(ctx *glib.CallbackContext) {
	_ = ctx.Data().(*cli.Context)
	gtk.MainQuit()
}

func showErrorMsg(msg string) {
	dialog := gtk.NewMessageDialog(
		nil,
		gtk.DIALOG_MODAL,
		gtk.MESSAGE_INFO,
		gtk.BUTTONS_OK,
		msg)
	dialog.Response(func() {
		dialog.Destroy()
	})
	dialog.Run()
}

func showMsg(msg string) {
	dialog := gtk.NewMessageDialog(
		nil,
		gtk.DIALOG_MODAL,
		gtk.MESSAGE_INFO,
		gtk.BUTTONS_OK,
		msg)
	dialog.Response(func() {
		dialog.Destroy()
	})
	dialog.Run()
}

func onTest(ctx *glib.CallbackContext) {
	c := ctx.Data().(*cli.Context)
	err := libmyna.CheckCard(c)
	var msg string
	if err != nil {
		msg = err.Error()
	} else {
		msg = "正常です。"
	}
	showErrorMsg(msg)
}

func popupPrompt(title string) string {
	dialog := gtk.NewDialog()
	dialog.SetTitle(title)
	vbox := dialog.GetVBox()
	label := gtk.NewLabel(title)
	vbox.Add(label)
	pinEntry := gtk.NewEntry()
	pinEntry.SetVisibility(false)
	pinEntry.Connect("activate", func() {
		dialog.Hide()
		dialog.Response(gtk.RESPONSE_OK)
	})
	vbox.Add(pinEntry)
	dialog.AddButton(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
	dialog.AddButton(gtk.STOCK_OK, gtk.RESPONSE_OK)
	dialog.SetDefaultResponse(gtk.RESPONSE_OK)
	dialog.ShowAll()
	res := dialog.Run()
	pin := pinEntry.GetText()
	dialog.Destroy()
	if res == gtk.RESPONSE_OK {
		return pin
	} else {
		return ""
	}
}

func popupPinPrompt() string {
	return popupPrompt("暗証番号(4桁)")
}

func popupPasswordPrompt() string {
	pass := popupPrompt("署名用パスワード(6-16桁)")
	if len(pass) < 6 || 16 < len(pass) {
		showErrorMsg("署名用パスワード(6-16桁)を入力してください。")
		return ""
	}
	return strings.ToUpper(pass)
}

func onCardInfo(ctx *glib.CallbackContext) {
	c := ctx.Data().(*cli.Context)
	err := libmyna.CheckCard(c)
	if err != nil {
		showErrorMsg(err.Error())
		return
	}
	pin := popupPinPrompt()
	if pin == "" {
		return
	}
	info, _ := libmyna.GetCardInfo(c, pin)
	var msg string
	msg += fmt.Sprintf("個人番号: %s\n", info["number"])
	msg += fmt.Sprintf("氏名:     %s\n", info["name"])
	msg += fmt.Sprintf("住所:     %s\n", info["address"])
	msg += fmt.Sprintf("生年月日: %s\n", info["birth"])
	msg += fmt.Sprintf("性別:     %s", info["sex"])
	showMsg(msg)
}

func onPinStatus(ctx *glib.CallbackContext) {
	c := ctx.Data().(*cli.Context)
	status, _ := libmyna.GetPinStatus(c)
	var msg string
	msg += fmt.Sprintf("認証用PIN: のこり%d回\n", status["auth"])
	msg += fmt.Sprintf("署名用PIN: のこり%d回\n", status["sign"])
	msg += fmt.Sprintf("券面入力補助PIN: のこり%d回\n", status["card"])
	msg += fmt.Sprintf("謎のPIN1: のこり%d回\n", status["unknown1"])
	msg += fmt.Sprintf("謎のPIN2: のこり%d回", status["unknown2"])
	showMsg(msg)
}

func onShowCert(ctx *glib.CallbackContext) {
	c := ctx.Data().(*cli.Context)
	rc := selectCert()
	var title string
	var ef string
	var pin string
	switch rc {
	case 0:
		// キャンセル
		return
	case 1:
		title = "認証用証明書"
		ef = "00 0A"
	case 2:
		title = "署名用証明書"
		ef = "00 01"
		pin = popupPasswordPrompt()
		if pin == "" {
			return
		}
	case 3:
		title = "認証用CA証明書"
		ef = "00 0B"
	case 4:
		title = "署名用CA証明書"
		ef = "00 02"
	}
	cert, err := libmyna.GetCert(c, ef, pin)
	if err != nil {
		showErrorMsg(err.Error())
		return
	}
	popupCertDialog(title, cert)
}

func popupCertDialog(title string, cert *x509.Certificate) {
	dialog := gtk.NewDialog()
	defer dialog.Destroy()
	dialog.SetTitle(title)
	vbox := dialog.GetVBox()

	vbox.PackStart(gtk.NewLabel("Subject: "), false, false, 10)
	subjectEntry := gtk.NewEntry()
	subjectEntry.SetText(libmyna.Name2String(cert.Subject))
	subjectEntry.SetWidthChars(64)
	vbox.PackStart(subjectEntry, false, false, 10)
	vbox.PackStart(gtk.NewLabel("Issuer: "), false, false, 10)
	issuerEntry := gtk.NewEntry()
	issuerEntry.SetText(libmyna.Name2String(cert.Issuer))
	issuerEntry.SetWidthChars(64)
	vbox.PackStart(issuerEntry, false, false, 10)
	dialog.AddButton(gtk.STOCK_OK, gtk.RESPONSE_OK)
	dialog.ShowAll()
	dialog.Run()
}

func selectCert() int {
	dialog := gtk.NewDialog()
	defer dialog.Destroy()
	dialog.SetTitle("証明書選択")
	vbox := dialog.GetVBox()
	radio1 := gtk.NewRadioButtonWithLabel(nil, "認証用証明書")
	radio2 := gtk.NewRadioButtonWithLabel(radio1.GetGroup(), "署名用証明書")
	radio3 := gtk.NewRadioButtonWithLabel(radio1.GetGroup(), "認証用CA証明書")
	radio4 := gtk.NewRadioButtonWithLabel(radio1.GetGroup(), "署名用CA証明書")

	vbox.PackStart(radio1, false, false, 10)
	vbox.PackStart(radio2, false, false, 10)
	vbox.PackStart(radio3, false, false, 10)
	vbox.PackStart(radio4, false, false, 10)

	dialog.AddButton(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
	dialog.AddButton(gtk.STOCK_OK, gtk.RESPONSE_OK)
	dialog.SetDefaultResponse(gtk.RESPONSE_OK)
	dialog.ShowAll()
	res := dialog.Run()
	if res == gtk.RESPONSE_OK {
		if radio1.GetActive() {
			return 1
		} else if radio2.GetActive() {
			return 2
		} else if radio3.GetActive() {
			return 3
		} else if radio4.GetActive() {
			return 4
		} else {
			return 0
		}
	} else {
		return 0
	}
}

func onSign(ctx *glib.CallbackContext) {
	//c := ctx.Data().(*cli.Context)
	dialog := gtk.NewDialog()
	defer dialog.Destroy()
	dialog.SetTitle("署名")

	inputEntry := gtk.NewEntry()
	inputEntry.SetWidthChars(64)
	inputEntry.SetEditable(false)
	outputEntry := gtk.NewEntry()
	outputEntry.SetWidthChars(64)
	outputEntry.SetEditable(false)

	vbox := dialog.GetVBox()
	inputButton := gtk.NewButtonWithLabel("入力ファイル")
	inputButton.Clicked(func() {
		filedialog := gtk.NewFileChooserDialog(
			"ファイル選択",
			nil,
			gtk.FILE_CHOOSER_ACTION_OPEN,
			gtk.STOCK_OK,
			gtk.RESPONSE_ACCEPT)
		filedialog.Response(func() {
			filename := filedialog.GetFilename()
			inputEntry.SetText(filename)
			filedialog.Destroy()
			if outputEntry.GetText() == "" {
				outputEntry.SetText(filename + ".p7s")
			}
		})
		filedialog.Run()
	})
	row := gtk.NewHBox(false, 1)
	row.Add(inputEntry)
	row.Add(inputButton)
	vbox.Add(row)

	outputButton := gtk.NewButtonWithLabel("出力ファイル")
	outputButton.Clicked(func() {
		filedialog := gtk.NewFileChooserDialog(
			"ファイル選択",
			nil,
			gtk.FILE_CHOOSER_ACTION_SAVE,
			gtk.STOCK_OK,
			gtk.RESPONSE_ACCEPT)
		filedialog.Response(func() {
			outputEntry.SetText(filedialog.GetFilename())
			filedialog.Destroy()
		})
		filedialog.Run()

	})
	row = gtk.NewHBox(false, 1)
	row.Add(outputEntry)
	row.Add(outputButton)
	vbox.Add(row)

	dialog.AddButton(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
	dialog.AddButton("署名", gtk.RESPONSE_OK)
	dialog.ShowAll()
	res := dialog.Run()
	if res != gtk.RESPONSE_OK {
		return
	}
	inputFile := inputEntry.GetText()
	if inputFile == "" {
		showErrorMsg("入力ファイルを指定してください")
		return
	}
	outputFile := outputEntry.GetText()
	if outputFile == "" {
		showErrorMsg("出力ファイルを指定してください")
		return
	}
	fmt.Printf("input: %s\n", inputFile)
	fmt.Printf("output: %s\n", outputFile)
}
<|endoftext|>


<commit_before>// The state package enables reading, observing, and changing
// the state stored in MongoDB of a whole environment
// managed by juju.
package mstate

import (
	"fmt"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
	"labix.org/v2/mgo/txn"
	"launchpad.net/juju-core/charm"
	"launchpad.net/juju-core/trivial"
	"launchpad.net/juju-core/version"
	"net/url"
)

const (
	environConfigKey = "environ"
)

// Tools describes a particular set of juju tools and where to find them.
type Tools struct {
	version.Binary
	URL string
}

type Life int8

const (
	Alive Life = iota
	Dying
	Dead
	nLife
)

var lifeStrings = [nLife]string{
	Alive: "alive",
	Dying: "dying",
	Dead:  "dead",
}

func (l Life) String() string {
	return lifeStrings[l]
}

// State represents the state of an environment
// managed by juju.
type State struct {
	db        *mgo.Database
	cfgnodes  *mgo.Collection
	charms    *mgo.Collection
	machines  *mgo.Collection
	relations *mgo.Collection
	services  *mgo.Collection
	txns      *mgo.Collection
	units     *mgo.Collection
	runner    *txn.Runner
}

// EnvironConfig returns the current configuration of the environment.
func (s *State) EnvironConfig() (*ConfigNode, error) {
	return readConfigNode(s, environConfigKey)
}

// AddMachine creates a new machine state.
func (s *State) AddMachine() (m *Machine, err error) {
	defer trivial.ErrorContextf(&err, "cannot add a new machine")
	id, err := s.sequence("machine")
	if err != nil {
		return nil, err
	}
	mdoc := machineDoc{
		Id:   id,
		Life: Alive,
	}
	err = s.machines.Insert(mdoc)
	if err != nil {
		return nil, err
	}
	return newMachine(s, &mdoc), nil
}

// RemoveMachine removes the machine with the the given id.
func (s *State) RemoveMachine(id int) error {
	sel := bson.D{{"_id", id}, {"life", Alive}}
	change := bson.D{{"$set", bson.D{{"life", Dying}}}}
	err := s.machines.Update(sel, change)
	if err != nil {
		return fmt.Errorf("cannot remove machine %d: %v", id, err)
	}
	return nil
}

// AllMachines returns all machines in the environment.
func (s *State) AllMachines() (machines []*Machine, err error) {
	mdocs := []machineDoc{}
	sel := bson.D{{"life", Alive}}
	err = s.machines.Find(sel).Select(bson.D{{"_id", 1}}).All(&mdocs)
	if err != nil {
		return nil, fmt.Errorf("cannot get all machines: %v", err)
	}
	for _, doc := range mdocs {
		machines = append(machines, newMachine(s, &doc))
	}
	return
}

// Machine returns the machine with the given id.
func (s *State) Machine(id int) (*Machine, error) {
	mdoc := &machineDoc{}
	sel := bson.D{{"_id", id}, {"life", Alive}}
	err := s.machines.Find(sel).One(mdoc)
	if err != nil {
		return nil, fmt.Errorf("cannot get machine %d: %v", id, err)
	}
	return newMachine(s, mdoc), nil
}

// AddCharm adds the ch charm with curl to the state.  bundleUrl must be
// set to a URL where the bundle for ch may be downloaded from.
// On success the newly added charm state is returned.
func (s *State) AddCharm(ch charm.Charm, curl *charm.URL, bundleURL *url.URL, bundleSha256 string) (stch *Charm, err error) {
	cdoc := &charmDoc{
		URL:          curl,
		Meta:         ch.Meta(),
		Config:       ch.Config(),
		BundleURL:    bundleURL,
		BundleSha256: bundleSha256,
	}
	err = s.charms.Insert(cdoc)
	if err != nil {
		return nil, fmt.Errorf("cannot add charm %q: %v", curl, err)
	}
	return newCharm(s, cdoc)
}

// Charm returns the charm with the given URL.
func (s *State) Charm(curl *charm.URL) (*Charm, error) {
	cdoc := &charmDoc{}
	err := s.charms.Find(bson.D{{"_id", curl}}).One(cdoc)
	if err != nil {
		return nil, fmt.Errorf("cannot get charm %q: %v", curl, err)
	}

	return newCharm(s, cdoc)
}

// AddService creates a new service state with the given unique name
// and the charm state.
func (s *State) AddService(name string, ch *Charm) (service *Service, err error) {
	sdoc := serviceDoc{
		Name:     name,
		CharmURL: ch.URL(),
		Life:     Alive,
	}
	err = s.services.Insert(sdoc)
	if err != nil {
		return nil, fmt.Errorf("cannot add service %q:", name, err)
	}
	return &Service{st: s, doc: sdoc}, nil
}

// RemoveService removes a service from the state. It will also remove all
// its units and break any of its existing relations.
func (s *State) RemoveService(svc *Service) (err error) {
	defer trivial.ErrorContextf(&err, "cannot remove service %q", svc)

	sel := bson.D{{"_id", svc.doc.Name}, {"life", Alive}}
	change := bson.D{{"$set", bson.D{{"life", Dying}}}}
	err = s.services.Update(sel, change)
	if err != nil {
		return err
	}

	sel = bson.D{{"service", svc.doc.Name}}
	change = bson.D{{"$set", bson.D{{"life", Dying}}}}
	_, err = s.units.UpdateAll(sel, change)
	return err
}

// Service returns a service state by name.
func (s *State) Service(name string) (service *Service, err error) {
	sdoc := serviceDoc{}
	sel := bson.D{{"_id", name}, {"life", Alive}}
	err = s.services.Find(sel).One(&sdoc)
	if err != nil {
		return nil, fmt.Errorf("cannot get service %q: %v", name, err)
	}
	return &Service{st: s, doc: sdoc}, nil
}

// AllServices returns all deployed services in the environment.
func (s *State) AllServices() (services []*Service, err error) {
	sdocs := []serviceDoc{}
	err = s.services.Find(bson.D{{"life", Alive}}).All(&sdocs)
	if err != nil {
		return nil, fmt.Errorf("cannot get all services")
	}
	for _, v := range sdocs {
		services = append(services, &Service{st: s, doc: v})
	}
	return services, nil
}

// AddRelation creates a new relation with the given endpoints.
func (s *State) AddRelation(endpoints ...RelationEndpoint) (r *Relation, err error) {
	defer trivial.ErrorContextf(&err, "cannot add relation %q", relationKey(endpoints))
	switch len(endpoints) {
	case 1:
		if endpoints[0].RelationRole != RolePeer {
			return nil, fmt.Errorf("single endpoint must be a peer relation")
		}
	case 2:
		if !endpoints[0].CanRelateTo(&endpoints[1]) {
			return nil, fmt.Errorf("endpoints do not relate")
		}
	default:
		return nil, fmt.Errorf("cannot relate %d endpoints", len(endpoints))
	}

	var scope charm.RelationScope
	for _, v := range endpoints {
		if v.RelationScope == charm.ScopeContainer {
			scope = charm.ScopeContainer
		}
		// BUG(aram): potential race in the time between getting the service
		// to validate the endpoint and actually writting the relation
		// into MongoDB; the service might have disappeared.
		_, err = s.Service(v.ServiceName)
		if err != nil {
			return nil, err
		}
	}
	if scope == charm.ScopeContainer {
		for i := range endpoints {
			endpoints[i].RelationScope = scope
		}
	}
	id, err := s.sequence("relation")
	if err != nil {
		return nil, err
	}
	doc := relationDoc{
		Id:        id,
		Key:       relationKey(endpoints),
		Endpoints: endpoints,
		Life:      Alive,
	}
	err = s.relations.Insert(doc)
	if err != nil {
		return nil, err
	}
	return newRelation(s, &doc), nil
}

// Relation returns the existing relation with the given endpoints.
func (s *State) Relation(endpoints ...RelationEndpoint) (r *Relation, err error) {
	defer trivial.ErrorContextf(&err, "cannot get relation %q", relationKey(endpoints))

	doc := relationDoc{}
	err = s.relations.Find(bson.D{{"key", relationKey(endpoints)}}).One(&doc)
	if err != nil {
		return nil, err
	}
	return newRelation(s, &doc), nil
}

// RemoveRelation removes the supplied relation.
func (s *State) RemoveRelation(r *Relation) (err error) {
	defer trivial.ErrorContextf(&err, "cannot remove relation %q", r.doc.Key)

	if r.doc.Life != Dead {
		panic(fmt.Errorf("relation %q is not dead", r))
	}
	sel := bson.D{
		{"_id", r.doc.Id},
		{"life", Dead},
	}
	err = s.relations.Remove(sel)
	if err != nil {
		return err
	}
	return nil
}

// Unit returns a unit by name.
func (s *State) Unit(name string) (*Unit, error) {
	doc := unitDoc{}
	err := s.units.FindId(name).One(&doc)
	if err != nil {
		return nil, fmt.Errorf("cannot get unit %q: %v", name, err)
	}
	return newUnit(s, &doc), nil
}
<commit_msg>mstate: use txn for AddMachine<commit_after>// The state package enables reading, observing, and changing
// the state stored in MongoDB of a whole environment
// managed by juju.
package mstate

import (
	"fmt"
	"labix.org/v2/mgo"
	"labix.org/v2/mgo/bson"
	"labix.org/v2/mgo/txn"
	"launchpad.net/juju-core/charm"
	"launchpad.net/juju-core/trivial"
	"launchpad.net/juju-core/version"
	"net/url"
)

const (
	environConfigKey = "environ"
)

// Tools describes a particular set of juju tools and where to find them.
type Tools struct {
	version.Binary
	URL string
}

type Life int8

const (
	Alive Life = iota
	Dying
	Dead
	nLife
)

var lifeStrings = [nLife]string{
	Alive: "alive",
	Dying: "dying",
	Dead:  "dead",
}

func (l Life) String() string {
	return lifeStrings[l]
}

// State represents the state of an environment
// managed by juju.
type State struct {
	db        *mgo.Database
	cfgnodes  *mgo.Collection
	charms    *mgo.Collection
	machines  *mgo.Collection
	relations *mgo.Collection
	services  *mgo.Collection
	txns      *mgo.Collection
	units     *mgo.Collection
	runner    *txn.Runner
}

// EnvironConfig returns the current configuration of the environment.
func (s *State) EnvironConfig() (*ConfigNode, error) {
	return readConfigNode(s, environConfigKey)
}

// AddMachine creates a new machine state.
func (s *State) AddMachine() (m *Machine, err error) {
	defer trivial.ErrorContextf(&err, "cannot add a new machine")
	id, err := s.sequence("machine")
	if err != nil {
		return nil, err
	}
	mdoc := machineDoc{
		Id:   id,
		Life: Alive,
	}
	op := []txn.Operation{{
		Collection: "machines",
		DocId:      id,
		Assert:     txn.DocMissing,
		Insert:     mdoc,
	}}
	err = s.runner.Run(op, "", nil)
	if err != nil {
		return nil, err
	}
	return newMachine(s, &mdoc), nil
}

// RemoveMachine removes the machine with the the given id.
func (s *State) RemoveMachine(id int) error {
	sel := bson.D{{"_id", id}, {"life", Alive}}
	change := bson.D{{"$set", bson.D{{"life", Dying}}}}
	err := s.machines.Update(sel, change)
	if err != nil {
		return fmt.Errorf("cannot remove machine %d: %v", id, err)
	}
	return nil
}

// AllMachines returns all machines in the environment.
func (s *State) AllMachines() (machines []*Machine, err error) {
	mdocs := []machineDoc{}
	sel := bson.D{{"life", Alive}}
	err = s.machines.Find(sel).Select(bson.D{{"_id", 1}}).All(&mdocs)
	if err != nil {
		return nil, fmt.Errorf("cannot get all machines: %v", err)
	}
	for _, doc := range mdocs {
		machines = append(machines, newMachine(s, &doc))
	}
	return
}

// Machine returns the machine with the given id.
func (s *State) Machine(id int) (*Machine, error) {
	mdoc := &machineDoc{}
	sel := bson.D{{"_id", id}, {"life", Alive}}
	err := s.machines.Find(sel).One(mdoc)
	if err != nil {
		return nil, fmt.Errorf("cannot get machine %d: %v", id, err)
	}
	return newMachine(s, mdoc), nil
}

// AddCharm adds the ch charm with curl to the state.  bundleUrl must be
// set to a URL where the bundle for ch may be downloaded from.
// On success the newly added charm state is returned.
func (s *State) AddCharm(ch charm.Charm, curl *charm.URL, bundleURL *url.URL, bundleSha256 string) (stch *Charm, err error) {
	cdoc := &charmDoc{
		URL:          curl,
		Meta:         ch.Meta(),
		Config:       ch.Config(),
		BundleURL:    bundleURL,
		BundleSha256: bundleSha256,
	}
	err = s.charms.Insert(cdoc)
	if err != nil {
		return nil, fmt.Errorf("cannot add charm %q: %v", curl, err)
	}
	return newCharm(s, cdoc)
}

// Charm returns the charm with the given URL.
func (s *State) Charm(curl *charm.URL) (*Charm, error) {
	cdoc := &charmDoc{}
	err := s.charms.Find(bson.D{{"_id", curl}}).One(cdoc)
	if err != nil {
		return nil, fmt.Errorf("cannot get charm %q: %v", curl, err)
	}

	return newCharm(s, cdoc)
}

// AddService creates a new service state with the given unique name
// and the charm state.
func (s *State) AddService(name string, ch *Charm) (service *Service, err error) {
	sdoc := serviceDoc{
		Name:     name,
		CharmURL: ch.URL(),
		Life:     Alive,
	}
	err = s.services.Insert(sdoc)
	if err != nil {
		return nil, fmt.Errorf("cannot add service %q:", name, err)
	}
	return &Service{st: s, doc: sdoc}, nil
}

// RemoveService removes a service from the state. It will also remove all
// its units and break any of its existing relations.
func (s *State) RemoveService(svc *Service) (err error) {
	defer trivial.ErrorContextf(&err, "cannot remove service %q", svc)

	sel := bson.D{{"_id", svc.doc.Name}, {"life", Alive}}
	change := bson.D{{"$set", bson.D{{"life", Dying}}}}
	err = s.services.Update(sel, change)
	if err != nil {
		return err
	}

	sel = bson.D{{"service", svc.doc.Name}}
	change = bson.D{{"$set", bson.D{{"life", Dying}}}}
	_, err = s.units.UpdateAll(sel, change)
	return err
}

// Service returns a service state by name.
func (s *State) Service(name string) (service *Service, err error) {
	sdoc := serviceDoc{}
	sel := bson.D{{"_id", name}, {"life", Alive}}
	err = s.services.Find(sel).One(&sdoc)
	if err != nil {
		return nil, fmt.Errorf("cannot get service %q: %v", name, err)
	}
	return &Service{st: s, doc: sdoc}, nil
}

// AllServices returns all deployed services in the environment.
func (s *State) AllServices() (services []*Service, err error) {
	sdocs := []serviceDoc{}
	err = s.services.Find(bson.D{{"life", Alive}}).All(&sdocs)
	if err != nil {
		return nil, fmt.Errorf("cannot get all services")
	}
	for _, v := range sdocs {
		services = append(services, &Service{st: s, doc: v})
	}
	return services, nil
}

// AddRelation creates a new relation with the given endpoints.
func (s *State) AddRelation(endpoints ...RelationEndpoint) (r *Relation, err error) {
	defer trivial.ErrorContextf(&err, "cannot add relation %q", relationKey(endpoints))
	switch len(endpoints) {
	case 1:
		if endpoints[0].RelationRole != RolePeer {
			return nil, fmt.Errorf("single endpoint must be a peer relation")
		}
	case 2:
		if !endpoints[0].CanRelateTo(&endpoints[1]) {
			return nil, fmt.Errorf("endpoints do not relate")
		}
	default:
		return nil, fmt.Errorf("cannot relate %d endpoints", len(endpoints))
	}

	var scope charm.RelationScope
	for _, v := range endpoints {
		if v.RelationScope == charm.ScopeContainer {
			scope = charm.ScopeContainer
		}
		// BUG(aram): potential race in the time between getting the service
		// to validate the endpoint and actually writting the relation
		// into MongoDB; the service might have disappeared.
		_, err = s.Service(v.ServiceName)
		if err != nil {
			return nil, err
		}
	}
	if scope == charm.ScopeContainer {
		for i := range endpoints {
			endpoints[i].RelationScope = scope
		}
	}
	id, err := s.sequence("relation")
	if err != nil {
		return nil, err
	}
	doc := relationDoc{
		Id:        id,
		Key:       relationKey(endpoints),
		Endpoints: endpoints,
		Life:      Alive,
	}
	err = s.relations.Insert(doc)
	if err != nil {
		return nil, err
	}
	return newRelation(s, &doc), nil
}

// Relation returns the existing relation with the given endpoints.
func (s *State) Relation(endpoints ...RelationEndpoint) (r *Relation, err error) {
	defer trivial.ErrorContextf(&err, "cannot get relation %q", relationKey(endpoints))

	doc := relationDoc{}
	err = s.relations.Find(bson.D{{"key", relationKey(endpoints)}}).One(&doc)
	if err != nil {
		return nil, err
	}
	return newRelation(s, &doc), nil
}

// RemoveRelation removes the supplied relation.
func (s *State) RemoveRelation(r *Relation) (err error) {
	defer trivial.ErrorContextf(&err, "cannot remove relation %q", r.doc.Key)

	if r.doc.Life != Dead {
		panic(fmt.Errorf("relation %q is not dead", r))
	}
	sel := bson.D{
		{"_id", r.doc.Id},
		{"life", Dead},
	}
	err = s.relations.Remove(sel)
	if err != nil {
		return err
	}
	return nil
}

// Unit returns a unit by name.
func (s *State) Unit(name string) (*Unit, error) {
	doc := unitDoc{}
	err := s.units.FindId(name).One(&doc)
	if err != nil {
		return nil, fmt.Errorf("cannot get unit %q: %v", name, err)
	}
	return newUnit(s, &doc), nil
}
<|endoftext|>


<commit_before>package natsx

import (
	"context"

	"github.com/altairsix/pkg/tracer"
	"github.com/altairsix/pkg/tracer/k"
	"github.com/savaki/nats-protobuf"
)

// Log provides the standardized logging service for nats queries
func Log(subject, bc string) nats_protobuf.Filter {
	return func(fn nats_protobuf.HandlerFunc) nats_protobuf.HandlerFunc {
		return func(ctx context.Context, m *nats_protobuf.Message) (*nats_protobuf.Message, error) {
			segment, ctx := tracer.NewSegment(ctx, "nats.api",
				k.String("subject", subject),
				k.String("bc", bc),
				k.String("method", m.Method),
			)
			defer segment.Finish()

			out, err := fn(ctx, m)
			if err != nil {
				segment.LogFields(k.Err(err))
				return nil, err
			}

			return out, nil
		}
	}
}
<commit_msg>- scratch that<commit_after>package natsx

import (
	"context"

	"github.com/altairsix/pkg/tracer"
	"github.com/altairsix/pkg/tracer/k"
	"github.com/savaki/nats-protobuf"
)

// Log provides the standardized logging service for nats queries
func Log(bc string) nats_protobuf.Filter {
	return func(fn nats_protobuf.HandlerFunc) nats_protobuf.HandlerFunc {
		return func(ctx context.Context, m *nats_protobuf.Message) (*nats_protobuf.Message, error) {
			segment, ctx := tracer.NewSegment(ctx, "nats.api",
				k.String("bc", bc),
				k.String("method", m.Method),
			)
			defer segment.Finish()

			out, err := fn(ctx, m)
			if err != nil {
				segment.LogFields(k.Err(err))
				return nil, err
			}

			return out, nil
		}
	}
}
<|endoftext|>


<commit_before>package core

import (
	"encoding/binary"
	"io"
	"log"
	"os"
)

const (
	DATAFILE_SIZE  = 1024 * 1024 * 256 // 256 MB
	DATABLOCK_SIZE = 1024 * 4          // 4KB
)

var (
	DatablockByteOrder = binary.BigEndian
)

type Datafile interface {
	Close() error
	ReadBlock(id uint16, data []byte) error
	WriteBlock(id uint16, data []byte) error
}

type datafile struct {
	file *os.File
}

func newDatafile(filename string) (Datafile, error) {
	file, err := openDatafile(filename)
	if err != nil {
		return nil, err
	}

	return &datafile{file: file}, nil
}

func openDatafile(filename string) (*os.File, error) {
	if _, err := os.Stat(filename); err == nil {
		log.Println("Datafile exists, reusing it")
		return os.OpenFile(filename, os.O_RDWR, 0666)
	}

	log.Println("Creating datafile...")
	file, err := os.Create(filename)
	if err != nil {
		return nil, err
	}
	file.Truncate(DATAFILE_SIZE)
	log.Println("DONE")

	return file, nil
}

func (df *datafile) ReadBlock(id uint16, data []byte) error {
	if _, err := df.file.Seek(int64(id*DATABLOCK_SIZE), 0); err != nil {
		return err
	}
	log.Printf("Reading datablock %016d", id)
	reader := &io.LimitedReader{df.file, DATABLOCK_SIZE}
	_, err := reader.Read(data)
	return err
}

func (df *datafile) WriteBlock(id uint16, data []byte) error {
	if _, err := df.file.Seek(int64(id*DATABLOCK_SIZE), 0); err != nil {
		return err
	}
	log.Printf("Writing datablock %016d", id)
	if _, err := df.file.Write(data); err != nil {
		return err
	}
	return df.file.Sync()
}

func (df *datafile) Close() error {
	log.Println("Closing datafile")
	return df.file.Close()
}

// func (df *datafile) WriteInt16(position int64, i uint16) error {
// 	if _, err := df.file.Seek(position, 0); err != nil {
// 		return err
// 	}
// 	log.Printf("Writing int16 `%d`", i)
// 	return binary.Write(df.file, DatablockByteOrder, i)
// }
<commit_msg>Return error when allocating datafile<commit_after>package core

import (
	"encoding/binary"
	"io"
	"log"
	"os"
)

const (
	DATAFILE_SIZE  = 1024 * 1024 * 256 // 256 MB
	DATABLOCK_SIZE = 1024 * 4          // 4KB
)

var (
	DatablockByteOrder = binary.BigEndian
)

type Datafile interface {
	Close() error
	ReadBlock(id uint16, data []byte) error
	WriteBlock(id uint16, data []byte) error
}

type datafile struct {
	file *os.File
}

func newDatafile(filename string) (Datafile, error) {
	file, err := openDatafile(filename)
	if err != nil {
		return nil, err
	}

	return &datafile{file: file}, nil
}

func openDatafile(filename string) (*os.File, error) {
	if _, err := os.Stat(filename); err == nil {
		log.Println("Datafile exists, reusing it")
		return os.OpenFile(filename, os.O_RDWR, 0666)
	}

	log.Println("Creating datafile")
	file, err := os.Create(filename)
	if err != nil {
		return nil, err
	}
	if err = file.Truncate(DATAFILE_SIZE); err != nil {
		return nil, err
	}
	return file, nil
}

func (df *datafile) ReadBlock(id uint16, data []byte) error {
	if _, err := df.file.Seek(int64(id*DATABLOCK_SIZE), 0); err != nil {
		return err
	}
	log.Printf("Reading datablock %016d", id)
	reader := &io.LimitedReader{df.file, DATABLOCK_SIZE}
	_, err := reader.Read(data)
	return err
}

func (df *datafile) WriteBlock(id uint16, data []byte) error {
	if _, err := df.file.Seek(int64(id*DATABLOCK_SIZE), 0); err != nil {
		return err
	}
	log.Printf("Writing datablock %016d", id)
	if _, err := df.file.Write(data); err != nil {
		return err
	}
	return df.file.Sync()
}

func (df *datafile) Close() error {
	log.Println("Closing datafile")
	return df.file.Close()
}

// func (df *datafile) WriteInt16(position int64, i uint16) error {
// 	if _, err := df.file.Seek(position, 0); err != nil {
// 		return err
// 	}
// 	log.Printf("Writing int16 `%d`", i)
// 	return binary.Write(df.file, DatablockByteOrder, i)
// }
<|endoftext|>


<commit_before>package json

import (
	"github.com/polydawn/refmt/tok/fixtures"
)

type situation byte

const (
	situationEncoding situation = 0x1
	situationDecoding situation = 0x2
)

var jsonFixtures = []struct {
	title    string
	sequence fixtures.Sequence
	serial   string
	only     situation
}{
	// Strings
	{"",
		fixtures.SequenceMap["empty string"],
		`""`,
		situationEncoding | situationDecoding,
	},
	{"decoding with extra whitespace",
		fixtures.SequenceMap["empty string"].SansLengthInfo(),
		`  "" `,
		situationDecoding,
	},
	{"",
		fixtures.SequenceMap["flat string"],
		`"value"`,
		situationEncoding | situationDecoding,
	},

	// Maps
	{"",
		fixtures.SequenceMap["empty map"].SansLengthInfo(),
		`{}`,
		situationEncoding | situationDecoding,
	},
	{"decoding with extra whitespace",
		fixtures.SequenceMap["empty map"].SansLengthInfo(),
		`{  }`,
		situationDecoding,
	},

	// Arrays
	{"",
		fixtures.SequenceMap["empty array"].SansLengthInfo(),
		`[]`,
		situationEncoding | situationDecoding,
	},
	{"decoding with extra whitespace",
		fixtures.SequenceMap["empty array"].SansLengthInfo(),
		`  [ ] `,
		situationDecoding,
	},
}
<commit_msg>test for json parse of escaped strings; passes.<commit_after>package json

import (
	"github.com/polydawn/refmt/tok/fixtures"
)

type situation byte

const (
	situationEncoding situation = 0x1
	situationDecoding situation = 0x2
)

var jsonFixtures = []struct {
	title    string
	sequence fixtures.Sequence
	serial   string
	only     situation
}{
	// Strings
	{"",
		fixtures.SequenceMap["empty string"],
		`""`,
		situationEncoding | situationDecoding,
	},
	{"decoding with extra whitespace",
		fixtures.SequenceMap["empty string"].SansLengthInfo(),
		`  "" `,
		situationDecoding,
	},
	{"",
		fixtures.SequenceMap["flat string"],
		`"value"`,
		situationEncoding | situationDecoding,
	},
	{"",
		fixtures.SequenceMap["strings needing escape"],
		`"str\nbroken\ttabbed"`,
		situationEncoding | situationDecoding,
	},

	// Maps
	{"",
		fixtures.SequenceMap["empty map"].SansLengthInfo(),
		`{}`,
		situationEncoding | situationDecoding,
	},
	{"decoding with extra whitespace",
		fixtures.SequenceMap["empty map"].SansLengthInfo(),
		`{  }`,
		situationDecoding,
	},

	// Arrays
	{"",
		fixtures.SequenceMap["empty array"].SansLengthInfo(),
		`[]`,
		situationEncoding | situationDecoding,
	},
	{"decoding with extra whitespace",
		fixtures.SequenceMap["empty array"].SansLengthInfo(),
		`  [ ] `,
		situationDecoding,
	},
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"fmt"
	"github.com/bwmarrin/discordgo"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strings"
	"github.com/CleverbotIO/go-cleverbot.io"
)

// DiscordLogin is a simple struct which contains a username and password for a Discord login
type DiscordLogin struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

var cb *cleverbot.Session
var botErr error

func main() {
	loginFile, fileErr := ioutil.ReadFile("./login.json")
	if fileErr != nil {
		fmt.Println(fileErr.Error())
		os.Exit(1)
	}

	var login DiscordLogin
	jsonErr := json.Unmarshal(loginFile, &login)

	if jsonErr != nil {
		fmt.Println(jsonErr.Error())
		os.Exit(1)
	}

	dg, err := discordgo.New(login.Username, login.Password)

	if err != nil {
		fmt.Println("Error creating session: ", err)
		os.Exit(1)
	} else {
		fmt.Println("Successfully logged in as " + login.Username)
	}

	dg.AddHandler(messageCreate)

	err = dg.Open()
	if err != nil {
		fmt.Println("Error opening connection: ", err)
		os.Exit(1)
	}

	cb, botErr = cleverbot.New("JHowZe3ddT6Da0JU","8NSK1vZVH1lRNMIcTbu4hU6kGEyIDxsW","")
	if botErr != nil {
		log.Fatal(botErr)
	}

	http.HandleFunc("/chat", func(w http.ResponseWriter, r *http.Request) {
		id := r.URL.Query().Get("id")
		msg := r.URL.Query().Get("msg")
		if id != "" && msg != "" {
			dg.ChannelMessageSend(id, "Message from HTTP chat endpoint: \n`"+msg+"`")
			fmt.Fprintf(w, "You are sending: \n"+msg+"\nto channel ID: \n"+id)
		}
	})

	fmt.Println("Bot is now running.  Press CTRL-C to exit.")
	// Simple way to keep program running until CTRL-C is pressed.
	log.Fatal(http.ListenAndServe(":8080", nil))
	<-make(chan struct{})
	return
}

// messageCreate is the handler function for all incoming Discord messages
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
	msg := strings.Split(m.Content, " ")

	switch msg[0] {
	case "nazoupdate": // Reminds everyone that Nazo is adorable
		s.ChannelMessageDelete(m.ChannelID, m.ID)
		s.ChannelMessageSend(m.ChannelID, "This is your daily reminder that <@!165846085020024832> is adorable.")
		break
	case "deltaspeak": // Echoes the given text from my own user account
		s.ChannelMessageDelete(m.ChannelID, m.ID)
		s.ChannelMessageSend(m.ChannelID, "`ds:` "+m.Content[11:len(m.Content)])
		break
	case "cb": // Communicates with Cleverbot.
		response, botErr2 := cb.Ask(m.Content[2:len(m.Content)])
		if botErr2 != nil {
			log.Fatal(botErr2)
		}

		s.ChannelMessageSend(m.ChannelID, "Cleverbot says:\n" + response)

		break
	}
}
<commit_msg>Adjusted cleverbot formatting<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"github.com/bwmarrin/discordgo"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strings"
	"github.com/CleverbotIO/go-cleverbot.io"
)

// DiscordLogin is a simple struct which contains a username and password for a Discord login
type DiscordLogin struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

var cb *cleverbot.Session
var botErr error

func main() {
	loginFile, fileErr := ioutil.ReadFile("./login.json")
	if fileErr != nil {
		fmt.Println(fileErr.Error())
		os.Exit(1)
	}

	var login DiscordLogin
	jsonErr := json.Unmarshal(loginFile, &login)

	if jsonErr != nil {
		fmt.Println(jsonErr.Error())
		os.Exit(1)
	}

	dg, err := discordgo.New(login.Username, login.Password)

	if err != nil {
		fmt.Println("Error creating session: ", err)
		os.Exit(1)
	} else {
		fmt.Println("Successfully logged in as " + login.Username)
	}

	dg.AddHandler(messageCreate)

	err = dg.Open()
	if err != nil {
		fmt.Println("Error opening connection: ", err)
		os.Exit(1)
	}

	cb, botErr = cleverbot.New("JHowZe3ddT6Da0JU","8NSK1vZVH1lRNMIcTbu4hU6kGEyIDxsW","")
	if botErr != nil {
		log.Fatal(botErr)
	}

	http.HandleFunc("/chat", func(w http.ResponseWriter, r *http.Request) {
		id := r.URL.Query().Get("id")
		msg := r.URL.Query().Get("msg")
		if id != "" && msg != "" {
			dg.ChannelMessageSend(id, "Message from HTTP chat endpoint: \n`"+msg+"`")
			fmt.Fprintf(w, "You are sending: \n"+msg+"\nto channel ID: \n"+id)
		}
	})

	fmt.Println("Bot is now running.  Press CTRL-C to exit.")
	// Simple way to keep program running until CTRL-C is pressed.
	log.Fatal(http.ListenAndServe(":8080", nil))
	<-make(chan struct{})
	return
}

// messageCreate is the handler function for all incoming Discord messages
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
	msg := strings.Split(m.Content, " ")

	switch msg[0] {
	case "nazoupdate": // Reminds everyone that Nazo is adorable
		s.ChannelMessageDelete(m.ChannelID, m.ID)
		s.ChannelMessageSend(m.ChannelID, "This is your daily reminder that <@!165846085020024832> is adorable.")
		break
	case "deltaspeak": // Echoes the given text from my own user account
		s.ChannelMessageDelete(m.ChannelID, m.ID)
		s.ChannelMessageSend(m.ChannelID, "`ds:` "+m.Content[11:len(m.Content)])
		break
	case "cb": // Communicates with Cleverbot.
		response, botErr2 := cb.Ask(m.Content[2:len(m.Content)])
		if botErr2 != nil {
			log.Fatal(botErr2)
		}
		s.ChannelMessageSend(m.ChannelID, "Cleverbot says:\n`" + response+"`")
		break
	}
}
<|endoftext|>


<commit_before>package goat

import (
	"fmt"
	"net"
)

// Listener interface method Listen defines a network listener which accepts connections
type Listener interface {
	Listen(in, out chan bool, port string)
}

// HttpListener listens for HTTP (TCP) connections
type HttpListener struct {
}

// Listen on specified TCP port, accept and handle connections
func (h HttpListener) Listen(in, out chan bool, port string) {
	l, err := net.Listen("tcp", port)
	if err != nil {
		fmt.Println(err)
	}
	for {
		conn, err := l.Accept()
		if err != nil {
			fmt.Println(err)
		}
		go new (HttpConnHandler).Handle(conn)
	}
}

// UdpListener listens for UDP connections
type UdpListener struct {
}

// Listen on specified UDP port, accept and handle connections
func (u UdpListener) Listen(in, out chan bool) {

}
<commit_msg>changed to only need port paramiter<commit_after>package goat

import (
	"fmt"
	"net"
)

type Listener interface {
	Listen(port string)
}
type HttpListener struct {
}

func (h HttpListener) Listen(port string) {
	l, err := net.Listen("tcp", ":"+port)
	if err != nil {
		fmt.Println(err)
	}
	for {
		conn, err := l.Accept()
		handle := new(HttpConnHandler)
		if err != nil {
			fmt.Println(err)
		}
		go handle.Handle(conn)
	}
}

type UdpListener struct {
}

func (u UdpListener) Listen(port string) {

}
<|endoftext|>


<commit_before>// +build !windows

/*
   Copyright The containerd Authors.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package client

import (
	"context"
	"fmt"
	"io"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"syscall"
	"time"

	"golang.org/x/sys/unix"

	"github.com/containerd/ttrpc"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"

	"github.com/containerd/containerd/events"
	"github.com/containerd/containerd/log"
	v1 "github.com/containerd/containerd/runtime/v1"
	"github.com/containerd/containerd/runtime/v1/shim"
	shimapi "github.com/containerd/containerd/runtime/v1/shim/v1"
	"github.com/containerd/containerd/sys"
	ptypes "github.com/gogo/protobuf/types"
)

var empty = &ptypes.Empty{}

// Opt is an option for a shim client configuration
type Opt func(context.Context, shim.Config) (shimapi.ShimService, io.Closer, error)

// WithStart executes a new shim process
func WithStart(binary, address, daemonAddress, cgroup string, debug bool, exitHandler func()) Opt {
	return func(ctx context.Context, config shim.Config) (_ shimapi.ShimService, _ io.Closer, err error) {
		socket, err := newSocket(address)
		if err != nil {
			return nil, nil, err
		}
		defer socket.Close()
		f, err := socket.File()
		if err != nil {
			return nil, nil, errors.Wrapf(err, "failed to get fd for socket %s", address)
		}
		defer f.Close()

		var stdoutLog io.ReadWriteCloser
		var stderrLog io.ReadWriteCloser
		if debug {
			stdoutLog, err = v1.OpenShimStdoutLog(ctx, config.WorkDir)
			if err != nil {
				return nil, nil, errors.Wrapf(err, "failed to create stdout log")
			}

			stderrLog, err = v1.OpenShimStderrLog(ctx, config.WorkDir)
			if err != nil {
				return nil, nil, errors.Wrapf(err, "failed to create stderr log")
			}

			go io.Copy(os.Stdout, stdoutLog)
			go io.Copy(os.Stderr, stderrLog)
		}

		cmd, err := newCommand(binary, daemonAddress, debug, config, f, stdoutLog, stderrLog)
		if err != nil {
			return nil, nil, err
		}
		if err := cmd.Start(); err != nil {
			return nil, nil, errors.Wrapf(err, "failed to start shim")
		}
		defer func() {
			if err != nil {
				cmd.Process.Kill()
			}
		}()
		go func() {
			cmd.Wait()
			exitHandler()
			if stdoutLog != nil {
				stdoutLog.Close()
			}
			if stderrLog != nil {
				stderrLog.Close()
			}
		}()
		log.G(ctx).WithFields(logrus.Fields{
			"pid":     cmd.Process.Pid,
			"address": address,
			"debug":   debug,
		}).Infof("shim %s started", binary)

		if err := writeFile(filepath.Join(config.Path, "address"), address); err != nil {
			return nil, nil, err
		}
		if err := writeFile(filepath.Join(config.Path, "shim.pid"), strconv.Itoa(cmd.Process.Pid)); err != nil {
			return nil, nil, err
		}
		// set shim in cgroup if it is provided
		if cgroup != "" {
			if err := setCgroup(cgroup, cmd); err != nil {
				return nil, nil, err
			}
			log.G(ctx).WithFields(logrus.Fields{
				"pid":     cmd.Process.Pid,
				"address": address,
			}).Infof("shim placed in cgroup %s", cgroup)
		}
		if err = setupOOMScore(cmd.Process.Pid); err != nil {
			return nil, nil, err
		}
		c, clo, err := WithConnect(address, func() {})(ctx, config)
		if err != nil {
			return nil, nil, errors.Wrap(err, "failed to connect")
		}
		return c, clo, nil
	}
}

// setupOOMScore gets containerd's oom score and adds +1 to it
// to ensure a shim has a lower* score than the daemons
func setupOOMScore(shimPid int) error {
	pid := os.Getpid()
	score, err := sys.GetOOMScoreAdj(pid)
	if err != nil {
		return errors.Wrap(err, "get daemon OOM score")
	}
	shimScore := score + 1
	if err := sys.SetOOMScore(shimPid, shimScore); err != nil {
		return errors.Wrap(err, "set shim OOM score")
	}
	return nil
}

func newCommand(binary, daemonAddress string, debug bool, config shim.Config, socket *os.File, stdout, stderr io.Writer) (*exec.Cmd, error) {
	selfExe, err := os.Executable()
	if err != nil {
		return nil, err
	}
	args := []string{
		"-namespace", config.Namespace,
		"-workdir", config.WorkDir,
		"-address", daemonAddress,
		"-containerd-binary", selfExe,
	}

	if config.Criu != "" {
		args = append(args, "-criu-path", config.Criu)
	}
	if config.RuntimeRoot != "" {
		args = append(args, "-runtime-root", config.RuntimeRoot)
	}
	if config.SystemdCgroup {
		args = append(args, "-systemd-cgroup")
	}
	if debug {
		args = append(args, "-debug")
	}

	cmd := exec.Command(binary, args...)
	cmd.Dir = config.Path
	// make sure the shim can be re-parented to system init
	// and is cloned in a new mount namespace because the overlay/filesystems
	// will be mounted by the shim
	cmd.SysProcAttr = getSysProcAttr()
	cmd.ExtraFiles = append(cmd.ExtraFiles, socket)
	cmd.Env = append(os.Environ(), "GOMAXPROCS=2")
	cmd.Stdout = stdout
	cmd.Stderr = stderr
	return cmd, nil
}

// writeFile writes a address file atomically
func writeFile(path, address string) error {
	path, err := filepath.Abs(path)
	if err != nil {
		return err
	}
	tempPath := filepath.Join(filepath.Dir(path), fmt.Sprintf(".%s", filepath.Base(path)))
	f, err := os.OpenFile(tempPath, os.O_RDWR|os.O_CREATE|os.O_EXCL|os.O_SYNC, 0666)
	if err != nil {
		return err
	}
	_, err = f.WriteString(address)
	f.Close()
	if err != nil {
		return err
	}
	return os.Rename(tempPath, path)
}

func newSocket(address string) (*net.UnixListener, error) {
	if len(address) > 106 {
		return nil, errors.Errorf("%q: unix socket path too long (> 106)", address)
	}
	l, err := net.Listen("unix", "\x00"+address)
	if err != nil {
		return nil, errors.Wrapf(err, "failed to listen to abstract unix socket %q", address)
	}

	return l.(*net.UnixListener), nil
}

func connect(address string, d func(string, time.Duration) (net.Conn, error)) (net.Conn, error) {
	return d(address, 100*time.Second)
}

func annonDialer(address string, timeout time.Duration) (net.Conn, error) {
	address = strings.TrimPrefix(address, "unix://")
	return net.DialTimeout("unix", "\x00"+address, timeout)
}

// WithConnect connects to an existing shim
func WithConnect(address string, onClose func()) Opt {
	return func(ctx context.Context, config shim.Config) (shimapi.ShimService, io.Closer, error) {
		conn, err := connect(address, annonDialer)
		if err != nil {
			return nil, nil, err
		}
		client := ttrpc.NewClient(conn, ttrpc.WithOnClose(onClose))
		return shimapi.NewShimClient(client), conn, nil
	}
}

// WithLocal uses an in process shim
func WithLocal(publisher events.Publisher) func(context.Context, shim.Config) (shimapi.ShimService, io.Closer, error) {
	return func(ctx context.Context, config shim.Config) (shimapi.ShimService, io.Closer, error) {
		service, err := shim.NewService(config, publisher)
		if err != nil {
			return nil, nil, err
		}
		return shim.NewLocal(service), nil, nil
	}
}

// New returns a new shim client
func New(ctx context.Context, config shim.Config, opt Opt) (*Client, error) {
	s, c, err := opt(ctx, config)
	if err != nil {
		return nil, err
	}
	return &Client{
		ShimService: s,
		c:           c,
		exitCh:      make(chan struct{}),
	}, nil
}

// Client is a shim client containing the connection to a shim
type Client struct {
	shimapi.ShimService

	c        io.Closer
	exitCh   chan struct{}
	exitOnce sync.Once
}

// IsAlive returns true if the shim can be contacted.
// NOTE: a negative answer doesn't mean that the process is gone.
func (c *Client) IsAlive(ctx context.Context) (bool, error) {
	_, err := c.ShimInfo(ctx, empty)
	if err != nil {
		// TODO(stevvooe): There are some error conditions that need to be
		// handle with unix sockets existence to give the right answer here.
		return false, err
	}
	return true, nil
}

// StopShim signals the shim to exit and wait for the process to disappear
func (c *Client) StopShim(ctx context.Context) error {
	return c.signalShim(ctx, unix.SIGTERM)
}

// KillShim kills the shim forcefully and wait for the process to disappear
func (c *Client) KillShim(ctx context.Context) error {
	return c.signalShim(ctx, unix.SIGKILL)
}

// Close the cient connection
func (c *Client) Close() error {
	if c.c == nil {
		return nil
	}
	return c.c.Close()
}

func (c *Client) signalShim(ctx context.Context, sig syscall.Signal) error {
	info, err := c.ShimInfo(ctx, empty)
	if err != nil {
		return err
	}
	pid := int(info.ShimPid)
	// make sure we don't kill ourselves if we are running a local shim
	if os.Getpid() == pid {
		return nil
	}
	if err := unix.Kill(pid, sig); err != nil && err != unix.ESRCH {
		return err
	}
	// wait for shim to die after being signaled
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-c.waitForExit(pid):
		return nil
	}
}

func (c *Client) waitForExit(pid int) <-chan struct{} {
	c.exitOnce.Do(func() {
		for {
			// use kill(pid, 0) here because the shim could have been reparented
			// and we are no longer able to waitpid(pid, ...) on the shim
			if err := unix.Kill(pid, 0); err == unix.ESRCH {
				close(c.exitCh)
				return
			}
			time.Sleep(10 * time.Millisecond)
		}
	})
	return c.exitCh
}
<commit_msg>fix mis-spelling in client.go<commit_after>// +build !windows

/*
   Copyright The containerd Authors.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package client

import (
	"context"
	"fmt"
	"io"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"syscall"
	"time"

	"golang.org/x/sys/unix"

	"github.com/containerd/ttrpc"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"

	"github.com/containerd/containerd/events"
	"github.com/containerd/containerd/log"
	v1 "github.com/containerd/containerd/runtime/v1"
	"github.com/containerd/containerd/runtime/v1/shim"
	shimapi "github.com/containerd/containerd/runtime/v1/shim/v1"
	"github.com/containerd/containerd/sys"
	ptypes "github.com/gogo/protobuf/types"
)

var empty = &ptypes.Empty{}

// Opt is an option for a shim client configuration
type Opt func(context.Context, shim.Config) (shimapi.ShimService, io.Closer, error)

// WithStart executes a new shim process
func WithStart(binary, address, daemonAddress, cgroup string, debug bool, exitHandler func()) Opt {
	return func(ctx context.Context, config shim.Config) (_ shimapi.ShimService, _ io.Closer, err error) {
		socket, err := newSocket(address)
		if err != nil {
			return nil, nil, err
		}
		defer socket.Close()
		f, err := socket.File()
		if err != nil {
			return nil, nil, errors.Wrapf(err, "failed to get fd for socket %s", address)
		}
		defer f.Close()

		var stdoutLog io.ReadWriteCloser
		var stderrLog io.ReadWriteCloser
		if debug {
			stdoutLog, err = v1.OpenShimStdoutLog(ctx, config.WorkDir)
			if err != nil {
				return nil, nil, errors.Wrapf(err, "failed to create stdout log")
			}

			stderrLog, err = v1.OpenShimStderrLog(ctx, config.WorkDir)
			if err != nil {
				return nil, nil, errors.Wrapf(err, "failed to create stderr log")
			}

			go io.Copy(os.Stdout, stdoutLog)
			go io.Copy(os.Stderr, stderrLog)
		}

		cmd, err := newCommand(binary, daemonAddress, debug, config, f, stdoutLog, stderrLog)
		if err != nil {
			return nil, nil, err
		}
		if err := cmd.Start(); err != nil {
			return nil, nil, errors.Wrapf(err, "failed to start shim")
		}
		defer func() {
			if err != nil {
				cmd.Process.Kill()
			}
		}()
		go func() {
			cmd.Wait()
			exitHandler()
			if stdoutLog != nil {
				stdoutLog.Close()
			}
			if stderrLog != nil {
				stderrLog.Close()
			}
		}()
		log.G(ctx).WithFields(logrus.Fields{
			"pid":     cmd.Process.Pid,
			"address": address,
			"debug":   debug,
		}).Infof("shim %s started", binary)

		if err := writeFile(filepath.Join(config.Path, "address"), address); err != nil {
			return nil, nil, err
		}
		if err := writeFile(filepath.Join(config.Path, "shim.pid"), strconv.Itoa(cmd.Process.Pid)); err != nil {
			return nil, nil, err
		}
		// set shim in cgroup if it is provided
		if cgroup != "" {
			if err := setCgroup(cgroup, cmd); err != nil {
				return nil, nil, err
			}
			log.G(ctx).WithFields(logrus.Fields{
				"pid":     cmd.Process.Pid,
				"address": address,
			}).Infof("shim placed in cgroup %s", cgroup)
		}
		if err = setupOOMScore(cmd.Process.Pid); err != nil {
			return nil, nil, err
		}
		c, clo, err := WithConnect(address, func() {})(ctx, config)
		if err != nil {
			return nil, nil, errors.Wrap(err, "failed to connect")
		}
		return c, clo, nil
	}
}

// setupOOMScore gets containerd's oom score and adds +1 to it
// to ensure a shim has a lower* score than the daemons
func setupOOMScore(shimPid int) error {
	pid := os.Getpid()
	score, err := sys.GetOOMScoreAdj(pid)
	if err != nil {
		return errors.Wrap(err, "get daemon OOM score")
	}
	shimScore := score + 1
	if err := sys.SetOOMScore(shimPid, shimScore); err != nil {
		return errors.Wrap(err, "set shim OOM score")
	}
	return nil
}

func newCommand(binary, daemonAddress string, debug bool, config shim.Config, socket *os.File, stdout, stderr io.Writer) (*exec.Cmd, error) {
	selfExe, err := os.Executable()
	if err != nil {
		return nil, err
	}
	args := []string{
		"-namespace", config.Namespace,
		"-workdir", config.WorkDir,
		"-address", daemonAddress,
		"-containerd-binary", selfExe,
	}

	if config.Criu != "" {
		args = append(args, "-criu-path", config.Criu)
	}
	if config.RuntimeRoot != "" {
		args = append(args, "-runtime-root", config.RuntimeRoot)
	}
	if config.SystemdCgroup {
		args = append(args, "-systemd-cgroup")
	}
	if debug {
		args = append(args, "-debug")
	}

	cmd := exec.Command(binary, args...)
	cmd.Dir = config.Path
	// make sure the shim can be re-parented to system init
	// and is cloned in a new mount namespace because the overlay/filesystems
	// will be mounted by the shim
	cmd.SysProcAttr = getSysProcAttr()
	cmd.ExtraFiles = append(cmd.ExtraFiles, socket)
	cmd.Env = append(os.Environ(), "GOMAXPROCS=2")
	cmd.Stdout = stdout
	cmd.Stderr = stderr
	return cmd, nil
}

// writeFile writes a address file atomically
func writeFile(path, address string) error {
	path, err := filepath.Abs(path)
	if err != nil {
		return err
	}
	tempPath := filepath.Join(filepath.Dir(path), fmt.Sprintf(".%s", filepath.Base(path)))
	f, err := os.OpenFile(tempPath, os.O_RDWR|os.O_CREATE|os.O_EXCL|os.O_SYNC, 0666)
	if err != nil {
		return err
	}
	_, err = f.WriteString(address)
	f.Close()
	if err != nil {
		return err
	}
	return os.Rename(tempPath, path)
}

func newSocket(address string) (*net.UnixListener, error) {
	if len(address) > 106 {
		return nil, errors.Errorf("%q: unix socket path too long (> 106)", address)
	}
	l, err := net.Listen("unix", "\x00"+address)
	if err != nil {
		return nil, errors.Wrapf(err, "failed to listen to abstract unix socket %q", address)
	}

	return l.(*net.UnixListener), nil
}

func connect(address string, d func(string, time.Duration) (net.Conn, error)) (net.Conn, error) {
	return d(address, 100*time.Second)
}

func annonDialer(address string, timeout time.Duration) (net.Conn, error) {
	address = strings.TrimPrefix(address, "unix://")
	return net.DialTimeout("unix", "\x00"+address, timeout)
}

// WithConnect connects to an existing shim
func WithConnect(address string, onClose func()) Opt {
	return func(ctx context.Context, config shim.Config) (shimapi.ShimService, io.Closer, error) {
		conn, err := connect(address, annonDialer)
		if err != nil {
			return nil, nil, err
		}
		client := ttrpc.NewClient(conn, ttrpc.WithOnClose(onClose))
		return shimapi.NewShimClient(client), conn, nil
	}
}

// WithLocal uses an in process shim
func WithLocal(publisher events.Publisher) func(context.Context, shim.Config) (shimapi.ShimService, io.Closer, error) {
	return func(ctx context.Context, config shim.Config) (shimapi.ShimService, io.Closer, error) {
		service, err := shim.NewService(config, publisher)
		if err != nil {
			return nil, nil, err
		}
		return shim.NewLocal(service), nil, nil
	}
}

// New returns a new shim client
func New(ctx context.Context, config shim.Config, opt Opt) (*Client, error) {
	s, c, err := opt(ctx, config)
	if err != nil {
		return nil, err
	}
	return &Client{
		ShimService: s,
		c:           c,
		exitCh:      make(chan struct{}),
	}, nil
}

// Client is a shim client containing the connection to a shim
type Client struct {
	shimapi.ShimService

	c        io.Closer
	exitCh   chan struct{}
	exitOnce sync.Once
}

// IsAlive returns true if the shim can be contacted.
// NOTE: a negative answer doesn't mean that the process is gone.
func (c *Client) IsAlive(ctx context.Context) (bool, error) {
	_, err := c.ShimInfo(ctx, empty)
	if err != nil {
		// TODO(stevvooe): There are some error conditions that need to be
		// handle with unix sockets existence to give the right answer here.
		return false, err
	}
	return true, nil
}

// StopShim signals the shim to exit and wait for the process to disappear
func (c *Client) StopShim(ctx context.Context) error {
	return c.signalShim(ctx, unix.SIGTERM)
}

// KillShim kills the shim forcefully and wait for the process to disappear
func (c *Client) KillShim(ctx context.Context) error {
	return c.signalShim(ctx, unix.SIGKILL)
}

// Close the client connection
func (c *Client) Close() error {
	if c.c == nil {
		return nil
	}
	return c.c.Close()
}

func (c *Client) signalShim(ctx context.Context, sig syscall.Signal) error {
	info, err := c.ShimInfo(ctx, empty)
	if err != nil {
		return err
	}
	pid := int(info.ShimPid)
	// make sure we don't kill ourselves if we are running a local shim
	if os.Getpid() == pid {
		return nil
	}
	if err := unix.Kill(pid, sig); err != nil && err != unix.ESRCH {
		return err
	}
	// wait for shim to die after being signaled
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-c.waitForExit(pid):
		return nil
	}
}

func (c *Client) waitForExit(pid int) <-chan struct{} {
	c.exitOnce.Do(func() {
		for {
			// use kill(pid, 0) here because the shim could have been reparented
			// and we are no longer able to waitpid(pid, ...) on the shim
			if err := unix.Kill(pid, 0); err == unix.ESRCH {
				close(c.exitCh)
				return
			}
			time.Sleep(10 * time.Millisecond)
		}
	})
	return c.exitCh
}
<|endoftext|>


<commit_before>package oauth

import (
	"log"
	"net/http"
	"os"

	"github.com/ViBiOh/dashboard/fetch"
)

const accessTokenURL = `https://github.com/login/oauth/access_token`

var stateSalt string

func Init() {
	stateSalt = os.Getenv(`OAUTH_STATE_SALT`)
}

// Handler for Docker request. Should be use with net/http
type Handler struct {
}

func (handler Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	body, err := fetch.ReadBody(r.Body)
	if err != nil {
		log.Printf(`Error while reading body: %v`, err)
	}

	log.Printf(`Code = %s`, body)
}
<commit_msg>Update oauth.go<commit_after>package oauth

import (
	"log"
	"net/http"
	"os"

	"github.com/ViBiOh/dashboard/fetch"
)

const accessTokenURL = `https://github.com/login/oauth/access_token`

var stateSalt string

func Init() {
	stateSalt = os.Getenv(`OAUTH_STATE_SALT`)
}

// Handler for Docker request. Should be use with net/http
type Handler struct {
}

func (handler Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	log.Printf(`Path = %s`, r.URL.Path)
}
<|endoftext|>


<commit_before>// Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved.
// Licensed under the Mozilla Public License v2.0

package oci

import (
	"log"
)

const Version = "4.5.0"

func PrintVersion() {
	log.Printf("[INFO] terraform-provider-oci %s\n", Version)
}
<commit_msg>Finalize changelog and release for version v4.6.0<commit_after>// Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved.
// Licensed under the Mozilla Public License v2.0

package oci

import (
	"log"
)

const Version = "4.6.0"

func PrintVersion() {
	log.Printf("[INFO] terraform-provider-oci %s\n", Version)
}
<|endoftext|>


<commit_before>/*
	import "github.com/thetruetrade/gotrade"

	Package indicators provides a range of technical trading indicators.
	All indicators follow the basic structure of:
		- receiving price data,	processing this price data and storing the transformed result.
		- maximum and minimum bounds of the transformed results are calculated automatically.
		- a lookback period indicating the lag between source data and the transformed result.
		- the source data bar from which the indicator is valid

 	Functions are provided for each indicator that provide indicator creation
 	for the following scenarios:

 	Online Usage
		- the data stream length is not known ahead of time, e.g. real time data streams
 	Offline Usage
		- the data stream length is known ahead of time, e.g. historical data streams

	Both scenarios provide the following indicator creation functions
 		* Indicator with default parameters
 		* Indicator with default parameters for attachment to a data stream
 		* Indicator with specified parameters
 		* Indicator with specified parameters for attachment to a data stream
 		* Indicator without storage with specified parameters
			- for use inside other indicators, has no storage of results which is instead
			- provided via a callback when it becomes available for use in the parent indicator.
*/
package indicators

import (
	"errors"
	"github.com/thetruetrade/gotrade"
	"math"
)

var (
	ErrSourceDataEmpty                      = errors.New("Source data is empty")
	ErrNotEnoughSourceDataForLookbackPeriod = errors.New("Source data does not contain enough data for the specfied lookback period")
	ErrLookbackPeriodMustBeGreaterThanZero  = errors.New("Lookback period must be greater than 0")

	// lookback minimum
	MinimumLookbackPeriod int = 0
	// lookback maximum
	MaximumLookbackPeriod int = 200
)

type Indicator interface {
	// the source data bar number from which this indicator is valid, starts at bar 1.
	ValidFromBar() int
	// the lookback period, if applicable, the amount of lag the indicator displays with regards to the source data.
	GetLookbackPeriod() int
	// the length of the transformed data generated by the indicator.
	Length() int
}

type IndicatorWithTimePeriod interface {
	GetTimePeriod() int
}

type IndicatorWithFloatBounds interface {
	// the minimum bound of the transformed data generated by the indicator.
	MinValue() float64
	// the maximum bound of the transformed data generated by the indicator.
	MaxValue() float64
}

type IndicatorWithIntBounds interface {
	// the minimum bound of the transformed data generated by the indicator.
	MinValue() int64
	// the maximum bound of the transformed data generated by the indicator.
	MaxValue() int64
}

type baseFloatBounds struct {
	minValue float64
	maxValue float64
}

func newBaseFloatBounds() *baseFloatBounds {
	ind := baseFloatBounds{minValue: math.MaxFloat64, maxValue: math.SmallestNonzeroFloat64}
	return &ind
}

func (ind *baseFloatBounds) MinValue() float64 {
	return ind.minValue
}

func (ind *baseFloatBounds) MaxValue() float64 {
	return ind.maxValue
}

type baseIntBounds struct {
	minValue int64
	maxValue int64
}

func newBaseIntBounds() *baseIntBounds {
	ind := baseIntBounds{minValue: math.MaxInt64, maxValue: math.MinInt64}
	return &ind
}

func (ind *baseIntBounds) MinValue() int64 {
	return ind.minValue
}

func (ind *baseIntBounds) MaxValue() int64 {
	return ind.maxValue
}

type baseIndicator struct {
	validFromBar   int
	dataLength     int
	selectData     gotrade.DataSelectionFunc
	lookbackPeriod int
}

func newBaseIndicator(lookbackPeriod int) *baseIndicator {
	ind := baseIndicator{lookbackPeriod: lookbackPeriod, validFromBar: -1}
	return &ind
}

func (ind *baseIndicator) ValidFromBar() int {
	return ind.validFromBar
}

func (ind *baseIndicator) GetLookbackPeriod() int {
	return ind.lookbackPeriod
}

func (ind *baseIndicator) Length() int {
	return ind.dataLength
}

type baseIndicatorWithTimePeriod struct {
	timePeriod int
}

type baseIndicatorWithFloatBounds struct {
	*baseIndicator
	*baseFloatBounds
}

func newBaseIndicatorWithFloatBounds(lookbackPeriod int) *baseIndicatorWithFloatBounds {
	ind := baseIndicatorWithFloatBounds{
		baseIndicator:   newBaseIndicator(lookbackPeriod),
		baseFloatBounds: newBaseFloatBounds()}
	return &ind
}

type baseIndicatorWithIntBounds struct {
	*baseIndicator
	*baseIntBounds
}

func newBaseIndicatorWithIntBounds(lookbackPeriod int) *baseIndicatorWithIntBounds {
	ind := baseIndicatorWithIntBounds{
		baseIndicator: newBaseIndicator(lookbackPeriod),
		baseIntBounds: newBaseIntBounds()}
	return &ind
}

func newBaseIndicatorWithTimePeriod(timePeriod int) *baseIndicatorWithTimePeriod {
	ind := baseIndicatorWithTimePeriod{timePeriod: timePeriod}
	return &ind
}

func (ind *baseIndicatorWithTimePeriod) GetTimePeriod() int {
	return ind.timePeriod
}

type ValueAvailableActionFloat func(dataItem float64, streamBarIndex int)
type ValueAvailableActionInt func(dataItem int64, streamBarIndex int)
type ValueAvailableActionDOHLCV func(dataItem gotrade.DOHLCV, streamBarIndex int)
type ValueAvailableActionBollinger func(dataItemUpperBand float64, dataItemMiddleBand float64, dataItemLowerBand float64, streamBarIndex int)
type ValueAvailableActionMACD func(dataItemMACD float64, dataItemSignal float64, dataItemHistogram float64, streamBarIndex int)
type ValueAvailableActionAroon func(dataItemAroonUp float64, dataItemAroonDown float64, streamBarIndex int)
type ValueAvailableActionStoch func(dataItemK float64, dataItemD float64, streamBarIndex int)
type ValueAvailableActionLinearReg func(dataItem float64, slope float64, intercept float64, streamBarIndex int)
<commit_msg>added some extra standard error messages<commit_after>/*
	import "github.com/thetruetrade/gotrade"

	Package indicators provides a range of technical trading indicators.
	All indicators follow the basic structure of:
		- receiving price data,	processing this price data and storing the transformed result.
		- maximum and minimum bounds of the transformed results are calculated automatically.
		- a lookback period indicating the lag between source data and the transformed result.
		- the source data bar from which the indicator is valid

 	Functions are provided for each indicator that provide indicator creation
 	for the following scenarios:

 	Online Usage
		- the data stream length is not known ahead of time, e.g. real time data streams
 	Offline Usage
		- the data stream length is known ahead of time, e.g. historical data streams

	Both scenarios provide the following indicator creation functions
 		* Indicator with default parameters
 		* Indicator with default parameters for attachment to a data stream
 		* Indicator with specified parameters
 		* Indicator with specified parameters for attachment to a data stream
 		* Indicator without storage with specified parameters
			- for use inside other indicators, has no storage of results which is instead
			- provided via a callback when it becomes available for use in the parent indicator.
*/
package indicators

import (
	"errors"
	"github.com/thetruetrade/gotrade"
	"math"
)

var (
	ErrSourceDataEmpty                      = errors.New("Source data is empty")
	ErrNotEnoughSourceDataForLookbackPeriod = errors.New("Source data does not contain enough data for the specfied lookback period")
	ErrLookbackPeriodMustBeGreaterThanZero  = errors.New("Lookback period must be greater than 0")
	ErrValueAvailableActionIsNil            = errors.New("ValueAvailableAction cannot be empty")

	// lookback minimum
	MinimumLookbackPeriod int = 0
	// lookback maximum
	MaximumLookbackPeriod int = 100000
)

type Indicator interface {
	// the source data bar number from which this indicator is valid, starts at bar 1.
	ValidFromBar() int
	// the lookback period, if applicable, the amount of lag the indicator displays with regards to the source data.
	GetLookbackPeriod() int
	// the length of the transformed data generated by the indicator.
	Length() int
}

type IndicatorWithTimePeriod interface {
	GetTimePeriod() int
}

type IndicatorWithFloatBounds interface {
	// the minimum bound of the transformed data generated by the indicator.
	MinValue() float64
	// the maximum bound of the transformed data generated by the indicator.
	MaxValue() float64
}

type IndicatorWithIntBounds interface {
	// the minimum bound of the transformed data generated by the indicator.
	MinValue() int64
	// the maximum bound of the transformed data generated by the indicator.
	MaxValue() int64
}

type baseFloatBounds struct {
	minValue float64
	maxValue float64
}

func newBaseFloatBounds() *baseFloatBounds {
	ind := baseFloatBounds{minValue: math.MaxFloat64, maxValue: math.SmallestNonzeroFloat64}
	return &ind
}

func (ind *baseFloatBounds) MinValue() float64 {
	return ind.minValue
}

func (ind *baseFloatBounds) MaxValue() float64 {
	return ind.maxValue
}

type baseIntBounds struct {
	minValue int64
	maxValue int64
}

func newBaseIntBounds() *baseIntBounds {
	ind := baseIntBounds{minValue: math.MaxInt64, maxValue: math.MinInt64}
	return &ind
}

func (ind *baseIntBounds) MinValue() int64 {
	return ind.minValue
}

func (ind *baseIntBounds) MaxValue() int64 {
	return ind.maxValue
}

type baseIndicator struct {
	validFromBar   int
	dataLength     int
	selectData     gotrade.DataSelectionFunc
	lookbackPeriod int
}

func newBaseIndicator(lookbackPeriod int) *baseIndicator {
	ind := baseIndicator{lookbackPeriod: lookbackPeriod, validFromBar: -1}
	return &ind
}

func (ind *baseIndicator) ValidFromBar() int {
	return ind.validFromBar
}

func (ind *baseIndicator) GetLookbackPeriod() int {
	return ind.lookbackPeriod
}

func (ind *baseIndicator) Length() int {
	return ind.dataLength
}

type baseIndicatorWithTimePeriod struct {
	timePeriod int
}

type baseIndicatorWithFloatBounds struct {
	*baseIndicator
	*baseFloatBounds
}

func newBaseIndicatorWithFloatBounds(lookbackPeriod int) *baseIndicatorWithFloatBounds {
	ind := baseIndicatorWithFloatBounds{
		baseIndicator:   newBaseIndicator(lookbackPeriod),
		baseFloatBounds: newBaseFloatBounds()}
	return &ind
}

type baseIndicatorWithIntBounds struct {
	*baseIndicator
	*baseIntBounds
}

func newBaseIndicatorWithIntBounds(lookbackPeriod int) *baseIndicatorWithIntBounds {
	ind := baseIndicatorWithIntBounds{
		baseIndicator: newBaseIndicator(lookbackPeriod),
		baseIntBounds: newBaseIntBounds()}
	return &ind
}

func newBaseIndicatorWithTimePeriod(timePeriod int) *baseIndicatorWithTimePeriod {
	ind := baseIndicatorWithTimePeriod{timePeriod: timePeriod}
	return &ind
}

func (ind *baseIndicatorWithTimePeriod) GetTimePeriod() int {
	return ind.timePeriod
}

type ValueAvailableActionFloat func(dataItem float64, streamBarIndex int)
type ValueAvailableActionInt func(dataItem int64, streamBarIndex int)
type ValueAvailableActionDOHLCV func(dataItem gotrade.DOHLCV, streamBarIndex int)
type ValueAvailableActionBollinger func(dataItemUpperBand float64, dataItemMiddleBand float64, dataItemLowerBand float64, streamBarIndex int)
type ValueAvailableActionMACD func(dataItemMACD float64, dataItemSignal float64, dataItemHistogram float64, streamBarIndex int)
type ValueAvailableActionAroon func(dataItemAroonUp float64, dataItemAroonDown float64, streamBarIndex int)
type ValueAvailableActionStoch func(dataItemK float64, dataItemD float64, streamBarIndex int)
type ValueAvailableActionLinearReg func(dataItem float64, slope float64, intercept float64, streamBarIndex int)
<|endoftext|>


<commit_before>package model_helpers

import (
	"encoding/json"
	"time"

	"code.cloudfoundry.org/bbs/models"
	. "github.com/onsi/gomega"
)

func NewValidActualLRP(guid string, index int32) *models.ActualLRP {
	actualLRP := &models.ActualLRP{
		ActualLRPKey:         models.NewActualLRPKey(guid, index, "some-domain"),
		ActualLRPInstanceKey: models.NewActualLRPInstanceKey("some-guid", "some-cell"),
		ActualLRPNetInfo:     models.NewActualLRPNetInfo("some-address", models.NewPortMapping(2222, 4444)),
		CrashCount:           33,
		CrashReason:          "badness",
		State:                models.ActualLRPStateRunning,
		Since:                1138,
		ModificationTag: models.ModificationTag{
			Epoch: "some-epoch",
			Index: 999,
		},
	}
	err := actualLRP.Validate()
	Expect(err).NotTo(HaveOccurred())

	return actualLRP
}

func NewValidDesiredLRP(guid string) *models.DesiredLRP {
	myRouterJSON := json.RawMessage(`{"foo":"bar"}`)
	modTag := models.NewModificationTag("epoch", 0)
	desiredLRP := &models.DesiredLRP{
		ProcessGuid:          guid,
		Domain:               "some-domain",
		RootFs:               "some:rootfs",
		Instances:            1,
		EnvironmentVariables: []*models.EnvironmentVariable{{Name: "FOO", Value: "bar"}},
		CachedDependencies: []*models.CachedDependency{
			{Name: "app bits", From: "blobstore.com/bits/app-bits", To: "/usr/local/app", CacheKey: "cache-key", LogSource: "log-source"},
			{Name: "app bits with checksum", From: "blobstore.com/bits/app-bits-checksum", To: "/usr/local/app-checksum", CacheKey: "cache-key", LogSource: "log-source", ChecksumAlgorithm: "md5", ChecksumValue: "checksum-value"},
		},
		Setup:          models.WrapAction(&models.RunAction{Path: "ls", User: "name"}),
		Action:         models.WrapAction(&models.RunAction{Path: "ls", User: "name"}),
		StartTimeoutMs: 15000,
		Monitor: models.WrapAction(models.EmitProgressFor(
			models.Timeout(models.Try(models.Parallel(models.Serial(&models.RunAction{Path: "ls", User: "name"}))),
				10*time.Second,
			),
			"start-message",
			"success-message",
			"failure-message",
		)),
		DiskMb:      512,
		MemoryMb:    1024,
		CpuWeight:   42,
		Routes:      &models.Routes{"my-router": &myRouterJSON},
		LogSource:   "some-log-source",
		LogGuid:     "some-log-guid",
		MetricsGuid: "some-metrics-guid",
		Annotation:  "some-annotation",
		Network: &models.Network{
			Properties: map[string]string{
				"some-key":       "some-value",
				"some-other-key": "some-other-value",
			},
		},
		EgressRules: []*models.SecurityGroupRule{{
			Protocol:     models.TCPProtocol,
			Destinations: []string{"1.1.1.1/32", "2.2.2.2/32"},
			PortRange:    &models.PortRange{Start: 10, End: 16000},
		}},
		ModificationTag:               &modTag,
		LegacyDownloadUser:            "legacy-dan",
		TrustedSystemCertificatesPath: "/etc/somepath",
		VolumeMounts: []*models.VolumeMount{
			{
				Driver:             "my-driver",
				DeprecatedVolumeId: "my-volume",
				ContainerDir:       "/mnt/mypath",
				DeprecatedMode:     models.BindMountMode_RO,
			},
		},
	}
	err := desiredLRP.Validate()
	Expect(err).NotTo(HaveOccurred())

	return desiredLRP
}

func NewValidTaskDefinition() *models.TaskDefinition {
	return &models.TaskDefinition{
		RootFs: "docker:///docker.com/docker",
		EnvironmentVariables: []*models.EnvironmentVariable{
			{
				Name:  "FOO",
				Value: "BAR",
			},
		},
		CachedDependencies: []*models.CachedDependency{
			{Name: "app bits", From: "blobstore.com/bits/app-bits", To: "/usr/local/app", CacheKey: "cache-key", LogSource: "log-source"},
			{Name: "app bits with checksum", From: "blobstore.com/bits/app-bits-checksum", To: "/usr/local/app-checksum", CacheKey: "cache-key", LogSource: "log-source", ChecksumAlgorithm: "md5", ChecksumValue: "checksum-value"},
		},
		Action: models.WrapAction(&models.RunAction{
			User:           "user",
			Path:           "echo",
			Args:           []string{"hello world"},
			ResourceLimits: &models.ResourceLimits{},
		}),
		MemoryMb:    256,
		DiskMb:      1024,
		CpuWeight:   42,
		Privileged:  true,
		LogGuid:     "123",
		LogSource:   "APP",
		MetricsGuid: "456",
		ResultFile:  "some-file.txt",
		EgressRules: []*models.SecurityGroupRule{
			{
				Protocol:     "tcp",
				Destinations: []string{"0.0.0.0/0"},
				PortRange: &models.PortRange{
					Start: 1,
					End:   1024,
				},
				Log: true,
			},
			{
				Protocol:     "udp",
				Destinations: []string{"8.8.0.0/16"},
				Ports:        []uint32{53},
			},
		},
		Annotation: `[{"anything": "you want!"}]... dude`,
		Network: &models.Network{
			Properties: map[string]string{
				"some-key":       "some-value",
				"some-other-key": "some-other-value",
			},
		},
		LegacyDownloadUser:            "legacy-jim",
		TrustedSystemCertificatesPath: "/etc/somepath",
		VolumeMounts: []*models.VolumeMount{
			{
				Driver:             "my-driver",
				DeprecatedVolumeId: "my-volume",
				ContainerDir:       "/mnt/mypath",
				DeprecatedMode:     models.BindMountMode_RO,
			},
		},
	}
}

func NewValidEgressRules() []models.SecurityGroupRule {
	return []models.SecurityGroupRule{
		{
			Protocol:     "tcp",
			Destinations: []string{"0.0.0.0/0"},
			PortRange: &models.PortRange{
				Start: 1,
				End:   1024,
			},
			Log: true,
		},
		{
			Protocol:     "udp",
			Destinations: []string{"8.8.0.0/16"},
			Ports:        []uint32{53},
		},
	}
}

func NewValidTask(guid string) *models.Task {
	task := &models.Task{
		TaskGuid:       guid,
		Domain:         "some-domain",
		TaskDefinition: NewValidTaskDefinition(),

		CreatedAt:        time.Date(2014, time.February, 25, 23, 46, 11, 00, time.UTC).UnixNano(),
		UpdatedAt:        time.Date(2014, time.February, 25, 23, 46, 11, 10, time.UTC).UnixNano(),
		FirstCompletedAt: time.Date(2014, time.February, 25, 23, 46, 11, 30, time.UTC).UnixNano(),

		CellId:        "cell",
		State:         models.Task_Pending,
		Result:        "turboencabulated",
		Failed:        true,
		FailureReason: "because i said so",
	}

	err := task.Validate()
	if err != nil {
		panic(err)
	}
	return task
}

func NewValidAction() *models.Action {
	return models.WrapAction(&models.RunAction{Path: "ls", User: "name"})
}
<commit_msg>unit test data for rep tests covers v2.10 api as well as v2.9 [#126092967]<commit_after>package model_helpers

import (
	"encoding/json"
	"time"

	"code.cloudfoundry.org/bbs/models"
	. "github.com/onsi/gomega"
)

func NewValidActualLRP(guid string, index int32) *models.ActualLRP {
	actualLRP := &models.ActualLRP{
		ActualLRPKey:         models.NewActualLRPKey(guid, index, "some-domain"),
		ActualLRPInstanceKey: models.NewActualLRPInstanceKey("some-guid", "some-cell"),
		ActualLRPNetInfo:     models.NewActualLRPNetInfo("some-address", models.NewPortMapping(2222, 4444)),
		CrashCount:           33,
		CrashReason:          "badness",
		State:                models.ActualLRPStateRunning,
		Since:                1138,
		ModificationTag: models.ModificationTag{
			Epoch: "some-epoch",
			Index: 999,
		},
	}
	err := actualLRP.Validate()
	Expect(err).NotTo(HaveOccurred())

	return actualLRP
}

func NewValidDesiredLRP(guid string) *models.DesiredLRP {
	myRouterJSON := json.RawMessage(`{"foo":"bar"}`)
	modTag := models.NewModificationTag("epoch", 0)
	desiredLRP := &models.DesiredLRP{
		ProcessGuid:          guid,
		Domain:               "some-domain",
		RootFs:               "some:rootfs",
		Instances:            1,
		EnvironmentVariables: []*models.EnvironmentVariable{{Name: "FOO", Value: "bar"}},
		CachedDependencies: []*models.CachedDependency{
			{Name: "app bits", From: "blobstore.com/bits/app-bits", To: "/usr/local/app", CacheKey: "cache-key", LogSource: "log-source"},
			{Name: "app bits with checksum", From: "blobstore.com/bits/app-bits-checksum", To: "/usr/local/app-checksum", CacheKey: "cache-key", LogSource: "log-source", ChecksumAlgorithm: "md5", ChecksumValue: "checksum-value"},
		},
		Setup:          models.WrapAction(&models.RunAction{Path: "ls", User: "name"}),
		Action:         models.WrapAction(&models.RunAction{Path: "ls", User: "name"}),
		StartTimeoutMs: 15000,
		Monitor: models.WrapAction(models.EmitProgressFor(
			models.Timeout(models.Try(models.Parallel(models.Serial(&models.RunAction{Path: "ls", User: "name"}))),
				10*time.Second,
			),
			"start-message",
			"success-message",
			"failure-message",
		)),
		DiskMb:      512,
		MemoryMb:    1024,
		CpuWeight:   42,
		Routes:      &models.Routes{"my-router": &myRouterJSON},
		LogSource:   "some-log-source",
		LogGuid:     "some-log-guid",
		MetricsGuid: "some-metrics-guid",
		Annotation:  "some-annotation",
		Network: &models.Network{
			Properties: map[string]string{
				"some-key":       "some-value",
				"some-other-key": "some-other-value",
			},
		},
		EgressRules: []*models.SecurityGroupRule{{
			Protocol:     models.TCPProtocol,
			Destinations: []string{"1.1.1.1/32", "2.2.2.2/32"},
			PortRange:    &models.PortRange{Start: 10, End: 16000},
		}},
		ModificationTag:               &modTag,
		LegacyDownloadUser:            "legacy-dan",
		TrustedSystemCertificatesPath: "/etc/somepath",
		VolumeMounts: []*models.VolumeMount{
			{
				Driver:             "my-driver",
				ContainerDir:       "/mnt/mypath",
				Mode:     "r",
				Shared: &models.SharedDevice{
					VolumeId: "my-volume",
				},
			},
			// TODO: this second entry tests api v2.9 backward cpmpatibility and should be removed soonish
			{
				Driver:             "my-driver",
				DeprecatedVolumeId: "my-volume",
				ContainerDir:       "/mnt/mypath",
				DeprecatedMode:     models.BindMountMode_RO,
			},
		},
	}
	err := desiredLRP.Validate()
	Expect(err).NotTo(HaveOccurred())

	return desiredLRP
}

func NewValidTaskDefinition() *models.TaskDefinition {
	return &models.TaskDefinition{
		RootFs: "docker:///docker.com/docker",
		EnvironmentVariables: []*models.EnvironmentVariable{
			{
				Name:  "FOO",
				Value: "BAR",
			},
		},
		CachedDependencies: []*models.CachedDependency{
			{Name: "app bits", From: "blobstore.com/bits/app-bits", To: "/usr/local/app", CacheKey: "cache-key", LogSource: "log-source"},
			{Name: "app bits with checksum", From: "blobstore.com/bits/app-bits-checksum", To: "/usr/local/app-checksum", CacheKey: "cache-key", LogSource: "log-source", ChecksumAlgorithm: "md5", ChecksumValue: "checksum-value"},
		},
		Action: models.WrapAction(&models.RunAction{
			User:           "user",
			Path:           "echo",
			Args:           []string{"hello world"},
			ResourceLimits: &models.ResourceLimits{},
		}),
		MemoryMb:    256,
		DiskMb:      1024,
		CpuWeight:   42,
		Privileged:  true,
		LogGuid:     "123",
		LogSource:   "APP",
		MetricsGuid: "456",
		ResultFile:  "some-file.txt",
		EgressRules: []*models.SecurityGroupRule{
			{
				Protocol:     "tcp",
				Destinations: []string{"0.0.0.0/0"},
				PortRange: &models.PortRange{
					Start: 1,
					End:   1024,
				},
				Log: true,
			},
			{
				Protocol:     "udp",
				Destinations: []string{"8.8.0.0/16"},
				Ports:        []uint32{53},
			},
		},
		Annotation: `[{"anything": "you want!"}]... dude`,
		Network: &models.Network{
			Properties: map[string]string{
				"some-key":       "some-value",
				"some-other-key": "some-other-value",
			},
		},
		LegacyDownloadUser:            "legacy-jim",
		TrustedSystemCertificatesPath: "/etc/somepath",
		VolumeMounts: []*models.VolumeMount{
			{
				Driver:             "my-driver",
				DeprecatedVolumeId: "my-volume",
				ContainerDir:       "/mnt/mypath",
				DeprecatedMode:     models.BindMountMode_RO,
			},
		},
	}
}

func NewValidEgressRules() []models.SecurityGroupRule {
	return []models.SecurityGroupRule{
		{
			Protocol:     "tcp",
			Destinations: []string{"0.0.0.0/0"},
			PortRange: &models.PortRange{
				Start: 1,
				End:   1024,
			},
			Log: true,
		},
		{
			Protocol:     "udp",
			Destinations: []string{"8.8.0.0/16"},
			Ports:        []uint32{53},
		},
	}
}

func NewValidTask(guid string) *models.Task {
	task := &models.Task{
		TaskGuid:       guid,
		Domain:         "some-domain",
		TaskDefinition: NewValidTaskDefinition(),

		CreatedAt:        time.Date(2014, time.February, 25, 23, 46, 11, 00, time.UTC).UnixNano(),
		UpdatedAt:        time.Date(2014, time.February, 25, 23, 46, 11, 10, time.UTC).UnixNano(),
		FirstCompletedAt: time.Date(2014, time.February, 25, 23, 46, 11, 30, time.UTC).UnixNano(),

		CellId:        "cell",
		State:         models.Task_Pending,
		Result:        "turboencabulated",
		Failed:        true,
		FailureReason: "because i said so",
	}

	err := task.Validate()
	if err != nil {
		panic(err)
	}
	return task
}

func NewValidAction() *models.Action {
	return models.WrapAction(&models.RunAction{Path: "ls", User: "name"})
}
<|endoftext|>


<commit_before>package infinispan

import (
	"bufio"
	"encoding/json"
	"fmt"
	"log"
	"net"
	"strings"
)

//Server represents an host and a port
type Server struct {
	Host string
	Port uint16
}

//Client represents a Client connection to an Hot Rod server
type Client struct {
	Servers   []Server
	CacheName string

	connection net.Conn
	buf        [1024]byte
}

//NewClientJSON creates a new client from a JSON file
func NewClientJSON(conf string) (*Client, error) {
	var c *Client
	if err := json.NewDecoder(strings.NewReader(conf)).Decode(&c); err != nil {
		log.Printf("Reverting to default conf because of error in JSON: %s", conf)
		c = &Client{Servers: []Server{Server{Host: "127.0.0.1", Port: 11222}}, CacheName: ""}
	}
	return c.connect()
}

func (c *Client) connect() (*Client, error) {

	server := fmt.Sprintf("%s:%d", c.Servers[0].Host, c.Servers[0].Port)
	log.Printf("Connecting to host: %s\n", server)

	conn, err := net.Dial("tcp", server)
	c.connection = conn
	return c, err
}

//Close Hot Rod Connection
func (c *Client) Close() error {
	if c.connection != nil {
		return c.connection.Close()
	}
	return nil
}

//Get gets a key
func (c *Client) Get(key []byte) (*ResponseGet, error) {
	get := createGet(key, <-id, c.CacheName)
	c.connection.Write(get)
	status, err := bufio.NewReader(c.connection).Read(c.buf[:1024])
	if err != nil {
		return &ResponseGet{}, err
	}
	p := NewBuffer(c.buf[:status])
	return p.DecodeGetResponse()
}

//Put puts an object with a key
func (c *Client) Put(key []byte, object []byte) (*ResponsePut, error) {
	return c.PutWithLifespanAndMaxidle(key, object, "0", "0")
}

//PutWithLifespan puts an object with a key and a lifespan
func (c *Client) PutWithLifespan(key []byte, object []byte, lifespan string) (*ResponsePut, error) {
	return c.PutWithLifespanAndMaxidle(key, object, lifespan, "0")
}

//PutWithMaxidle puts an object with a key and a maxidle
func (c *Client) PutWithMaxidle(key []byte, object []byte, maxidle string) (*ResponsePut, error) {
	return c.PutWithLifespanAndMaxidle(key, object, "0", maxidle)
}

//PutWithLifespanAndMaxidle puts an object with a key and a lifespan/maxidle
func (c *Client) PutWithLifespanAndMaxidle(key []byte, object []byte, lifespan string, maxidle string) (*ResponsePut, error) {
	if put, createErr := createPut(key, object, <-id, c.CacheName, lifespan, maxidle); createErr == nil {
		c.connection.Write(put)
		if status, ioErr := bufio.NewReader(c.connection).Read(c.buf[:1024]); ioErr == nil {
			p := NewBuffer(c.buf[:status])
			return p.DecodePutResponse()
		} else {
			return &ResponsePut{}, ioErr
		}
	} else {
		return &ResponsePut{}, createErr
	}

}
<commit_msg>Added options as a map parameter to put. Implemented a PUT with lifespan integration test<commit_after>package infinispan

import (
	"bufio"
	"encoding/json"
	"fmt"
	"log"
	"net"
	"strconv"
	"strings"
)

//Server represents an host and a port
type Server struct {
	Host string
	Port uint16
}

//Client represents a Client connection to an Hot Rod server
type Client struct {
	Servers   []Server
	CacheName string

	connection net.Conn
	buf        [1024]byte
}

//NewClientJSON creates a new client from a JSON file
func NewClientJSON(conf string) (*Client, error) {
	var c *Client
	if err := json.NewDecoder(strings.NewReader(conf)).Decode(&c); err != nil {
		log.Printf("Reverting to default conf because of error in JSON: %s", conf)
		c = &Client{Servers: []Server{Server{Host: "127.0.0.1", Port: 11222}}, CacheName: ""}
	}
	return c.connect()
}

func (c *Client) connect() (*Client, error) {

	server := fmt.Sprintf("%s:%d", c.Servers[0].Host, c.Servers[0].Port)
	log.Printf("Connecting to host: %s\n", server)

	conn, err := net.Dial("tcp", server)
	c.connection = conn
	return c, err
}

//Close Hot Rod Connection
func (c *Client) Close() error {
	if c.connection != nil {
		return c.connection.Close()
	}
	return nil
}

//Get gets a key
func (c *Client) Get(key []byte) (*ResponseGet, error) {
	get := createGet(key, <-id, c.CacheName)
	c.connection.Write(get)
	status, err := bufio.NewReader(c.connection).Read(c.buf[:1024])
	if err != nil {
		return &ResponseGet{}, err
	}
	p := NewBuffer(c.buf[:status])
	return p.DecodeGetResponse()
}

//Put puts an object with a key
func (c *Client) Put(key []byte, object []byte) (*ResponsePut, error) {
	return c.realPut(key, object, "0", "0", false)
}

//PutWithOptions puts an object with a key and optional parameters
func (c *Client) PutWithOptions(key []byte, object []byte, opts map[string]string) (*ResponsePut, error) {
	lifespan := opts["lifespan"]
	if lifespan == "" {
		lifespan = "0"
	}

	maxidle := opts["maxidle"]
	if maxidle == "" {
		maxidle = "0"
	}

	returnValues, err := strconv.ParseBool(opts["returnValues"])

	if err == nil {
		return c.realPut(key, object, lifespan, maxidle, false)
	}
	return c.realPut(key, object, lifespan, maxidle, returnValues)

}

//PutWithLifespanAndMaxidle puts an object with a key and a lifespan/maxidle
func (c *Client) realPut(key []byte, object []byte, lifespan string, maxidle string, returnValue bool) (*ResponsePut, error) {
	if put, createErr := createPut(key, object, <-id, c.CacheName, lifespan, maxidle); createErr == nil {
		c.connection.Write(put)
		if status, ioErr := bufio.NewReader(c.connection).Read(c.buf[:1024]); ioErr == nil {
			p := NewBuffer(c.buf[:status])
			return p.DecodePutResponse()
		} else {
			return &ResponsePut{}, ioErr
		}
	} else {
		return &ResponsePut{}, createErr
	}

}
<|endoftext|>


<commit_before>// Protocol is a package that klient and several other packages uses. It
// contains the information which is passed to the kite library during booting.
// They are a part of the KiteQuert.
package protocol

var (
	Version string
)

const (
	Name        = "klient"
	Environment = "public-host"
	Region      = "public-region"
)
<commit_msg>go/package: simplify passing ld flags<commit_after>// Protocol is a package that klient and several other packages uses. It
// contains the information which is passed to the kite library during booting.
// They are a part of the KiteQuert.
package protocol

var (
	Version     string
	Environment string
)

const (
	Name   = "klient"
	Region = "public-region"
)
<|endoftext|>