<commit_before>// +build integration

/*
Copyright (C) 2016 Red Hat, Inc.

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 integration

import (
	"fmt"
	"testing"
	"time"

	commonutil "github.com/jimmidyson/minishift/pkg/util"
	"k8s.io/kubernetes/pkg/api"

	"github.com/jimmidyson/minishift/test/integration/util"
)

var (
	addonManagerCmd = []string{"get", "pod", "kube-addon-manager-minikubevm", "--namespace=kube-system"}
	dashboardRcCmd  = []string{"get", "rc", "kubernetes-dashboard", "--namespace=kube-system"}
	dashboardSvcCmd = []string{"get", "svc", "kubernetes-dashboard", "--namespace=kube-system"}
)

func TestAddons(t *testing.T) {
	minikubeRunner := util.MinikubeRunner{
		BinaryPath: *binaryPath,
		Args:       *args,
		T:          t}

	minikubeRunner.EnsureRunning()
	kubectlRunner := util.NewKubectlRunner(t)

	checkAddon := func() error {
		p := api.Pod{}
		if err := kubectlRunner.RunCommandParseOutput(addonManagerCmd, &p); err != nil {
			return err
		}

		if p.Status.Phase != "Running" {
			return fmt.Errorf("Pod is not Running. Status: %s", p.Status.Phase)
		}
		return nil
	}

	if err := commonutil.RetryAfter(10, checkAddon, 5*time.Second); err != nil {
		t.Fatalf("Addon Manager pod is unhealthy: %s", err)
	}
}

func TestDashboard(t *testing.T) {
	minikubeRunner := util.MinikubeRunner{
		BinaryPath: *binaryPath,
		Args:       *args,
		T:          t}
	minikubeRunner.Start()
	minikubeRunner.CheckStatus("Running")
	kubectlRunner := util.NewKubectlRunner(t)

	checkDashboard := func() error {
		rc := api.ReplicationController{}
		svc := api.Service{}
		if err := kubectlRunner.RunCommandParseOutput(dashboardRcCmd, &rc); err != nil {
			return err
		}

		if err := kubectlRunner.RunCommandParseOutput(dashboardSvcCmd, &svc); err != nil {
			return err
		}

		if rc.Status.Replicas != rc.Status.FullyLabeledReplicas {
			return fmt.Errorf("Not enough pods running. Expected %s, got %s.", rc.Status.Replicas, rc.Status.FullyLabeledReplicas)
		}

		if svc.Spec.Ports[0].NodePort != 30000 {
			return fmt.Errorf("Dashboard is not exposed on port {}", svc.Spec.Ports[0].NodePort)
		}

		return nil
	}

	if err := commonutil.RetryAfter(10, checkDashboard, 5*time.Second); err != nil {
		t.Fatalf("Dashboard is unhealthy: %s", err)
	}
}
<commit_msg>Increase the timeout on the addon manager pod.<commit_after>// +build integration

/*
Copyright (C) 2016 Red Hat, Inc.

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 integration

import (
	"fmt"
	"testing"
	"time"

	commonutil "github.com/jimmidyson/minishift/pkg/util"
	"k8s.io/kubernetes/pkg/api"

	"github.com/jimmidyson/minishift/test/integration/util"
)

var (
	addonManagerCmd = []string{"get", "pod", "kube-addon-manager-minikubevm", "--namespace=kube-system"}
	dashboardRcCmd  = []string{"get", "rc", "kubernetes-dashboard", "--namespace=kube-system"}
	dashboardSvcCmd = []string{"get", "svc", "kubernetes-dashboard", "--namespace=kube-system"}
)

func TestAddons(t *testing.T) {
	minikubeRunner := util.MinikubeRunner{
		BinaryPath: *binaryPath,
		Args:       *args,
		T:          t}

	minikubeRunner.EnsureRunning()
	kubectlRunner := util.NewKubectlRunner(t)

	checkAddon := func() error {
		p := api.Pod{}
		if err := kubectlRunner.RunCommandParseOutput(addonManagerCmd, &p); err != nil {
			return err
		}

		if p.Status.Phase != "Running" {
			return fmt.Errorf("Pod is not Running. Status: %s", p.Status.Phase)
		}
		return nil
	}

	if err := commonutil.RetryAfter(20, checkAddon, 5*time.Second); err != nil {
		t.Fatalf("Addon Manager pod is unhealthy: %s", err)
	}
}

func TestDashboard(t *testing.T) {
	minikubeRunner := util.MinikubeRunner{
		BinaryPath: *binaryPath,
		Args:       *args,
		T:          t}
	minikubeRunner.Start()
	minikubeRunner.CheckStatus("Running")
	kubectlRunner := util.NewKubectlRunner(t)

	checkDashboard := func() error {
		rc := api.ReplicationController{}
		svc := api.Service{}
		if err := kubectlRunner.RunCommandParseOutput(dashboardRcCmd, &rc); err != nil {
			return err
		}

		if err := kubectlRunner.RunCommandParseOutput(dashboardSvcCmd, &svc); err != nil {
			return err
		}

		if rc.Status.Replicas != rc.Status.FullyLabeledReplicas {
			return fmt.Errorf("Not enough pods running. Expected %s, got %s.", rc.Status.Replicas, rc.Status.FullyLabeledReplicas)
		}

		if svc.Spec.Ports[0].NodePort != 30000 {
			return fmt.Errorf("Dashboard is not exposed on port {}", svc.Spec.Ports[0].NodePort)
		}

		return nil
	}

	if err := commonutil.RetryAfter(10, checkDashboard, 5*time.Second); err != nil {
		t.Fatalf("Dashboard is unhealthy: %s", err)
	}
}
<|endoftext|>


<commit_before>/*
   Copyright 2011-2017 gtalent2@gmail.com

   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 liccor

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

	"github.com/monochromegane/go-gitignore"
	"github.com/paulvollmer/go-verbose"

	"gopkg.in/yaml.v2"
)

// Version store the version as string
const Version = "1.9.0"

type liccorFile struct {
	Source          []string `yaml:"source"`
	CopyrightNotice string   `yaml:"copyright_notice"`
	Ignore          string   `yaml:"ignore"`
}

// Liccor the license corrector
type Liccor struct {
	Log              verbose.Verbose
	Source           []string
	NoticeBeforeText string
	NoticeAfterText  string
	copyrightNotice  string
	ignore           gitignore.IgnoreMatcher
}

// New initialize and return a new Liccor instance
func New() *Liccor {
	l := Liccor{}
	// ignore error, it's ok if there is no gitignore
	l.ignore, _ = gitignore.NewGitIgnore(".gitignore")
	l.Log = *verbose.New(os.Stdout, false)
	return &l
}

// Load liccor file search for a license file
func (l *Liccor) LoadConfig(dir, liccorFileName string) error {
	l.Log.Printf("Search for a license file at directory '%s'\n", dir)

	d, err := ioutil.ReadDir(dir)
	if err != nil {
		return fmt.Errorf("Could not find license file. %v", err)
	}

	fileName := ""
	if liccorFileName == "" { // no specified liccor file, search for default file names
		for _, v := range d {
			fileName = v.Name()
			// search the license file
			if fileName == ".liccor" || fileName == ".liccor.yml" || fileName == ".liccor.yaml" {
				println("'" + fileName + "'")
				break
			}
		}
	} else {
		if _, err := os.Stat(liccorFileName); err == nil {
			fileName = liccorFileName
		}
	}

	switch {
	case fileName == "":
		break
	case strings.HasSuffix(fileName, ".yaml"), strings.HasSuffix(fileName, ".yml"):
		var lf liccorFile
		data, err := ioutil.ReadFile(dir + "/" + fileName)
		if err != nil {
			return err
		}

		err = yaml.Unmarshal(data, &lf)
		if err != nil {
			return err
		}

		l.copyrightNotice = lf.CopyrightNotice
		l.Source = lf.Source
		if lf.Ignore != "" {
			l.ignore = gitignore.NewGitIgnoreFromReader("", strings.NewReader(lf.Ignore))
		}
		return err
	default:
		copyrightNotice, err := ioutil.ReadFile(dir + "/" + fileName)
		if err != nil {
			err = fmt.Errorf("Could not access " + fileName + " file")
		}
		l.Log.Printf("License file '%s' found...\n", fileName)
		l.copyrightNotice = string(copyrightNotice)
		l.copyrightNotice = l.copyrightNotice[:len(l.copyrightNotice)-1]
		return err
	}

	return l.LoadConfig(dir+"./.", liccorFileName)
}

// FindSrcFiles search for source files
func (l *Liccor) FindSrcFiles(dir string) ([]string, error) {
	l.Log.Printf("Search source files at '%s'\n", dir)

	d, err := ioutil.ReadDir(dir)
	if err != nil {
		return nil, err
	}
	var output []string
	for _, v := range d {
		if v.IsDir() {
			// ignore .git dir
			if v.Name() != ".git" {
				files, err2 := l.FindSrcFiles(dir + "/" + v.Name())
				if err2 != nil {
					return output, err2
				}
				for _, v2 := range files {
					output = append(output, v2)
				}
			}
		} else {
			pt := strings.LastIndex(v.Name(), ".")
			if pt == -1 {
				continue
			}
			switch v.Name()[pt:] {
			case SuffixGO, SuffixC, SuffixCPP, SuffixCXX, SuffixH, SuffixHPP, SuffixJAVA, SuffixJS:
				srcPath := dir + "/" + v.Name()
				output = append(output, srcPath)
				l.Log.Printf("Found source '%s'\n", srcPath)
			}
		}
	}
	return output, err
}

// HasLicense check if sourcecode has a license at the top
func (l *Liccor) HasLicense(file string) (bool, int) {
	for i, c := range file {
		switch c {
		case ' ', '\t', '\n':
			continue
		case '/':
			i++
			if len(file) > i && file[i] == '*' {
				return true, i
			}
		default:
			return false, -1
		}
	}
	return false, -1
}

// Correct a source file license
func (l *Liccor) Correct(path, license string) (bool, error) {
	input, err := ioutil.ReadFile(path)
	if err != nil || (l.ignore != nil && l.ignore.Match(path, false)) {
		return false, err
	}
	file := string(input)
	orig := file
	if hasLicense, licenseStart := l.HasLicense(file); hasLicense {
		//remove old license
		for i := licenseStart; i < len(file); i++ {
			if file[i] == '*' && file[i+1] == '/' {
				i += 2
				if file[i] == '\n' {
					i++
				}
				file = file[i:len(file)]
				break
			}
		}
	}
	file = license + file
	output := []byte(file)
	if file != orig {
		err = ioutil.WriteFile(path, output, 0)
		return true, err
	}
	return false, nil
}

// Process run the liccor magic
func (l *Liccor) Process() {
	if l.NoticeBeforeText != "" {
		l.Log.Printf("License before text set to '%s'\n", l.NoticeBeforeText)
		l.copyrightNotice = l.NoticeBeforeText + "\n" + l.copyrightNotice
	}
	if l.NoticeAfterText != "" {
		l.Log.Printf("License after text set to '%s'\n", l.NoticeAfterText)
		l.copyrightNotice = l.copyrightNotice + "\n" + l.NoticeAfterText
	}

	lics := make(map[string]string)
	clike := "/*\n * " + strings.Replace(string(l.copyrightNotice), "\n", "\n * ", -1) + "\n */\n"
	lics["c-like"] = strings.Replace(clike, "\n * \n", "\n *\n", -1)
	lics["go"] = func() string {
		golic := "/*\n   " + strings.Replace(string(l.copyrightNotice), "\n", "\n   ", -1) + "\n*/\n"
		golic = strings.Replace(golic, "\n   \n", "\n\n", -1)
		return golic
	}()

	allSuccess := true
	for _, source := range l.Source {
		files, err := l.FindSrcFiles(source)
		if err != nil {
			fmt.Errorf("Error encountered while searching "+source+", %v", err)
			continue
		}

		for i := 0; i < len(files); i++ {
			pt := strings.LastIndex(files[i], ".")
			lic := ""
			//determine how to format the license
			switch files[i][pt:] {
			case SuffixGO:
				lic = lics["go"]
			case SuffixC, SuffixCPP, SuffixCXX, SuffixH, SuffixHPP, SuffixJAVA, SuffixJS:
				lic = lics["c-like"]
			}
			changed, err := l.Correct(files[i], lic)
			if changed {
				var file string
				if files[i][:2] == "./" {
					file = files[i][2:]
				} else {
					file = files[i]
				}
				if err != nil {
					fmt.Println("Correcting '" + file + "'... Failure!")
					allSuccess = false
				} else {
					fmt.Println("Correcting '" + file + "'... Success!")
				}
			}
		}
	}
	if allSuccess {
		fmt.Println("All files up to date!")
	}
}
<commit_msg>Remove debug line<commit_after>/*
   Copyright 2011-2017 gtalent2@gmail.com

   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 liccor

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

	"github.com/monochromegane/go-gitignore"
	"github.com/paulvollmer/go-verbose"

	"gopkg.in/yaml.v2"
)

// Version store the version as string
const Version = "1.9.0"

type liccorFile struct {
	Source          []string `yaml:"source"`
	CopyrightNotice string   `yaml:"copyright_notice"`
	Ignore          string   `yaml:"ignore"`
}

// Liccor the license corrector
type Liccor struct {
	Log              verbose.Verbose
	Source           []string
	NoticeBeforeText string
	NoticeAfterText  string
	copyrightNotice  string
	ignore           gitignore.IgnoreMatcher
}

// New initialize and return a new Liccor instance
func New() *Liccor {
	l := Liccor{}
	// ignore error, it's ok if there is no gitignore
	l.ignore, _ = gitignore.NewGitIgnore(".gitignore")
	l.Log = *verbose.New(os.Stdout, false)
	return &l
}

// Load liccor file search for a license file
func (l *Liccor) LoadConfig(dir, liccorFileName string) error {
	l.Log.Printf("Search for a license file at directory '%s'\n", dir)

	d, err := ioutil.ReadDir(dir)
	if err != nil {
		return fmt.Errorf("Could not find license file. %v", err)
	}

	fileName := ""
	if liccorFileName == "" { // no specified liccor file, search for default file names
		for _, v := range d {
			fileName = v.Name()
			// search the license file
			if fileName == ".liccor" || fileName == ".liccor.yml" || fileName == ".liccor.yaml" {
				break
			}
		}
	} else {
		if _, err := os.Stat(liccorFileName); err == nil {
			fileName = liccorFileName
		}
	}

	switch {
	case fileName == "":
		break
	case strings.HasSuffix(fileName, ".yaml"), strings.HasSuffix(fileName, ".yml"):
		var lf liccorFile
		data, err := ioutil.ReadFile(dir + "/" + fileName)
		if err != nil {
			return err
		}

		err = yaml.Unmarshal(data, &lf)
		if err != nil {
			return err
		}

		l.copyrightNotice = lf.CopyrightNotice
		l.Source = lf.Source
		if lf.Ignore != "" {
			l.ignore = gitignore.NewGitIgnoreFromReader("", strings.NewReader(lf.Ignore))
		}
		return err
	default:
		copyrightNotice, err := ioutil.ReadFile(dir + "/" + fileName)
		if err != nil {
			err = fmt.Errorf("Could not access " + fileName + " file")
		}
		l.Log.Printf("License file '%s' found...\n", fileName)
		l.copyrightNotice = string(copyrightNotice)
		l.copyrightNotice = l.copyrightNotice[:len(l.copyrightNotice)-1]
		return err
	}

	return l.LoadConfig(dir+"./.", liccorFileName)
}

// FindSrcFiles search for source files
func (l *Liccor) FindSrcFiles(dir string) ([]string, error) {
	l.Log.Printf("Search source files at '%s'\n", dir)

	d, err := ioutil.ReadDir(dir)
	if err != nil {
		return nil, err
	}
	var output []string
	for _, v := range d {
		if v.IsDir() {
			// ignore .git dir
			if v.Name() != ".git" {
				files, err2 := l.FindSrcFiles(dir + "/" + v.Name())
				if err2 != nil {
					return output, err2
				}
				for _, v2 := range files {
					output = append(output, v2)
				}
			}
		} else {
			pt := strings.LastIndex(v.Name(), ".")
			if pt == -1 {
				continue
			}
			switch v.Name()[pt:] {
			case SuffixGO, SuffixC, SuffixCPP, SuffixCXX, SuffixH, SuffixHPP, SuffixJAVA, SuffixJS:
				srcPath := dir + "/" + v.Name()
				output = append(output, srcPath)
				l.Log.Printf("Found source '%s'\n", srcPath)
			}
		}
	}
	return output, err
}

// HasLicense check if sourcecode has a license at the top
func (l *Liccor) HasLicense(file string) (bool, int) {
	for i, c := range file {
		switch c {
		case ' ', '\t', '\n':
			continue
		case '/':
			i++
			if len(file) > i && file[i] == '*' {
				return true, i
			}
		default:
			return false, -1
		}
	}
	return false, -1
}

// Correct a source file license
func (l *Liccor) Correct(path, license string) (bool, error) {
	input, err := ioutil.ReadFile(path)
	if err != nil || (l.ignore != nil && l.ignore.Match(path, false)) {
		return false, err
	}
	file := string(input)
	orig := file
	if hasLicense, licenseStart := l.HasLicense(file); hasLicense {
		//remove old license
		for i := licenseStart; i < len(file); i++ {
			if file[i] == '*' && file[i+1] == '/' {
				i += 2
				if file[i] == '\n' {
					i++
				}
				file = file[i:len(file)]
				break
			}
		}
	}
	file = license + file
	output := []byte(file)
	if file != orig {
		err = ioutil.WriteFile(path, output, 0)
		return true, err
	}
	return false, nil
}

// Process run the liccor magic
func (l *Liccor) Process() {
	if l.NoticeBeforeText != "" {
		l.Log.Printf("License before text set to '%s'\n", l.NoticeBeforeText)
		l.copyrightNotice = l.NoticeBeforeText + "\n" + l.copyrightNotice
	}
	if l.NoticeAfterText != "" {
		l.Log.Printf("License after text set to '%s'\n", l.NoticeAfterText)
		l.copyrightNotice = l.copyrightNotice + "\n" + l.NoticeAfterText
	}

	lics := make(map[string]string)
	clike := "/*\n * " + strings.Replace(string(l.copyrightNotice), "\n", "\n * ", -1) + "\n */\n"
	lics["c-like"] = strings.Replace(clike, "\n * \n", "\n *\n", -1)
	lics["go"] = func() string {
		golic := "/*\n   " + strings.Replace(string(l.copyrightNotice), "\n", "\n   ", -1) + "\n*/\n"
		golic = strings.Replace(golic, "\n   \n", "\n\n", -1)
		return golic
	}()

	allSuccess := true
	for _, source := range l.Source {
		files, err := l.FindSrcFiles(source)
		if err != nil {
			fmt.Errorf("Error encountered while searching "+source+", %v", err)
			continue
		}

		for i := 0; i < len(files); i++ {
			pt := strings.LastIndex(files[i], ".")
			lic := ""
			//determine how to format the license
			switch files[i][pt:] {
			case SuffixGO:
				lic = lics["go"]
			case SuffixC, SuffixCPP, SuffixCXX, SuffixH, SuffixHPP, SuffixJAVA, SuffixJS:
				lic = lics["c-like"]
			}
			changed, err := l.Correct(files[i], lic)
			if changed {
				var file string
				if files[i][:2] == "./" {
					file = files[i][2:]
				} else {
					file = files[i]
				}
				if err != nil {
					fmt.Println("Correcting '" + file + "'... Failure!")
					allSuccess = false
				} else {
					fmt.Println("Correcting '" + file + "'... Success!")
				}
			}
		}
	}
	if allSuccess {
		fmt.Println("All files up to date!")
	}
}
<|endoftext|>


<commit_before>package client

import (
	"bufio"
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"mime"
	"net/http"
	"pfi/sensorbee/sensorbee/server/response"
	"strconv"
	"strings"
)

// Response wraps a raw HTTP response. Response must only be manipulated from
// one goroutine (i.e. it isn't thread-safe).
type Response struct {
	// Raw has a raw HTTP response.
	Raw *http.Response

	closeStream  chan struct{}
	streamClosed chan struct{}
	streamErr    error

	closed   bool
	closeErr error

	bodyCache []byte
	errCache  *response.Error
	readErr   error

	mimeType     string
	mimeParams   map[string]string
	mimeParseErr error
}

// Close closes the body of the response.
func (r *Response) Close() error {
	if r.closed {
		return r.closeErr
	}
	r.closed = true

	if r.closeStream != nil {
		close(r.closeStream)
	}

	r.closeErr = r.Raw.Body.Close()

	if r.closeStream != nil {
		<-r.streamClosed // wait until stream is closed
	}
	return r.closeErr
}

// IsStream returns true when the response from the server is a stream which
// might have unbounded data.
func (r *Response) IsStream() bool {
	if err := r.parseMediaType(); err != nil {
		return false
	}

	if !strings.Contains(r.mimeType, "multipart") {
		return false
	}
	return r.mimeParams["boundary"] != ""
}

func (r *Response) parseMediaType() error {
	if r.mimeType != "" || r.mimeParseErr != nil {
		return r.mimeParseErr
	}
	t, p, err := mime.ParseMediaType(r.Raw.Header.Get("Content-Type"))
	if err != nil {
		r.mimeParseErr = err
		return err
	}
	r.mimeType = t
	r.mimeParams = p
	return nil
}

// Body returns the response body. Invoking this method will close Raw.Body.
// Don't call this method on a stream response (i.e. a response having
// unlimited length).
func (r *Response) Body() ([]byte, error) {
	if r.IsStream() {
		return nil, errors.New("cannot perform Body method on a stream response")
	}
	if r.bodyCache != nil || r.readErr != nil {
		return r.bodyCache, r.readErr
	}

	defer r.Close()
	r.bodyCache, r.readErr = ioutil.ReadAll(r.Raw.Body)
	return r.bodyCache, r.readErr
}

// IsError returns true when the response is an error.
func (r *Response) IsError() bool {
	return r.Raw.StatusCode < 200 || 300 <= r.Raw.StatusCode
}

// Error reads an error response from the server. It fails if the response
// isn't an error.
func (r *Response) Error() (*response.Error, error) {
	if !r.IsError() {
		return nil, errors.New("the response isn't an error")
	}
	if r.errCache != nil || r.readErr != nil {
		return r.errCache, r.readErr
	}

	res := struct {
		Error *response.Error `json:"error"`
	}{}
	if err := r.ReadJSON(&res); err != nil {
		return nil, err
	}
	if res.Error == nil {
		return nil, errors.New("invalid error response")
	}
	r.errCache = res.Error
	return r.errCache, nil
}

// ReadJSON reads the response body as a json and unmarshals it to the given
// data structure. This method closed the response body. This method can be
// called multiple times with different types of arguments. Don't call this
// method on a stream response (i.e. a response having unlimited length).
func (r *Response) ReadJSON(js interface{}) error {
	body, err := r.Body()
	if err != nil {
		return err
	}
	if err := json.Unmarshal(body, js); err != nil {
		r.readErr = err
		return err
	}
	return nil
}

// ReadStreamJSON returns multiple parsed JSONs as interface{}. The caller
// must call Response.Close when it require no more JSONs.
func (r *Response) ReadStreamJSON() (<-chan interface{}, error) {
	if !r.IsStream() {
		return nil, errors.New("the response isn't a stream")
	}

	ch := make(chan interface{})
	r.closeStream = make(chan struct{})
	r.streamClosed = make(chan struct{})

	// TODO: refactor this dirty long goroutine.
	go func() {
		defer func() {
			close(ch)
			close(r.streamClosed)
		}()

		reader := bufio.NewReader(r.Raw.Body)
		nextLine := func() ([]byte, []byte, error) {
			line, err := reader.ReadBytes('\n')
			if err != nil {
				return nil, nil, err
			}
			nl := line
			line = line[:len(line)-1] // remove '\n'
			if l := len(line); l > 0 && line[l-1] == '\r' {
				line = line[:l-1]
				nl = nl[len(nl)-2:]
			} else {
				nl = nl[len(nl)-1:]
			}
			return line, nl, nil
		}
		boundary := append([]byte("--"), []byte(r.mimeParams["boundary"])...)
		isBoundaryLine := func(line []byte) (bool, bool) {
			if !bytes.HasPrefix(line, boundary) {
				return false, false
			}
			line = line[len(boundary):]
			isFinal := false
			if bytes.HasPrefix(line, []byte("--")) {
				isFinal = true
				line = line[2:]
			}
			for len(line) > 0 && (line[0] == ' ' || line[0] == '\t') {
				line = line[1:]
			}
			return len(line) == 0, isFinal
		}

		for { // find first boundary
			if line, _, err := nextLine(); err != nil {
				if err == io.EOF {
					r.streamErr = io.ErrUnexpectedEOF
				} else {
					r.streamErr = err
				}
				return

			} else if b, final := isBoundaryLine(line); b {
				if final {
					return
				}
				break
			}
		}

		body := make([]byte, 0, 4096)
		for { // read each part
			body = body[:0]
			header := http.Header{}
			for { // read header
				line, _, err := nextLine()
				if err != nil {
					if err != io.EOF {
						r.streamErr = err
					}
					return
				}
				if len(line) == 0 {
					break
				}
				l := string(line)
				i := strings.Index(l, ": ")
				if i < 0 {
					continue
				}
				header.Set(l[:i], l[i+2:])
			}

			if ct := header.Get("Content-Type"); !strings.Contains(ct, "application/json") {
				r.streamErr = errors.New("the stream contains non-JSON contents")
				return
			}

			var contentLength int
			clStr := header.Get("Content-Length")
			if clStr != "" {
				cl, err := strconv.Atoi(clStr)
				if err != nil {
					r.streamErr = err
					return
				}
				contentLength = cl
			}

			boundaryFound := false
			finalPart := false
			for {
				line, nl, err := nextLine()
				if err != nil {
					if err != io.EOF {
						r.streamErr = err
					}
					return
				}
				if boundaryFound, finalPart = isBoundaryLine(line); boundaryFound {
					break
				}

				if len(body) != 0 {
					body = append(body, nl...)
				}
				body = append(body, line...)
				if contentLength != 0 && len(body) >= contentLength {
					break
				}
			}

			var js interface{}
			if err := json.Unmarshal(body, &js); err != nil {
				r.streamErr = fmt.Errorf("cannot parse JSON: %v", err)
				return
			}
			select {
			case <-r.closeStream:
			case ch <- js:
			}

			if !boundaryFound {
				for {
					line, _, err := nextLine()
					if err != nil {
						if err != io.EOF {
							r.streamErr = err
						}
						return
					}
					if boundaryFound, finalPart = isBoundaryLine(line); boundaryFound {
						break
					}
				}
			}
			if finalPart {
				return
			}
		}
	}()
	return ch, nil
}

// StreamError returns an error which occurred in a goroutine spawned from
// ReadStreamJSON method. Don't call this method before the channel returned
// from ReadStreamJSON is closed.
func (r *Response) StreamError() error {
	return r.streamErr
}
<commit_msg>Add missing return<commit_after>package client

import (
	"bufio"
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"mime"
	"net/http"
	"pfi/sensorbee/sensorbee/server/response"
	"strconv"
	"strings"
)

// Response wraps a raw HTTP response. Response must only be manipulated from
// one goroutine (i.e. it isn't thread-safe).
type Response struct {
	// Raw has a raw HTTP response.
	Raw *http.Response

	closeStream  chan struct{}
	streamClosed chan struct{}
	streamErr    error

	closed   bool
	closeErr error

	bodyCache []byte
	errCache  *response.Error
	readErr   error

	mimeType     string
	mimeParams   map[string]string
	mimeParseErr error
}

// Close closes the body of the response.
func (r *Response) Close() error {
	if r.closed {
		return r.closeErr
	}
	r.closed = true

	if r.closeStream != nil {
		close(r.closeStream)
	}

	r.closeErr = r.Raw.Body.Close()

	if r.closeStream != nil {
		<-r.streamClosed // wait until stream is closed
	}
	return r.closeErr
}

// IsStream returns true when the response from the server is a stream which
// might have unbounded data.
func (r *Response) IsStream() bool {
	if err := r.parseMediaType(); err != nil {
		return false
	}

	if !strings.Contains(r.mimeType, "multipart") {
		return false
	}
	return r.mimeParams["boundary"] != ""
}

func (r *Response) parseMediaType() error {
	if r.mimeType != "" || r.mimeParseErr != nil {
		return r.mimeParseErr
	}
	t, p, err := mime.ParseMediaType(r.Raw.Header.Get("Content-Type"))
	if err != nil {
		r.mimeParseErr = err
		return err
	}
	r.mimeType = t
	r.mimeParams = p
	return nil
}

// Body returns the response body. Invoking this method will close Raw.Body.
// Don't call this method on a stream response (i.e. a response having
// unlimited length).
func (r *Response) Body() ([]byte, error) {
	if r.IsStream() {
		return nil, errors.New("cannot perform Body method on a stream response")
	}
	if r.bodyCache != nil || r.readErr != nil {
		return r.bodyCache, r.readErr
	}

	defer r.Close()
	r.bodyCache, r.readErr = ioutil.ReadAll(r.Raw.Body)
	return r.bodyCache, r.readErr
}

// IsError returns true when the response is an error.
func (r *Response) IsError() bool {
	return r.Raw.StatusCode < 200 || 300 <= r.Raw.StatusCode
}

// Error reads an error response from the server. It fails if the response
// isn't an error.
func (r *Response) Error() (*response.Error, error) {
	if !r.IsError() {
		return nil, errors.New("the response isn't an error")
	}
	if r.errCache != nil || r.readErr != nil {
		return r.errCache, r.readErr
	}

	res := struct {
		Error *response.Error `json:"error"`
	}{}
	if err := r.ReadJSON(&res); err != nil {
		return nil, err
	}
	if res.Error == nil {
		return nil, errors.New("invalid error response")
	}
	r.errCache = res.Error
	return r.errCache, nil
}

// ReadJSON reads the response body as a json and unmarshals it to the given
// data structure. This method closed the response body. This method can be
// called multiple times with different types of arguments. Don't call this
// method on a stream response (i.e. a response having unlimited length).
func (r *Response) ReadJSON(js interface{}) error {
	body, err := r.Body()
	if err != nil {
		return err
	}
	if err := json.Unmarshal(body, js); err != nil {
		r.readErr = err
		return err
	}
	return nil
}

// ReadStreamJSON returns multiple parsed JSONs as interface{}. The caller
// must call Response.Close when it require no more JSONs.
func (r *Response) ReadStreamJSON() (<-chan interface{}, error) {
	if !r.IsStream() {
		return nil, errors.New("the response isn't a stream")
	}

	ch := make(chan interface{})
	r.closeStream = make(chan struct{})
	r.streamClosed = make(chan struct{})

	// TODO: refactor this dirty long goroutine.
	go func() {
		defer func() {
			close(ch)
			close(r.streamClosed)
		}()

		reader := bufio.NewReader(r.Raw.Body)
		nextLine := func() ([]byte, []byte, error) {
			line, err := reader.ReadBytes('\n')
			if err != nil {
				return nil, nil, err
			}
			nl := line
			line = line[:len(line)-1] // remove '\n'
			if l := len(line); l > 0 && line[l-1] == '\r' {
				line = line[:l-1]
				nl = nl[len(nl)-2:]
			} else {
				nl = nl[len(nl)-1:]
			}
			return line, nl, nil
		}
		boundary := append([]byte("--"), []byte(r.mimeParams["boundary"])...)
		isBoundaryLine := func(line []byte) (bool, bool) {
			if !bytes.HasPrefix(line, boundary) {
				return false, false
			}
			line = line[len(boundary):]
			isFinal := false
			if bytes.HasPrefix(line, []byte("--")) {
				isFinal = true
				line = line[2:]
			}
			for len(line) > 0 && (line[0] == ' ' || line[0] == '\t') {
				line = line[1:]
			}
			return len(line) == 0, isFinal
		}

		for { // find first boundary
			if line, _, err := nextLine(); err != nil {
				if err == io.EOF {
					r.streamErr = io.ErrUnexpectedEOF
				} else {
					r.streamErr = err
				}
				return

			} else if b, final := isBoundaryLine(line); b {
				if final {
					return
				}
				break
			}
		}

		body := make([]byte, 0, 4096)
		for { // read each part
			body = body[:0]
			header := http.Header{}
			for { // read header
				line, _, err := nextLine()
				if err != nil {
					if err != io.EOF {
						r.streamErr = err
					}
					return
				}
				if len(line) == 0 {
					break
				}
				l := string(line)
				i := strings.Index(l, ": ")
				if i < 0 {
					continue
				}
				header.Set(l[:i], l[i+2:])
			}

			if ct := header.Get("Content-Type"); !strings.Contains(ct, "application/json") {
				r.streamErr = errors.New("the stream contains non-JSON contents")
				return
			}

			var contentLength int
			clStr := header.Get("Content-Length")
			if clStr != "" {
				cl, err := strconv.Atoi(clStr)
				if err != nil {
					r.streamErr = err
					return
				}
				contentLength = cl
			}

			boundaryFound := false
			finalPart := false
			for {
				line, nl, err := nextLine()
				if err != nil {
					if err != io.EOF {
						r.streamErr = err
					}
					return
				}
				if boundaryFound, finalPart = isBoundaryLine(line); boundaryFound {
					break
				}

				if len(body) != 0 {
					body = append(body, nl...)
				}
				body = append(body, line...)
				if contentLength != 0 && len(body) >= contentLength {
					break
				}
			}

			var js interface{}
			if err := json.Unmarshal(body, &js); err != nil {
				r.streamErr = fmt.Errorf("cannot parse JSON: %v", err)
				return
			}
			select {
			case <-r.closeStream:
				return
			case ch <- js:
			}

			if !boundaryFound {
				for {
					line, _, err := nextLine()
					if err != nil {
						if err != io.EOF {
							r.streamErr = err
						}
						return
					}
					if boundaryFound, finalPart = isBoundaryLine(line); boundaryFound {
						break
					}
				}
			}
			if finalPart {
				return
			}
		}
	}()
	return ch, nil
}

// StreamError returns an error which occurred in a goroutine spawned from
// ReadStreamJSON method. Don't call this method before the channel returned
// from ReadStreamJSON is closed.
func (r *Response) StreamError() error {
	return r.streamErr
}
<|endoftext|>


<commit_before>package cloudbrain

import (
	"crypto/subtle"
	"encoding/hex"

	"github.com/Sirupsen/logrus"
	"github.com/travis-ci/cloud-brain/cbcontext"
	"github.com/travis-ci/cloud-brain/cloud"
	"github.com/travis-ci/cloud-brain/database"
	"github.com/travis-ci/cloud-brain/worker"
	"golang.org/x/crypto/scrypt"
	"golang.org/x/net/context"
)

const MaxCreateRetries = 10

type Core struct {
	cloudProviders map[string]cloud.Provider
	db             database.DB
	wb             worker.Backend
}

// TODO(henrikhodne): Is this necessary? Why not just make a Core directly?
type CoreConfig struct {
	DB            database.DB
	WorkerBackend worker.Backend
}

func NewCore(conf *CoreConfig) (*Core, error) {
	dbCloudProviders, err := conf.DB.ListProviders()
	if err != nil {
		return nil, err
	}

	cloudProviders := make(map[string]cloud.Provider)

	for _, dbCloudProvider := range dbCloudProviders {
		cloudProvider, err := cloud.NewProvider(dbCloudProvider.Type, dbCloudProvider.Config)
		if err != nil {
			return nil, err
		}

		cloudProviders[dbCloudProvider.Name] = cloudProvider
	}

	return &Core{
		cloudProviders: cloudProviders,
		db:             conf.DB,
		wb:             conf.WorkerBackend,
	}, nil
}

// GetInstance gets the instance information stored in the database for a given
// instance ID.
func (c *Core) GetInstance(ctx context.Context, id string) (*Instance, error) {
	instance, err := c.db.GetInstance(id)

	if err == database.ErrInstanceNotFound {
		return nil, nil
	}

	if err != nil {
		return nil, err
	}

	return &Instance{
		ID:           instance.ID,
		ProviderName: instance.ProviderName,
		Image:        instance.Image,
		State:        instance.State,
		IPAddress:    instance.IPAddress,
	}, nil
}

// CreateInstanceAttributes contains attributes needed to start an instance
type CreateInstanceAttributes struct {
	ImageName    string
	InstanceType string
	PublicSSHKey string
}

// CreateInstance creates an instance in the database and queues off the cloud
// create job in the background.
func (c *Core) CreateInstance(ctx context.Context, providerName string, attr CreateInstanceAttributes) (*Instance, error) {
	id, err := c.db.CreateInstance(database.Instance{
		ProviderName: providerName,
		Image:        attr.ImageName,
		InstanceType: attr.InstanceType,
		PublicSSHKey: attr.PublicSSHKey,
		State:        "creating",
	})
	if err != nil {
		cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
			"err":        err,
			"provider":   providerName,
			"image_name": attr.ImageName,
		}).Error("error creating instance in database")
		return nil, err
	}

	err = c.wb.Enqueue(worker.Job{
		Context:    ctx,
		Payload:    []byte(id),
		Queue:      "create",
		MaxRetries: MaxCreateRetries,
	})
	if err != nil {
		cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
			"err":         err,
			"instance_id": id,
		}).Error("error enqueueing 'create' job in the background")
		// TODO(henrikhodne): Delete the record in the database?
		return nil, err
	}

	return &Instance{
		ID:           id,
		ProviderName: providerName,
		Image:        attr.ImageName,
		State:        "creating",
	}, nil
}

func (c *Core) ProviderCreateInstance(ctx context.Context, byteID []byte) error {
	id := string(byteID)

	cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
		"instance_id": id,
	}).Info("creating instance")

	dbInstance, err := c.db.GetInstance(id)
	if err != nil {
		cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
			"err":         err,
			"instance_id": id,
		}).Error("error fetching instance from DB")
		return err
	}

	cloudProvider, ok := c.cloudProviders[dbInstance.ProviderName]
	if !ok {
		cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
			"instance_id":   id,
			"provider_name": dbInstance.ProviderName,
		}).Error("couldn't find provider with given name")
		return err
	}

	instance, err := cloudProvider.Create(id, cloud.CreateAttributes{
		ImageName:    dbInstance.Image,
		InstanceType: cloud.InstanceType(dbInstance.InstanceType),
		PublicSSHKey: dbInstance.PublicSSHKey,
	})
	if err != nil {
		cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
			"err":         err,
			"instance_id": id,
		}).Error("error creating instance")
		return err
	}

	dbInstance.State = "starting"

	err = c.db.UpdateInstance(dbInstance)
	if err != nil {
		cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
			"err":         err,
			"instance_id": id,
			"provider_id": instance.ID,
		}).Error("couldn't update instance in DB")
		return err
	}

	cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
		"instance_id": id,
		"provider_id": instance.ID,
	}).Info("created instance")

	return nil
}

func (c *Core) ProviderRefresh(ctx context.Context) error {
	for providerName, cloudProvider := range c.cloudProviders {
		// TODO(henrikhodne): An error on one provider shouldn't affect other providers
		instances, err := cloudProvider.List()
		if err != nil {
			return err
		}

		for _, instance := range instances {
			dbInstance, err := c.db.GetInstance(instance.ID)
			if err != nil {
				cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
					"provider_name": providerName,
					"provider_id":   instance.ID,
				}).Error("failed fetching instance from database")
				continue
			}

			dbInstance.IPAddress = instance.IPAddress
			dbInstance.State = string(instance.State)

			err = c.db.UpdateInstance(dbInstance)
			if err != nil {
				cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
					"provider":    providerName,
					"provider_id": instance.ID,
					"db_id":       dbInstance.ID,
				}).Error("failed to update instance in database")
			}
		}

		cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
			"provider":       providerName,
			"instance_count": len(instances),
		}).Info("refreshed instances")
	}

	return nil
}

func (c *Core) CheckToken(tokenID uint64, token string) (bool, error) {
	salt, hash, err := c.db.GetSaltAndHashForTokenID(tokenID)
	if err != nil {
		return false, err
	}

	decodedToken, err := hex.DecodeString(token)
	if err != nil {
		return false, err
	}

	generatedHash, err := scrypt.Key(decodedToken, salt, 16384, 8, 1, 32)
	if err != nil {
		return false, err
	}

	return subtle.ConstantTimeCompare(generatedHash, hash) == 1, nil
}

type Instance struct {
	ID           string
	ProviderName string
	Image        string
	State        string
	IPAddress    string
}
<commit_msg>core: get cloud providers on demand<commit_after>package cloudbrain

import (
	"crypto/subtle"
	"encoding/hex"
	"fmt"
	"sync"

	"github.com/Sirupsen/logrus"
	"github.com/travis-ci/cloud-brain/cbcontext"
	"github.com/travis-ci/cloud-brain/cloud"
	"github.com/travis-ci/cloud-brain/database"
	"github.com/travis-ci/cloud-brain/worker"
	"golang.org/x/crypto/scrypt"
	"golang.org/x/net/context"
)

const MaxCreateRetries = 10

type Core struct {
	db database.DB
	wb worker.Backend

	cloudProvidersMutex sync.Mutex
	cloudProviders      map[string]cloud.Provider
}

// TODO(henrikhodne): Is this necessary? Why not just make a Core directly?
type CoreConfig struct {
	DB            database.DB
	WorkerBackend worker.Backend
}

func NewCore(conf *CoreConfig) (*Core, error) {
	return &Core{
		db: conf.DB,
		wb: conf.WorkerBackend,
	}, nil
}

// GetInstance gets the instance information stored in the database for a given
// instance ID.
func (c *Core) GetInstance(ctx context.Context, id string) (*Instance, error) {
	instance, err := c.db.GetInstance(id)

	if err == database.ErrInstanceNotFound {
		return nil, nil
	}

	if err != nil {
		return nil, err
	}

	return &Instance{
		ID:           instance.ID,
		ProviderName: instance.ProviderName,
		Image:        instance.Image,
		State:        instance.State,
		IPAddress:    instance.IPAddress,
	}, nil
}

// CreateInstanceAttributes contains attributes needed to start an instance
type CreateInstanceAttributes struct {
	ImageName    string
	InstanceType string
	PublicSSHKey string
}

// CreateInstance creates an instance in the database and queues off the cloud
// create job in the background.
func (c *Core) CreateInstance(ctx context.Context, providerName string, attr CreateInstanceAttributes) (*Instance, error) {
	id, err := c.db.CreateInstance(database.Instance{
		ProviderName: providerName,
		Image:        attr.ImageName,
		InstanceType: attr.InstanceType,
		PublicSSHKey: attr.PublicSSHKey,
		State:        "creating",
	})
	if err != nil {
		cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
			"err":        err,
			"provider":   providerName,
			"image_name": attr.ImageName,
		}).Error("error creating instance in database")
		return nil, err
	}

	err = c.wb.Enqueue(worker.Job{
		Context:    ctx,
		Payload:    []byte(id),
		Queue:      "create",
		MaxRetries: MaxCreateRetries,
	})
	if err != nil {
		cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
			"err":         err,
			"instance_id": id,
		}).Error("error enqueueing 'create' job in the background")
		// TODO(henrikhodne): Delete the record in the database?
		return nil, err
	}

	return &Instance{
		ID:           id,
		ProviderName: providerName,
		Image:        attr.ImageName,
		State:        "creating",
	}, nil
}

func (c *Core) ProviderCreateInstance(ctx context.Context, byteID []byte) error {
	id := string(byteID)

	cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
		"instance_id": id,
	}).Info("creating instance")

	dbInstance, err := c.db.GetInstance(id)
	if err != nil {
		cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
			"err":         err,
			"instance_id": id,
		}).Error("error fetching instance from DB")
		return err
	}

	cloudProvider, err := c.cloudProvider(dbInstance.ProviderName)
	if err != nil {
		cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
			"instance_id":   id,
			"provider_name": dbInstance.ProviderName,
			"err":           err,
		}).Error("couldn't find provider with given name")
		return err
	}

	instance, err := cloudProvider.Create(id, cloud.CreateAttributes{
		ImageName:    dbInstance.Image,
		InstanceType: cloud.InstanceType(dbInstance.InstanceType),
		PublicSSHKey: dbInstance.PublicSSHKey,
	})
	if err != nil {
		cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
			"err":         err,
			"instance_id": id,
		}).Error("error creating instance")
		return err
	}

	dbInstance.State = "starting"

	err = c.db.UpdateInstance(dbInstance)
	if err != nil {
		cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
			"err":         err,
			"instance_id": id,
			"provider_id": instance.ID,
		}).Error("couldn't update instance in DB")
		return err
	}

	cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
		"instance_id": id,
		"provider_id": instance.ID,
	}).Info("created instance")

	return nil
}

func (c *Core) ProviderRefresh(ctx context.Context) error {
	c.refreshProviders()
	c.cloudProvidersMutex.Lock()
	defer c.cloudProvidersMutex.Unlock()

	for providerName, cloudProvider := range c.cloudProviders {
		// TODO(henrikhodne): An error on one provider shouldn't affect other providers
		instances, err := cloudProvider.List()
		if err != nil {
			return err
		}

		for _, instance := range instances {
			dbInstance, err := c.db.GetInstance(instance.ID)
			if err != nil {
				cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
					"provider_name": providerName,
					"provider_id":   instance.ID,
				}).Error("failed fetching instance from database")
				continue
			}

			dbInstance.IPAddress = instance.IPAddress
			dbInstance.State = string(instance.State)

			err = c.db.UpdateInstance(dbInstance)
			if err != nil {
				cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
					"provider":    providerName,
					"provider_id": instance.ID,
					"db_id":       dbInstance.ID,
				}).Error("failed to update instance in database")
			}
		}

		cbcontext.LoggerFromContext(ctx).WithFields(logrus.Fields{
			"provider":       providerName,
			"instance_count": len(instances),
		}).Info("refreshed instances")
	}

	return nil
}

func (c *Core) CheckToken(tokenID uint64, token string) (bool, error) {
	salt, hash, err := c.db.GetSaltAndHashForTokenID(tokenID)
	if err != nil {
		return false, err
	}

	decodedToken, err := hex.DecodeString(token)
	if err != nil {
		return false, err
	}

	generatedHash, err := scrypt.Key(decodedToken, salt, 16384, 8, 1, 32)
	if err != nil {
		return false, err
	}

	return subtle.ConstantTimeCompare(generatedHash, hash) == 1, nil
}

func (c *Core) cloudProvider(name string) (cloud.Provider, error) {
	c.cloudProvidersMutex.Lock()
	cloudProvider, ok := c.cloudProviders[name]
	c.cloudProvidersMutex.Unlock()
	if !ok {
		err := c.refreshProviders()
		if err != nil {
			return nil, err
		}

		c.cloudProvidersMutex.Lock()
		cloudProvider, ok = c.cloudProviders[name]
		c.cloudProvidersMutex.Unlock()
		if !ok {
			// This really shouldn't happen, since the database should ensure
			// that a provider with a matching name exists.
			return nil, fmt.Errorf("couldn't find a provider with that name")
		}
	}

	return cloudProvider, nil
}

func (c *Core) refreshProviders() error {
	c.cloudProvidersMutex.Lock()
	defer c.cloudProvidersMutex.Unlock()
	dbCloudProviders, err := c.db.ListProviders()
	if err != nil {
		return err
	}

	cloudProviders := make(map[string]cloud.Provider)

	for _, dbCloudProvider := range dbCloudProviders {
		cloudProvider, err := cloud.NewProvider(dbCloudProvider.Type, dbCloudProvider.Config)
		if err != nil {
			return err
		}

		cloudProviders[dbCloudProvider.Name] = cloudProvider
	}

	c.cloudProviders = cloudProviders

	return nil
}

type Instance struct {
	ID           string
	ProviderName string
	Image        string
	State        string
	IPAddress    string
}
<|endoftext|>


<commit_before>// Copyright 2012 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.

// +build 386 arm,!arm64

package cmac

import (
	"log"
	"unsafe"
)

// XOR the blockSize bytes starting at a and b, writing the result over dst.
func xorBlock(
	dstPtr unsafe.Pointer,
	aPtr unsafe.Pointer,
	bPtr unsafe.Pointer) {
	// Check assumptions. (These are compile-time constants, so this should
	// compile out.)
	const wordSize = unsafe.Sizeof(uintptr(0))
	if blockSize != 4*wordSize {
		log.Panicf("%d %d", blockSize, wordSize)
	}

	// Convert.
	a := (*[4]uintptr)(aPtr)
	b := (*[4]uintptr)(bPtr)
	dst := (*[4]uintptr)(dstPtr)

	// Compute.
	dst[0] = a[0] ^ b[0]
	dst[1] = a[1] ^ b[1]
	dst[2] = a[2] ^ b[2]
	dst[3] = a[3] ^ b[3]
}
<commit_msg>Add support for mips and mipsle (32bit)<commit_after>// Copyright 2012 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.

// +build 386 arm,!arm64 mips mipsle

package cmac

import (
	"log"
	"unsafe"
)

// XOR the blockSize bytes starting at a and b, writing the result over dst.
func xorBlock(
	dstPtr unsafe.Pointer,
	aPtr unsafe.Pointer,
	bPtr unsafe.Pointer) {
	// Check assumptions. (These are compile-time constants, so this should
	// compile out.)
	const wordSize = unsafe.Sizeof(uintptr(0))
	if blockSize != 4*wordSize {
		log.Panicf("%d %d", blockSize, wordSize)
	}

	// Convert.
	a := (*[4]uintptr)(aPtr)
	b := (*[4]uintptr)(bPtr)
	dst := (*[4]uintptr)(dstPtr)

	// Compute.
	dst[0] = a[0] ^ b[0]
	dst[1] = a[1] ^ b[1]
	dst[2] = a[2] ^ b[2]
	dst[3] = a[3] ^ b[3]
}
<|endoftext|>


<commit_before>/*
This package is just a collection of test cases
*/
package main

import (
	"github.com/codegangsta/cli"
	"os"
	"sort"
	"strings"
)

var (
	// flags
	fWant4 bool
	fWant6 bool

	fAllProbes bool
	fAllMeasurements bool

	fAsn string
	fCountry string
	fFieldList string
	fFormat string
	fOptFields string
	fSortOrder string
	fMeasureType string

	fVerbose bool
	fWantAnchor bool

	cliCommands []cli.Command
)

type ByAlphabet []cli.Command

func (a ByAlphabet) Len() int           { return len(a) }
func (a ByAlphabet) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByAlphabet) Less(i, j int) bool { return a[i].Name < a[j].Name }

// checkGlobalFlags is the place to check global parameters
func checkGlobalFlags(o map[string]string) (map[string]string) {
	opts := o
	if fSortOrder != "" {
		opts["sort"] = fSortOrder
	}

	if fFieldList != "" {
		opts["fields"] = fFieldList
	}

	if fOptFields != "" {
		opts["optional_fields"] = fOptFields
	}

	if fFormat != "" && validateFormat(fFormat) {
		opts["format"] = fFormat
	}
	return opts
}

// validateFormat allows only supported formats
func validateFormat(fmt string) bool {
	f := strings.ToLower(fmt)
	if f == "json" || f == "xml" || f == "api" || f == "txt" || f == "jsonp" {
		return true
	}
	return false
}

// main is the starting point (and everything)
func main() {
	app := cli.NewApp()
	app.Name = "atlas"
	app.Usage = "RIPE Atlas cli interface"
	app.Author = "Ollivier Robert <roberto@keltia.net>"
	app.Version = "0.1.0"
	app.HideVersion = true

	// General flags
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name: "format,f",
			Usage: "specify output format",
			Destination: &fFormat,
		},
		cli.BoolFlag{
			Name: "verbose,v",
			Usage: "verbose mode",
			Destination: &fVerbose,
		},
		cli.StringFlag{
			Name: "fields,F",
			Usage: "specify which fields are wanted",
			Destination: &fFieldList,
		},
		cli.StringFlag{
			Name: "opt-fields,O",
			Usage: "specify which optional fields are wanted",
			Destination: &fOptFields,
		},
		cli.StringFlag{
			Name:        "sort,S",
			Usage:       "sort results",
			Value:       "id",
			Destination: &fSortOrder,
		},
	}

	sort.Sort(ByAlphabet(cliCommands))
	app.Commands = cliCommands
	app.Run(os.Args)
}
<commit_msg>Use atlas.LoadConfig() to load the API key.<commit_after>/*
This package is just a collection of test cases
*/
package main

import (
	"github.com/codegangsta/cli"
	"os"
	"sort"
	"strings"
	"github.com/keltia/ripe-atlas"
)

var (
	// flags
	fWant4 bool
	fWant6 bool

	fAllProbes bool
	fAllMeasurements bool

	fAsn string
	fCountry string
	fFieldList string
	fFormat string
	fOptFields string
	fSortOrder string
	fMeasureType string

	fVerbose bool
	fWantAnchor bool

	cliCommands []cli.Command
)

type ByAlphabet []cli.Command

func (a ByAlphabet) Len() int           { return len(a) }
func (a ByAlphabet) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByAlphabet) Less(i, j int) bool { return a[i].Name < a[j].Name }

// checkGlobalFlags is the place to check global parameters
func checkGlobalFlags(o map[string]string) (map[string]string) {
	opts := o
	if fSortOrder != "" {
		opts["sort"] = fSortOrder
	}

	if fFieldList != "" {
		opts["fields"] = fFieldList
	}

	if fOptFields != "" {
		opts["optional_fields"] = fOptFields
	}

	if fFormat != "" && validateFormat(fFormat) {
		opts["format"] = fFormat
	}
	return opts
}

// validateFormat allows only supported formats
func validateFormat(fmt string) bool {
	f := strings.ToLower(fmt)
	if f == "json" || f == "xml" || f == "api" || f == "txt" || f == "jsonp" {
		return true
	}
	return false
}

// main is the starting point (and everything)
func main() {
	app := cli.NewApp()
	app.Name = "atlas"
	app.Usage = "RIPE Atlas cli interface"
	app.Author = "Ollivier Robert <roberto@keltia.net>"
	app.Version = "0.1.0"
	app.HideVersion = true

	// General flags
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name: "format,f",
			Usage: "specify output format",
			Destination: &fFormat,
		},
		cli.BoolFlag{
			Name: "verbose,v",
			Usage: "verbose mode",
			Destination: &fVerbose,
		},
		cli.StringFlag{
			Name: "fields,F",
			Usage: "specify which fields are wanted",
			Destination: &fFieldList,
		},
		cli.StringFlag{
			Name: "opt-fields,O",
			Usage: "specify which optional fields are wanted",
			Destination: &fOptFields,
		},
		cli.StringFlag{
			Name:        "sort,S",
			Usage:       "sort results",
			Value:       "id",
			Destination: &fSortOrder,
		},
	}

	conf, err := atlas.LoadConfig("ripe-atlas")
	if conf.ApiKey != "" && err != nil {
		atlas.SetAuth(conf.ApiKey)
	}
	sort.Sort(ByAlphabet(cliCommands))
	app.Commands = cliCommands
	app.Run(os.Args)
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"context"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"net"
	"net/http"
	"path/filepath"
	"strings"
	"time"

	"github.com/containerd/console"
	contentapi "github.com/containerd/containerd/api/services/content"
	imagesapi "github.com/containerd/containerd/api/services/images"
	"github.com/containerd/containerd/content"
	"github.com/containerd/containerd/images"
	"github.com/containerd/containerd/remotes"
	"github.com/containerd/containerd/remotes/docker"
	"github.com/containerd/containerd/rootfs"
	contentservice "github.com/containerd/containerd/services/content"
	imagesservice "github.com/containerd/containerd/services/images"
	ocispec "github.com/opencontainers/image-spec/specs-go/v1"
	"github.com/pkg/errors"
	"github.com/urfave/cli"
	"google.golang.org/grpc"
)

var registryFlags = []cli.Flag{
	cli.BoolFlag{
		Name:  "skip-verify,k",
		Usage: "Skip SSL certificate validation",
	},
	cli.BoolFlag{
		Name:  "plain-http",
		Usage: "Allow connections using plain HTTP",
	},
	cli.StringFlag{
		Name:  "user,u",
		Usage: "user[:password] Registry user and password",
	},
	cli.StringFlag{
		Name:  "refresh",
		Usage: "Refresh token for authorization server",
	},
}

func resolveContentStore(context *cli.Context) (content.Store, error) {
	root := filepath.Join(context.GlobalString("root"), "content")
	if !filepath.IsAbs(root) {
		var err error
		root, err = filepath.Abs(root)
		if err != nil {
			return nil, err
		}
	}
	conn, err := connectGRPC(context)
	if err != nil {
		return nil, err
	}

	return contentservice.NewStoreFromClient(contentapi.NewContentClient(conn)), nil
}

func resolveImageStore(clicontext *cli.Context) (images.Store, error) {
	conn, err := connectGRPC(clicontext)
	if err != nil {
		return nil, err
	}
	return imagesservice.NewStoreFromClient(imagesapi.NewImagesClient(conn)), nil
}

func connectGRPC(context *cli.Context) (*grpc.ClientConn, error) {
	address := context.GlobalString("address")
	timeout := context.GlobalDuration("connect-timeout")
	return grpc.Dial(address,
		grpc.WithTimeout(timeout),
		grpc.WithBlock(),
		grpc.WithInsecure(),
		grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
			return net.DialTimeout("unix", address, timeout)
		}),
	)
}

// getResolver prepares the resolver from the environment and options.
func getResolver(ctx context.Context, clicontext *cli.Context) (remotes.Resolver, error) {
	username := clicontext.String("user")
	var secret string
	if i := strings.IndexByte(username, ':'); i > 0 {
		secret = username[i+1:]
		username = username[0:i]
	}
	options := docker.ResolverOptions{
		PlainHTTP: clicontext.Bool("plain-http"),
	}
	if username != "" {
		if secret == "" {
			fmt.Printf("Password: ")

			var err error
			secret, err = passwordPrompt()
			if err != nil {
				return nil, err
			}

			fmt.Print("\n")
		}
	} else if rt := clicontext.String("refresh"); rt != "" {
		secret = rt
	}

	options.Credentials = func(host string) (string, string, error) {
		// Only one host
		return username, secret, nil
	}

	tr := &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		DialContext: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
			DualStack: true,
		}).DialContext,
		MaxIdleConns:        10,
		IdleConnTimeout:     30 * time.Second,
		TLSHandshakeTimeout: 10 * time.Second,
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: clicontext.Bool("insecure"),
		},
		ExpectContinueTimeout: 5 * time.Second,
	}

	options.Client = &http.Client{
		Transport: tr,
	}

	return docker.NewResolver(options), nil
}

func passwordPrompt() (string, error) {
	c := console.Current()
	defer c.Reset()

	if err := c.DisableEcho(); err != nil {
		return "", errors.Wrap(err, "failed to disable echo")
	}

	line, _, err := bufio.NewReader(c).ReadLine()
	if err != nil {
		return "", errors.Wrap(err, "failed to read line")
	}
	return string(line), nil
}

func getImageLayers(ctx context.Context, image images.Image, cs content.Store) ([]rootfs.Layer, error) {
	p, err := content.ReadBlob(ctx, cs, image.Target.Digest)
	if err != nil {
		return nil, errors.Wrapf(err, "failed to read manifest blob")
	}

	var manifest ocispec.Manifest
	if err := json.Unmarshal(p, &manifest); err != nil {
		return nil, errors.Wrap(err, "failed to unmarshal manifest")
	}

	diffIDs, err := image.RootFS(ctx, cs)
	if err != nil {
		return nil, errors.Wrap(err, "failed to resolve rootfs")
	}

	if len(diffIDs) != len(manifest.Layers) {
		return nil, errors.Errorf("mismatched image rootfs and manifest layers")
	}

	layers := make([]rootfs.Layer, len(diffIDs))
	for i := range diffIDs {
		layers[i].Diff = ocispec.Descriptor{
			// TODO: derive media type from compressed type
			MediaType: ocispec.MediaTypeImageLayer,
			Digest:    diffIDs[i],
		}
		layers[i].Blob = manifest.Layers[i]
	}

	return layers, nil
}
<commit_msg>cmd/dist: remove unnecessary path manipulation<commit_after>package main

import (
	"bufio"
	"context"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"net"
	"net/http"
	"strings"
	"time"

	"github.com/containerd/console"
	contentapi "github.com/containerd/containerd/api/services/content"
	imagesapi "github.com/containerd/containerd/api/services/images"
	"github.com/containerd/containerd/content"
	"github.com/containerd/containerd/images"
	"github.com/containerd/containerd/remotes"
	"github.com/containerd/containerd/remotes/docker"
	"github.com/containerd/containerd/rootfs"
	contentservice "github.com/containerd/containerd/services/content"
	imagesservice "github.com/containerd/containerd/services/images"
	ocispec "github.com/opencontainers/image-spec/specs-go/v1"
	"github.com/pkg/errors"
	"github.com/urfave/cli"
	"google.golang.org/grpc"
)

var registryFlags = []cli.Flag{
	cli.BoolFlag{
		Name:  "skip-verify,k",
		Usage: "Skip SSL certificate validation",
	},
	cli.BoolFlag{
		Name:  "plain-http",
		Usage: "Allow connections using plain HTTP",
	},
	cli.StringFlag{
		Name:  "user,u",
		Usage: "user[:password] Registry user and password",
	},
	cli.StringFlag{
		Name:  "refresh",
		Usage: "Refresh token for authorization server",
	},
}

func resolveContentStore(context *cli.Context) (content.Store, error) {
	conn, err := connectGRPC(context)
	if err != nil {
		return nil, err
	}

	return contentservice.NewStoreFromClient(contentapi.NewContentClient(conn)), nil
}

func resolveImageStore(clicontext *cli.Context) (images.Store, error) {
	conn, err := connectGRPC(clicontext)
	if err != nil {
		return nil, err
	}
	return imagesservice.NewStoreFromClient(imagesapi.NewImagesClient(conn)), nil
}

func connectGRPC(context *cli.Context) (*grpc.ClientConn, error) {
	address := context.GlobalString("address")
	timeout := context.GlobalDuration("connect-timeout")
	return grpc.Dial(address,
		grpc.WithTimeout(timeout),
		grpc.WithBlock(),
		grpc.WithInsecure(),
		grpc.WithDialer(func(addr string, timeout time.Duration) (net.Conn, error) {
			return net.DialTimeout("unix", address, timeout)
		}),
	)
}

// getResolver prepares the resolver from the environment and options.
func getResolver(ctx context.Context, clicontext *cli.Context) (remotes.Resolver, error) {
	username := clicontext.String("user")
	var secret string
	if i := strings.IndexByte(username, ':'); i > 0 {
		secret = username[i+1:]
		username = username[0:i]
	}
	options := docker.ResolverOptions{
		PlainHTTP: clicontext.Bool("plain-http"),
	}
	if username != "" {
		if secret == "" {
			fmt.Printf("Password: ")

			var err error
			secret, err = passwordPrompt()
			if err != nil {
				return nil, err
			}

			fmt.Print("\n")
		}
	} else if rt := clicontext.String("refresh"); rt != "" {
		secret = rt
	}

	options.Credentials = func(host string) (string, string, error) {
		// Only one host
		return username, secret, nil
	}

	tr := &http.Transport{
		Proxy: http.ProxyFromEnvironment,
		DialContext: (&net.Dialer{
			Timeout:   30 * time.Second,
			KeepAlive: 30 * time.Second,
			DualStack: true,
		}).DialContext,
		MaxIdleConns:        10,
		IdleConnTimeout:     30 * time.Second,
		TLSHandshakeTimeout: 10 * time.Second,
		TLSClientConfig: &tls.Config{
			InsecureSkipVerify: clicontext.Bool("insecure"),
		},
		ExpectContinueTimeout: 5 * time.Second,
	}

	options.Client = &http.Client{
		Transport: tr,
	}

	return docker.NewResolver(options), nil
}

func passwordPrompt() (string, error) {
	c := console.Current()
	defer c.Reset()

	if err := c.DisableEcho(); err != nil {
		return "", errors.Wrap(err, "failed to disable echo")
	}

	line, _, err := bufio.NewReader(c).ReadLine()
	if err != nil {
		return "", errors.Wrap(err, "failed to read line")
	}
	return string(line), nil
}

func getImageLayers(ctx context.Context, image images.Image, cs content.Store) ([]rootfs.Layer, error) {
	p, err := content.ReadBlob(ctx, cs, image.Target.Digest)
	if err != nil {
		return nil, errors.Wrapf(err, "failed to read manifest blob")
	}

	var manifest ocispec.Manifest
	if err := json.Unmarshal(p, &manifest); err != nil {
		return nil, errors.Wrap(err, "failed to unmarshal manifest")
	}

	diffIDs, err := image.RootFS(ctx, cs)
	if err != nil {
		return nil, errors.Wrap(err, "failed to resolve rootfs")
	}

	if len(diffIDs) != len(manifest.Layers) {
		return nil, errors.Errorf("mismatched image rootfs and manifest layers")
	}

	layers := make([]rootfs.Layer, len(diffIDs))
	for i := range diffIDs {
		layers[i].Diff = ocispec.Descriptor{
			// TODO: derive media type from compressed type
			MediaType: ocispec.MediaTypeImageLayer,
			Digest:    diffIDs[i],
		}
		layers[i].Blob = manifest.Layers[i]
	}

	return layers, nil
}
<|endoftext|>


<commit_before>/*
Copyright 2016 The Kubernetes Authors All rights reserved.

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 main

import (
	"errors"
	"fmt"

	"github.com/codegangsta/cli"
	"github.com/kubernetes/helm/pkg/client"
	"github.com/kubernetes/helm/pkg/format"
	"github.com/kubernetes/helm/pkg/kubectl"
)

// ErrAlreadyInstalled indicates that Helm Server is already installed.
var ErrAlreadyInstalled = errors.New("Already Installed")

func init() {
	addCommands(dmCmd())
}

func dmCmd() cli.Command {
	return cli.Command{
		Name:  "server",
		Usage: "Manage Helm server-side components",
		Description: `Server commands manage the in-cluster portion of Helm.

   Helm  has several components that run inside of Kubernetes. Before Helm can
   be used to install and manage packages, it must be installed into the
   Kubernetes cluster in which packages will be installed.

   The 'helm server' commands rely upon a properly configured 'kubectl' to
   communicate with the Kubernetes cluster. To verify that your 'kubectl'
   client is pointed to the correct cluster, use 'kubectl cluster-info'.

   Use 'helm server install' to install the in-cluster portion of Helm.
`,
		Subcommands: []cli.Command{
			{
				Name:      "install",
				Usage:     "Install Helm server components on Kubernetes.",
				ArgsUsage: "",
				Description: `Use kubectl to install Helm components in their own namespace on Kubernetes.

	Make sure your Kubernetes environment is pointed to the cluster on which you
	wish to install.`,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "dry-run",
						Usage: "Show what would be installed, but don't install anything.",
					},
					cli.StringFlag{
						Name:   "resourcifier-image",
						Usage:  "The full image name of the Docker image for resourcifier.",
						EnvVar: "HELM_RESOURCIFIER_IMAGE",
					},
					cli.StringFlag{
						Name:   "expandybird-image",
						Usage:  "The full image name of the Docker image for expandybird.",
						EnvVar: "HELM_EXPANDYBIRD_IMAGE",
					},
					cli.StringFlag{
						Name:   "manager-image",
						Usage:  "The full image name of the Docker image for manager.",
						EnvVar: "HELM_MANAGER_IMAGE",
					},
				},
				Action: func(c *cli.Context) { run(c, installServer) },
			},
			{
				Name:        "uninstall",
				Usage:       "Uninstall the Helm server-side from Kubernetes.",
				ArgsUsage:   "",
				Description: ``,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "dry-run",
						Usage: "Show what would be uninstalled, but don't remove anything.",
					},
				},
				Action: func(c *cli.Context) { run(c, uninstallServer) },
			},
			{
				Name:      "status",
				Usage:     "Show status of Helm server-side components.",
				ArgsUsage: "",
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "dry-run",
						Usage: "Only display the underlying kubectl commands.",
					},
				},
				Action: func(c *cli.Context) { run(c, statusServer) },
			},
			{
				Name:      "target",
				Usage:     "Displays information about the Kubernetes cluster.",
				ArgsUsage: "",
				Action:    func(c *cli.Context) { run(c, targetServer) },
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "dry-run",
						Usage: "Only display the underlying kubectl commands.",
					},
				},
			},
		},
	}
}

func installServer(c *cli.Context) error {
	resImg := c.String("resourcifier-image")
	ebImg := c.String("expandybird-image")
	manImg := c.String("manager-image")

	dryRun := c.Bool("dry-run")
	kubectlPath := c.GlobalString("kubectl")
	runner := buildKubectlRunner(kubectlPath, dryRun)

	i := client.NewInstaller()
	i.Manager["Image"] = manImg
	i.Resourcifier["Image"] = resImg
	i.Expandybird["Image"] = ebImg

	out, err := i.Install(runner)
	if err != nil {
		return fmt.Errorf("error installing %s %s", string(out), err)
	}
	format.Msg(out)
	return nil
}

func uninstallServer(c *cli.Context) error {
	dryRun := c.Bool("dry-run")
	kubectlPath := c.GlobalString("kubectl")
	runner := buildKubectlRunner(kubectlPath, dryRun)

	out, err := client.Uninstall(runner)
	if err != nil {
		return fmt.Errorf("error uninstalling: %s %s", out, err)
	}
	format.Msg(out)
	return nil
}

func statusServer(c *cli.Context) error {
	dryRun := c.Bool("dry-run")
	kubectlPath := c.GlobalString("kubectl")
	runner := buildKubectlRunner(kubectlPath, dryRun)

	out, err := runner.GetByKind("pods", "", "dm")
	if err != nil {
		return err
	}
	format.Msg(string(out))
	return nil
}

func targetServer(c *cli.Context) error {
	dryRun := c.Bool("dry-run")
	kubectlPath := c.GlobalString("kubectl")
	runner := buildKubectlRunner(kubectlPath, dryRun)

	out, err := runner.ClusterInfo()
	if err != nil {
		return fmt.Errorf("%s (%s)", out, err)
	}
	format.Msg(string(out))
	return nil
}

func buildKubectlRunner(kubectlPath string, dryRun bool) kubectl.Runner {
	if dryRun {
		return &kubectl.PrintRunner{}
	}
	// TODO: Refactor out kubectl.Path global
	if kubectlPath != "" {
		kubectl.Path = kubectlPath
	}
	return &kubectl.RealRunner{}
}
<commit_msg>fix namespace for helm server status<commit_after>/*
Copyright 2016 The Kubernetes Authors All rights reserved.

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 main

import (
	"errors"
	"fmt"

	"github.com/codegangsta/cli"
	"github.com/kubernetes/helm/pkg/client"
	"github.com/kubernetes/helm/pkg/format"
	"github.com/kubernetes/helm/pkg/kubectl"
)

// ErrAlreadyInstalled indicates that Helm Server is already installed.
var ErrAlreadyInstalled = errors.New("Already Installed")

func init() {
	addCommands(dmCmd())
}

func dmCmd() cli.Command {
	return cli.Command{
		Name:  "server",
		Usage: "Manage Helm server-side components",
		Description: `Server commands manage the in-cluster portion of Helm.

   Helm  has several components that run inside of Kubernetes. Before Helm can
   be used to install and manage packages, it must be installed into the
   Kubernetes cluster in which packages will be installed.

   The 'helm server' commands rely upon a properly configured 'kubectl' to
   communicate with the Kubernetes cluster. To verify that your 'kubectl'
   client is pointed to the correct cluster, use 'kubectl cluster-info'.

   Use 'helm server install' to install the in-cluster portion of Helm.
`,
		Subcommands: []cli.Command{
			{
				Name:      "install",
				Usage:     "Install Helm server components on Kubernetes.",
				ArgsUsage: "",
				Description: `Use kubectl to install Helm components in their own namespace on Kubernetes.

	Make sure your Kubernetes environment is pointed to the cluster on which you
	wish to install.`,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "dry-run",
						Usage: "Show what would be installed, but don't install anything.",
					},
					cli.StringFlag{
						Name:   "resourcifier-image",
						Usage:  "The full image name of the Docker image for resourcifier.",
						EnvVar: "HELM_RESOURCIFIER_IMAGE",
					},
					cli.StringFlag{
						Name:   "expandybird-image",
						Usage:  "The full image name of the Docker image for expandybird.",
						EnvVar: "HELM_EXPANDYBIRD_IMAGE",
					},
					cli.StringFlag{
						Name:   "manager-image",
						Usage:  "The full image name of the Docker image for manager.",
						EnvVar: "HELM_MANAGER_IMAGE",
					},
				},
				Action: func(c *cli.Context) { run(c, installServer) },
			},
			{
				Name:        "uninstall",
				Usage:       "Uninstall the Helm server-side from Kubernetes.",
				ArgsUsage:   "",
				Description: ``,
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "dry-run",
						Usage: "Show what would be uninstalled, but don't remove anything.",
					},
				},
				Action: func(c *cli.Context) { run(c, uninstallServer) },
			},
			{
				Name:      "status",
				Usage:     "Show status of Helm server-side components.",
				ArgsUsage: "",
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "dry-run",
						Usage: "Only display the underlying kubectl commands.",
					},
				},
				Action: func(c *cli.Context) { run(c, statusServer) },
			},
			{
				Name:      "target",
				Usage:     "Displays information about the Kubernetes cluster.",
				ArgsUsage: "",
				Action:    func(c *cli.Context) { run(c, targetServer) },
				Flags: []cli.Flag{
					cli.BoolFlag{
						Name:  "dry-run",
						Usage: "Only display the underlying kubectl commands.",
					},
				},
			},
		},
	}
}

func installServer(c *cli.Context) error {
	resImg := c.String("resourcifier-image")
	ebImg := c.String("expandybird-image")
	manImg := c.String("manager-image")

	dryRun := c.Bool("dry-run")
	kubectlPath := c.GlobalString("kubectl")
	runner := buildKubectlRunner(kubectlPath, dryRun)

	i := client.NewInstaller()
	i.Manager["Image"] = manImg
	i.Resourcifier["Image"] = resImg
	i.Expandybird["Image"] = ebImg

	out, err := i.Install(runner)
	if err != nil {
		return fmt.Errorf("error installing %s %s", string(out), err)
	}
	format.Msg(out)
	return nil
}

func uninstallServer(c *cli.Context) error {
	dryRun := c.Bool("dry-run")
	kubectlPath := c.GlobalString("kubectl")
	runner := buildKubectlRunner(kubectlPath, dryRun)

	out, err := client.Uninstall(runner)
	if err != nil {
		return fmt.Errorf("error uninstalling: %s %s", out, err)
	}
	format.Msg(out)
	return nil
}

func statusServer(c *cli.Context) error {
	dryRun := c.Bool("dry-run")
	kubectlPath := c.GlobalString("kubectl")
	runner := buildKubectlRunner(kubectlPath, dryRun)

	out, err := runner.GetByKind("pods", "", "helm")
	if err != nil {
		return err
	}
	format.Msg(string(out))
	return nil
}

func targetServer(c *cli.Context) error {
	dryRun := c.Bool("dry-run")
	kubectlPath := c.GlobalString("kubectl")
	runner := buildKubectlRunner(kubectlPath, dryRun)

	out, err := runner.ClusterInfo()
	if err != nil {
		return fmt.Errorf("%s (%s)", out, err)
	}
	format.Msg(string(out))
	return nil
}

func buildKubectlRunner(kubectlPath string, dryRun bool) kubectl.Runner {
	if dryRun {
		return &kubectl.PrintRunner{}
	}
	// TODO: Refactor out kubectl.Path global
	if kubectlPath != "" {
		kubectl.Path = kubectlPath
	}
	return &kubectl.RealRunner{}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"sort"

	"github.com/gonuts/commander"
	"github.com/kusabashira/lclip"
	"github.com/yuya-takeyama/argf"
)

var cmd_get = &commander.Command{
	UsageLine: "get LABEL",
	Short:     "get text from LABEL",
	Run: func(cmd *commander.Command, args []string) error {
		if len(args) < 1 {
			return fmt.Errorf("no specify LABEL")
		}
		label := args[0]

		path, err := lclip.DefaultPath()
		if err != nil {
			return err
		}
		c, err := lclip.NewClipboard(path)
		if err != nil {
			return err
		}

		dst := c.Get(label)
		if _, err = os.Stdout.Write(dst); err != nil {
			return err
		}
		if _, err = os.Stdout.Write([]byte("\n")); err != nil {
			return err
		}
		return c.Close()
	},
}

var cmd_set = &commander.Command{
	UsageLine: "set LABEL [FILE]...",
	Short:     "set text to LABEL",
	Run: func(cmd *commander.Command, args []string) error {
		if len(args) < 1 {
			return fmt.Errorf("no specify LABEL")
		}
		label := args[0]

		path, err := lclip.DefaultPath()
		if err != nil {
			return err
		}
		c, err := lclip.NewClipboard(path)
		if err != nil {
			return err
		}

		r, err := argf.From(args[1:])
		if err != nil {
			return err
		}
		src, err := ioutil.ReadAll(r)
		if err != nil {
			return err
		}

		c.Set(label, src)
		return c.Close()
	},
}

var cmd_labels = &commander.Command{
	UsageLine: "labels",
	Short:     "list labels",
	Run: func(cmd *commander.Command, args []string) error {
		path, err := lclip.DefaultPath()
		if err != nil {
			return err
		}
		c, err := lclip.NewClipboard(path)
		if err != nil {
			return err
		}

		labels := c.Labels()
		sort.Strings(labels)
		for _, label := range labels {
			fmt.Println(label)
		}
		return c.Close()
	},
}

var command = &commander.Command{
	UsageLine: "lclip",
	Short:     "cli interface for labeled clipboard",
	Subcommands: []*commander.Command{
		cmd_get,
		cmd_set,
		cmd_labels,
	},
}

func main() {
	if err := command.Dispatch(os.Args[1:]); err != nil {
		fmt.Fprintln(os.Stderr, "lclip:", err)
		os.Exit(1)
	}
}
<commit_msg>Fix too many new line<commit_after>package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"sort"

	"github.com/gonuts/commander"
	"github.com/kusabashira/lclip"
	"github.com/yuya-takeyama/argf"
)

var cmd_get = &commander.Command{
	UsageLine: "get LABEL",
	Short:     "get text from LABEL",
	Run: func(cmd *commander.Command, args []string) error {
		if len(args) < 1 {
			return fmt.Errorf("no specify LABEL")
		}
		label := args[0]

		path, err := lclip.DefaultPath()
		if err != nil {
			return err
		}
		c, err := lclip.NewClipboard(path)
		if err != nil {
			return err
		}

		dst := c.Get(label)
		if _, err = os.Stdout.Write(dst); err != nil {
			return err
		}
		return c.Close()
	},
}

var cmd_set = &commander.Command{
	UsageLine: "set LABEL [FILE]...",
	Short:     "set text to LABEL",
	Run: func(cmd *commander.Command, args []string) error {
		if len(args) < 1 {
			return fmt.Errorf("no specify LABEL")
		}
		label := args[0]

		path, err := lclip.DefaultPath()
		if err != nil {
			return err
		}
		c, err := lclip.NewClipboard(path)
		if err != nil {
			return err
		}

		r, err := argf.From(args[1:])
		if err != nil {
			return err
		}
		src, err := ioutil.ReadAll(r)
		if err != nil {
			return err
		}

		c.Set(label, src)
		return c.Close()
	},
}

var cmd_labels = &commander.Command{
	UsageLine: "labels",
	Short:     "list labels",
	Run: func(cmd *commander.Command, args []string) error {
		path, err := lclip.DefaultPath()
		if err != nil {
			return err
		}
		c, err := lclip.NewClipboard(path)
		if err != nil {
			return err
		}

		labels := c.Labels()
		sort.Strings(labels)
		for _, label := range labels {
			fmt.Println(label)
		}
		return c.Close()
	},
}

var command = &commander.Command{
	UsageLine: "lclip",
	Short:     "cli interface for labeled clipboard",
	Subcommands: []*commander.Command{
		cmd_get,
		cmd_set,
		cmd_labels,
	},
}

func main() {
	if err := command.Dispatch(os.Args[1:]); err != nil {
		fmt.Fprintln(os.Stderr, "lclip:", err)
		os.Exit(1)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"path/filepath"
	"time"
)

var year = fmt.Sprintf("%d", time.Now().Year())

var usageHeader = `
$ ponzu [flags] command <params>

Ponzu is a powerful and efficient open-source HTTP server framework and CMS. It
provides automatic, free, and secure HTTP/2 over TLS (certificates obtained via
[Let's Encrypt](https://letsencrypt.org)), a useful CMS and scaffolding to
generate set-up code, and a fast HTTP API on which to build modern applications.

Ponzu is released under the BSD-3-Clause license (see LICENSE).
(c) 2016 - ` + year + ` Boss Sauce Creative, LLC

COMMANDS:

`

var usageHelp = `
help, h (command)

	Help command will print the usage for Ponzu, or if a command is entered, it
	will show only the usage for that specific command.

	Example:
	$ ponzu help generate

`

var usageNew = `
new <directory>

	Creates a 'ponzu' directory, or one by the name supplied as a parameter
	immediately following the 'new' option in the $GOPATH/src directory. Note:
	'new' depends on the program 'git' and possibly a network connection. If
	there is no local repository to clone from at the local machine's $GOPATH,
	'new' will attempt to clone the 'github.com/ponzu-cms/ponzu' package from
	over the network.

	Example:
	$ ponzu new myProject
	> New ponzu project created at $GOPATH/src/myProject

	Errors will be reported, but successful commands retrun nothing.

`

var usageGenerate = `
generate, gen, g <generator type (,...fields)>

	Generate boilerplate code for various Ponzu components, such as 'content'.

	Example:
	$ ponzu gen content review title:"string" body:"string" rating:"int" tags:"[]string"

	The command above will generate a file 'content/review.go' with boilerplate
	methods, as well as struct definition, and corresponding field tags like:

	type Review struct {
		Title  string   ` + "`json:" + `"title"` + "`" + `
		Body   string   ` + "`json:" + `"body"` + "`" + `
		Rating int      ` + "`json:" + `"rating"` + "`" + `
		Tags   []string ` + "`json:" + `"tags"` + "`" + `
	}

	The generate command will intelligently parse more sophisticated field names
	such as 'field_name' and convert it to 'FieldName' and vice versa, only where
	appropriate as per common Go idioms. Errors will be reported, but successful
	generate commands retrun nothing.

`

var usageBuild = `
[-gocmd=go] build

	From within your Ponzu project directory, running build will copy and move
	the necessary files from your workspace into the vendored directory, and
	will build/compile the project to then be run.

	Example:
	$ ponzu build
	(or)
	$ ponzu -gocmd=go1.8rc1 build

	By providing the 'gocmd' flag, you can specify which Go command to build the
	project, if testing a different release of Go.

	Errors will be reported, but successful build commands return nothing.

`

var usageRun = `
[[-port=8080] [--https|--devhttps]] run <service(,service)>

	Starts the 'ponzu' HTTP server for the JSON API, Admin System, or both.
	The segments, separated by a comma, describe which services to start, either
	'admin' (Admin System / CMS backend) or 'api' (JSON API), and, optionally,
	if the server should utilize TLS encryption - served over HTTPS, which is
	automatically managed using Let's Encrypt (https://letsencrypt.org)

	Example:
	$ ponzu run
	(or)
	$ ponzu -port=8080 --https run admin,api
	(or)
	$ ponzu run admin
	(or)
	$ ponzu -port=8888 run api

	Defaults to '-port=8080 run admin,api' (running Admin & API on port 8080, without TLS)

	Note:
	Admin and API cannot run on separate processes unless you use a copy of the
	database, since the first process to open it receives a lock. If you intend
	to run the Admin and API on separate processes, you must call them with the
	'ponzu' command independently.

`

var usageUpgrade = `
upgrade

	Will backup your own custom project code (like content, addons, uploads, etc) so
	we can safely re-clone Ponzu from the latest version you have or from the network
	if necessary. Before running '$ ponzu upgrade', you should update the 'ponzu'
	package by running '$ go get -u github.com/ponzu-cms/ponzu/...'

	Example:
	$ ponzu upgrade

`

var usageVersion = `
[--cli] version, v

	Prints the version of Ponzu your project is using. Must be called from
	within a Ponzu project directory.

	Example:
	$ ponzu version
	> Ponzu v0.7.1
	(or)
	$ ponzu --cli version
	> Ponzu v0.7.2

`

var usageAdd = `
add, a <import path>

	Downloads addon from specified import path to $GOPATH/src and copys it to the
	current project's ./addons directory. Must be called from within a
	Ponzu project directory.

	Example:
	$ ponzu add github.com/bosssauce/fbscheduler

`

func ponzu(isCLI bool) (map[string]interface{}, error) {
	kv := make(map[string]interface{})

	info := filepath.Join("cmd", "ponzu", "ponzu.json")
	if isCLI {
		gopath, err := getGOPATH()
		if err != nil {
			return nil, err
		}
		repo := filepath.Join(gopath, "src", "github.com", "ponzu-cms", "ponzu")
		info = filepath.Join(repo, "cmd", "ponzu", "ponzu.json")
	}

	b, err := ioutil.ReadFile(info)
	if err != nil {
		return nil, err
	}

	err = json.Unmarshal(b, &kv)
	if err != nil {
		return nil, err
	}

	return kv, nil
}
<commit_msg>fix typo retrun should be return<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"path/filepath"
	"time"
)

var year = fmt.Sprintf("%d", time.Now().Year())

var usageHeader = `
$ ponzu [flags] command <params>

Ponzu is a powerful and efficient open-source HTTP server framework and CMS. It
provides automatic, free, and secure HTTP/2 over TLS (certificates obtained via
[Let's Encrypt](https://letsencrypt.org)), a useful CMS and scaffolding to
generate set-up code, and a fast HTTP API on which to build modern applications.

Ponzu is released under the BSD-3-Clause license (see LICENSE).
(c) 2016 - ` + year + ` Boss Sauce Creative, LLC

COMMANDS:

`

var usageHelp = `
help, h (command)

	Help command will print the usage for Ponzu, or if a command is entered, it
	will show only the usage for that specific command.

	Example:
	$ ponzu help generate

`

var usageNew = `
new <directory>

	Creates a 'ponzu' directory, or one by the name supplied as a parameter
	immediately following the 'new' option in the $GOPATH/src directory. Note:
	'new' depends on the program 'git' and possibly a network connection. If
	there is no local repository to clone from at the local machine's $GOPATH,
	'new' will attempt to clone the 'github.com/ponzu-cms/ponzu' package from
	over the network.

	Example:
	$ ponzu new myProject
	> New ponzu project created at $GOPATH/src/myProject

	Errors will be reported, but successful commands return nothing.

`

var usageGenerate = `
generate, gen, g <generator type (,...fields)>

	Generate boilerplate code for various Ponzu components, such as 'content'.

	Example:
	$ ponzu gen content review title:"string" body:"string" rating:"int" tags:"[]string"

	The command above will generate a file 'content/review.go' with boilerplate
	methods, as well as struct definition, and corresponding field tags like:

	type Review struct {
		Title  string   ` + "`json:" + `"title"` + "`" + `
		Body   string   ` + "`json:" + `"body"` + "`" + `
		Rating int      ` + "`json:" + `"rating"` + "`" + `
		Tags   []string ` + "`json:" + `"tags"` + "`" + `
	}

	The generate command will intelligently parse more sophisticated field names
	such as 'field_name' and convert it to 'FieldName' and vice versa, only where
	appropriate as per common Go idioms. Errors will be reported, but successful
	generate commands return nothing.

`

var usageBuild = `
[-gocmd=go] build

	From within your Ponzu project directory, running build will copy and move
	the necessary files from your workspace into the vendored directory, and
	will build/compile the project to then be run.

	Example:
	$ ponzu build
	(or)
	$ ponzu -gocmd=go1.8rc1 build

	By providing the 'gocmd' flag, you can specify which Go command to build the
	project, if testing a different release of Go.

	Errors will be reported, but successful build commands return nothing.

`

var usageRun = `
[[-port=8080] [--https|--devhttps]] run <service(,service)>

	Starts the 'ponzu' HTTP server for the JSON API, Admin System, or both.
	The segments, separated by a comma, describe which services to start, either
	'admin' (Admin System / CMS backend) or 'api' (JSON API), and, optionally,
	if the server should utilize TLS encryption - served over HTTPS, which is
	automatically managed using Let's Encrypt (https://letsencrypt.org)

	Example:
	$ ponzu run
	(or)
	$ ponzu -port=8080 --https run admin,api
	(or)
	$ ponzu run admin
	(or)
	$ ponzu -port=8888 run api

	Defaults to '-port=8080 run admin,api' (running Admin & API on port 8080, without TLS)

	Note:
	Admin and API cannot run on separate processes unless you use a copy of the
	database, since the first process to open it receives a lock. If you intend
	to run the Admin and API on separate processes, you must call them with the
	'ponzu' command independently.

`

var usageUpgrade = `
upgrade

	Will backup your own custom project code (like content, addons, uploads, etc) so
	we can safely re-clone Ponzu from the latest version you have or from the network
	if necessary. Before running '$ ponzu upgrade', you should update the 'ponzu'
	package by running '$ go get -u github.com/ponzu-cms/ponzu/...'

	Example:
	$ ponzu upgrade

`

var usageVersion = `
[--cli] version, v

	Prints the version of Ponzu your project is using. Must be called from
	within a Ponzu project directory.

	Example:
	$ ponzu version
	> Ponzu v0.7.1
	(or)
	$ ponzu --cli version
	> Ponzu v0.7.2

`

var usageAdd = `
add, a <import path>

	Downloads addon from specified import path to $GOPATH/src and copys it to the
	current project's ./addons directory. Must be called from within a
	Ponzu project directory.

	Example:
	$ ponzu add github.com/bosssauce/fbscheduler

`

func ponzu(isCLI bool) (map[string]interface{}, error) {
	kv := make(map[string]interface{})

	info := filepath.Join("cmd", "ponzu", "ponzu.json")
	if isCLI {
		gopath, err := getGOPATH()
		if err != nil {
			return nil, err
		}
		repo := filepath.Join(gopath, "src", "github.com", "ponzu-cms", "ponzu")
		info = filepath.Join(repo, "cmd", "ponzu", "ponzu.json")
	}

	b, err := ioutil.ReadFile(info)
	if err != nil {
		return nil, err
	}

	err = json.Unmarshal(b, &kv)
	if err != nil {
		return nil, err
	}

	return kv, nil
}
<|endoftext|>


<commit_before>// Copyright (C) 2014 Constantin Schomburg <me@cschomburg.com>
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.

package main

import (
	"flag"

	"github.com/xconstruct/stark/core"
	"github.com/xconstruct/stark/log"

	_ "github.com/xconstruct/stark/services/hostscan"
	_ "github.com/xconstruct/stark/services/location"
	_ "github.com/xconstruct/stark/services/router"
	_ "github.com/xconstruct/stark/web"
	_ "github.com/xconstruct/stark/xmpp"
)

var verbose = flag.Bool("v", false, "verbose debug output")

type Config struct {
	EnabledModules []string
}

func main() {
	flag.Parse()

	app, err := core.NewApp("stark")
	app.Must(err)
	defer app.Close()

	if *verbose {
		app.Log.SetLevel(log.LevelDebug)
	}

	cfg := Config{
		EnabledModules: []string{"web"},
	}
	app.Must(app.Config.Get("server", &cfg))

	for _, module := range cfg.EnabledModules {
		app.Must(app.EnableModule(module))
	}

	app.WaitUntilInterrupt()
}
<commit_msg>server: also build with mysql support<commit_after>// Copyright (C) 2014 Constantin Schomburg <me@cschomburg.com>
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.

package main

import (
	"flag"

	"github.com/xconstruct/stark/core"
	"github.com/xconstruct/stark/log"

	_ "github.com/go-sql-driver/mysql"

	_ "github.com/xconstruct/stark/services/hostscan"
	_ "github.com/xconstruct/stark/services/location"
	_ "github.com/xconstruct/stark/services/router"
	_ "github.com/xconstruct/stark/web"
	_ "github.com/xconstruct/stark/xmpp"
)

var verbose = flag.Bool("v", false, "verbose debug output")

type Config struct {
	EnabledModules []string
}

func main() {
	flag.Parse()

	app, err := core.NewApp("stark")
	app.Must(err)
	defer app.Close()

	if *verbose {
		app.Log.SetLevel(log.LevelDebug)
	}

	cfg := Config{
		EnabledModules: []string{"web"},
	}
	app.Must(app.Config.Get("server", &cfg))

	for _, module := range cfg.EnabledModules {
		app.Must(app.EnableModule(module))
	}

	app.WaitUntilInterrupt()
}
<|endoftext|>