<commit_before>// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// 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 oglemock_test

import (
	. "github.com/jacobsa/oglematchers"
	. "github.com/jacobsa/oglemock"
	. "github.com/jacobsa/ogletest"
	"reflect"
)

////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////

var emptyReturnSig reflect.Type = reflect.TypeOf(func(i int) {})
var float64ReturnSig reflect.Type = reflect.TypeOf(func(i int) float64 { return 17.0 })

type CallExpectationTest struct {
}

func init() { RegisterTestSuite(&CallExpectationTest{}) }

////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////

func (t *CallExpectationTest) StoresFileNameAndLineNumber() {
	args := []interface{}{}
	exp := InternalNewExpectation(emptyReturnSig, args, "taco", 17)

	ExpectThat(exp.FileName, Equals("taco"))
	ExpectThat(exp.LineNumber, Equals(17))
}

func (t *CallExpectationTest) NoArgs() {
	args := []interface{}{}
	exp := InternalNewExpectation(emptyReturnSig, args, "", 0)

	ExpectThat(len(exp.ArgMatchers), Equals(0))
}

func (t *CallExpectationTest) MixOfMatchersAndNonMatchers() {
	args := []interface{}{Equals(17), 19, Equals(23)}
	exp := InternalNewExpectation(emptyReturnSig, args, "", 0)

	// Matcher args
	ExpectThat(len(exp.ArgMatchers), Equals(3))
	ExpectThat(exp.ArgMatchers[0], Equals(args[0]))
	ExpectThat(exp.ArgMatchers[2], Equals(args[2]))

	// Non-matcher arg
	var res MatchResult
	matcher1 := exp.ArgMatchers[1]

	res, _ = matcher1.Matches(17)
	ExpectThat(res, Equals(MATCH_FALSE))

	res, _ = matcher1.Matches(19)
	ExpectThat(res, Equals(MATCH_TRUE))

	res, _ = matcher1.Matches(23)
	ExpectThat(res, Equals(MATCH_FALSE))
}

func (t *CallExpectationTest) NoTimes() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)

	ExpectThat(exp.ExpectedNumMatches, Equals(-1))
}

func (t *CallExpectationTest) TimesN() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)
	exp.Times(17)

	ExpectThat(exp.ExpectedNumMatches, Equals(17))
}

func (t *CallExpectationTest) NoActions() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)

	ExpectThat(len(exp.OneTimeActions), Equals(0))
	ExpectThat(exp.FallbackAction, Equals(nil))
}

func (t *CallExpectationTest) WillOnce() {
	action0 := Return(17.0)
	action1 := Return(19.0)

	exp := InternalNewExpectation(float64ReturnSig, []interface{}{}, "", 0)
	exp.WillOnce(action0).WillOnce(action1)

	ExpectThat(len(exp.OneTimeActions), Equals(2))
	ExpectThat(exp.OneTimeActions[0], Equals(action0))
	ExpectThat(exp.OneTimeActions[1], Equals(action1))
}

func (t *CallExpectationTest) WillRepeatedly() {
	action := Return(17.0)

	exp := InternalNewExpectation(float64ReturnSig, []interface{}{}, "", 0)
	exp.WillRepeatedly(action)

	ExpectThat(exp.FallbackAction, Equals(action))
}

func (t *CallExpectationTest) BothKindsOfAction() {
	action0 := Return(17.0)
	action1 := Return(19.0)
	action2 := Return(23.0)

	exp := InternalNewExpectation(float64ReturnSig, []interface{}{}, "", 0)
	exp.WillOnce(action0).WillOnce(action1).WillRepeatedly(action2)

	ExpectThat(len(exp.OneTimeActions), Equals(2))
	ExpectThat(exp.OneTimeActions[0], Equals(action0))
	ExpectThat(exp.OneTimeActions[1], Equals(action1))
	ExpectThat(exp.FallbackAction, Equals(action2))
}

func (t *CallExpectationTest) TimesCalledWithHugeNumber() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)

	ExpectThat(
		func() { exp.Times(1 << 30) },
		Panics(Error(HasSubstr("Times: N must be at most 1000"))))
}

func (t *CallExpectationTest) TimesCalledTwice() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)

	ExpectThat(
		func() { exp.Times(17).Times(17) },
		Panics(Error(HasSubstr("Times called more than"))))
}

func (t *CallExpectationTest) TimesCalledAfterWillOnce() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)

	ExpectThat(
		func() { exp.WillOnce(Return()).Times(17) },
		Panics(Error(HasSubstr("Times called after WillOnce"))))
}

func (t *CallExpectationTest) TimesCalledAfterWillRepeatedly() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)

	ExpectThat(
		func() { exp.WillRepeatedly(Return()).Times(17) },
		Panics(Error(HasSubstr("Times called after WillRepeatedly"))))
}

func (t *CallExpectationTest) WillOnceCalledAfterWillRepeatedly() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)

	ExpectThat(
		func() { exp.WillRepeatedly(Return()).WillOnce(Return()) },
		Panics(Error(HasSubstr("WillOnce called after WillRepeatedly"))))
}

func (t *CallExpectationTest) OneTimeActionRejectsSignature() {
	action := Return("taco")
	exp := InternalNewExpectation(float64ReturnSig, []interface{}{}, "", 0)

	ExpectThat(
		func() { exp.WillOnce(action) },
		Panics(Error(HasSubstr("arg 0; expected float64"))))
}

func (t *CallExpectationTest) WillRepeatedlyCalledTwice() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)

	ExpectThat(
		func() { exp.WillRepeatedly(Return()).WillRepeatedly(Return()) },
		Panics(Error(HasSubstr("WillRepeatedly called more than once"))))
}

func (t *CallExpectationTest) FallbackActionRejectsSignature() {
	action := Return("taco")
	exp := InternalNewExpectation(float64ReturnSig, []interface{}{}, "", 0)

	ExpectThat(
		func() { exp.WillRepeatedly(action) },
		Panics(Error(HasSubstr("arg 0; expected float64"))))
}
<commit_msg>Fixed a test bug.<commit_after>// Copyright 2011 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// 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 oglemock_test

import (
	. "github.com/jacobsa/oglematchers"
	. "github.com/jacobsa/oglemock"
	. "github.com/jacobsa/ogletest"
	"reflect"
)

////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////

var emptyReturnSig reflect.Type = reflect.TypeOf(func(i int) {})
var float64ReturnSig reflect.Type = reflect.TypeOf(func(i int) float64 { return 17.0 })

type CallExpectationTest struct {
}

func init() { RegisterTestSuite(&CallExpectationTest{}) }

////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////

func (t *CallExpectationTest) StoresFileNameAndLineNumber() {
	args := []interface{}{}
	exp := InternalNewExpectation(emptyReturnSig, args, "taco", 17)

	ExpectThat(exp.FileName, Equals("taco"))
	ExpectThat(exp.LineNumber, Equals(17))
}

func (t *CallExpectationTest) NoArgs() {
	args := []interface{}{}
	exp := InternalNewExpectation(emptyReturnSig, args, "", 0)

	ExpectThat(len(exp.ArgMatchers), Equals(0))
}

func (t *CallExpectationTest) MixOfMatchersAndNonMatchers() {
	args := []interface{}{Equals(17), 19, Equals(23)}
	exp := InternalNewExpectation(emptyReturnSig, args, "", 0)

	// Matcher args
	ExpectThat(len(exp.ArgMatchers), Equals(3))
	ExpectThat(exp.ArgMatchers[0], Equals(args[0]))
	ExpectThat(exp.ArgMatchers[2], Equals(args[2]))

	// Non-matcher arg
	var res MatchResult
	matcher1 := exp.ArgMatchers[1]

	res, _ = matcher1.Matches(17)
	ExpectThat(res, Equals(MATCH_FALSE))

	res, _ = matcher1.Matches(19)
	ExpectThat(res, Equals(MATCH_TRUE))

	res, _ = matcher1.Matches(23)
	ExpectThat(res, Equals(MATCH_FALSE))
}

func (t *CallExpectationTest) NoTimes() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)

	ExpectThat(exp.ExpectedNumMatches, Equals(-1))
}

func (t *CallExpectationTest) TimesN() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)
	exp.Times(17)

	ExpectThat(exp.ExpectedNumMatches, Equals(17))
}

func (t *CallExpectationTest) NoActions() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)

	ExpectThat(len(exp.OneTimeActions), Equals(0))
	ExpectThat(exp.FallbackAction, Equals(nil))
}

func (t *CallExpectationTest) WillOnce() {
	action0 := Return(17.0)
	action1 := Return(19.0)

	exp := InternalNewExpectation(float64ReturnSig, []interface{}{}, "", 0)
	exp.WillOnce(action0).WillOnce(action1)

	ExpectThat(len(exp.OneTimeActions), Equals(2))
	ExpectThat(exp.OneTimeActions[0], Equals(action0))
	ExpectThat(exp.OneTimeActions[1], Equals(action1))
}

func (t *CallExpectationTest) WillRepeatedly() {
	action := Return(17.0)

	exp := InternalNewExpectation(float64ReturnSig, []interface{}{}, "", 0)
	exp.WillRepeatedly(action)

	ExpectThat(exp.FallbackAction, Equals(action))
}

func (t *CallExpectationTest) BothKindsOfAction() {
	action0 := Return(17.0)
	action1 := Return(19.0)
	action2 := Return(23.0)

	exp := InternalNewExpectation(float64ReturnSig, []interface{}{}, "", 0)
	exp.WillOnce(action0).WillOnce(action1).WillRepeatedly(action2)

	ExpectThat(len(exp.OneTimeActions), Equals(2))
	ExpectThat(exp.OneTimeActions[0], Equals(action0))
	ExpectThat(exp.OneTimeActions[1], Equals(action1))
	ExpectThat(exp.FallbackAction, Equals(action2))
}

func (t *CallExpectationTest) TimesCalledWithHugeNumber() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)

	ExpectThat(
		func() { exp.Times(1 << 30) },
		Panics(Error(HasSubstr("Times: N must be at most 1000"))))
}

func (t *CallExpectationTest) TimesCalledTwice() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)

	ExpectThat(
		func() { exp.Times(17).Times(17) },
		Panics(Error(HasSubstr("Times called more than"))))
}

func (t *CallExpectationTest) TimesCalledAfterWillOnce() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)

	ExpectThat(
		func() { exp.WillOnce(Return()).Times(17) },
		Panics(Error(HasSubstr("Times called after WillOnce"))))
}

func (t *CallExpectationTest) TimesCalledAfterWillRepeatedly() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)

	ExpectThat(
		func() { exp.WillRepeatedly(Return()).Times(17) },
		Panics(Error(HasSubstr("Times called after WillRepeatedly"))))
}

func (t *CallExpectationTest) WillOnceCalledAfterWillRepeatedly() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)

	ExpectThat(
		func() { exp.WillRepeatedly(Return()).WillOnce(Return()) },
		Panics(Error(HasSubstr("WillOnce called after WillRepeatedly"))))
}

func (t *CallExpectationTest) OneTimeActionRejectsSignature() {
	action := Return("taco")
	exp := InternalNewExpectation(float64ReturnSig, []interface{}{}, "", 0)

	ExpectThat(
		func() { exp.WillOnce(action) },
		Panics(Error(HasSubstr("arg 0; expected float64"))))
}

func (t *CallExpectationTest) WillRepeatedlyCalledTwice() {
	exp := InternalNewExpectation(emptyReturnSig, []interface{}{}, "", 0)

	ExpectThat(
		func() { exp.WillRepeatedly(Return()).WillRepeatedly(Return()) },
		Panics(Error(HasSubstr("WillRepeatedly called more than once"))))
}

func (t *CallExpectationTest) FallbackActionRejectsSignature() {
	action := Return("taco")
	exp := InternalNewExpectation(float64ReturnSig, []interface{}{}, "", 0)

	ExpectThat(
		func() { exp.WillRepeatedly(action) },
		Panics(HasSubstr("arg 0; expected float64")))
}
<|endoftext|>


<commit_before>package cmd_test

import (
	"path/filepath"

	"github.com/cloudfoundry/cli/testhelpers/pluginbuilder"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"testing"
)

func TestMain(t *testing.T) {
	RegisterFailHandler(Fail)

	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "test_1")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "test_2")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "test_with_push")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "test_with_push_short_name")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "test_with_help")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "my_say")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "call_core_cmd")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "input")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "panics")

	//compile plugin examples to ensure they're up to date
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "plugin_examples"), "basic_plugin")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "plugin_examples"), "echo")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "plugin_examples"), "interactive")

	RunSpecs(t, "Cmd Suite")
}
<commit_msg>Increase timeout on cmd suite<commit_after>package cmd_test

import (
	"path/filepath"
	"time"

	"github.com/cloudfoundry/cli/testhelpers/pluginbuilder"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	"testing"
)

func TestMain(t *testing.T) {
	RegisterFailHandler(Fail)

	SetDefaultEventuallyTimeout(2 * time.Second)

	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "test_1")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "test_2")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "test_with_push")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "test_with_push_short_name")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "test_with_help")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "my_say")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "call_core_cmd")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "input")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "fixtures", "plugins"), "panics")

	//compile plugin examples to ensure they're up to date
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "plugin_examples"), "basic_plugin")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "plugin_examples"), "echo")
	pluginbuilder.BuildTestBinary(filepath.Join("..", "..", "plugin_examples"), "interactive")

	RunSpecs(t, "Cmd Suite")
}
<|endoftext|>


<commit_before>package procfs

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

import (
	"io/ioutil"
	"log"
	"os"
	"path"
	"strconv"
	"strings"

	"github.com/jandre/procfs/limits"
	"github.com/jandre/procfs/stat"
	"github.com/jandre/procfs/statm"
)

//
// Process describes a /proc/<pid> entry
//
type Process struct {
	Pid       int               // Process ID
	Environ   map[string]string // Environment variables
	Cmdline   []string          // Command line of process (argv array)
	Cwd       string            // Process current working directory
	Exe       string            // Symlink to executed command.
	Root      string            // Per-process root (e.g. chroot)
	prefix    string            // directory path, e.g. /proc/<pid>
	stat      *stat.Stat        // Status information from /proc/pid/stat - see Stat()
	statm     *statm.Statm      // Memory Status information from /proc/pid/statm - see Statm()
	limits    *limits.Limits    // Per process rlimit settings from /proc/pid/limits - see Limits()
	loginuid  *int              // Maybe loginuid from /proc/pid/loginuid - see Loginuid()
	sessionid *int              // Maybe sessionid from /proc/pid/sessionid- see Sessionid()

}

//
// Read /proc information for `pid`
//
func NewProcess(pid int, lazy bool) (*Process, error) {
	prefix := path.Join("/proc", strconv.Itoa(pid))
	return NewProcessFromPath(pid, prefix, lazy)
}

//
// Read a process entry from a directory path
//
// if lazy = true, then preload the stat, limits, and other files.
//
func NewProcessFromPath(pid int, prefix string, lazy bool) (*Process, error) {
	var err error

	if _, err = os.Stat(prefix); err != nil {
		// error reading pid
		return nil, err
	}

	process := &Process{prefix: prefix, Pid: pid}
	if process.Cmdline, err = readCmdLine(prefix); err != nil {
		return nil, err
	}

	if process.Exe, err = readLink(prefix, "exe"); err != nil {
		process.Exe = ""
	}

	if process.Cwd, err = readLink(prefix, "cwd"); err != nil {
		return nil, err
	}

	if process.Root, err = readLink(prefix, "root"); err != nil {
		return nil, err
	}

	process.readEnviron()

	if !lazy {
		// preload all of the subdirs
		process.Stat()
		process.Limits()
		process.Loginuid()
		process.Sessionid()
	}

	return process, nil
}

const NO_VALUE = 4294967295

func clearEmpty(strings []string) []string {
	var filtered []string
	for _, v := range strings {
		if len(v) != 0 {
			filtered = append(filtered, v)
		}
	}
	return filtered
}

//
// read integer from file
//
func readFileInteger(prefix string, file string) (*int, error) {
	filename := path.Join(prefix, file)
	str, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	if val, err := strconv.Atoi(string(str)); err != nil {
		return nil, err
	} else {
		return &val, nil
	}
}

//

//
// read link
//
func readLink(prefix string, file string) (string, error) {
	filename := path.Join(prefix, file)
	str, err := os.Readlink(filename)
	if err != nil {
		return "", err
	}
	return string(str), nil
}

//
// Read a /proc/<pid>/cmdline file and break up into array
// of argv
//
func readCmdLine(prefix string) ([]string, error) {
	filename := path.Join(prefix, "cmdline")
	str, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	return clearEmpty(strings.Split(string(str), "\x00")), nil
}

//
// Parser for /proc/<pid>/stat
//
func (p *Process) Stat() (*stat.Stat, error) {
	var err error
	if p.stat == nil {
		if p.stat, err = stat.New(path.Join(p.prefix, "stat")); err != nil {
			return nil, err
		}
	}

	return p.stat, nil
}

//
// Parser for /proc/<pid>/limits
//
func (p *Process) Limits() (*limits.Limits, error) {
	var err error
	if p.limits == nil {
		if p.limits, err = limits.New(path.Join(p.prefix, "limits")); err != nil {
			return nil, err
		}
	}

	return p.limits, nil
}

//
// Parses contents of /proc/pid/loginuid (if present)
//
func (p *Process) Loginuid() int {
	var err error
	if p.loginuid == nil {
		p.loginuid, err = readFileInteger(p.prefix, "loginuid")
		if err != nil {
			log.Println("Warning: unable to read loginuid so returning nil:", err)
		}

	}

	if p.loginuid != nil {
		return *p.loginuid
	}
	return NO_VALUE

}

//
// Parses contents of /proc/pid/sessionid (if present)
//
func (p *Process) Sessionid() int {
	var err error
	if p.sessionid == nil {
		p.sessionid, err = readFileInteger(p.prefix, "sessionid")
		if err != nil {
			log.Println("Warning: unable to read sessionid so returning nil:", err)
		}

	}

	if p.sessionid != nil {
		return *p.sessionid
	}
	return NO_VALUE
}

func (p *Process) readEnviron() {
	p.Environ = make(map[string]string, 0)
	bytes, err := ioutil.ReadFile(path.Join(p.prefix, "environ"))
	if err != nil {
		return
	}
	for _, item := range strings.Split(string(bytes), "\x00") {
		fields := strings.SplitN(item, "=", 2)
		if (len(fields) == 2) {
			p.Environ[fields[0]] = fields[1]
		}
	}
}
<commit_msg>Added Status poll method to the Process Struct<commit_after>package procfs

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

import (
	"io/ioutil"
	"log"
	"os"
	"path"
	"strconv"
	"strings"

	"github.com/jandre/procfs/limits"
	"github.com/jandre/procfs/stat"
	"github.com/jandre/procfs/statm"
	"github.com/jandre/procfs/status"
)

//
// Process describes a /proc/<pid> entry
//
type Process struct {
	Pid       int               // Process ID
	Environ   map[string]string // Environment variables
	Cmdline   []string          // Command line of process (argv array)
	Cwd       string            // Process current working directory
	Exe       string            // Symlink to executed command.
	Root      string            // Per-process root (e.g. chroot)
	prefix    string            // directory path, e.g. /proc/<pid>
	stat      *stat.Stat        // Status information from /proc/pid/stat - see Stat()
	statm     *statm.Statm      // Memory Status information from /proc/pid/statm - see Statm()
	limits    *limits.Limits    // Per process rlimit settings from /proc/pid/limits - see Limits()
	status    *status.Status    //Status information from /proc/pid/status see Status()
	loginuid  *int              // Maybe loginuid from /proc/pid/loginuid - see Loginuid()
	sessionid *int              // Maybe sessionid from /proc/pid/sessionid- see Sessionid()

}

//
// Read /proc information for `pid`
//
func NewProcess(pid int, lazy bool) (*Process, error) {
	prefix := path.Join("/proc", strconv.Itoa(pid))
	return NewProcessFromPath(pid, prefix, lazy)
}

//
// Read a process entry from a directory path
//
// if lazy = true, then preload the stat, limits, and other files.
//
func NewProcessFromPath(pid int, prefix string, lazy bool) (*Process, error) {
	var err error

	if _, err = os.Stat(prefix); err != nil {
		// error reading pid
		return nil, err
	}

	process := &Process{prefix: prefix, Pid: pid}
	if process.Cmdline, err = readCmdLine(prefix); err != nil {
		return nil, err
	}

	if process.Exe, err = readLink(prefix, "exe"); err != nil {
		process.Exe = ""
	}

	if process.Cwd, err = readLink(prefix, "cwd"); err != nil {
		return nil, err
	}

	if process.Root, err = readLink(prefix, "root"); err != nil {
		return nil, err
	}

	process.readEnviron()

	if !lazy {
		// preload all of the subdirs
		process.Stat()
		process.Limits()
		process.Loginuid()
		process.Sessionid()
	}

	return process, nil
}

const NO_VALUE = 4294967295

func clearEmpty(strings []string) []string {
	var filtered []string
	for _, v := range strings {
		if len(v) != 0 {
			filtered = append(filtered, v)
		}
	}
	return filtered
}

//
// read integer from file
//
func readFileInteger(prefix string, file string) (*int, error) {
	filename := path.Join(prefix, file)
	str, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	if val, err := strconv.Atoi(string(str)); err != nil {
		return nil, err
	} else {
		return &val, nil
	}
}

//

//
// read link
//
func readLink(prefix string, file string) (string, error) {
	filename := path.Join(prefix, file)
	str, err := os.Readlink(filename)
	if err != nil {
		return "", err
	}
	return string(str), nil
}

//
// Read a /proc/<pid>/cmdline file and break up into array
// of argv
//
func readCmdLine(prefix string) ([]string, error) {
	filename := path.Join(prefix, "cmdline")
	str, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	return clearEmpty(strings.Split(string(str), "\x00")), nil
}

//
// Parser for /proc/<pid>/stat
//
func (p *Process) Stat() (*stat.Stat, error) {
	var err error
	if p.stat == nil {
		if p.stat, err = stat.New(path.Join(p.prefix, "stat")); err != nil {
			return nil, err
		}
	}

	return p.stat, nil
}

//
// Parser for /proc/<pid>/status
//
func (p *Process) Status() (*status.Status, error) {
	var err error
	if p.status == nil {
		if p.status, err = status.New(path.Join(p.prefix, "status")); err != nil {
			return nil, err
		}
	}

	return p.status, nil
}

//
// Parser for /proc/<pid>/limits
//
func (p *Process) Limits() (*limits.Limits, error) {
	var err error
	if p.limits == nil {
		if p.limits, err = limits.New(path.Join(p.prefix, "limits")); err != nil {
			return nil, err
		}
	}

	return p.limits, nil
}

//
// Parses contents of /proc/pid/loginuid (if present)
//
func (p *Process) Loginuid() int {
	var err error
	if p.loginuid == nil {
		p.loginuid, err = readFileInteger(p.prefix, "loginuid")
		if err != nil {
			log.Println("Warning: unable to read loginuid so returning nil:", err)
		}

	}

	if p.loginuid != nil {
		return *p.loginuid
	}
	return NO_VALUE

}

//
// Parses contents of /proc/pid/sessionid (if present)
//
func (p *Process) Sessionid() int {
	var err error
	if p.sessionid == nil {
		p.sessionid, err = readFileInteger(p.prefix, "sessionid")
		if err != nil {
			log.Println("Warning: unable to read sessionid so returning nil:", err)
		}

	}

	if p.sessionid != nil {
		return *p.sessionid
	}
	return NO_VALUE
}

func (p *Process) readEnviron() {
	p.Environ = make(map[string]string, 0)
	bytes, err := ioutil.ReadFile(path.Join(p.prefix, "environ"))
	if err != nil {
		return
	}
	for _, item := range strings.Split(string(bytes), "\x00") {
		fields := strings.SplitN(item, "=", 2)
		if len(fields) == 2 {
			p.Environ[fields[0]] = fields[1]
		}
	}
}
<|endoftext|>


<commit_before>package steam

import (
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
)

const (
	PrivacyStatePrivate     = 1
	PrivacyStateFriendsOnly = 2
	PrivacyStatePublic      = 3
)

const (
	CommentSettingSelf    = "commentselfonly"
	CommentSettingFriends = "commentfriendsonly"
	CommentSettingPublic  = "commentanyone"
)

func (session *Session) GetProfileURL() (string, error) {
	/* We do not follow redirect, we want to know where it'd redirect us.  */
	session.client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
		return errors.New("do not redirect")
	}

	/* Query normal, this will redirect us.  */
	resp, err := session.client.Get("https://steamcommunity.com/my")

	/* We restore redirect policy to default.  */
	session.client.CheckRedirect = nil

	if resp == nil {
		return "", err
	}

	io.Copy(ioutil.Discard, resp.Body)
	resp.Body.Close()

	if resp.StatusCode != http.StatusFound {
		return "", fmt.Errorf("http error: %d", resp.StatusCode)
	}

	/* We now have a few useful variables in header, for now, we will just grap "Location".  */
	return resp.Header.Get("Location"), nil
}

func (session *Session) SetupProfile(profileURL string) error {
	resp, err := session.client.Get(profileURL + "/edit?welcomed=1")
	if resp != nil {
		io.Copy(ioutil.Discard, resp.Body)
		resp.Body.Close()
	}

	if err != nil {
		return err
	}

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("http error: %d", resp.StatusCode)
	}

	return nil
}

func (session *Session) SetProfileInfo(profileURL string, values *map[string][]string) error {
	(*values)["sessionID"] = []string{session.sessionID}
	(*values)["type"] = []string{"profileSave"}

	resp, err := session.client.PostForm(profileURL+"/edit", *values)
	if resp != nil {
		io.Copy(ioutil.Discard, resp.Body)
		defer resp.Body.Close()
	}

	if err != nil {
		return err
	}

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("http error: %d", resp.StatusCode)
	}

	return nil
}

func (session *Session) SetProfilePrivacy(profileURL string, commentPrivacy string, privacy uint8) error {
	resp, err := session.client.PostForm(profileURL+"/edit/settings", url.Values{
		"sessionID":               {session.sessionID},
		"type":                    {"profileSettings"},
		"commentSetting":          {commentPrivacy},
		"privacySetting":          {strconv.FormatUint(uint64(privacy&0x3), 10)},
		"inventoryPrivacySetting": {strconv.FormatUint(uint64((privacy>>2)&0x3), 10)},
		"inventoryGiftPrivacy":    {strconv.FormatUint(uint64((privacy>>4)&0x3), 10)},
	})
	if resp != nil {
		io.Copy(ioutil.Discard, resp.Body)
		resp.Body.Close()
	}

	if err != nil {
		return err
	}

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("http error: %d", resp.StatusCode)
	}

	return nil
}
<commit_msg>Use a temporary client object in GetProfileURL<commit_after>package steam

import (
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
)

const (
	PrivacyStatePrivate     = 1
	PrivacyStateFriendsOnly = 2
	PrivacyStatePublic      = 3
)

const (
	CommentSettingSelf    = "commentselfonly"
	CommentSettingFriends = "commentfriendsonly"
	CommentSettingPublic  = "commentanyone"
)

func (session *Session) GetProfileURL() (string, error) {
	tmpClient := http.Client{Jar: session.client.Jar}

	/* We do not follow redirect, we want to know where it'd redirect us.  */
	tmpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
		return errors.New("do not redirect")
	}

	/* Query normal, this will redirect us.  */
	resp, err := tmpClient.Get("https://steamcommunity.com/my")
	if resp == nil {
		return "", err
	}

	io.Copy(ioutil.Discard, resp.Body)
	resp.Body.Close()

	if resp.StatusCode != http.StatusFound {
		return "", fmt.Errorf("http error: %d", resp.StatusCode)
	}

	/* We now have a few useful variables in header, for now, we will just grap "Location".  */
	return resp.Header.Get("Location"), nil
}

func (session *Session) SetupProfile(profileURL string) error {
	resp, err := session.client.Get(profileURL + "/edit?welcomed=1")
	if resp != nil {
		io.Copy(ioutil.Discard, resp.Body)
		resp.Body.Close()
	}

	if err != nil {
		return err
	}

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("http error: %d", resp.StatusCode)
	}

	return nil
}

func (session *Session) SetProfileInfo(profileURL string, values *map[string][]string) error {
	(*values)["sessionID"] = []string{session.sessionID}
	(*values)["type"] = []string{"profileSave"}

	resp, err := session.client.PostForm(profileURL+"/edit", *values)
	if resp != nil {
		io.Copy(ioutil.Discard, resp.Body)
		defer resp.Body.Close()
	}

	if err != nil {
		return err
	}

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("http error: %d", resp.StatusCode)
	}

	return nil
}

func (session *Session) SetProfilePrivacy(profileURL string, commentPrivacy string, privacy uint8) error {
	resp, err := session.client.PostForm(profileURL+"/edit/settings", url.Values{
		"sessionID":               {session.sessionID},
		"type":                    {"profileSettings"},
		"commentSetting":          {commentPrivacy},
		"privacySetting":          {strconv.FormatUint(uint64(privacy&0x3), 10)},
		"inventoryPrivacySetting": {strconv.FormatUint(uint64((privacy>>2)&0x3), 10)},
		"inventoryGiftPrivacy":    {strconv.FormatUint(uint64((privacy>>4)&0x3), 10)},
	})
	if resp != nil {
		io.Copy(ioutil.Discard, resp.Body)
		resp.Body.Close()
	}

	if err != nil {
		return err
	}

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("http error: %d", resp.StatusCode)
	}

	return nil
}
<|endoftext|>


<commit_before>package xbl

import (
	"fmt"
	"net/url"
	"strconv"
	"strings"
)

// Profile describe's a gamer's Xbox Live account.
type Profile struct {
	ID             string `json:"id"`
	Gamertag       string `json:"gamertag,omitempty"`
	Gamerscore     int    `json:"gamerscore,omitempty"`
	GamerPicture   string `json:"gamer_picture,omitempty"`
	AccountTier    string `json:"account_tier,omitempty"`
	Reputation     string `json:"reputation,omitempty"`
	PreferredColor string `json:"preferred_color,omitempty"`
	Tenure         int    `json:"tenure_level,omitempty"`
	Bio            string `json:"bio,omitempty"`
	Location       string `json:"location,omitempty"`
}

var profileSettings = []string{
	"Gamerscore", "Gamertag", "GameDisplayPicRaw", "AccountTier", "Bio",
	"XboxOneRep", "PreferredColor", "TenureLevel", "Location",
}

// Profile retrieves the profile for the provided gamertag.
func (c *Client) Profile(gamertag string) (*Profile, error) {
	u := url.URL{
		Scheme:   "https",
		Host:     "profile.xboxlive.com",
		Path:     fmt.Sprintf("/users/gt(%s)/settings", gamertag),
		RawQuery: url.Values{"settings": {strings.Join(profileSettings, ",")}}.Encode(),
	}

	var resp profileResponse
	err := c.get(u.String(), vBoth, &resp)
	if err != nil {
		return nil, err
	}

	profiles, err := resp.parseProfiles()
	if err != nil {
		return nil, err
	}
	if len(profiles) < 1 {
		return nil, nil
	}
	return profiles[0], nil
}

// Profiles retrieves the profiles for the users with the provided IDs.
func (c *Client) Profiles(userIDs ...string) ([]*Profile, error) {
	const url = "https://profile.xboxlive.com/users/batch/profile/settings"

	req := struct {
		Settings []string `json:"settings"`
		UserIDs  []string `json:"userIds"`
	}{
		Settings: profileSettings,
		UserIDs:  userIDs,
	}
	var resp profileResponse
	err := c.post(url, vBoth, req, &resp)
	if err != nil {
		return nil, err
	}

	profiles, err := resp.parseProfiles()
	if err != nil {
		return nil, err
	}
	return profiles, nil
}

type profileResponse struct {
	ProfileUsers []struct {
		ID       string              `json:"id"`
		Settings []map[string]string `json:"settings"`
	} `json:"profileUsers"`
}

func (resp *profileResponse) parseProfiles() ([]*Profile, error) {
	profiles := make([]*Profile, 0, len(resp.ProfileUsers))
	for _, pu := range resp.ProfileUsers {
		m := map[string]string{}
		for _, setting := range pu.Settings {
			m[setting["id"]] = setting["value"]
		}
		tenure, err := strconv.Atoi(m["TenureLevel"])
		if err != nil {
			return nil, err
		}
		gamerscore, err := strconv.Atoi(m["Gamerscore"])
		if err != nil {
			return nil, err
		}

		profiles = append(profiles, &Profile{
			ID:             pu.ID,
			Gamertag:       m["Gamertag"],
			Gamerscore:     gamerscore,
			GamerPicture:   m["GameDisplayPicRaw"],
			AccountTier:    m["AccountTier"],
			Reputation:     m["XboxOneRep"],
			PreferredColor: m["PreferredColor"],
			Tenure:         tenure,
			Bio:            m["Bio"],
			Location:       m["Location"],
		})
	}
	return profiles, nil
}
<commit_msg>include picture_url in json<commit_after>package xbl

import (
	"fmt"
	"net/url"
	"strconv"
	"strings"
)

// Profile describe's a gamer's Xbox Live account.
type Profile struct {
	ID             string `json:"id"`
	Gamertag       string `json:"gamertag,omitempty"`
	Gamerscore     int    `json:"gamerscore,omitempty"`
	GamerPicture   string `json:"picture_url,omitempty"`
	AccountTier    string `json:"account_tier,omitempty"`
	Reputation     string `json:"reputation,omitempty"`
	PreferredColor string `json:"-"`
	Tenure         int    `json:"-"`
	Bio            string `json:"bio,omitempty"`
	Location       string `json:"location,omitempty"`
}

var profileSettings = []string{
	"Gamerscore", "Gamertag", "GameDisplayPicRaw", "AccountTier", "Bio",
	"XboxOneRep", "PreferredColor", "TenureLevel", "Location",
}

// Profile retrieves the profile for the provided gamertag.
func (c *Client) Profile(gamertag string) (*Profile, error) {
	u := url.URL{
		Scheme:   "https",
		Host:     "profile.xboxlive.com",
		Path:     fmt.Sprintf("/users/gt(%s)/settings", gamertag),
		RawQuery: url.Values{"settings": {strings.Join(profileSettings, ",")}}.Encode(),
	}

	var resp profileResponse
	err := c.get(u.String(), vBoth, &resp)
	if err != nil {
		return nil, err
	}

	profiles, err := resp.parseProfiles()
	if err != nil {
		return nil, err
	}
	if len(profiles) < 1 {
		return nil, nil
	}
	return profiles[0], nil
}

// Profiles retrieves the profiles for the users with the provided IDs.
func (c *Client) Profiles(userIDs ...string) ([]*Profile, error) {
	const url = "https://profile.xboxlive.com/users/batch/profile/settings"

	req := struct {
		Settings []string `json:"settings"`
		UserIDs  []string `json:"userIds"`
	}{
		Settings: profileSettings,
		UserIDs:  userIDs,
	}
	var resp profileResponse
	err := c.post(url, vBoth, req, &resp)
	if err != nil {
		return nil, err
	}

	profiles, err := resp.parseProfiles()
	if err != nil {
		return nil, err
	}
	return profiles, nil
}

type profileResponse struct {
	ProfileUsers []struct {
		ID       string              `json:"id"`
		Settings []map[string]string `json:"settings"`
	} `json:"profileUsers"`
}

func (resp *profileResponse) parseProfiles() ([]*Profile, error) {
	profiles := make([]*Profile, 0, len(resp.ProfileUsers))
	for _, pu := range resp.ProfileUsers {
		m := map[string]string{}
		for _, setting := range pu.Settings {
			m[setting["id"]] = setting["value"]
		}
		tenure, err := strconv.Atoi(m["TenureLevel"])
		if err != nil {
			return nil, err
		}
		gamerscore, err := strconv.Atoi(m["Gamerscore"])
		if err != nil {
			return nil, err
		}

		profiles = append(profiles, &Profile{
			ID:             pu.ID,
			Gamertag:       m["Gamertag"],
			Gamerscore:     gamerscore,
			GamerPicture:   m["GameDisplayPicRaw"],
			AccountTier:    m["AccountTier"],
			Reputation:     m["XboxOneRep"],
			PreferredColor: m["PreferredColor"],
			Tenure:         tenure,
			Bio:            m["Bio"],
			Location:       m["Location"],
		})
	}
	return profiles, nil
}
<|endoftext|>


<commit_before>// Package profile provides a simple way to manage runtime/pprof
// profiling of your Go application.
package profile

import (
	"io/ioutil"
	"log"
	"os"
	"os/signal"
	"path/filepath"
	"runtime"
	"runtime/pprof"
	"sync/atomic"
)

const (
	cpuMode = iota
	memMode
	blockMode
)

type profile struct {
	// quiet suppresses informational messages during profiling.
	quiet bool

	// noShutdownHook controls whether the profiling package should
	// hook SIGINT to write profiles cleanly.
	noShutdownHook bool

	// mode holds the type of profiling that will be made
	mode int

	// path holds the base path where various profiling files are  written.
	// If blank, the base path will be generated by ioutil.TempDir.
	path string

	// memProfileRate holds the rate for the memory profile.
	memProfileRate int

	// closer holds a cleanup function that run after each profile
	closer func()

	// stopped records if a call to profile.Stop has been made
	stopped uint32
}

// NoShutdownHook controls whether the profiling package should
// hook SIGINT to write profiles cleanly.
// Programs with more sophisticated signal handling should set
// this to true and ensure the Stop() function returned from Start()
// is called during shutdown.
func NoShutdownHook(p *profile) { p.noShutdownHook = true }

// Quiet suppresses informational messages during profiling.
func Quiet(p *profile) { p.quiet = true }

// CPUProfile controls if cpu profiling will be enabled. It disables any previous profiling settings.
func CPUProfile(p *profile) { p.mode = cpuMode }

// DefaultMemProfileRate is the default memory profiling rate.
// See also http://golang.org/pkg/runtime/#pkg-variables
const DefaultMemProfileRate = 4096

// MemProfile controls if memory profiling will be enabled. It disables any previous profiling settings.
func MemProfile(p *profile) {
	p.memProfileRate = DefaultMemProfileRate
	p.mode = memMode
}

// MemProfileRate controls if memory profiling will be enabled. Additionally, it takes a parameter which
// allows the setting of the memory profile rate.
func MemProfileRate(rate int) func(*profile) {
	return func(p *profile) {
		p.memProfileRate = rate
		p.mode = memMode
	}
}

// BlockProfile controls if block (contention) profiling will be enabled. It disables any previous profiling settings.
func BlockProfile(p *profile) { p.mode = blockMode }

// ProfilePath controls the base path where various profiling
// files are written. If blank, the base path will be generated
// by ioutil.TempDir.
func ProfilePath(path string) func(*profile) {
	return func(p *profile) {
		p.path = path
	}
}

// Stop stops the profile and flushes any unwritten data.
func (p *profile) Stop() {
	if !atomic.CompareAndSwapUint32(&p.stopped, 0, 1) {
		// someone has already called close
		return
	}
	p.closer()
	atomic.StoreUint32(&started, 0)
}

// started is non zero if a profile is running.
var started uint32

// Start starts a new profiling session.
// The caller should call the Stop method on the value returned
// to cleanly stop profiling.
func Start(options ...func(*profile)) interface {
	Stop()
} {
	if !atomic.CompareAndSwapUint32(&started, 0, 1) {
		log.Fatal("profile: Start() already called")
	}

	var prof profile
	for _, option := range options {
		option(&prof)
	}

	path, err := func() (string, error) {
		if p := prof.path; p != "" {
			return p, os.MkdirAll(p, 0777)
		}
		return ioutil.TempDir("", "profile")
	}()

	if err != nil {
		log.Fatalf("profile: could not create initial output directory: %v", err)
	}

	logf := func(format string, args ...interface{}) {
		if !prof.quiet {
			log.Printf(format, args...)
		}
	}

	switch prof.mode {
	case cpuMode:
		fn := filepath.Join(path, "cpu.pprof")
		f, err := os.Create(fn)
		if err != nil {
			log.Fatalf("profile: could not create cpu profile %q: %v", fn, err)
		}
		logf("profile: cpu profiling enabled, %s", fn)
		pprof.StartCPUProfile(f)
		prof.closer = func() {
			pprof.StopCPUProfile()
			f.Close()
			logf("profile: cpu profiling disabled, %s", fn)
		}

	case memMode:
		fn := filepath.Join(path, "mem.pprof")
		f, err := os.Create(fn)
		if err != nil {
			log.Fatalf("profile: could not create memory profile %q: %v", fn, err)
		}
		old := runtime.MemProfileRate
		runtime.MemProfileRate = prof.memProfileRate
		logf("profile: memory profiling enabled (rate %d), %s", runtime.MemProfileRate, fn)
		prof.closer = func() {
			pprof.Lookup("heap").WriteTo(f, 0)
			f.Close()
			runtime.MemProfileRate = old
			logf("profile: memory profiling disabled, %s", fn)
		}

	case blockMode:
		fn := filepath.Join(path, "block.pprof")
		f, err := os.Create(fn)
		if err != nil {
			log.Fatalf("profile: could not create block profile %q: %v", fn, err)
		}
		runtime.SetBlockProfileRate(1)
		logf("profile: block profiling enabled, %s", fn)
		prof.closer = func() {
			pprof.Lookup("block").WriteTo(f, 0)
			f.Close()
			runtime.SetBlockProfileRate(0)
			logf("profile: block profiling disabled, %s", fn)
		}
	}

	if !prof.noShutdownHook {
		go func() {
			c := make(chan os.Signal, 1)
			signal.Notify(c, os.Interrupt)
			<-c

			log.Println("profile: caught interrupt, stopping profiles")
			prof.Stop()

			os.Exit(0)
		}()
	}

	return &prof
}
<commit_msg>comment cleanup<commit_after>// Package profile provides a simple way to manage runtime/pprof
// profiling of your Go application.
package profile

import (
	"io/ioutil"
	"log"
	"os"
	"os/signal"
	"path/filepath"
	"runtime"
	"runtime/pprof"
	"sync/atomic"
)

const (
	cpuMode = iota
	memMode
	blockMode
)

type profile struct {
	// quiet suppresses informational messages during profiling.
	quiet bool

	// noShutdownHook controls whether the profiling package should
	// hook SIGINT to write profiles cleanly.
	noShutdownHook bool

	// mode holds the type of profiling that will be made
	mode int

	// path holds the base path where various profiling files are  written.
	// If blank, the base path will be generated by ioutil.TempDir.
	path string

	// memProfileRate holds the rate for the memory profile.
	memProfileRate int

	// closer holds a cleanup function that run after each profile
	closer func()

	// stopped records if a call to profile.Stop has been made
	stopped uint32
}

// NoShutdownHook controls whether the profiling package should
// hook SIGINT to write profiles cleanly.
// Programs with more sophisticated signal handling should set
// this to true and ensure the Stop() function returned from Start()
// is called during shutdown.
func NoShutdownHook(p *profile) { p.noShutdownHook = true }

// Quiet suppresses informational messages during profiling.
func Quiet(p *profile) { p.quiet = true }

// CPUProfile enables cpu profiling.
// It disables any previous profiling settings.
func CPUProfile(p *profile) { p.mode = cpuMode }

// DefaultMemProfileRate is the default memory profiling rate.
// See also http://golang.org/pkg/runtime/#pkg-variables
const DefaultMemProfileRate = 4096

// MemProfile enables memory profiling.
// It disables any previous profiling settings.
func MemProfile(p *profile) {
	p.memProfileRate = DefaultMemProfileRate
	p.mode = memMode
}

// MemProfileRate enables memory profiling at the preferred rate.
// It disables any previous profiling settings.
func MemProfileRate(rate int) func(*profile) {
	return func(p *profile) {
		p.memProfileRate = rate
		p.mode = memMode
	}
}

// BlockProfile enables block (contention) profiling.
// It disables any previous profiling settings.
func BlockProfile(p *profile) { p.mode = blockMode }

// ProfilePath controls the base path where various profiling
// files are written. If blank, the base path will be generated
// by ioutil.TempDir.
func ProfilePath(path string) func(*profile) {
	return func(p *profile) {
		p.path = path
	}
}

// Stop stops the profile and flushes any unwritten data.
func (p *profile) Stop() {
	if !atomic.CompareAndSwapUint32(&p.stopped, 0, 1) {
		// someone has already called close
		return
	}
	p.closer()
	atomic.StoreUint32(&started, 0)
}

// started is non zero if a profile is running.
var started uint32

// Start starts a new profiling session.
// The caller should call the Stop method on the value returned
// to cleanly stop profiling.
func Start(options ...func(*profile)) interface {
	Stop()
} {
	if !atomic.CompareAndSwapUint32(&started, 0, 1) {
		log.Fatal("profile: Start() already called")
	}

	var prof profile
	for _, option := range options {
		option(&prof)
	}

	path, err := func() (string, error) {
		if p := prof.path; p != "" {
			return p, os.MkdirAll(p, 0777)
		}
		return ioutil.TempDir("", "profile")
	}()

	if err != nil {
		log.Fatalf("profile: could not create initial output directory: %v", err)
	}

	logf := func(format string, args ...interface{}) {
		if !prof.quiet {
			log.Printf(format, args...)
		}
	}

	switch prof.mode {
	case cpuMode:
		fn := filepath.Join(path, "cpu.pprof")
		f, err := os.Create(fn)
		if err != nil {
			log.Fatalf("profile: could not create cpu profile %q: %v", fn, err)
		}
		logf("profile: cpu profiling enabled, %s", fn)
		pprof.StartCPUProfile(f)
		prof.closer = func() {
			pprof.StopCPUProfile()
			f.Close()
			logf("profile: cpu profiling disabled, %s", fn)
		}

	case memMode:
		fn := filepath.Join(path, "mem.pprof")
		f, err := os.Create(fn)
		if err != nil {
			log.Fatalf("profile: could not create memory profile %q: %v", fn, err)
		}
		old := runtime.MemProfileRate
		runtime.MemProfileRate = prof.memProfileRate
		logf("profile: memory profiling enabled (rate %d), %s", runtime.MemProfileRate, fn)
		prof.closer = func() {
			pprof.Lookup("heap").WriteTo(f, 0)
			f.Close()
			runtime.MemProfileRate = old
			logf("profile: memory profiling disabled, %s", fn)
		}

	case blockMode:
		fn := filepath.Join(path, "block.pprof")
		f, err := os.Create(fn)
		if err != nil {
			log.Fatalf("profile: could not create block profile %q: %v", fn, err)
		}
		runtime.SetBlockProfileRate(1)
		logf("profile: block profiling enabled, %s", fn)
		prof.closer = func() {
			pprof.Lookup("block").WriteTo(f, 0)
			f.Close()
			runtime.SetBlockProfileRate(0)
			logf("profile: block profiling disabled, %s", fn)
		}
	}

	if !prof.noShutdownHook {
		go func() {
			c := make(chan os.Signal, 1)
			signal.Notify(c, os.Interrupt)
			<-c

			log.Println("profile: caught interrupt, stopping profiles")
			prof.Stop()

			os.Exit(0)
		}()
	}

	return &prof
}
<|endoftext|>


<commit_before>package main

import "github.com/hopkinsth/lambda-phage/Godeps/_workspace/src/github.com/spf13/cobra"
import "github.com/hopkinsth/lambda-phage/Godeps/_workspace/src/gopkg.in/yaml.v2"
import "io/ioutil"
import "github.com/hopkinsth/lambda-phage/Godeps/_workspace/src/github.com/tj/go-debug"
import "os"
import "os/user"
import "fmt"
import "crypto/sha1"
import "regexp"

func init() {
	prjCmd := &cobra.Command{
		Use:   "project [command]",
		Short: "does project stuff",
	}

	//flg := prjCmd.Flags()

	prjCmd.AddCommand(&cobra.Command{
		Use:   "create [name]",
		Short: "creates a new project with the specified name & adds the current folder to it",
		RunE:  createProjectCmd,
	})

	prjCmd.AddCommand(&cobra.Command{
		Use:   "add [project]",
		Short: "adds the current folder to a project",
		RunE:  addToProjectCmd,
	})

	deployPrjCmd := &cobra.Command{
		Use:   "deploy [project1] [project2 ... projectN])",
		Short: "deploys all the functions in the given project name",
		RunE:  deployProjectCmd,
	}
	deployPrjCmd.Flags().String("filter", "", "pattern for filtering function names to deploy")
	deployPrjCmd.Flags().Bool("dry-run", false, "print what functions we would deploy rather than actually doing it")

	prjCmd.AddCommand(deployPrjCmd)

	cmds = append(cmds, prjCmd)
}

// loads a project file or creates a new struct for one
func getProject(pName string) (*Project, error) {
	var err error
	prjDir, err := createProjectDir()
	if err != nil {
		return nil, err
	}

	pFilePath := fmt.Sprintf("%s/%s.yml", prjDir, pName)

	pCfg, err := openProject(pFilePath)

	if err != nil {
		return nil, fmt.Errorf("Error getting project file:\n%s\n", err)
	}

	pCfg.fName = pFilePath
	return pCfg, nil
}

// defines the configuration for a project
type Project struct {
	// YAML filename for project
	fName     string
	fromFile  bool
	Functions map[string]ProjectFunction
}

type ProjectFunction struct {
	Id     string
	Config *Config
	Path   string
}

// writes this to a yaml file
func (p *Project) writeToFile() error {
	return writeToYamlFile(p, p.fName)
}

// adds a lambda function to this project
// or maybe not if the config file path
// is
func (p *Project) addFunction(c *Config) *Project {
	debug := debug.Debug("project.addFunction")
	var nHash string

	if c.Name == nil {
		debug("bummer, your lambda function doesn't have a name")
		return p
	}

	nHash = fmt.Sprintf("%x", sha1.Sum([]byte(*c.Name+c.fName)))

	p.Functions[*c.Name] = ProjectFunction{
		Id:     nHash,
		Config: c,
		Path:   c.fName,
	}

	return p
}

// cobra command for creating project
func createProjectCmd(c *cobra.Command, args []string) error {
	if len(args) == 0 || args[0] == "" {
		return fmt.Errorf("You didn't give us a project name! Please give us one.")
	}
	pName := args[0]
	pCfg, err := getProject(pName)

	if err != nil {
		fmt.Printf("Error creating or opening project:\n%s\n", err)
		return nil
	}

	// add the current function to the project
	if cfg != nil {
		pCfg.addFunction(cfg)
		cfg.addProject(pName)
		err = cfg.writeToFile(cfg.fName)

		if err != nil {
			fmt.Printf("Error updating config with project:\n%s\n", err)
			return nil
		}
	}

	err = pCfg.writeToFile()
	if err != nil {
		fmt.Printf("Error saving project:\n%s\n", err)
		return nil
	}

	var action string

	switch c.Name() {
	case "add":
		action = fmt.Sprintf("added %s to", *cfg.Name)
	default:
		action = "created"
	}

	fmt.Printf("%s project %s\n", action, pName)

	return nil
}

// adds the current config file to the project
// uses createProjectCmd now, but will be separate from that
// so we reserve the right to change it whenever
func addToProjectCmd(c *cobra.Command, args []string) error {
	if cfg == nil || (cfg != nil && cfg.Name == nil) {
		return fmt.Errorf("No project configuration found! Please run `lambda-phage init` first!")
	}
	// just use create project for now
	return createProjectCmd(c, args)
}

// deploys an optionally-filtered set of lambda functions
// for the project(s) you specify
func deployProjectCmd(c *cobra.Command, args []string) error {
	debug := debug.Debug("cmd.deployProjectCmd")
	if len(args) == 0 {
		fmt.Println("Need to have at least one project name to deploy :( Please type one.")
		return nil
	}

	isDryRun, _ := c.Flags().GetBool("dry-run")
	filter, _ := c.Flags().GetString("filter")
	reg, err := regexp.Compile(filter)

	if err != nil {
		return fmt.Errorf("Invalid filter, %s\n", err)
	}

	for _, prj := range args {
		pCfg, err := getProject(prj)
		if err != nil {
			fmt.Printf("Error loading project %s:\n%s\n", prj, err)
		} else if pCfg.fromFile == true {
			for _, f := range pCfg.Functions {
				cfg, err := loadConfig(f.Path)
				if err != nil {
					fmt.Printf(
						"Error loading config for function %s in project %s:\n%s\n",
						f.Config.Name,
						prj,
						err,
					)
					continue
				}

				if reg != nil && !reg.MatchString(*cfg.Name) {
					// skip current project if it doesn't match regex
					continue
				}

				if isDryRun {
					fmt.Printf(
						"Would deploy function %s in project %s:\n%s\n",
						*cfg.Name,
						prj,
						err,
					)
					continue
				}

				// if loading config succeeded, deploy this thing
				d := deployer{cfg}
				err = d.deploy(c, args)
				if err != nil {
					fmt.Printf(
						"Deploy failed for function %s in project %s:\n%s\n",
						f.Config.Name,
						prj,
						err,
					)
				}
			}
		} else {
			debug("skipped project %s because it wasn't found", prj)
		}
	}
	return nil
}

// parses or creates a project config file
func openProject(fName string) (*Project, error) {
	debug := debug.Debug("core.openProject")
	// read the project file
	b, err := ioutil.ReadFile(fName)

	if err != nil && err == os.ErrNotExist {
		return nil, fmt.Errorf("Error reading project file: %s\n", err)
	}

	var pCfg *Project

	if b != nil {
		debug("have project data from %s, trying to parse it", fName)
		// if we got data from the file, parse it
		err = yaml.Unmarshal(b, &pCfg)
		if err != nil {
			return nil, fmt.Errorf("Error parsing project file %s:\n %s\n", fName, err)
		}
		pCfg.fromFile = true
	} else {
		debug("no project found, making empty struct")
		pCfg = new(Project)
		pCfg.fName = fName
		pCfg.Functions = make(map[string]ProjectFunction)
	}

	return pCfg, nil
}

// creates a directory for storing projects
// returns the path to that directory
// or an error if doing something failed
//
// TODO: wtf will this do on windows?
func createProjectDir() (string, error) {
	debug := debug.Debug("project.createProjectDir")
	u, err := user.Current()
	if err != nil {
		return "", err
	}

	debug("got user info; home directory is %s", u.HomeDir)

	cfgDir := u.HomeDir + `/.lambda_phage`
	prjDir := cfgDir + "/projects"

	f, err := os.Stat(prjDir)
	if f != nil && f.IsDir() {
		return prjDir, nil
	}

	err = os.Mkdir(prjDir, 0755)
	if err != nil {
		return "", err
	}

	prjDir += "/projects"
	err = os.Mkdir(prjDir, 0755)
	if err != nil {
		return "", err
	}

	return prjDir, nil
}
<commit_msg>add note to regex; fix dryrun printout<commit_after>package main

import "github.com/hopkinsth/lambda-phage/Godeps/_workspace/src/github.com/spf13/cobra"
import "github.com/hopkinsth/lambda-phage/Godeps/_workspace/src/gopkg.in/yaml.v2"
import "io/ioutil"
import "github.com/hopkinsth/lambda-phage/Godeps/_workspace/src/github.com/tj/go-debug"
import "os"
import "os/user"
import "fmt"
import "crypto/sha1"
import "regexp"

func init() {
	prjCmd := &cobra.Command{
		Use:   "project [command]",
		Short: "does project stuff",
	}

	//flg := prjCmd.Flags()

	prjCmd.AddCommand(&cobra.Command{
		Use:   "create [name]",
		Short: "creates a new project with the specified name & adds the current folder to it",
		RunE:  createProjectCmd,
	})

	prjCmd.AddCommand(&cobra.Command{
		Use:   "add [project]",
		Short: "adds the current folder to a project",
		RunE:  addToProjectCmd,
	})

	deployPrjCmd := &cobra.Command{
		Use:   "deploy [project1] [project2 ... projectN])",
		Short: "deploys all the functions in the given project name",
		RunE:  deployProjectCmd,
	}
	deployPrjCmd.Flags().String("filter", "", "pattern for filtering function names to deploy; only does regex!!")
	deployPrjCmd.Flags().Bool("dry-run", false, "print what functions we would deploy rather than actually doing it")

	prjCmd.AddCommand(deployPrjCmd)

	cmds = append(cmds, prjCmd)
}

// loads a project file or creates a new struct for one
func getProject(pName string) (*Project, error) {
	var err error
	prjDir, err := createProjectDir()
	if err != nil {
		return nil, err
	}

	pFilePath := fmt.Sprintf("%s/%s.yml", prjDir, pName)

	pCfg, err := openProject(pFilePath)

	if err != nil {
		return nil, fmt.Errorf("Error getting project file:\n%s\n", err)
	}

	pCfg.fName = pFilePath
	return pCfg, nil
}

// defines the configuration for a project
type Project struct {
	// YAML filename for project
	fName     string
	fromFile  bool
	Functions map[string]ProjectFunction
}

type ProjectFunction struct {
	Id     string
	Config *Config
	Path   string
}

// writes this to a yaml file
func (p *Project) writeToFile() error {
	return writeToYamlFile(p, p.fName)
}

// adds a lambda function to this project
// or maybe not if the config file path
// is
func (p *Project) addFunction(c *Config) *Project {
	debug := debug.Debug("project.addFunction")
	var nHash string

	if c.Name == nil {
		debug("bummer, your lambda function doesn't have a name")
		return p
	}

	nHash = fmt.Sprintf("%x", sha1.Sum([]byte(*c.Name+c.fName)))

	p.Functions[*c.Name] = ProjectFunction{
		Id:     nHash,
		Config: c,
		Path:   c.fName,
	}

	return p
}

// cobra command for creating project
func createProjectCmd(c *cobra.Command, args []string) error {
	if len(args) == 0 || args[0] == "" {
		return fmt.Errorf("You didn't give us a project name! Please give us one.")
	}
	pName := args[0]
	pCfg, err := getProject(pName)

	if err != nil {
		fmt.Printf("Error creating or opening project:\n%s\n", err)
		return nil
	}

	// add the current function to the project
	if cfg != nil {
		pCfg.addFunction(cfg)
		cfg.addProject(pName)
		err = cfg.writeToFile(cfg.fName)

		if err != nil {
			fmt.Printf("Error updating config with project:\n%s\n", err)
			return nil
		}
	}

	err = pCfg.writeToFile()
	if err != nil {
		fmt.Printf("Error saving project:\n%s\n", err)
		return nil
	}

	var action string

	switch c.Name() {
	case "add":
		action = fmt.Sprintf("added %s to", *cfg.Name)
	default:
		action = "created"
	}

	fmt.Printf("%s project %s\n", action, pName)

	return nil
}

// adds the current config file to the project
// uses createProjectCmd now, but will be separate from that
// so we reserve the right to change it whenever
func addToProjectCmd(c *cobra.Command, args []string) error {
	if cfg == nil || (cfg != nil && cfg.Name == nil) {
		return fmt.Errorf("No project configuration found! Please run `lambda-phage init` first!")
	}
	// just use create project for now
	return createProjectCmd(c, args)
}

// deploys an optionally-filtered set of lambda functions
// for the project(s) you specify
func deployProjectCmd(c *cobra.Command, args []string) error {
	debug := debug.Debug("cmd.deployProjectCmd")
	if len(args) == 0 {
		fmt.Println("Need to have at least one project name to deploy :( Please type one.")
		return nil
	}

	isDryRun, _ := c.Flags().GetBool("dry-run")
	filter, _ := c.Flags().GetString("filter")
	reg, err := regexp.Compile(filter)

	if err != nil {
		return fmt.Errorf("Invalid filter, %s\n", err)
	}

	for _, prj := range args {
		pCfg, err := getProject(prj)
		if err != nil {
			fmt.Printf("Error loading project %s:\n%s\n", prj, err)
		} else if pCfg.fromFile == true {
			for _, f := range pCfg.Functions {
				cfg, err := loadConfig(f.Path)
				if err != nil {
					fmt.Printf(
						"Error loading config for function %s in project %s:\n%s\n",
						f.Config.Name,
						prj,
						err,
					)
					continue
				}

				if reg != nil && !reg.MatchString(*cfg.Name) {
					// skip current project if it doesn't match regex
					continue
				}

				if isDryRun {
					fmt.Printf(
						"Would deploy function %s in project %s\n",
						*cfg.Name,
						prj,
					)
					continue
				}

				// if loading config succeeded, deploy this thing
				d := deployer{cfg}
				err = d.deploy(c, args)
				if err != nil {
					fmt.Printf(
						"Deploy failed for function %s in project %s:\n%s\n",
						f.Config.Name,
						prj,
						err,
					)
				}
			}
		} else {
			debug("skipped project %s because it wasn't found", prj)
		}
	}
	return nil
}

// parses or creates a project config file
func openProject(fName string) (*Project, error) {
	debug := debug.Debug("core.openProject")
	// read the project file
	b, err := ioutil.ReadFile(fName)

	if err != nil && err == os.ErrNotExist {
		return nil, fmt.Errorf("Error reading project file: %s\n", err)
	}

	var pCfg *Project

	if b != nil {
		debug("have project data from %s, trying to parse it", fName)
		// if we got data from the file, parse it
		err = yaml.Unmarshal(b, &pCfg)
		if err != nil {
			return nil, fmt.Errorf("Error parsing project file %s:\n %s\n", fName, err)
		}
		pCfg.fromFile = true
	} else {
		debug("no project found, making empty struct")
		pCfg = new(Project)
		pCfg.fName = fName
		pCfg.Functions = make(map[string]ProjectFunction)
	}

	return pCfg, nil
}

// creates a directory for storing projects
// returns the path to that directory
// or an error if doing something failed
//
// TODO: wtf will this do on windows?
func createProjectDir() (string, error) {
	debug := debug.Debug("project.createProjectDir")
	u, err := user.Current()
	if err != nil {
		return "", err
	}

	debug("got user info; home directory is %s", u.HomeDir)

	cfgDir := u.HomeDir + `/.lambda_phage`
	prjDir := cfgDir + "/projects"

	f, err := os.Stat(prjDir)
	if f != nil && f.IsDir() {
		return prjDir, nil
	}

	err = os.Mkdir(prjDir, 0755)
	if err != nil {
		return "", err
	}

	prjDir += "/projects"
	err = os.Mkdir(prjDir, 0755)
	if err != nil {
		return "", err
	}

	return prjDir, nil
}
<|endoftext|>


<commit_before><commit_msg>functions: 0.3.74 release [skip ci]<commit_after><|endoftext|>


<commit_before><commit_msg>fnserver: 0.3.236 release [skip ci]<commit_after><|endoftext|>


<commit_before>/*-
Copyright (c) 2016, Jörg Pernfuß <joerg.pernfuss@1und1.de>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package main

import (
	"database/sql"
	"log"
	"time"

	"github.com/mjolnir42/scrypth64"
	"github.com/satori/go.uuid"
)

func (s *supervisor) startupLoad() {

	s.startupRoot()

	s.startupUsersAndTeams()
	s.startupPermissions()

	if !s.readonly {
		s.startupCredentials()
	}

	s.startupTokens()

}

func (s *supervisor) startupRoot() {
	var (
		err                  error
		flag, crypt          string
		mcf                  scrypth64.Mcf
		validFrom, expiresAt time.Time
		state                bool
		rows                 *sql.Rows
	)

	rows, err = s.conn.Query(stmt.LoadRootFlags)
	if err != nil {
		log.Fatal(`supervisor/load-root-flags,query: `, err)
	}
	defer rows.Close()

	for rows.Next() {
		if err = rows.Scan(
			&flag,
			&state,
		); err != nil {
			log.Fatal(`supervisor/load-root-flags,scan: `, err)
		}
		switch flag {
		case `disabled`:
			s.root_disabled = state
		case `restricted`:
			s.root_restricted = state
		}
	}
	if err = rows.Err(); err != nil {
		log.Fatal(`supervisor/load-root-flags,next: `, err)
	}

	// only load root credentials on master instance
	if !s.readonly {
		if err = s.conn.QueryRow(stmt.LoadRootPassword).Scan(
			&crypt,
			&validFrom,
			&expiresAt,
		); err == sql.ErrNoRows {
			// root bootstrap outstanding
			return
		} else if err != nil {
			log.Fatal(`supervisor/load-root-password: `, err)
		}
		if mcf, err = scrypth64.FromString(crypt); err != nil {
			log.Fatal(`supervisor/string-to-mcf: `, err)
		}
		s.credentials.insert(`root`, uuid.Nil, validFrom.UTC(),
			PosTimeInf.UTC(), mcf)
	}
}

func (s *supervisor) startupCredentials() {
	var (
		err                  error
		rows                 *sql.Rows
		user_id, user, crypt string
		reset                bool
		validFrom, expiresAt time.Time
		id                   uuid.UUID
		mcf                  scrypth64.Mcf
	)

	rows, err = s.conn.Query(stmt.LoadAllUserCredentials)
	if err != nil {
		log.Fatal(`supervisor/load-credentials,query: `, err)
	}
	defer rows.Close()

	for rows.Next() {
		if err = rows.Scan(
			&user_id,
			&crypt,
			&reset,
			&validFrom,
			&expiresAt,
			&user,
		); err != nil {
			log.Fatal(`supervisor/load-credentials,scan: `, err)
		}

		if id, err = uuid.FromString(user_id); err != nil {
			log.Fatal(`supervisor/string-to-uuid: `, err)
		}
		if mcf, err = scrypth64.FromString(crypt); err != nil {
			log.Fatal(`supervisor/string-to-mcf: `, err)
		}

		s.credentials.restore(user, id, validFrom, expiresAt, mcf, reset, true)
	}
	if err = rows.Err(); err != nil {
		log.Fatal(`supervisor/load-credentials,next: `, err)
	}
}

func (s *supervisor) startupTokens() {
	var (
		err                         error
		token, salt, valid, expires string
		validFrom, expiresAt        time.Time
		rows                        *sql.Rows
	)

	rows, err = s.conn.Query(stmt.LoadAllTokens)
	if err != nil {
		log.Fatal(`supervisor/load-tokens,query: `, err)
	}
	defer rows.Close()

	for rows.Next() {
		if err = rows.Scan(
			&token,
			&salt,
			&validFrom,
			&expiresAt,
		); err != nil {
			log.Fatal(`supervisor/load-tokens,scan: `, err)
		}
		valid = validFrom.Format(rfc3339Milli)
		expires = expiresAt.Format(rfc3339Milli)

		if err = s.tokens.insert(token, valid, expires, salt); err != nil {
			log.Fatal(`supervisor/load-tokens,insert: `, err)
		}
	}
	if err = rows.Err(); err != nil {
		log.Fatal(`supervisor/load-tokens,next: `, err)
	}
}

func (s *supervisor) startupUsersAndTeams() {
	var (
		err                                    error
		userUUID, userName, teamUUID, teamName string
		rows                                   *sql.Rows
	)

	rows, err = s.conn.Query(stmt.LoadUserTeamMapping)
	if err != nil {
		log.Fatal(`supervisor/load-user-team-mapping,query: `, err)
	}
	defer rows.Close()

	// reduce lock overhead by locking here once and then using the
	// unlocked bulk interface
	s.id_user.lock()
	defer s.id_user.unlock()
	s.id_team.lock()
	defer s.id_team.unlock()
	s.id_userteam.lock()
	defer s.id_userteam.unlock()

	for rows.Next() {
		if err = rows.Scan(
			&userUUID,
			&userName,
			&teamUUID,
			&teamName,
		); err != nil {
			log.Fatal(`supervisor/load-user-team-mapping,scan: `, err)
		}
		s.id_user.load(userUUID, userName)
		s.id_team.load(teamUUID, teamName)
		s.id_userteam.load(userUUID, teamUUID)
	}
	if err = rows.Err(); err != nil {
		log.Fatal(`supervisor/load-user-team-mapping,next: `, err)
	}
}

func (s *supervisor) startupPermissions() {
	var (
		err                error
		permUUID, permName string
		rows               *sql.Rows
	)

	rows, err = s.conn.Query(stmt.LoadUserTeamMapping)
	if err != nil {
		log.Fatal(`supervisor/load-permissions,query: `, err)
	}
	defer rows.Close()

	// reduce lock overhead by locking here once and then using the
	// unlocked bulk interface
	s.id_permission.lock()
	defer s.id_permission.unlock()

	for rows.Next() {
		if err = rows.Scan(
			&permUUID,
			&permName,
		); err != nil {
			log.Fatal(`supervisor/load-permissions,scan: `, err)
		}
		s.id_permission.load(permName, permUUID)
	}
	if err = rows.Err(); err != nil {
		log.Fatal(`supervisor/load-permissions,next: `, err)
	}
}

// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
<commit_msg>Use correct SQL in permission startup loading<commit_after>/*-
Copyright (c) 2016, Jörg Pernfuß <joerg.pernfuss@1und1.de>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package main

import (
	"database/sql"
	"log"
	"time"

	"github.com/mjolnir42/scrypth64"
	"github.com/satori/go.uuid"
)

func (s *supervisor) startupLoad() {

	s.startupRoot()

	s.startupUsersAndTeams()
	s.startupPermissions()

	if !s.readonly {
		s.startupCredentials()
	}

	s.startupTokens()

}

func (s *supervisor) startupRoot() {
	var (
		err                  error
		flag, crypt          string
		mcf                  scrypth64.Mcf
		validFrom, expiresAt time.Time
		state                bool
		rows                 *sql.Rows
	)

	rows, err = s.conn.Query(stmt.LoadRootFlags)
	if err != nil {
		log.Fatal(`supervisor/load-root-flags,query: `, err)
	}
	defer rows.Close()

	for rows.Next() {
		if err = rows.Scan(
			&flag,
			&state,
		); err != nil {
			log.Fatal(`supervisor/load-root-flags,scan: `, err)
		}
		switch flag {
		case `disabled`:
			s.root_disabled = state
		case `restricted`:
			s.root_restricted = state
		}
	}
	if err = rows.Err(); err != nil {
		log.Fatal(`supervisor/load-root-flags,next: `, err)
	}

	// only load root credentials on master instance
	if !s.readonly {
		if err = s.conn.QueryRow(stmt.LoadRootPassword).Scan(
			&crypt,
			&validFrom,
			&expiresAt,
		); err == sql.ErrNoRows {
			// root bootstrap outstanding
			return
		} else if err != nil {
			log.Fatal(`supervisor/load-root-password: `, err)
		}
		if mcf, err = scrypth64.FromString(crypt); err != nil {
			log.Fatal(`supervisor/string-to-mcf: `, err)
		}
		s.credentials.insert(`root`, uuid.Nil, validFrom.UTC(),
			PosTimeInf.UTC(), mcf)
	}
}

func (s *supervisor) startupCredentials() {
	var (
		err                  error
		rows                 *sql.Rows
		user_id, user, crypt string
		reset                bool
		validFrom, expiresAt time.Time
		id                   uuid.UUID
		mcf                  scrypth64.Mcf
	)

	rows, err = s.conn.Query(stmt.LoadAllUserCredentials)
	if err != nil {
		log.Fatal(`supervisor/load-credentials,query: `, err)
	}
	defer rows.Close()

	for rows.Next() {
		if err = rows.Scan(
			&user_id,
			&crypt,
			&reset,
			&validFrom,
			&expiresAt,
			&user,
		); err != nil {
			log.Fatal(`supervisor/load-credentials,scan: `, err)
		}

		if id, err = uuid.FromString(user_id); err != nil {
			log.Fatal(`supervisor/string-to-uuid: `, err)
		}
		if mcf, err = scrypth64.FromString(crypt); err != nil {
			log.Fatal(`supervisor/string-to-mcf: `, err)
		}

		s.credentials.restore(user, id, validFrom, expiresAt, mcf, reset, true)
	}
	if err = rows.Err(); err != nil {
		log.Fatal(`supervisor/load-credentials,next: `, err)
	}
}

func (s *supervisor) startupTokens() {
	var (
		err                         error
		token, salt, valid, expires string
		validFrom, expiresAt        time.Time
		rows                        *sql.Rows
	)

	rows, err = s.conn.Query(stmt.LoadAllTokens)
	if err != nil {
		log.Fatal(`supervisor/load-tokens,query: `, err)
	}
	defer rows.Close()

	for rows.Next() {
		if err = rows.Scan(
			&token,
			&salt,
			&validFrom,
			&expiresAt,
		); err != nil {
			log.Fatal(`supervisor/load-tokens,scan: `, err)
		}
		valid = validFrom.Format(rfc3339Milli)
		expires = expiresAt.Format(rfc3339Milli)

		if err = s.tokens.insert(token, valid, expires, salt); err != nil {
			log.Fatal(`supervisor/load-tokens,insert: `, err)
		}
	}
	if err = rows.Err(); err != nil {
		log.Fatal(`supervisor/load-tokens,next: `, err)
	}
}

func (s *supervisor) startupUsersAndTeams() {
	var (
		err                                    error
		userUUID, userName, teamUUID, teamName string
		rows                                   *sql.Rows
	)

	rows, err = s.conn.Query(stmt.LoadUserTeamMapping)
	if err != nil {
		log.Fatal(`supervisor/load-user-team-mapping,query: `, err)
	}
	defer rows.Close()

	// reduce lock overhead by locking here once and then using the
	// unlocked bulk interface
	s.id_user.lock()
	defer s.id_user.unlock()
	s.id_team.lock()
	defer s.id_team.unlock()
	s.id_userteam.lock()
	defer s.id_userteam.unlock()

	for rows.Next() {
		if err = rows.Scan(
			&userUUID,
			&userName,
			&teamUUID,
			&teamName,
		); err != nil {
			log.Fatal(`supervisor/load-user-team-mapping,scan: `, err)
		}
		s.id_user.load(userUUID, userName)
		s.id_team.load(teamUUID, teamName)
		s.id_userteam.load(userUUID, teamUUID)
	}
	if err = rows.Err(); err != nil {
		log.Fatal(`supervisor/load-user-team-mapping,next: `, err)
	}
}

func (s *supervisor) startupPermissions() {
	var (
		err                error
		permUUID, permName string
		rows               *sql.Rows
	)

	rows, err = s.conn.Query(stmt.LoadPermissions)
	if err != nil {
		log.Fatal(`supervisor/load-permissions,query: `, err)
	}
	defer rows.Close()

	// reduce lock overhead by locking here once and then using the
	// unlocked bulk interface
	s.id_permission.lock()
	defer s.id_permission.unlock()

	for rows.Next() {
		if err = rows.Scan(
			&permUUID,
			&permName,
		); err != nil {
			log.Fatal(`supervisor/load-permissions,scan: `, err)
		}
		s.id_permission.load(permName, permUUID)
	}
	if err = rows.Err(); err != nil {
		log.Fatal(`supervisor/load-permissions,next: `, err)
	}
}

// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
<|endoftext|>


<commit_before>package command

import (
	"flag"
	"io"
	"io/ioutil"
	"strings"

	"github.com/mitchellh/cli"
)

var _ cli.Command = (*AuthCommand)(nil)

type AuthCommand struct {
	*BaseCommand

	Handlers map[string]LoginHandler

	testStdin io.Reader // for tests
}

func (c *AuthCommand) Synopsis() string {
	return "Interact with auth methods"
}

func (c *AuthCommand) Help() string {
	return strings.TrimSpace(`
Usage: vault auth <subcommand> [options] [args]

  This command groups subcommands for interacting with Vault's auth methods.
  Users can list, enable, disable, and get help for different auth methods.

  To authenticate to Vault as a user or machine, use the "vault login" command
  instead. This command is for interacting with the auth methods themselves, not
  authenticating to Vault.

  List all enabled auth methods:

      $ vault auth list

  Enable a new auth method "userpass";

      $ vault auth enable userpass

  Get detailed help information about how to authenticate to a particular auth
  method:

      $ vault auth help github

  Please see the individual subcommand help for detailed usage information.
`)
}

func (c *AuthCommand) Run(args []string) int {
	// If we entered the run method, none of the subcommands picked up. This
	// means the user is still trying to use auth as "vault auth TOKEN" or
	// similar, so direct them to vault login instead.
	//
	// This run command is a bit messy to maintain BC for a bit. In the future,
	// it will just be a tiny function, but for now we have to maintain bc.
	//
	// Deprecation
	// TODO: remove in 0.9.0

	// Parse the args for our deprecations and defer to the proper areas.
	for _, arg := range args {
		switch {
		case strings.HasPrefix(arg, "-methods"):
			c.UI.Warn(wrapAtLength(
				"WARNING! The -methods flag is deprecated. Please use "+
					"\"vault auth list\" instead. This flag will be removed in "+
					"Vault 0.11 (or later).") + "\n")
			return (&AuthListCommand{
				BaseCommand: &BaseCommand{
					UI:     c.UI,
					client: c.client,
				},
			}).Run(nil)
		case strings.HasPrefix(arg, "-method-help"):
			c.UI.Warn(wrapAtLength(
				"WARNING! The -method-help flag is deprecated. Please use "+
					"\"vault auth help\" instead. This flag will be removed in "+
					"Vault 0.11 (or later).") + "\n")
			// Parse the args to pull out the method, suppressing any errors because
			// there could be other flags that we don't care about.
			f := flag.NewFlagSet("", flag.ContinueOnError)
			f.Usage = func() {}
			f.SetOutput(ioutil.Discard)
			flagMethod := f.String("method", "", "")
			f.Parse(args)

			return (&AuthHelpCommand{
				BaseCommand: &BaseCommand{
					UI:     c.UI,
					client: c.client,
				},
				Handlers: c.Handlers,
			}).Run([]string{*flagMethod})
		}
	}

	// If we got this far, we have an arg or a series of args that should be
	// passed directly to the new "vault login" command.
	c.UI.Warn(wrapAtLength(
		"WARNING! The \"vault auth ARG\" command is deprecated and is now a "+
			"subcommand for interacting with auth methods. To authenticate "+
			"locally to Vault, use \"vault login\" instead. This backwards "+
			"compatability will be removed in Vault 0.11 (or later).") + "\n")
	return (&LoginCommand{
		BaseCommand: &BaseCommand{
			UI:          c.UI,
			client:      c.client,
			tokenHelper: c.tokenHelper,
			flagAddress: c.flagAddress,
		},
		Handlers: c.Handlers,
	}).Run(args)
}
<commit_msg>Fix misspelling in vault auth deprecation message (#4460)<commit_after>package command

import (
	"flag"
	"io"
	"io/ioutil"
	"strings"

	"github.com/mitchellh/cli"
)

var _ cli.Command = (*AuthCommand)(nil)

type AuthCommand struct {
	*BaseCommand

	Handlers map[string]LoginHandler

	testStdin io.Reader // for tests
}

func (c *AuthCommand) Synopsis() string {
	return "Interact with auth methods"
}

func (c *AuthCommand) Help() string {
	return strings.TrimSpace(`
Usage: vault auth <subcommand> [options] [args]

  This command groups subcommands for interacting with Vault's auth methods.
  Users can list, enable, disable, and get help for different auth methods.

  To authenticate to Vault as a user or machine, use the "vault login" command
  instead. This command is for interacting with the auth methods themselves, not
  authenticating to Vault.

  List all enabled auth methods:

      $ vault auth list

  Enable a new auth method "userpass";

      $ vault auth enable userpass

  Get detailed help information about how to authenticate to a particular auth
  method:

      $ vault auth help github

  Please see the individual subcommand help for detailed usage information.
`)
}

func (c *AuthCommand) Run(args []string) int {
	// If we entered the run method, none of the subcommands picked up. This
	// means the user is still trying to use auth as "vault auth TOKEN" or
	// similar, so direct them to vault login instead.
	//
	// This run command is a bit messy to maintain BC for a bit. In the future,
	// it will just be a tiny function, but for now we have to maintain bc.
	//
	// Deprecation
	// TODO: remove in 0.9.0

	// Parse the args for our deprecations and defer to the proper areas.
	for _, arg := range args {
		switch {
		case strings.HasPrefix(arg, "-methods"):
			c.UI.Warn(wrapAtLength(
				"WARNING! The -methods flag is deprecated. Please use "+
					"\"vault auth list\" instead. This flag will be removed in "+
					"Vault 0.11 (or later).") + "\n")
			return (&AuthListCommand{
				BaseCommand: &BaseCommand{
					UI:     c.UI,
					client: c.client,
				},
			}).Run(nil)
		case strings.HasPrefix(arg, "-method-help"):
			c.UI.Warn(wrapAtLength(
				"WARNING! The -method-help flag is deprecated. Please use "+
					"\"vault auth help\" instead. This flag will be removed in "+
					"Vault 0.11 (or later).") + "\n")
			// Parse the args to pull out the method, suppressing any errors because
			// there could be other flags that we don't care about.
			f := flag.NewFlagSet("", flag.ContinueOnError)
			f.Usage = func() {}
			f.SetOutput(ioutil.Discard)
			flagMethod := f.String("method", "", "")
			f.Parse(args)

			return (&AuthHelpCommand{
				BaseCommand: &BaseCommand{
					UI:     c.UI,
					client: c.client,
				},
				Handlers: c.Handlers,
			}).Run([]string{*flagMethod})
		}
	}

	// If we got this far, we have an arg or a series of args that should be
	// passed directly to the new "vault login" command.
	c.UI.Warn(wrapAtLength(
		"WARNING! The \"vault auth ARG\" command is deprecated and is now a "+
			"subcommand for interacting with auth methods. To authenticate "+
			"locally to Vault, use \"vault login\" instead. This backwards "+
			"compatibility will be removed in Vault 0.11 (or later).") + "\n")
	return (&LoginCommand{
		BaseCommand: &BaseCommand{
			UI:          c.UI,
			client:      c.client,
			tokenHelper: c.tokenHelper,
			flagAddress: c.flagAddress,
		},
		Handlers: c.Handlers,
	}).Run(args)
}
<|endoftext|>


<commit_before><commit_msg>purged sample client<commit_after><|endoftext|>


<commit_before>package command

import (
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

const (
	// DefaultInitName is the default name we use when
	// initializing the example file
	DefaultInitName = "example.nomad"
)

// InitCommand generates a new job template that you can customize to your
// liking, like vagrant init
type InitCommand struct {
	Meta
}

func (c *InitCommand) Help() string {
	helpText := `
Usage: nomad init

  Creates an example job file that can be used as a starting
  point to customize further.
`
	return strings.TrimSpace(helpText)
}

func (c *InitCommand) Synopsis() string {
	return "Create an example job file"
}

func (c *InitCommand) Run(args []string) int {
	// Check for misuse
	if len(args) != 0 {
		c.Ui.Error(c.Help())
		return 1
	}

	// Check if the file already exists
	_, err := os.Stat(DefaultInitName)
	if err != nil && !os.IsNotExist(err) {
		c.Ui.Error(fmt.Sprintf("Failed to stat '%s': %v", DefaultInitName, err))
		return 1
	}
	if !os.IsNotExist(err) {
		c.Ui.Error(fmt.Sprintf("Job '%s' already exists", DefaultInitName))
		return 1
	}

	// Write out the example
	err = ioutil.WriteFile(DefaultInitName, []byte(defaultJob), 0660)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Failed to write '%s': %v", DefaultInitName, err))
		return 1
	}

	// Success
	c.Ui.Output(fmt.Sprintf("Example job file written to %s", DefaultInitName))
	return 0
}

var defaultJob = strings.TrimSpace(`
# There can only be a single job definition per file.
# Create a job with ID and Name 'example'
job "example" {
	# Run the job in the global region, which is the default.
	# region = "global"

	# Specify the datacenters within the region this job can run in.
	datacenters = ["dc1"]

	# Service type jobs optimize for long-lived services. This is
	# the default but we can change to batch for short-lived tasks.
	# type = "service"

	# Priority controls our access to resources and scheduling priority.
	# This can be 1 to 100, inclusively, and defaults to 50.
	# priority = 50

	# Restrict our job to only linux. We can specify multiple
	# constraints as needed.
	constraint {
		attribute = "$attr.kernel.name"
		value = "linux"
	}

	# Configure the job to do rolling updates
	update {
		# Stagger updates every 10 seconds
		stagger = "10s"

		# Update a single task at a time
		max_parallel = 1
	}

	# Create a 'cache' group. Each task in the group will be
	# scheduled onto the same machine.
	group "cache" {
		# Control the number of instances of this groups.
		# Defaults to 1
		# count = 1

		# Restart Policy - This block defines the restart policy for TaskGroups,
		# the attempts value defines the number of restarts Nomad will do if Tasks
		# in this TaskGroup fails in a rolling window of interval duration
		# The delay value makes Nomad wait for that duration to restart after a Task
		# fails or crashes.
		restart {
			interval = "5m"
			attempts = 10
			delay = "25s"
		}

		# Define a task to run
		task "redis" {
			# Use Docker to run the task.
			driver = "docker"

			# Configure Docker driver with the image
			config {
				image = "redis:latest"
				port_map {
					db = 6379
				}
			}

			# We must specify the resources required for
			# this task to ensure it runs on a machine with
			# enough capacity.
			resources {
				cpu = 500 # 500 Mhz
				memory = 256 # 256MB
				network {
					mbits = 10
					port "db" {
					}
				}
			}
		}
	}
}
`)
<commit_msg>Added the example for service block<commit_after>package command

import (
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

const (
	// DefaultInitName is the default name we use when
	// initializing the example file
	DefaultInitName = "example.nomad"
)

// InitCommand generates a new job template that you can customize to your
// liking, like vagrant init
type InitCommand struct {
	Meta
}

func (c *InitCommand) Help() string {
	helpText := `
Usage: nomad init

  Creates an example job file that can be used as a starting
  point to customize further.
`
	return strings.TrimSpace(helpText)
}

func (c *InitCommand) Synopsis() string {
	return "Create an example job file"
}

func (c *InitCommand) Run(args []string) int {
	// Check for misuse
	if len(args) != 0 {
		c.Ui.Error(c.Help())
		return 1
	}

	// Check if the file already exists
	_, err := os.Stat(DefaultInitName)
	if err != nil && !os.IsNotExist(err) {
		c.Ui.Error(fmt.Sprintf("Failed to stat '%s': %v", DefaultInitName, err))
		return 1
	}
	if !os.IsNotExist(err) {
		c.Ui.Error(fmt.Sprintf("Job '%s' already exists", DefaultInitName))
		return 1
	}

	// Write out the example
	err = ioutil.WriteFile(DefaultInitName, []byte(defaultJob), 0660)
	if err != nil {
		c.Ui.Error(fmt.Sprintf("Failed to write '%s': %v", DefaultInitName, err))
		return 1
	}

	// Success
	c.Ui.Output(fmt.Sprintf("Example job file written to %s", DefaultInitName))
	return 0
}

var defaultJob = strings.TrimSpace(`
# There can only be a single job definition per file.
# Create a job with ID and Name 'example'
job "example" {
	# Run the job in the global region, which is the default.
	# region = "global"

	# Specify the datacenters within the region this job can run in.
	datacenters = ["dc1"]

	# Service type jobs optimize for long-lived services. This is
	# the default but we can change to batch for short-lived tasks.
	# type = "service"

	# Priority controls our access to resources and scheduling priority.
	# This can be 1 to 100, inclusively, and defaults to 50.
	# priority = 50

	# Restrict our job to only linux. We can specify multiple
	# constraints as needed.
	constraint {
		attribute = "$attr.kernel.name"
		value = "linux"
	}

	# Configure the job to do rolling updates
	update {
		# Stagger updates every 10 seconds
		stagger = "10s"

		# Update a single task at a time
		max_parallel = 1
	}

	# Create a 'cache' group. Each task in the group will be
	# scheduled onto the same machine.
	group "cache" {
		# Control the number of instances of this groups.
		# Defaults to 1
		# count = 1

		# Restart Policy - This block defines the restart policy for TaskGroups,
		# the attempts value defines the number of restarts Nomad will do if Tasks
		# in this TaskGroup fails in a rolling window of interval duration
		# The delay value makes Nomad wait for that duration to restart after a Task
		# fails or crashes.
		restart {
			interval = "5m"
			attempts = 10
			delay = "25s"
		}

		# Define a task to run
		task "redis" {
			# Use Docker to run the task.
			driver = "docker"

			# Configure Docker driver with the image
			config {
				image = "redis:latest"
				port_map {
					db = 6379
				}
			}

			service {
				# name = redis
				tags = ["global", "cache"]
				port = "db"
				check {
					id = "id-alive-check"
					name = "alive"
					type = "tcp"
					interval = "10s"
					timeout = "2s"
				}
			}

			# We must specify the resources required for
			# this task to ensure it runs on a machine with
			# enough capacity.
			resources {
				cpu = 500 # 500 Mhz
				memory = 256 # 256MB
				network {
					mbits = 10
					port "db" {
					}
				}
			}
		}
	}
}
`)
<|endoftext|>


<commit_before>package commands

import (
	"fmt"
	"sync"

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

// Declaring single global session.
var conn *session.Session
var once sync.Once

func awsSession() (*session.Session, error) {
	var err error

	// Using sync.Once to ensure session is created only once.
	once.Do(func() {
		//define session options
		options := session.Options{
			Config:            aws.Config{Region: aws.String(config.Region)},
			Profile:           job.profile,
			SharedConfigState: session.SharedConfigEnable,
		}

		Log(fmt.Sprintf("Creating AWS Session with options: Regioin: %s, Profile: %s ", region, job.profile), level.debug)
		conn, err = session.NewSessionWithOptions(options)
	})

	if err != nil {
		return conn, err
	}

	return conn, nil
}
<commit_msg>added region switch<commit_after>package commands

import (
	"fmt"
	"sync"

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

// Declaring single global session.
var conn *session.Session
var once sync.Once

func awsSession() (*session.Session, error) {
	var err error

	// Using sync.Once to ensure session is created only once.
	once.Do(func() {
		// set region
		var r string
		switch config.Region {
		case "":
			r = region
		default:
			r = config.Region
		}

		//define session options
		options := session.Options{
			Config:            aws.Config{Region: &r},
			Profile:           job.profile,
			SharedConfigState: session.SharedConfigEnable,
		}

		Log(fmt.Sprintf("Creating AWS Session with options: Regioin: %s, Profile: %s ", region, job.profile), level.debug)
		conn, err = session.NewSessionWithOptions(options)
	})

	if err != nil {
		return conn, err
	}

	return conn, nil
}
<|endoftext|>


<commit_before>package commands

type FlyCommand struct {
	Target string `short:"t" long:"target" description:"Concourse target name or URL" default:"http://192.168.100.4:8080"`

	Login LoginCommand `command:"login" alias:"l" description:"Authenticate with the target"`
	Sync  SyncCommand  `command:"sync"  alias:"s" description:"Download and replace the current fly from the target"`

	// SetTeam SetTeamCommand `command:"set-team"  alias:"st" description:"Create or modify a team to have the given credentials"`

	Checklist ChecklistCommand `command:"checklist" alias:"cl" description:"Print a Checkfile of the given pipeline"`

	Execute ExecuteCommand `command:"execute" alias:"e" description:"Execute a one-off build using local bits"`
	Watch   WatchCommand   `command:"watch"   alias:"w" description:"Stream a build's output"`

	Containers ContainersCommand `command:"containers" alias:"cs" description:"Print the active containers"`
	Hijack     HijackCommand     `command:"hijack"     alias:"intercept" alias:"i" description:"Execute a command in a container"`

	Pipelines       PipelinesCommand       `command:"pipelines"        alias:"ps" description:"List the configured pipelines"`
	DestroyPipeline DestroyPipelineCommand `command:"destroy-pipeline" alias:"dp" description:"Destroy a pipeline"`
	GetPipeline     GetPipelineCommand     `command:"get-pipeline"     alias:"gp" description:"Get a pipeline's current configuration"`
	SetPipeline     SetPipelineCommand     `command:"set-pipeline"     alias:"sp" description:"Create or update a pipeline's configuration"`
	PausePipeline   PausePipelineCommand   `command:"pause-pipeline"   alias:"pp" description:"Pause a pipeline"`
	UnpausePipeline UnpausePipelineCommand `command:"unpause-pipeline" alias:"up" description:"Un-pause a pipeline"`

	Builds BuildsCommand `command:"builds" alias:"bs" description:"List builds data"`

	Volumes VolumesCommand `command:"volumes" alias:"vs" description:"List the active volumes"`
	Workers WorkersCommand `command:"workers" alias:"ws" description:"List the registered workers"`
}

var Fly FlyCommand
<commit_msg>Switch this to hidden not commment out, you know, for the tests.<commit_after>package commands

type FlyCommand struct {
	Target string `short:"t" long:"target" description:"Concourse target name or URL" default:"http://192.168.100.4:8080"`

	Login LoginCommand `command:"login" alias:"l" description:"Authenticate with the target"`
	Sync  SyncCommand  `command:"sync"  alias:"s" description:"Download and replace the current fly from the target"`

	SetTeam SetTeamCommand `hidden:"yes" command:"set-team"  alias:"st" description:"Create or modify a team to have the given credentials"`

	Checklist ChecklistCommand `command:"checklist" alias:"cl" description:"Print a Checkfile of the given pipeline"`

	Execute ExecuteCommand `command:"execute" alias:"e" description:"Execute a one-off build using local bits"`
	Watch   WatchCommand   `command:"watch"   alias:"w" description:"Stream a build's output"`

	Containers ContainersCommand `command:"containers" alias:"cs" description:"Print the active containers"`
	Hijack     HijackCommand     `command:"hijack"     alias:"intercept" alias:"i" description:"Execute a command in a container"`

	Pipelines       PipelinesCommand       `command:"pipelines"        alias:"ps" description:"List the configured pipelines"`
	DestroyPipeline DestroyPipelineCommand `command:"destroy-pipeline" alias:"dp" description:"Destroy a pipeline"`
	GetPipeline     GetPipelineCommand     `command:"get-pipeline"     alias:"gp" description:"Get a pipeline's current configuration"`
	SetPipeline     SetPipelineCommand     `command:"set-pipeline"     alias:"sp" description:"Create or update a pipeline's configuration"`
	PausePipeline   PausePipelineCommand   `command:"pause-pipeline"   alias:"pp" description:"Pause a pipeline"`
	UnpausePipeline UnpausePipelineCommand `command:"unpause-pipeline" alias:"up" description:"Un-pause a pipeline"`

	Builds BuildsCommand `command:"builds" alias:"bs" description:"List builds data"`

	Volumes VolumesCommand `command:"volumes" alias:"vs" description:"List the active volumes"`
	Workers WorkersCommand `command:"workers" alias:"ws" description:"List the registered workers"`
}

var Fly FlyCommand
<|endoftext|>