<commit_before>// Package ciolite ...
package ciolite

// Imports
import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/garyburd/go-oauth/oauth"
	"net/http"
	"time"
)

// clientRequest ...
// Defines information that can be used to make a request to Medium.
type clientRequest struct {
	method      string
	path        string
	formValues  CioParams
	queryValues CioParams
	format      string
}

const (
	// The default host of Medium's API
	host = "https://api.context.io/lite"

	// The default timeout duration used on HTTP requests
	defaultTimeout = 10 * time.Second
)

// doFormRequest ...
// Makes the actual request
func (cioLite *CioLite) doFormRequest(request clientRequest, result interface{}) error {

	// Construct the url
	url := host + request.path + request.queryValues.QueryString()

	// Construct the body
	var bodyReader *bytes.Reader
	if request.formValues.FormValues() != nil {
		bodyBytes := []byte(request.formValues.FormValues().Encode())
		bodyReader = bytes.NewReader(bodyBytes)
	} else {
		bodyReader = bytes.NewReader(make([]byte, 0, 0))
	}

	// Construct the request
	httpReq, err := http.NewRequest(request.method, url, bodyReader)
	if err != nil {
		return fmt.Errorf("Could not create request: %s", err)
	}

	// oAuth signature
	var client oauth.Client
	client.Credentials = oauth.Credentials{cioLite.apiKey, cioLite.apiSecret}

	// Add headers
	httpReq.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	httpReq.Header.Add("Accept", "application/json")
	httpReq.Header.Add("Accept-Charset", "utf-8")
	httpReq.Header.Add("Authorization", client.AuthorizationHeader(nil, request.method, httpReq.URL, request.formValues.FormValues()))

	// Create the HTTP client
	httpClient := &http.Client{
		Transport: http.DefaultTransport,
		Timeout:   defaultTimeout,
	}

	// Make the request
	res, err := httpClient.Do(httpReq)
	if err != nil {
		return fmt.Errorf("Failed to make request: %s", err)
	}

	// Determine status
	if res.StatusCode != http.StatusOK {
		return fmt.Errorf("Invalid status code: %d", res.StatusCode)
	}

	// Parse the response
	defer res.Body.Close()
	return json.NewDecoder(res.Body).Decode(&result)
}
<commit_msg>reverting per comments<commit_after>// Package ciolite ...
package ciolite

// Imports
import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/garyburd/go-oauth/oauth"
	"net/http"
	"time"
)

// clientRequest ...
// Defines information that can be used to make a request to Medium.
type clientRequest struct {
	method      string
	path        string
	formValues  CioParams
	queryValues CioParams
	format      string
}

const (
	// The default host of Medium's API
	host = "https://api.context.io/lite"

	// The default timeout duration used on HTTP requests
	defaultTimeout = 10 * time.Second
)

// doFormRequest ...
// Makes the actual request
func (cioLite *CioLite) doFormRequest(request clientRequest, result interface{}) error {

	// Construct the url
	url := host + request.path + request.queryValues.QueryString()

	// Construct the body
	var bodyReader *bytes.Reader
	if request.formValues.FormValues() != nil {
		bodyBytes := []byte(request.formValues.FormValues().Encode())
		bodyReader = bytes.NewReader(bodyBytes)
	} else {
		bodyReader = bytes.NewReader(make([]byte, 0, 0))
	}

	// Construct the request
	httpReq, err := http.NewRequest(request.method, url, bodyReader)
	if err != nil {
		return fmt.Errorf("Could not create request: %s", err)
	}

	// oAuth signature
	var client oauth.Client
	client.Credentials = oauth.Credentials{cioLite.apiKey, cioLite.apiSecret}

	// Add headers
	httpReq.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	httpReq.Header.Add("Accept", "application/json")
	httpReq.Header.Add("Accept-Charset", "utf-8")
	httpReq.Header.Add("Authorization", client.AuthorizationHeader(nil, request.method, httpReq.URL, request.formValues.FormValues()))

	// Create the HTTP client
	httpClient := &http.Client{
		Transport: http.DefaultTransport,
		Timeout:   defaultTimeout,
	}

	// Make the request
	res, err := httpClient.Do(httpReq)
	if err != nil {
		return fmt.Errorf("Failed to make request: %s", err)
	}

	// Determine status
	if res.StatusCode != http.StatusOK {
		return fmt.Errorf("Invalid status code: %d", res.StatusCode)
	}

	// Parse the response
	defer res.Body.Close()
	resBody, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return fmt.Errorf("Could not read response: %s", err)
	}

	// Unmarshal result
	return json.Unmarshal(resBody, &result)
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"os"
	"strings"

	"github.com/peterh/liner"
)

// Resolve asks the user to resolve the identifiers
func Resolve(identifiers []*Identifier, config *Config, in *bufio.Reader, out *bufio.Writer) map[string]map[string]string {
	line := liner.NewLiner()
	defer line.Close()
	line.SetCtrlCAborts(true)
	values := make(map[string]map[string]string)

	scopeAsked := make(map[string]bool)
	if in == nil {
		for _, id := range identifiers {
			if !found(values, id) && id.scope != "" && !scopeAsked[id.scope] {
				scopeAsked[id.scope] = true
				var keys []string
				added := make(map[string]bool)
				for _, d := range identifiers {
					if id.scope == d.scope && !added[d.key] {
						keys = append(keys, d.key)
						added[d.key] = true
					}
				}
				if len(keys) > 0 {
					hs := config.historyPairs(&IdentifierGroup{scope: id.scope, keys: keys})
					if len(hs) == 0 {
						continue
					}
					line.ClearHistory()
					for i := len(hs) - 1; i >= 0; i-- {
						line.AppendHistory(hs[i])
					}
					prompt := fmt.Sprintf("[%s] %s: ", id.scope, strings.Join(keys, ", "))
					text, err := line.Prompt(prompt)
					if err != nil {
						if err == liner.ErrPromptAborted || err == io.EOF {
							os.Exit(1)
						}
						log.Fatal(err)
					}
					xs := strings.Split(strings.TrimSuffix(text, "\n"), ", ")
					if len(xs) == len(keys) {
						for i, key := range keys {
							id := &Identifier{scope: id.scope, key: key}
							insert(values, id, strings.Replace(xs[i], ",\\ ", ", ", -1))
						}
					}
				}
			}
		}
	}

	for _, id := range identifiers {
		if !found(values, id) {
			prompt := fmt.Sprintf("%s: ", id.key)
			if id.scope != "" {
				prompt = fmt.Sprintf("[%s] %s: ", id.scope, id.key)
			}
			var text string
			var err error
			if in == nil {
				line.ClearHistory()
				hs := config.history(id)
				for i := len(hs) - 1; i >= 0; i-- {
					line.AppendHistory(hs[i])
				}
				text, err = line.Prompt(prompt)
				if err != nil {
					if err == liner.ErrPromptAborted || err == io.EOF {
						os.Exit(1)
					}
					log.Fatal(err)
				}
			} else {
				out.WriteString(prompt)
				out.Flush()
				text, err = in.ReadString('\n')
				if err != nil {
					log.Fatal(err)
				}
			}
			insert(values, id, strings.TrimSuffix(text, "\n"))
		}
	}

	return values
}
<commit_msg>quick continue to reduce indent depth<commit_after>package main

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"os"
	"strings"

	"github.com/peterh/liner"
)

// Resolve asks the user to resolve the identifiers
func Resolve(identifiers []*Identifier, config *Config, in *bufio.Reader, out *bufio.Writer) map[string]map[string]string {
	line := liner.NewLiner()
	defer line.Close()
	line.SetCtrlCAborts(true)
	values := make(map[string]map[string]string)

	scopeAsked := make(map[string]bool)
	if in == nil {
		for _, id := range identifiers {
			if found(values, id) || id.scope == "" || scopeAsked[id.scope] {
				continue
			}
			scopeAsked[id.scope] = true
			var keys []string
			added := make(map[string]bool)
			for _, d := range identifiers {
				if id.scope == d.scope && !added[d.key] {
					keys = append(keys, d.key)
					added[d.key] = true
				}
			}
			if len(keys) == 0 {
				continue
			}
			hs := config.historyPairs(&IdentifierGroup{scope: id.scope, keys: keys})
			if len(hs) == 0 {
				continue
			}
			line.ClearHistory()
			for i := len(hs) - 1; i >= 0; i-- {
				line.AppendHistory(hs[i])
			}
			prompt := fmt.Sprintf("[%s] %s: ", id.scope, strings.Join(keys, ", "))
			text, err := line.Prompt(prompt)
			if err != nil {
				if err == liner.ErrPromptAborted || err == io.EOF {
					os.Exit(1)
				}
				log.Fatal(err)
			}
			xs := strings.Split(strings.TrimSuffix(text, "\n"), ", ")
			if len(xs) == len(keys) {
				for i, key := range keys {
					id := &Identifier{scope: id.scope, key: key}
					insert(values, id, strings.Replace(xs[i], ",\\ ", ", ", -1))
				}
			}
		}
	}

	for _, id := range identifiers {
		if found(values, id) {
			continue
		}
		prompt := fmt.Sprintf("%s: ", id.key)
		if id.scope != "" {
			prompt = fmt.Sprintf("[%s] %s: ", id.scope, id.key)
		}
		var text string
		var err error
		if in == nil {
			line.ClearHistory()
			hs := config.history(id)
			for i := len(hs) - 1; i >= 0; i-- {
				line.AppendHistory(hs[i])
			}
			text, err = line.Prompt(prompt)
			if err != nil {
				if err == liner.ErrPromptAborted || err == io.EOF {
					os.Exit(1)
				}
				log.Fatal(err)
			}
		} else {
			out.WriteString(prompt)
			out.Flush()
			text, err = in.ReadString('\n')
			if err != nil {
				log.Fatal(err)
			}
		}
		insert(values, id, strings.TrimSuffix(text, "\n"))
	}

	return values
}
<|endoftext|>


<commit_before>package horizon

import (
	"github.com/jagregory/halgo"
	"github.com/stellar/go-horizon/render/hal"
	"net/http"
)

type RootResource struct {
	halgo.Links
}

var globalRootResource RootResource

func init() {
	links := halgo.Links{}.
		Self("/").
		Link("account", "/accounts/{address}").
		Link("account_transactions", "/accounts/{address}/transactions{?cursor,limit,order}").
		Link("transaction", "/transactions/{hash}").
		Link("transactions", "/transactions{?cursor,limit,order}").
		Link("metrics", "/metrics").
		Link("friendbot", "/friendbot{?addr}")

	globalRootResource = RootResource{
		Links: links,
	}
}

func rootAction(w http.ResponseWriter, r *http.Request) {
	hal.Render(w, globalRootResource)
}
<commit_msg>Delist and simplify rootAction<commit_after>package horizon

import (
	"net/http"

	"github.com/jagregory/halgo"
	"github.com/stellar/go-horizon/render/hal"
)

// RootResource is the initial map of links into the api.
type RootResource struct {
	halgo.Links
}

var globalRootResource = RootResource{
	Links: halgo.Links{}.
		Self("/").
		Link("account", "/accounts/{address}").
		Link("account_transactions", "/accounts/{address}/transactions{?cursor,limit,order}").
		Link("transaction", "/transactions/{hash}").
		Link("transactions", "/transactions{?cursor,limit,order}").
		Link("metrics", "/metrics").
		Link("friendbot", "/friendbot{?addr}"),
}

func rootAction(w http.ResponseWriter, r *http.Request) {
	hal.Render(w, globalRootResource)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"strconv"

	"github.com/frenata/gaga/decktet"
)

func oneGame() int {
	player := decktet.NewAdamanPlayer()

	player.Shuffle(-1)

	score := player.Play()
	return score
}

func runStats(runs int) {
	stats := make(map[string]int)
	var total, highscore int

	for i := 0; i < runs; i++ {
		score := oneGame()
		total += score
		switch {
		case score == 0:
			stats["total loss"]++
		case score < 70:
			stats["loss"]++
		case score >= 70:
			stats["win"]++
		default:
			stats["error"]++
		}
		if score > highscore {
			highscore = score
		}
	}
	average := total / runs
	winPer := float64(stats["win"]) / float64(runs) * 100
	lossPer := float64(stats["loss"]) / float64(runs) * 100
	totalLossPer := float64(stats["total loss"]) / float64(runs) * 100

	fmt.Println("Average:", average)
	fmt.Println("Win% :", winPer)
	fmt.Println("Loss% :", lossPer)
	fmt.Println("Total Loss% :", totalLossPer)
	fmt.Println("High Score:", highscore)
	fmt.Println(stats)
}

func main() {
	var runs int = 1

	if len(os.Args) > 1 {
		runs, _ = strconv.Atoi(os.Args[1])
	}

	runStats(runs)
}
<commit_msg>added a bunch of documentation<commit_after>// Adaman AI Game, run x of games and run stats.
package main

import (
	"fmt"
	"os"
	"strconv"

	"github.com/frenata/gaga/decktet"
)

func oneGame() int {
	player := decktet.NewAdamanPlayer()

	player.Shuffle(-1)

	score := player.Play()
	return score
}

func runStats(runs int) {
	stats := make(map[string]int)
	var total, highscore int

	for i := 0; i < runs; i++ {
		score := oneGame()
		total += score
		switch {
		case score == 0:
			stats["total loss"]++
		case score < 70:
			stats["loss"]++
		case score >= 70:
			stats["win"]++
		default:
			stats["error"]++
		}
		if score > highscore {
			highscore = score
		}
	}
	average := total / runs
	winPer := float64(stats["win"]) / float64(runs) * 100
	lossPer := float64(stats["loss"]) / float64(runs) * 100
	totalLossPer := float64(stats["total loss"]) / float64(runs) * 100

	fmt.Println("Average:", average)
	fmt.Println("Win% :", winPer)
	fmt.Println("Loss% :", lossPer)
	fmt.Println("Total Loss% :", totalLossPer)
	fmt.Println("High Score:", highscore)
	fmt.Println(stats)
}

func main() {
	var runs int = 1

	if len(os.Args) > 1 {
		runs, _ = strconv.Atoi(os.Args[1])
	}

	runStats(runs)
}
<|endoftext|>


<commit_before>// Adaman AI Game, run x of games and run stats.
package main

import (
	"fmt"
	"os"
	"strconv"

	//"github.com/frenata/decktet"
)

func oneGame(player *AdamanPlayer) int {
	player.Shuffle(1)
	score := player.Play()

	//fmt.Println(player)
	//fmt.Println(player.discard)
	//fmt.Println(len(player.Cards()))
	player.cleanup()
	//fmt.Printf("cards: %s\ndiscards: %s\n", player.Cards(), player.Discards())
	player.Shuffle(1)
	//fmt.Printf("cards: %s\ndiscards: %s\n", player.Cards(), player.Discards())
	//fmt.Println(len(player.Cards()))
	return score
}

func runStats(player *AdamanPlayer, runs int) {
	stats := make(map[string]int)
	var total, highscore int

	for i := 0; i < runs; i++ {
		score := oneGame(player)
		total += score
		switch {
		case score == 0:
			stats["total loss"]++
		case score < 70:
			stats["loss"]++
		case score >= 70:
			stats["win"]++
		default:
			stats["error"]++
		}
		if score > highscore {
			highscore = score
		}
	}
	average := total / runs
	winPer := float64(stats["win"]) / float64(runs) * 100
	lossPer := float64(stats["loss"]) / float64(runs) * 100
	totalLossPer := float64(stats["total loss"]) / float64(runs) * 100

	fmt.Println("Average:", average)
	fmt.Println("Win% :", winPer)
	fmt.Println("Loss% :", lossPer)
	fmt.Println("Total Loss% :", totalLossPer)
	fmt.Println("High Score:", highscore)
	fmt.Println(stats)
}

func main() {
	var runs int = 1

	if len(os.Args) > 1 {
		runs, _ = strconv.Atoi(os.Args[1])
	}

	player := NewAdamanPlayer()
	runStats(player, runs)
}
<commit_msg>replaced random seed<commit_after>// Adaman AI Game, run x of games and run stats.
package main

import (
	"fmt"
	"os"
	"strconv"

	//"github.com/frenata/decktet"
)

func oneGame(player *AdamanPlayer) int {
	player.Shuffle(-1)
	score := player.Play()

	//fmt.Println(player)
	//fmt.Println(player.discard)
	//fmt.Println(len(player.Cards()))
	player.cleanup()
	//fmt.Printf("cards: %s\ndiscards: %s\n", player.Cards(), player.Discards())
	player.Shuffle(-1)
	//fmt.Printf("cards: %s\ndiscards: %s\n", player.Cards(), player.Discards())
	//fmt.Println(len(player.Cards()))
	return score
}

func runStats(player *AdamanPlayer, runs int) {
	stats := make(map[string]int)
	var total, highscore int

	for i := 0; i < runs; i++ {
		score := oneGame(player)
		total += score
		switch {
		case score == 0:
			stats["total loss"]++
		case score < 70:
			stats["loss"]++
		case score >= 70:
			stats["win"]++
		default:
			stats["error"]++
		}
		if score > highscore {
			highscore = score
		}
	}
	average := total / runs
	winPer := float64(stats["win"]) / float64(runs) * 100
	lossPer := float64(stats["loss"]) / float64(runs) * 100
	totalLossPer := float64(stats["total loss"]) / float64(runs) * 100

	fmt.Println("Average:", average)
	fmt.Println("Win% :", winPer)
	fmt.Println("Loss% :", lossPer)
	fmt.Println("Total Loss% :", totalLossPer)
	fmt.Println("High Score:", highscore)
	fmt.Println(stats)
}

func main() {
	var runs int = 1

	if len(os.Args) > 1 {
		runs, _ = strconv.Atoi(os.Args[1])
	}

	player := NewAdamanPlayer()
	runStats(player, runs)
}
<|endoftext|>


<commit_before>/*
Copyright 2018 The Kubernetes Authors.

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

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

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

package windows

import (
	"fmt"

	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/uuid"
	"k8s.io/kubernetes/test/e2e/framework"
	e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper"
	imageutils "k8s.io/kubernetes/test/utils/image"

	"github.com/onsi/ginkgo"
	"github.com/onsi/gomega"
)

const (
	linuxOS   = "linux"
	windowsOS = "windows"
)

var (
	windowsBusyBoximage = imageutils.GetE2EImage(imageutils.Agnhost)
	linuxBusyBoxImage   = "docker.io/library/nginx:1.15-alpine"
)

var _ = SIGDescribe("Hybrid cluster network", func() {
	f := framework.NewDefaultFramework("hybrid-network")

	ginkgo.BeforeEach(func() {
		e2eskipper.SkipUnlessNodeOSDistroIs("windows")
	})

	ginkgo.Context("for all supported CNIs", func() {

		ginkgo.It("should have stable networking for Linux and Windows pods", func() {
			ginkgo.By("creating linux and windows pods")
			linuxPod := createTestPod(f, linuxBusyBoxImage, linuxOS)
			linuxPod = f.PodClient().CreateSync(linuxPod)
			windowsPod := createTestPod(f, windowsBusyBoximage, windowsOS)
			windowsPod.Spec.Containers[0].Args = []string{"test-webserver"}
			windowsPod = f.PodClient().CreateSync(windowsPod)

			ginkgo.By("checking connectivity to 8.8.8.8 53 (google.com) from Linux")
			assertConsistentConnectivity(f, linuxPod.ObjectMeta.Name, linuxOS, linuxCheck("8.8.8.8", 53))

			ginkgo.By("checking connectivity to www.google.com from Windows")
			assertConsistentConnectivity(f, windowsPod.ObjectMeta.Name, windowsOS, windowsCheck("www.google.com"))

			ginkgo.By("checking connectivity from Linux to Windows")
			assertConsistentConnectivity(f, linuxPod.ObjectMeta.Name, linuxOS, linuxCheck(windowsPod.Status.PodIP, 80))

			ginkgo.By("checking connectivity from Windows to Linux")
			assertConsistentConnectivity(f, windowsPod.ObjectMeta.Name, windowsOS, windowsCheck(linuxPod.Status.PodIP))

		})

	})
})

var (
	duration     = "10s"
	pollInterval = "1s"
	timeout      = 10 // seconds
)

func assertConsistentConnectivity(f *framework.Framework, podName string, os string, cmd []string) {
	gomega.Consistently(func() error {
		ginkgo.By(fmt.Sprintf("checking connectivity of %s-container in %s", os, podName))
		_, _, err := f.ExecCommandInContainerWithFullOutput(podName, os+"-container", cmd...)
		return err
	}, duration, pollInterval).ShouldNot(gomega.HaveOccurred())
}

func linuxCheck(address string, port int) []string {
	nc := fmt.Sprintf("nc -vz %s %v -w %v", address, port, timeout)
	cmd := []string{"/bin/sh", "-c", nc}
	return cmd
}

func windowsCheck(address string) []string {
	curl := fmt.Sprintf("curl.exe %s --connect-timeout %v --fail", address, timeout)
	cmd := []string{"cmd", "/c", curl}
	return cmd
}

func createTestPod(f *framework.Framework, image string, os string) *v1.Pod {
	containerName := fmt.Sprintf("%s-container", os)
	podName := "pod-" + string(uuid.NewUUID())
	pod := &v1.Pod{
		TypeMeta: metav1.TypeMeta{
			Kind:       "Pod",
			APIVersion: "v1",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name: podName,
		},
		Spec: v1.PodSpec{
			Containers: []v1.Container{
				{
					Name:  containerName,
					Image: image,
					Ports: []v1.ContainerPort{{ContainerPort: 80}},
				},
			},
			NodeSelector: map[string]string{
				"kubernetes.io/os": os,
			},
		},
	}
	if os == linuxOS {
		pod.Spec.Tolerations = []v1.Toleration{
			{
				Operator: v1.TolerationOpExists,
				Effect:   v1.TaintEffectNoSchedule,
			},
		}
	}
	return pod
}
<commit_msg>Update hybrid_network.go<commit_after>/*
Copyright 2018 The Kubernetes Authors.

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

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

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

package windows

import (
	"fmt"

	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/uuid"
	"k8s.io/kubernetes/test/e2e/framework"
	e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper"
	imageutils "k8s.io/kubernetes/test/utils/image"

	"github.com/onsi/ginkgo"
	"github.com/onsi/gomega"
)

const (
	linuxOS   = "linux"
	windowsOS = "windows"
)

var (
	windowsBusyBoximage = imageutils.GetE2EImage(imageutils.Agnhost)
	linuxBusyBoxImage   = "docker.io/library/nginx:1.15-alpine"
)

var _ = SIGDescribe("Hybrid cluster network", func() {
	f := framework.NewDefaultFramework("hybrid-network")

	ginkgo.BeforeEach(func() {
		e2eskipper.SkipUnlessNodeOSDistroIs("windows")
	})

	ginkgo.Context("for all supported CNIs", func() {

		ginkgo.It("should have stable networking for Linux and Windows pods", func() {

			linuxPod := createTestPod(f, linuxBusyBoxImage, linuxOS)
			ginkgo.By("creating a linux pod and waiting for it to be running")
			linuxPod = f.PodClient().CreateSync(linuxPod)

			windowsPod := createTestPod(f, windowsBusyBoximage, windowsOS)

			windowsPod.Spec.Containers[0].Args = []string{"test-webserver"}
			ginkgo.By("creating a windows pod and waiting for it to be running")
			windowsPod = f.PodClient().CreateSync(windowsPod)

			ginkgo.By("verifying pod external connectivity to the internet")

			ginkgo.By("checking connectivity to 8.8.8.8 53 (google.com) from Linux")
			assertConsistentConnectivity(f, linuxPod.ObjectMeta.Name, linuxOS, linuxCheck("8.8.8.8", 53))

			ginkgo.By("checking connectivity to www.google.com from Windows")
			assertConsistentConnectivity(f, windowsPod.ObjectMeta.Name, windowsOS, windowsCheck("www.google.com"))

			ginkgo.By("verifying pod internal connectivity to the cluster dataplane")

			ginkgo.By("checking connectivity from Linux to Windows")
			assertConsistentConnectivity(f, linuxPod.ObjectMeta.Name, linuxOS, linuxCheck(windowsPod.Status.PodIP, 80))

			ginkgo.By("checking connectivity from Windows to Linux")
			assertConsistentConnectivity(f, windowsPod.ObjectMeta.Name, windowsOS, windowsCheck(linuxPod.Status.PodIP))

		})

	})
})

var (
	duration       = "10s"
	pollInterval   = "1s"
	timeoutSeconds = 10
)

func assertConsistentConnectivity(f *framework.Framework, podName string, os string, cmd []string) {
	gomega.Consistently(func() error {
		ginkgo.By(fmt.Sprintf("checking connectivity of %s-container in %s", os, podName))
		// TODO, we should be retrying this similar to what is done in DialFromNode, in the test/e2e/networking/networking.go tests
		_, _, err := f.ExecCommandInContainerWithFullOutput(podName, os+"-container", cmd...)
		return err
	}, duration, pollInterval).ShouldNot(gomega.HaveOccurred())
}

func linuxCheck(address string, port int) []string {
	nc := fmt.Sprintf("nc -vz %s %v -w %v", address, port, timeoutSeconds)
	cmd := []string{"/bin/sh", "-c", nc}
	return cmd
}

func windowsCheck(address string) []string {
	curl := fmt.Sprintf("curl.exe %s --connect-timeout %v --fail", address, timeoutSeconds)
	cmd := []string{"cmd", "/c", curl}
	return cmd
}

func createTestPod(f *framework.Framework, image string, os string) *v1.Pod {
	containerName := fmt.Sprintf("%s-container", os)
	podName := "pod-" + string(uuid.NewUUID())
	pod := &v1.Pod{
		TypeMeta: metav1.TypeMeta{
			Kind:       "Pod",
			APIVersion: "v1",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name: podName,
		},
		Spec: v1.PodSpec{
			Containers: []v1.Container{
				{
					Name:  containerName,
					Image: image,
					Ports: []v1.ContainerPort{{ContainerPort: 80}},
				},
			},
			NodeSelector: map[string]string{
				"kubernetes.io/os": os,
			},
		},
	}
	if os == linuxOS {
		pod.Spec.Tolerations = []v1.Toleration{
			{
				Operator: v1.TolerationOpExists,
				Effect:   v1.TaintEffectNoSchedule,
			},
		}
	}
	return pod
}
<|endoftext|>


<commit_before>package main

import (
	. "github.com/minio-io/check"
	"log"
	"testing"
)

type MySuite struct{}

func Test(t *testing.T) { TestingT(t) }

var _ = Suite(&MySuite{})

func (s *MySuite) TestIsvalidAliasName(c *C) {
	c.Check(isValidAliasName("helloWorld0"), Equals, true)
	c.Check(isValidAliasName("h0SFD2k24Fdsa"), Equals, true)
	c.Check(isValidAliasName("fdslka-4"), Equals, true)
	c.Check(isValidAliasName("fdslka-"), Equals, true)
	c.Check(isValidAliasName("helloWorld$"), Equals, false)
	c.Check(isValidAliasName("h0SFD2k2#Fdsa"), Equals, false)
	c.Check(isValidAliasName("0dslka-4"), Equals, false)
	c.Check(isValidAliasName("-fdslka"), Equals, false)
}

func (s *MySuite) TestInvalidUrlInAliasExpand(c *C) {
	c.Skip("Test still being written")
	invalidURL := "foohello"
	url, err := aliasExpand(invalidURL, nil)
	c.Assert(err, Not(IsNil))
	log.Println(url)
	log.Println(err)
}
<commit_msg>Adding tests for aliasExpand<commit_after>package main

import (
	. "github.com/minio-io/check"
	"testing"
)

type MySuite struct{}

func Test(t *testing.T) { TestingT(t) }

var _ = Suite(&MySuite{})

func (s *MySuite) TestIsvalidAliasName(c *C) {
	c.Check(isValidAliasName("helloWorld0"), Equals, true)
	c.Check(isValidAliasName("h0SFD2k24Fdsa"), Equals, true)
	c.Check(isValidAliasName("fdslka-4"), Equals, true)
	c.Check(isValidAliasName("fdslka-"), Equals, true)
	c.Check(isValidAliasName("helloWorld$"), Equals, false)
	c.Check(isValidAliasName("h0SFD2k2#Fdsa"), Equals, false)
	c.Check(isValidAliasName("0dslka-4"), Equals, false)
	c.Check(isValidAliasName("-fdslka"), Equals, false)
}

func (s *MySuite) TestEmptyExpansions(c *C) {
	//	c.Skip("Test still being written")
	url, err := aliasExpand("hello", nil)
	c.Assert(url, Equals, "hello")
	c.Assert(err, IsNil)

	url, err = aliasExpand("minio://hello", nil)
	c.Assert(url, Equals, "minio://hello")
	c.Assert(err, IsNil)

	url, err = aliasExpand("$#\\", nil)
	c.Assert(url, Equals, "$#\\")
	c.Assert(err, IsNil)

	url, err = aliasExpand("foo:bar", map[string]string{"foo": "http://foo/"})
	c.Assert(url, Equals, "http://foo/bar")
	c.Assert(err, IsNil)

	url, err = aliasExpand("myfoo:bar", map[string]string{"foo": "http://foo/"})
	c.Assert(url, Equals, "myfoo:bar")
	c.Assert(err, IsNil)

	url, err = aliasExpand("", map[string]string{"foo": "http://foo/"})
	c.Assert(url, Equals, "")
	c.Assert(err, IsNil)

	url, err = aliasExpand("hello", nil)
	c.Assert(url, Equals, "hello")
	c.Assert(err, IsNil)
}
<|endoftext|>


<commit_before>// Copyright 2017 Jeff Foley. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package amass

import (
	"bufio"
	"context"
	"errors"
	//"fmt"
	"io"
	"net"
	"net/http"
	"sync"
	"time"

	"github.com/gamexg/proxyclient"
)

// AmassConfig - Passes along optional configurations
type AmassConfig struct {
	sync.Mutex

	// The ASNs that the enumeration will target
	ASNs []int

	// The CIDRs that the enumeration will target
	CIDRs []*net.IPNet

	// The IPs that the enumeration will target
	IPs []net.IP

	// The IP address ranges that the enumeration will target
	Ranges []*IPRange

	// The ports that will be checked for certificates
	Ports []int

	// The list of words to use when generating names
	Wordlist []string

	// Will the enumeration including brute forcing techniques
	BruteForcing bool

	// Will recursive brute forcing be performed?
	Recursive bool

	// Will discovered subdomain name alterations be generated?
	Alterations bool

	// Sets the maximum number of DNS queries per minute
	Frequency time.Duration

	// The channel that will receive the results
	Output chan *AmassRequest

	// Indicate that Amass cannot add domains to the config
	AdditionalDomains bool

	// The root domain names that the enumeration will target
	domains []string

	// Is responsible for performing simple DNS resolutions
	dns *queries

	// Performs lookups of root domain names from subdomain names
	domainLookup *DomainLookup

	// Detects DNS wildcards
	wildcards *Wildcards

	// The optional proxy connection for the enumeration to use
	proxy proxyclient.ProxyClient
}

func (c *AmassConfig) Setup() {
	// Setup the services potentially needed by all of amass
	c.dns = newQueriesSubsystem(c)
	c.domainLookup = NewDomainLookup(c)
	c.wildcards = NewWildcardDetection(c)
}

func (c *AmassConfig) SetupProxyConnection(addr string) error {
	client, err := proxyclient.NewProxyClient(addr)
	if err == nil {
		c.proxy = client
		// Override the Go default DNS resolver
		/*net.DefaultResolver = &net.Resolver{
			//PreferGo: true,
			Dial: c.DNSDialContext,
		}*/
	}
	return err
}

func (c *AmassConfig) AddDomains(names []string) {
	c.Lock()
	defer c.Unlock()

	c.domains = UniqueAppend(c.domains, names...)
}

func (c *AmassConfig) Domains() []string {
	c.Lock()
	defer c.Unlock()

	return c.domains
}

func (c *AmassConfig) DNSDialContext(ctx context.Context, network, address string) (net.Conn, error) {
	if c.proxy != nil {
		return c.proxy.Dial(network, NextNameserver())
	}

	d := &net.Dialer{}
	return d.DialContext(ctx, network, NextNameserver())
}

func (c *AmassConfig) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
	/*d := &net.Dialer{
		Resolver: &net.Resolver{
			PreferGo: true,
			Dial:     c.DNSDialContext,
		},
	}*/
	if c.proxy != nil {
		return c.proxy.Dial(network, address)
	}
	d := &net.Dialer{}
	//fmt.Println(network + ": " + addr)
	return d.DialContext(ctx, network, address)
}

func CheckConfig(config *AmassConfig) error {
	if len(config.Wordlist) == 0 {
		return errors.New("The configuration contains no wordlist")
	}

	if config.Frequency < DefaultConfig().Frequency {
		return errors.New("The configuration contains a invalid frequency")
	}

	if config.Output == nil {
		return errors.New("The configuration did not have an output channel")
	}
	return nil
}

// DefaultConfig returns a config with values that have been tested
func DefaultConfig() *AmassConfig {
	config := &AmassConfig{
		Ports:       []int{443},
		Recursive:   true,
		Alterations: true,
		Frequency:   10 * time.Millisecond,
	}
	return config
}

// Ensures that all configuration elements have valid values
func CustomConfig(ac *AmassConfig) *AmassConfig {
	config := DefaultConfig()

	if len(ac.Domains()) > 0 {
		config.AddDomains(ac.Domains())
	}

	config.ASNs = ac.ASNs
	config.CIDRs = ac.CIDRs
	config.Ranges = ac.Ranges
	config.IPs = ac.IPs

	if len(ac.Ports) > 0 {
		config.Ports = ac.Ports
	}

	if len(ac.Wordlist) == 0 {
		config.Wordlist = GetDefaultWordlist()
	} else {
		config.Wordlist = ac.Wordlist
	}

	config.BruteForcing = ac.BruteForcing
	config.Recursive = ac.Recursive

	// Check that the config values have been set appropriately
	if ac.Frequency > config.Frequency {
		config.Frequency = ac.Frequency
	}

	if ac.proxy != nil {
		config.proxy = ac.proxy
	}

	config.Output = ac.Output
	config.AdditionalDomains = ac.AdditionalDomains
	return config
}

func GetDefaultWordlist() []string {
	var list []string
	var wordlist io.Reader

	resp, err := http.Get(defaultWordlistURL)
	if err != nil {
		return list
	}
	defer resp.Body.Close()
	wordlist = resp.Body

	scanner := bufio.NewScanner(wordlist)
	// Once we have used all the words, we are finished
	for scanner.Scan() {
		// Get the next word in the list
		word := scanner.Text()
		if word != "" {
			// Add the word to the list
			list = append(list, word)
		}
	}
	return list
}
<commit_msg>fixes that prevent DNS leakage while using a proxy<commit_after>// Copyright 2017 Jeff Foley. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package amass

import (
	"bufio"
	"context"
	"errors"
	//"fmt"
	"io"
	"net"
	"net/http"
	"sync"
	"time"

	"github.com/gamexg/proxyclient"
)

// AmassConfig - Passes along optional configurations
type AmassConfig struct {
	sync.Mutex

	// The ASNs that the enumeration will target
	ASNs []int

	// The CIDRs that the enumeration will target
	CIDRs []*net.IPNet

	// The IPs that the enumeration will target
	IPs []net.IP

	// The IP address ranges that the enumeration will target
	Ranges []*IPRange

	// The ports that will be checked for certificates
	Ports []int

	// The list of words to use when generating names
	Wordlist []string

	// Will the enumeration including brute forcing techniques
	BruteForcing bool

	// Will recursive brute forcing be performed?
	Recursive bool

	// Will discovered subdomain name alterations be generated?
	Alterations bool

	// Sets the maximum number of DNS queries per minute
	Frequency time.Duration

	// The channel that will receive the results
	Output chan *AmassRequest

	// Indicate that Amass cannot add domains to the config
	AdditionalDomains bool

	// The root domain names that the enumeration will target
	domains []string

	// Is responsible for performing simple DNS resolutions
	dns *queries

	// Performs lookups of root domain names from subdomain names
	domainLookup *DomainLookup

	// Detects DNS wildcards
	wildcards *Wildcards

	// The optional proxy connection for the enumeration to use
	proxy proxyclient.ProxyClient
}

func (c *AmassConfig) Setup() {
	// Setup the services potentially needed by all of amass
	c.dns = newQueriesSubsystem(c)
	c.domainLookup = NewDomainLookup(c)
	c.wildcards = NewWildcardDetection(c)
}

func (c *AmassConfig) SetupProxyConnection(addr string) error {
	client, err := proxyclient.NewProxyClient(addr)
	if err == nil {
		c.proxy = client
		// Override the Go default DNS resolver to prevent leakage
		net.DefaultResolver = &net.Resolver{
			PreferGo: true,
			Dial:     c.DNSDialContext,
		}
	}
	return err
}

func (c *AmassConfig) AddDomains(names []string) {
	c.Lock()
	defer c.Unlock()

	c.domains = UniqueAppend(c.domains, names...)
}

func (c *AmassConfig) Domains() []string {
	c.Lock()
	defer c.Unlock()

	return c.domains
}

func (c *AmassConfig) DNSDialContext(ctx context.Context, network, address string) (net.Conn, error) {
	if c.proxy != nil {
		return c.proxy.Dial(network, NextNameserver())
	}

	d := &net.Dialer{}
	return d.DialContext(ctx, network, NextNameserver())
}

func (c *AmassConfig) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
	if c.proxy != nil {
		return c.proxy.Dial(network, address)
	}

	d := &net.Dialer{
		Resolver: &net.Resolver{
			PreferGo: true,
			Dial:     c.DNSDialContext,
		},
	}
	return d.DialContext(ctx, network, address)
}

func CheckConfig(config *AmassConfig) error {
	if len(config.Wordlist) == 0 {
		return errors.New("The configuration contains no wordlist")
	}

	if config.Frequency < DefaultConfig().Frequency {
		return errors.New("The configuration contains a invalid frequency")
	}

	if config.Output == nil {
		return errors.New("The configuration did not have an output channel")
	}
	return nil
}

// DefaultConfig returns a config with values that have been tested
func DefaultConfig() *AmassConfig {
	config := &AmassConfig{
		Ports:       []int{443},
		Recursive:   true,
		Alterations: true,
		Frequency:   10 * time.Millisecond,
	}
	return config
}

// Ensures that all configuration elements have valid values
func CustomConfig(ac *AmassConfig) *AmassConfig {
	config := DefaultConfig()

	if len(ac.Domains()) > 0 {
		config.AddDomains(ac.Domains())
	}

	config.ASNs = ac.ASNs
	config.CIDRs = ac.CIDRs
	config.Ranges = ac.Ranges
	config.IPs = ac.IPs

	if len(ac.Ports) > 0 {
		config.Ports = ac.Ports
	}

	if len(ac.Wordlist) == 0 {
		config.Wordlist = GetDefaultWordlist()
	} else {
		config.Wordlist = ac.Wordlist
	}

	config.BruteForcing = ac.BruteForcing
	config.Recursive = ac.Recursive

	// Check that the config values have been set appropriately
	if ac.Frequency > config.Frequency {
		config.Frequency = ac.Frequency
	}

	if ac.proxy != nil {
		config.proxy = ac.proxy
	}

	config.Output = ac.Output
	config.AdditionalDomains = ac.AdditionalDomains
	return config
}

func GetDefaultWordlist() []string {
	var list []string
	var wordlist io.Reader

	resp, err := http.Get(defaultWordlistURL)
	if err != nil {
		return list
	}
	defer resp.Body.Close()
	wordlist = resp.Body

	scanner := bufio.NewScanner(wordlist)
	// Once we have used all the words, we are finished
	for scanner.Scan() {
		// Get the next word in the list
		word := scanner.Text()
		if word != "" {
			// Add the word to the list
			list = append(list, word)
		}
	}
	return list
}
<|endoftext|>


<commit_before>package mcstore

import (
	"net/http"

	"sync"

	r "github.com/dancannon/gorethink"
	"github.com/emicklei/go-restful"
	"github.com/materials-commons/mcstore/pkg/db/dai"
	"github.com/materials-commons/mcstore/pkg/db/schema"
)

// apikeyFilter implements a filter for checking the apikey
// passed in with a request.
type apikeyFilter struct {
	apikeys map[string]*schema.User
	mutex   sync.RWMutex
}

// newAPIKeyFilter creates a new apikeyFilter instance.
func newAPIKeyFilter() *apikeyFilter {
	return &apikeyFilter{
		apikeys: make(map[string]*schema.User),
	}
}

// changes will monitor for changes to user apikeys and will
// update the server with the new key.
func (f *apikeyFilter) changes() {
	var session *r.Session
	go func() {
		var c struct {
			NewValue schema.User `gorethink:"new_value"`
			OldValue schema.User `gorethink:"old_value"`
		}
		users, _ := r.Table("users").Changes().Run(session)
		for users.Next(&c) {
			if c.OldValue.APIKey != "" && c.OldValue.APIKey != c.NewValue.APIKey {
				f.updateAPIKeyWithWriteLock(c.OldValue.APIKey, c.NewValue.APIKey, &c.NewValue)
			}
		}
	}()
}

// Filter implements the Filter interface for apikey lookup. It checks if an apikey is
// valid. If the apikey is found it sets the "user" attribute to the user structure. If
// the apikey is invalid then the filter doesn't pass the request on, and instead returns
// an http.StatusUnauthorized.
func (f *apikeyFilter) Filter(request *restful.Request, response *restful.Response, chain *restful.FilterChain) {
	apikey := request.Request.URL.Query().Get("apikey")
	session := request.Attribute("session").(*r.Session)
	rusers := dai.NewRUsers(session)
	user, found := f.getUser(apikey, rusers)
	if !found {
		response.WriteErrorString(http.StatusUnauthorized, "Not authorized")
	} else {
		request.SetAttribute("user", *user)
		chain.ProcessFilter(request, response)
	}
}

// getUser matches the user with the apikey. If it cannot find a match then it returns false.
// getUser caches the key/user pair in f.apikeys.
func (f *apikeyFilter) getUser(apikey string, users dai.Users) (*schema.User, bool) {
	if apikey == "" {
		// No key was passed.
		return nil, false
	}

	user, found := f.getUserWithReadLock(apikey)
	if !found {
		user, err := users.ByAPIKey(apikey)
		if err != nil {
			return nil, false
		}
		f.setUserWithWriteLock(apikey, user)
		return user, true
	}

	return user, true
}

// getUserWithReadLock will acquire a read lock and look the user up in the
// hash table cache.
func (f *apikeyFilter) getUserWithReadLock(apikey string) (*schema.User, bool) {
	defer f.mutex.RUnlock()
	f.mutex.RLock()

	user, found := f.apikeys[apikey]
	return user, found
}

// setUserWithWriteLock will acquire a write lock and add the user to the
// hash table cache.
func (f *apikeyFilter) setUserWithWriteLock(apikey string, user *schema.User) {
	defer f.mutex.Unlock()
	f.mutex.Lock()

	f.apikeys[apikey] = user
}

func (f *apikeyFilter) updateAPIKeyWithWriteLock(oldAPIkey, newAPIkey string, user *schema.User) {
	defer f.mutex.Unlock()
	f.mutex.Lock()
	delete(f.apikeys, oldAPIkey)
	f.apikeys[newAPIkey] = user
}
<commit_msg>Remove the keycache from the filter and move it to a separate data structure. Pass in the keycache to the filter constructor. Refactor filter to use keycache. Comment out the changes method. This will be moved to a separate go routine that will access the shared cache.<commit_after>package mcstore

import (
	"net/http"

	r "github.com/dancannon/gorethink"
	"github.com/emicklei/go-restful"
	"github.com/materials-commons/mcstore/pkg/db/dai"
	"github.com/materials-commons/mcstore/pkg/db/schema"
)

// apikeyFilter implements a filter for checking the apikey
// passed in with a request.
type apikeyFilter struct {
	keycache *apikeyCache
}

// newAPIKeyFilter creates a new apikeyFilter instance.
func newAPIKeyFilter(keycache *apikeyCache) *apikeyFilter {
	return &apikeyFilter{
		keycache: keycache,
	}
}

// changes will monitor for changes to user apikeys and will
// update the server with the new key.
//func (f *apikeyFilter) changes() {
//	var session *r.Session
//	go func() {
//		var c struct {
//			NewUserValue schema.User `gorethink:"new_value"`
//			OldUserValue schema.User `gorethink:"old_value"`
//		}
//		users, _ := r.Table("users").Changes().Run(session)
//		for users.Next(&c) {
//			switch {
//			case c.OldUserValue.ID == "":
//				// no old id, so new user added
//				f.keycache.addKey(c.NewUserValue.APIKey, &c.NewUserValue)
//			case c.OldUserValue.APIKey != "" && c.OldUserValue.APIKey != c.NewUserValue.APIKey:
//				f.keycache.resetKey(c.OldUserValue.APIKey, c.NewUserValue.APIKey, &c.NewUserValue)
//			}
//		}
//	}()
//}

// Filter implements the Filter interface for apikey lookup. It checks if an apikey is
// valid. If the apikey is found it sets the "user" attribute to the user structure. If
// the apikey is invalid then the filter doesn't pass the request on, and instead returns
// an http.StatusUnauthorized.
func (f *apikeyFilter) Filter(request *restful.Request, response *restful.Response, chain *restful.FilterChain) {
	apikey := request.Request.URL.Query().Get("apikey")
	session := request.Attribute("session").(*r.Session)
	rusers := dai.NewRUsers(session)
	user, found := f.getUser(apikey, rusers)
	if !found {
		response.WriteErrorString(http.StatusUnauthorized, "Not authorized")
	} else {
		request.SetAttribute("user", *user)
		chain.ProcessFilter(request, response)
	}
}

// getUser matches the user with the apikey. If it cannot find a match then it returns false.
// getUser caches the key/user pair in f.apikeys.
func (f *apikeyFilter) getUser(apikey string, users dai.Users) (*schema.User, bool) {
	if apikey == "" {
		// No key was passed.
		return nil, false
	}

	if user := f.keycache.getUser(apikey); user == nil {
		user, err := users.ByAPIKey(apikey)
		if err != nil {
			return nil, false
		}
		f.keycache.addKey(apikey, user)
		return user, true
	} else {
		return user, true
	}
}
<|endoftext|>


<commit_before>package run

import (
	"errors"
	"net/http"
	"os"
	"strconv"
	"time"

	"gopkg.in/tylerb/graceful.v1"

	"github.com/Sirupsen/logrus"
	"github.com/solher/snakepit/root"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

const (
	Port    = "app.port"
	Timeout = "app.timeout"
)

var (
	port    int
	timeout time.Duration
	Logger  = logrus.New()
)

var Builder func(v *viper.Viper, l *logrus.Logger) http.Handler

var Cmd = &cobra.Command{
	Use:   "run",
	Short: "Runs the service",
	RunE: func(cmd *cobra.Command, args []string) error {
		if Builder == nil {
			return errors.New("nil builder func")
		}

		Logger.Info("Building...")
		appHandler := Builder(root.Viper, Logger)

		Logger.Infof("Listening on port %d.", port)
		graceful.Run(":"+strconv.Itoa(port), timeout, appHandler)
		return nil
	},
}

func init() {
	Logger.Formatter = &logrus.TextFormatter{}
	Logger.Out = os.Stdout
	Logger.Level = logrus.DebugLevel

	Cmd.PersistentFlags().IntVarP(&port, "port", "p", 3000, "listening port")
	root.Viper.BindPFlag(Port, Cmd.PersistentFlags().Lookup("port"))

	Cmd.PersistentFlags().DurationVar(&timeout, "timeout", 10*time.Second, "graceful shutdown timeout (0 for infinite)")
	root.Viper.BindPFlag(Timeout, Cmd.PersistentFlags().Lookup("timeout"))
}
<commit_msg>Port and timeout flags fixed.<commit_after>package run

import (
	"errors"
	"net/http"
	"os"
	"strconv"
	"time"

	"gopkg.in/tylerb/graceful.v1"

	"github.com/Sirupsen/logrus"
	"github.com/solher/snakepit/root"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

const (
	Port    = "app.port"
	Timeout = "app.timeout"
)

var (
	Logger = logrus.New()
)

var Builder func(v *viper.Viper, l *logrus.Logger) http.Handler

var Cmd = &cobra.Command{
	Use:   "run",
	Short: "Runs the service",
	RunE: func(cmd *cobra.Command, args []string) error {
		if Builder == nil {
			return errors.New("nil builder func")
		}

		Logger.Infof("Building...")
		appHandler := Builder(root.Viper, Logger)

		port := root.Viper.GetInt(Port)
		timeout := root.Viper.GetDuration(Timeout)

		Logger.Infof("Listening on port %d.", port)
		graceful.Run(":"+strconv.Itoa(port), timeout, appHandler)
		return nil
	},
}

func init() {
	Logger.Formatter = &logrus.TextFormatter{}
	Logger.Out = os.Stdout
	Logger.Level = logrus.DebugLevel

	Cmd.PersistentFlags().IntP("port", "p", 3000, "listening port")
	root.Viper.BindPFlag(Port, Cmd.PersistentFlags().Lookup("port"))

	Cmd.PersistentFlags().Duration("timeout", 5*time.Second, "graceful shutdown timeout (0 for infinite)")
	root.Viper.BindPFlag(Timeout, Cmd.PersistentFlags().Lookup("timeout"))
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"strconv"
	"time"

	"gopkg.in/resty.v0"

	"github.com/boltdb/bolt"
	"github.com/codegangsta/cli"
)

var Client *resty.Client

func runtimePreCmd(c *cli.Context) error {
	var (
		err  error
		mode uint64
	)
	err = configSetup(c)
	if err != nil {
		return err
	}
	dbTimeout := time.Duration(Cfg.BoltDB.Timeout)
	if mode, err = strconv.ParseUint(Cfg.BoltDB.Mode, 8, 32); err != nil {
		fmt.Fprintf(os.Stderr,
			"Failed to parse configuration field boltdb.mode: %s\n", err)
		os.Exit(1)
	}
	if err = store.Open(
		Cfg.Run.PathBoltDB,
		os.FileMode(uint32(mode)),
		&bolt.Options{Timeout: dbTimeout * time.Second},
	); err != nil {
		fmt.Fprintf(os.Stderr, "Failed to open database: %s\n", err)
		os.Exit(1)
	}

	//
	//initLogFile()

	//
	utl.SetUrl(Cfg.Api)
	utl.SetPropertyTypes([]string{"system", "service", "custom", "oncall"})
	utl.SetViews([]string{"internal", "external", "local", "any"})

	//
	return nil
}

// initCommon provides common startup initialization
func initCommon(c *cli.Context) {
	var (
		err  error
		resp *resty.Response
	)
	if err = configSetup(c); err != nil {
		fmt.Fprintf(os.Stderr, "Failed to read the configuration: "+
			"%s\n", err.Error())
		os.Exit(1)
	}

	// open database
	if err = store.Open(
		Cfg.Run.PathBoltDB,
		os.FileMode(uint32(Cfg.Run.ModeBoltDB)),
		&bolt.Options{Timeout: Cfg.Run.TimeoutBoltDB * time.Second},
	); err != nil {
		fmt.Fprintf(os.Stderr, "Failed to open database: %s\n", err)
		os.Exit(1)
	}

	// ensure database content structure is in place
	if err = store.EnsureBuckets(); err != nil {
		fmt.Fprintf(os.Stderr, "Database bucket error: %s\n", err)
		os.Exit(1)
	}

	// set the configured API endpoint
	utl.SetUrl(Cfg.Api)

	// setup our REST client
	Client = resty.New().SetRESTMode().
		SetDisableWarn(true).
		SetHeader(`User-Agent`, `somaadm 0.4.8`).
		SetHostURL(utl.ApiUrl.String())

	// check configured API
	if resp, err = Client.R().Head(`/`); err != nil {
		fmt.Fprintf(os.Stderr, "Error tasting the API endpoint: %s\n",
			err.Error())
	} else if resp.StatusCode() != 204 {
		fmt.Fprintf(os.Stderr, "Error, API Url returned %d instead of 204."+
			" Sure this is SOMA?\n", resp.StatusCode())
		os.Exit(1)
	}

	// check who we talked to
	if resp.Header().Get(`X-Powered-By`) != `SOMA Configuration System` {
		fmt.Fprintf(os.Stderr, `Just FYI, at the end of that API URL`+
			` is not SOMA`)
		os.Exit(1)
	}
}

// boottime is the pre-run target for bootstrapping SOMA
func boottime(action cli.ActionFunc) cli.ActionFunc {
	return func(c *cli.Context) error {
		initCommon(c)

		return action(c)
	}
}

// runtime is the regular pre-run target
func runtime(action cli.ActionFunc) cli.ActionFunc {
	return func(c *cli.Context) error {
		initCommon(c)

		return action(c)
	}
}

// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix
<commit_msg>Nuke old runtime<commit_after>package main

import (
	"fmt"
	"os"
	"time"

	"gopkg.in/resty.v0"

	"github.com/boltdb/bolt"
	"github.com/codegangsta/cli"
)

var Client *resty.Client

// initCommon provides common startup initialization
func initCommon(c *cli.Context) {
	var (
		err  error
		resp *resty.Response
	)
	if err = configSetup(c); err != nil {
		fmt.Fprintf(os.Stderr, "Failed to read the configuration: "+
			"%s\n", err.Error())
		os.Exit(1)
	}

	// open database
	if err = store.Open(
		Cfg.Run.PathBoltDB,
		os.FileMode(uint32(Cfg.Run.ModeBoltDB)),
		&bolt.Options{Timeout: Cfg.Run.TimeoutBoltDB * time.Second},
	); err != nil {
		fmt.Fprintf(os.Stderr, "Failed to open database: %s\n", err)
		os.Exit(1)
	}

	// ensure database content structure is in place
	if err = store.EnsureBuckets(); err != nil {
		fmt.Fprintf(os.Stderr, "Database bucket error: %s\n", err)
		os.Exit(1)
	}

	// set the configured API endpoint
	utl.SetUrl(Cfg.Api)

	// setup our REST client
	Client = resty.New().SetRESTMode().
		SetDisableWarn(true).
		SetHeader(`User-Agent`, `somaadm 0.4.8`).
		SetHostURL(utl.ApiUrl.String())

	// check configured API
	if resp, err = Client.R().Head(`/`); err != nil {
		fmt.Fprintf(os.Stderr, "Error tasting the API endpoint: %s\n",
			err.Error())
	} else if resp.StatusCode() != 204 {
		fmt.Fprintf(os.Stderr, "Error, API Url returned %d instead of 204."+
			" Sure this is SOMA?\n", resp.StatusCode())
		os.Exit(1)
	}

	// check who we talked to
	if resp.Header().Get(`X-Powered-By`) != `SOMA Configuration System` {
		fmt.Fprintf(os.Stderr, `Just FYI, at the end of that API URL`+
			` is not SOMA`)
		os.Exit(1)
	}
}

// boottime is the pre-run target for bootstrapping SOMA
func boottime(action cli.ActionFunc) cli.ActionFunc {
	return func(c *cli.Context) error {
		initCommon(c)

		return action(c)
	}
}

// runtime is the regular pre-run target
func runtime(action cli.ActionFunc) cli.ActionFunc {
	return func(c *cli.Context) error {
		initCommon(c)

		return action(c)
	}
}

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


<commit_before>package validationUtils

import (
	"regexp"

	. "github.com/francoishill/goangi2/utils/errorUtils"
)

//Thanks to github.com/astaxie/beego/validation
var emailPattern = regexp.MustCompile("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[a-zA-Z0-9](?:[\\w-]*[\\w])?")

func IsValidEmail(emailStr string) bool {
	return emailPattern.Match([]byte(emailStr))
}

func CheckValidEmail(emailStr, errorIfInvalidEmail string) {
	if !IsValidEmail(emailStr) {
		PanicValidationError(errorIfInvalidEmail)
	}
}
<commit_msg>Added zero-length check to email validation.<commit_after>package validationUtils

import (
	"regexp"
	"strings"

	. "github.com/francoishill/goangi2/utils/errorUtils"
)

//Thanks to github.com/astaxie/beego/validation
var emailPattern = regexp.MustCompile("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[a-zA-Z0-9](?:[\\w-]*[\\w])?")

func IsValidEmail(emailStr string) bool {
	return emailPattern.Match([]byte(emailStr))
}

func CheckValidEmail(emailStr, errorIfInvalidEmail string) {
	if strings.Trim(emailStr, " ") == "" {
		PanicValidationError(errorIfInvalidEmail)
	}
	if !IsValidEmail(emailStr) {
		PanicValidationError(errorIfInvalidEmail)
	}
}
<|endoftext|>


<commit_before>// Copyright 2018 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package version

import (
	"bytes"
	"encoding/json"
	"fmt"
	"regexp"
	"strings"
	"testing"

	"github.com/spf13/cobra"
	"sigs.k8s.io/yaml"
)

func TestOpts(t *testing.T) {
	ordinaryCmd := CobraCommand()
	remoteCmd := CobraCommandWithOptions(
		CobraOptions{GetRemoteVersion: mockRemoteMesh(&meshInfoMultiVersion, nil)})

	cases := []struct {
		args       string
		cmd        *cobra.Command
		expectFail bool
	}{
		{
			"version",
			ordinaryCmd,
			false,
		},
		{
			"version --short",
			ordinaryCmd,
			false,
		},
		{
			"version --output yaml",
			ordinaryCmd,
			false,
		},
		{
			"version --output json",
			ordinaryCmd,
			false,
		},
		{
			"version --output xuxa",
			ordinaryCmd,
			true,
		},
		{
			"version --remote",
			ordinaryCmd,
			true,
		},

		{
			"version --remote",
			remoteCmd,
			false,
		},
		{
			"version --remote --short",
			remoteCmd,
			false,
		},
		{
			"version --remote --output yaml",
			remoteCmd,
			false,
		},
		{
			"version --remote --output json",
			remoteCmd,
			false,
		},
	}

	for _, v := range cases {
		t.Run(v.args, func(t *testing.T) {
			v.cmd.SetArgs(strings.Split(v.args, " "))
			var out bytes.Buffer
			v.cmd.SetOutput(&out)
			err := v.cmd.Execute()

			if !v.expectFail && err != nil {
				t.Errorf("Got %v, expecting success", err)
			}
			if v.expectFail && err == nil {
				t.Errorf("Expected failure, got success")
			}
		})
	}
}

var meshEmptyVersion = MeshInfo{}

var meshInfoSingleVersion = MeshInfo{
	{"Pilot", BuildInfo{"1.2.0", "gitSHA123", "go1.10", "Clean", "tag"}},
	{"Injector", BuildInfo{"1.2.0", "gitSHAabc", "go1.10.1", "Modified", "tag"}},
	{"Citadel", BuildInfo{"1.2.0", "gitSHA321", "go1.11.0", "Clean", "tag"}},
}

var meshInfoMultiVersion = MeshInfo{
	{"Pilot", BuildInfo{"1.0.0", "gitSHA123", "go1.10", "Clean", "1.0.0"}},
	{"Injector", BuildInfo{"1.0.1", "gitSHAabc", "go1.10.1", "Modified", "1.0.1"}},
	{"Citadel", BuildInfo{"1.2", "gitSHA321", "go1.11.0", "Clean", "1.2"}},
}

func mockRemoteMesh(meshInfo *MeshInfo, err error) GetRemoteVersionFunc {
	return func() (*MeshInfo, error) {
		return meshInfo, err
	}
}

type outputKind int

const (
	rawOutputMock outputKind = iota
	shortOutputMock
	jsonOutputMock
	yamlOutputMock
)

func printMeshVersion(meshInfo *MeshInfo, kind outputKind) string {
	switch kind {
	case yamlOutputMock:
		ver := &Version{MeshVersion: meshInfo}
		res, _ := yaml.Marshal(ver)
		return string(res)
	case jsonOutputMock:
		res, _ := json.MarshalIndent(meshInfo, "", "  ")
		return string(res)
	}

	res := ""
	for _, info := range *meshInfo {
		switch kind {
		case rawOutputMock:
			res += fmt.Sprintf("%s version: %#v\n", info.Component, info.Info)
		case shortOutputMock:
			res += fmt.Sprintf("%s version: %s\n", info.Component, info.Info.Version)
		}
	}
	return res
}

func TestVersion(t *testing.T) {
	cases := []struct {
		args           []string
		remoteMesh     *MeshInfo
		err            error
		expectFail     bool
		expectedOutput string         // Expected constant output
		expectedRegexp *regexp.Regexp // Expected regexp output
	}{
		{ // case 0 client-side only, normal output
			args: strings.Split("version --remote=false --short=false", " "),
			expectedRegexp: regexp.MustCompile("version.BuildInfo{Version:\"unknown\", GitRevision:\"unknown\", " +
				"GolangVersion:\"go1.([0-9+?(\\.)?]+)(rc[0-9]?)?(beta[0-9]?)?\", " +
				"BuildStatus:\"unknown\", GitTag:\"unknown\"}"),
		},
		{ // case 1 client-side only, short output
			args:           strings.Split("version -s --remote=false", " "),
			expectedOutput: "unknown\n",
		},
		{ // case 2 client-side only, yaml output
			args: strings.Split("version --remote=false -o yaml", " "),
			expectedRegexp: regexp.MustCompile("clientVersion:\n" +
				"  golang_version: go1.([0-9+?(\\.)?]+)(rc[0-9]?)?(beta[0-9]?)?\n" +
				"  revision: unknown\n" +
				"  status: unknown\n" +
				"  tag: unknown\n" +
				"  version: unknown\n\n"),
		},
		{ // case 3 client-side only, json output
			args: strings.Split("version --remote=false -o json", " "),
			expectedRegexp: regexp.MustCompile("{\n" +
				"  \"clientVersion\": {\n" +
				"    \"version\": \"unknown\",\n" +
				"    \"revision\": \"unknown\",\n" +
				"    \"golang_version\": \"go1.([0-9+?(\\.)?]+)(rc[0-9]?)?(beta[0-9]?)?\",\n" +
				"    \"status\": \"unknown\",\n" +
				"    \"tag\": \"unknown\"\n" +
				"  }\n" +
				"}\n"),
		},

		{ // case 4 remote, normal output
			args:       strings.Split("version --remote=true --short=false --output=", " "),
			remoteMesh: &meshInfoMultiVersion,
			expectedRegexp: regexp.MustCompile("client version: version.BuildInfo{Version:\"unknown\", GitRevision:\"unknown\", " +
				"GolangVersion:\"go1.([0-9+?(\\.)?]+)(rc[0-9]?)?(beta[0-9]?)?\", " +
				"BuildStatus:\"unknown\", GitTag:\"unknown\"}\n" +
				printMeshVersion(&meshInfoMultiVersion, rawOutputMock)),
		},
		{ // case 5 remote, short output
			args:           strings.Split("version --short=true --remote=true --output=", " "),
			remoteMesh:     &meshInfoMultiVersion,
			expectedOutput: "client version: unknown\n" + printMeshVersion(&meshInfoMultiVersion, shortOutputMock),
		},
		{ // case 6 remote, yaml output
			args:       strings.Split("version --remote=true -o yaml", " "),
			remoteMesh: &meshInfoMultiVersion,
			expectedRegexp: regexp.MustCompile("clientVersion:\n" +
				"  golang_version: go1.([0-9+?(\\.)?]+)(rc[0-9]?)?(beta[0-9]?)?\n" +
				"  revision: unknown\n" +
				"  status: unknown\n" +
				"  tag: unknown\n" +
				"  version: unknown\n" + printMeshVersion(&meshInfoMultiVersion, yamlOutputMock)),
		},
		{ // case 7 remote, json output
			args:       strings.Split("version --remote=true -o json", " "),
			remoteMesh: &meshInfoMultiVersion,
			expectedRegexp: regexp.MustCompile("{\n" +
				"  \"clientVersion\": {\n" +
				"    \"version\": \"unknown\",\n" +
				"    \"revision\": \"unknown\",\n" +
				"    \"golang_version\": \"go1.([0-9+?(\\.)?]+)(rc[0-9]?)?(beta[0-9]?)?\",\n" +
				"    \"status\": \"unknown\",\n" +
				"    \"tag\": \"unknown\"\n" +
				"  },\n" +
				printMeshVersion(&meshInfoMultiVersion, jsonOutputMock)),
		},

		{ // case 8 bogus arg
			args:           strings.Split("version --typo", " "),
			expectedRegexp: regexp.MustCompile("Error: unknown flag: --typo\n"),
			expectFail:     true,
		},

		{ // case 9 bogus output arg
			args:           strings.Split("version --output xyz", " "),
			expectedRegexp: regexp.MustCompile("Error: --output must be 'yaml' or 'json'\n"),
			expectFail:     true,
		},
		{ // case 10 remote, coalesced version output
			args:       strings.Split("version --short=true --remote=true --output=", " "),
			remoteMesh: &meshInfoSingleVersion,
			expectedOutput: `client version: unknown
control plane version: 1.2.0
`,
		},
		{ // case 11 remote, GetRemoteVersion returns a server error
			args:       strings.Split("version --remote=true", " "),
			remoteMesh: &meshEmptyVersion,
			err:        fmt.Errorf("server error"),
			expectFail: true,
		},
	}

	for i, v := range cases {
		t.Run(fmt.Sprintf("case %d %s", i, strings.Join(v.args, " ")), func(t *testing.T) {
			cmd := CobraCommandWithOptions(CobraOptions{GetRemoteVersion: mockRemoteMesh(v.remoteMesh, v.err)})
			var out bytes.Buffer
			cmd.SetOutput(&out)
			cmd.SetArgs(v.args)
			err := cmd.Execute()
			output := out.String()

			if v.expectedOutput != "" && v.expectedOutput != output {
				t.Fatalf("Unexpected output for 'istioctl %s'\n got: %q\nwant: %q",
					strings.Join(v.args, " "), output, v.expectedOutput)
			}

			if v.expectedRegexp != nil && !v.expectedRegexp.MatchString(output) {
				t.Fatalf("Output didn't match for 'istioctl %s'\n got %v\nwant: %v",
					strings.Join(v.args, " "), output, v.expectedRegexp)
			}

			if !v.expectFail && err != nil {
				t.Errorf("Got %v, expecting success", err)
			}
			if v.expectFail && err == nil {
				t.Errorf("Expected failure, got success")
			}
		})
	}
}
<commit_msg>fix deprecated setoutput (#616)<commit_after>// Copyright 2018 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package version

import (
	"bytes"
	"encoding/json"
	"fmt"
	"regexp"
	"strings"
	"testing"

	"github.com/spf13/cobra"
	"sigs.k8s.io/yaml"
)

func TestOpts(t *testing.T) {
	ordinaryCmd := CobraCommand()
	remoteCmd := CobraCommandWithOptions(
		CobraOptions{GetRemoteVersion: mockRemoteMesh(&meshInfoMultiVersion, nil)})

	cases := []struct {
		args       string
		cmd        *cobra.Command
		expectFail bool
	}{
		{
			"version",
			ordinaryCmd,
			false,
		},
		{
			"version --short",
			ordinaryCmd,
			false,
		},
		{
			"version --output yaml",
			ordinaryCmd,
			false,
		},
		{
			"version --output json",
			ordinaryCmd,
			false,
		},
		{
			"version --output xuxa",
			ordinaryCmd,
			true,
		},
		{
			"version --remote",
			ordinaryCmd,
			true,
		},

		{
			"version --remote",
			remoteCmd,
			false,
		},
		{
			"version --remote --short",
			remoteCmd,
			false,
		},
		{
			"version --remote --output yaml",
			remoteCmd,
			false,
		},
		{
			"version --remote --output json",
			remoteCmd,
			false,
		},
	}

	for _, v := range cases {
		t.Run(v.args, func(t *testing.T) {
			v.cmd.SetArgs(strings.Split(v.args, " "))
			var out bytes.Buffer
			v.cmd.SetOut(&out)
			v.cmd.SetErr(&out)
			err := v.cmd.Execute()

			if !v.expectFail && err != nil {
				t.Errorf("Got %v, expecting success", err)
			}
			if v.expectFail && err == nil {
				t.Errorf("Expected failure, got success")
			}
		})
	}
}

var meshEmptyVersion = MeshInfo{}

var meshInfoSingleVersion = MeshInfo{
	{"Pilot", BuildInfo{"1.2.0", "gitSHA123", "go1.10", "Clean", "tag"}},
	{"Injector", BuildInfo{"1.2.0", "gitSHAabc", "go1.10.1", "Modified", "tag"}},
	{"Citadel", BuildInfo{"1.2.0", "gitSHA321", "go1.11.0", "Clean", "tag"}},
}

var meshInfoMultiVersion = MeshInfo{
	{"Pilot", BuildInfo{"1.0.0", "gitSHA123", "go1.10", "Clean", "1.0.0"}},
	{"Injector", BuildInfo{"1.0.1", "gitSHAabc", "go1.10.1", "Modified", "1.0.1"}},
	{"Citadel", BuildInfo{"1.2", "gitSHA321", "go1.11.0", "Clean", "1.2"}},
}

func mockRemoteMesh(meshInfo *MeshInfo, err error) GetRemoteVersionFunc {
	return func() (*MeshInfo, error) {
		return meshInfo, err
	}
}

type outputKind int

const (
	rawOutputMock outputKind = iota
	shortOutputMock
	jsonOutputMock
	yamlOutputMock
)

func printMeshVersion(meshInfo *MeshInfo, kind outputKind) string {
	switch kind {
	case yamlOutputMock:
		ver := &Version{MeshVersion: meshInfo}
		res, _ := yaml.Marshal(ver)
		return string(res)
	case jsonOutputMock:
		res, _ := json.MarshalIndent(meshInfo, "", "  ")
		return string(res)
	}

	res := ""
	for _, info := range *meshInfo {
		switch kind {
		case rawOutputMock:
			res += fmt.Sprintf("%s version: %#v\n", info.Component, info.Info)
		case shortOutputMock:
			res += fmt.Sprintf("%s version: %s\n", info.Component, info.Info.Version)
		}
	}
	return res
}

func TestVersion(t *testing.T) {
	cases := []struct {
		args           []string
		remoteMesh     *MeshInfo
		err            error
		expectFail     bool
		expectedOutput string         // Expected constant output
		expectedRegexp *regexp.Regexp // Expected regexp output
	}{
		{ // case 0 client-side only, normal output
			args: strings.Split("version --remote=false --short=false", " "),
			expectedRegexp: regexp.MustCompile("version.BuildInfo{Version:\"unknown\", GitRevision:\"unknown\", " +
				"GolangVersion:\"go1.([0-9+?(\\.)?]+)(rc[0-9]?)?(beta[0-9]?)?\", " +
				"BuildStatus:\"unknown\", GitTag:\"unknown\"}"),
		},
		{ // case 1 client-side only, short output
			args:           strings.Split("version -s --remote=false", " "),
			expectedOutput: "unknown\n",
		},
		{ // case 2 client-side only, yaml output
			args: strings.Split("version --remote=false -o yaml", " "),
			expectedRegexp: regexp.MustCompile("clientVersion:\n" +
				"  golang_version: go1.([0-9+?(\\.)?]+)(rc[0-9]?)?(beta[0-9]?)?\n" +
				"  revision: unknown\n" +
				"  status: unknown\n" +
				"  tag: unknown\n" +
				"  version: unknown\n\n"),
		},
		{ // case 3 client-side only, json output
			args: strings.Split("version --remote=false -o json", " "),
			expectedRegexp: regexp.MustCompile("{\n" +
				"  \"clientVersion\": {\n" +
				"    \"version\": \"unknown\",\n" +
				"    \"revision\": \"unknown\",\n" +
				"    \"golang_version\": \"go1.([0-9+?(\\.)?]+)(rc[0-9]?)?(beta[0-9]?)?\",\n" +
				"    \"status\": \"unknown\",\n" +
				"    \"tag\": \"unknown\"\n" +
				"  }\n" +
				"}\n"),
		},

		{ // case 4 remote, normal output
			args:       strings.Split("version --remote=true --short=false --output=", " "),
			remoteMesh: &meshInfoMultiVersion,
			expectedRegexp: regexp.MustCompile("client version: version.BuildInfo{Version:\"unknown\", GitRevision:\"unknown\", " +
				"GolangVersion:\"go1.([0-9+?(\\.)?]+)(rc[0-9]?)?(beta[0-9]?)?\", " +
				"BuildStatus:\"unknown\", GitTag:\"unknown\"}\n" +
				printMeshVersion(&meshInfoMultiVersion, rawOutputMock)),
		},
		{ // case 5 remote, short output
			args:           strings.Split("version --short=true --remote=true --output=", " "),
			remoteMesh:     &meshInfoMultiVersion,
			expectedOutput: "client version: unknown\n" + printMeshVersion(&meshInfoMultiVersion, shortOutputMock),
		},
		{ // case 6 remote, yaml output
			args:       strings.Split("version --remote=true -o yaml", " "),
			remoteMesh: &meshInfoMultiVersion,
			expectedRegexp: regexp.MustCompile("clientVersion:\n" +
				"  golang_version: go1.([0-9+?(\\.)?]+)(rc[0-9]?)?(beta[0-9]?)?\n" +
				"  revision: unknown\n" +
				"  status: unknown\n" +
				"  tag: unknown\n" +
				"  version: unknown\n" + printMeshVersion(&meshInfoMultiVersion, yamlOutputMock)),
		},
		{ // case 7 remote, json output
			args:       strings.Split("version --remote=true -o json", " "),
			remoteMesh: &meshInfoMultiVersion,
			expectedRegexp: regexp.MustCompile("{\n" +
				"  \"clientVersion\": {\n" +
				"    \"version\": \"unknown\",\n" +
				"    \"revision\": \"unknown\",\n" +
				"    \"golang_version\": \"go1.([0-9+?(\\.)?]+)(rc[0-9]?)?(beta[0-9]?)?\",\n" +
				"    \"status\": \"unknown\",\n" +
				"    \"tag\": \"unknown\"\n" +
				"  },\n" +
				printMeshVersion(&meshInfoMultiVersion, jsonOutputMock)),
		},

		{ // case 8 bogus arg
			args:           strings.Split("version --typo", " "),
			expectedRegexp: regexp.MustCompile("Error: unknown flag: --typo\n"),
			expectFail:     true,
		},

		{ // case 9 bogus output arg
			args:           strings.Split("version --output xyz", " "),
			expectedRegexp: regexp.MustCompile("Error: --output must be 'yaml' or 'json'\n"),
			expectFail:     true,
		},
		{ // case 10 remote, coalesced version output
			args:       strings.Split("version --short=true --remote=true --output=", " "),
			remoteMesh: &meshInfoSingleVersion,
			expectedOutput: `client version: unknown
control plane version: 1.2.0
`,
		},
		{ // case 11 remote, GetRemoteVersion returns a server error
			args:       strings.Split("version --remote=true", " "),
			remoteMesh: &meshEmptyVersion,
			err:        fmt.Errorf("server error"),
			expectFail: true,
		},
	}

	for i, v := range cases {
		t.Run(fmt.Sprintf("case %d %s", i, strings.Join(v.args, " ")), func(t *testing.T) {
			cmd := CobraCommandWithOptions(CobraOptions{GetRemoteVersion: mockRemoteMesh(v.remoteMesh, v.err)})
			var out bytes.Buffer
			cmd.SetOut(&out)
			cmd.SetErr(&out)
			cmd.SetArgs(v.args)
			err := cmd.Execute()
			output := out.String()

			if v.expectedOutput != "" && v.expectedOutput != output {
				t.Fatalf("Unexpected output for 'istioctl %s'\n got: %q\nwant: %q",
					strings.Join(v.args, " "), output, v.expectedOutput)
			}

			if v.expectedRegexp != nil && !v.expectedRegexp.MatchString(output) {
				t.Fatalf("Output didn't match for 'istioctl %s'\n got %v\nwant: %v",
					strings.Join(v.args, " "), output, v.expectedRegexp)
			}

			if !v.expectFail && err != nil {
				t.Errorf("Got %v, expecting success", err)
			}
			if v.expectFail && err == nil {
				t.Errorf("Expected failure, got success")
			}
		})
	}
}
<|endoftext|>


<commit_before>package config

import (
	"crypto/tls"
	"fmt"
	"github.com/aws/aws-sdk-go/service/dynamodb"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go/service/sqs"
)

var (
	// Start with sensible default values
	defaultCnf = &Config{
		Broker:          "amqp://guest:guest@localhost:5672/",
		DefaultQueue:    "machinery_tasks",
		ResultBackend:   "amqp://guest:guest@localhost:5672/",
		ResultsExpireIn: 3600,
		AMQP: &AMQPConfig{
			Exchange:      "machinery_exchange",
			ExchangeType:  "direct",
			BindingKey:    "machinery_task",
			PrefetchCount: 3,
		},
		DynamoDB: &DynamoDBConfig{
			TaskStatesTable: "task_states",
			GroupMetasTable: "group_metas",
		},
		Redis: &RedisConfig{
			MaxIdle:                3,
			IdleTimeout:            240,
			ReadTimeout:            15,
			WriteTimeout:           15,
			ConnectTimeout:         15,
			DelayedTasksPollPeriod: 20,
		},
	}

	reloadDelay = time.Second * 10
)

// Config holds all configuration for our program
type Config struct {
	Broker          string       `yaml:"broker" envconfig:"BROKER"`
	DefaultQueue    string       `yaml:"default_queue" envconfig:"DEFAULT_QUEUE"`
	ResultBackend   string       `yaml:"result_backend" envconfig:"RESULT_BACKEND"`
	ResultsExpireIn int          `yaml:"results_expire_in" envconfig:"RESULTS_EXPIRE_IN"`
	AMQP            *AMQPConfig  `yaml:"amqp"`
	SQS             *SQSConfig   `yaml:"sqs"`
	Redis           *RedisConfig `yaml:"redis"`
	TLSConfig       *tls.Config
	// NoUnixSignals - when set disables signal handling in machinery
	NoUnixSignals bool            `yaml:"no_unix_signals" envconfig:"NO_UNIX_SIGNALS"`
	DynamoDB      *DynamoDBConfig `yaml:"dynamodb"`
}

// QueueBindingArgs arguments which are used when binding to the exchange
type QueueBindingArgs map[string]interface{}

// AMQPConfig wraps RabbitMQ related configuration
type AMQPConfig struct {
	Exchange         string           `yaml:"exchange" envconfig:"AMQP_EXCHANGE"`
	ExchangeType     string           `yaml:"exchange_type" envconfig:"AMQP_EXCHANGE_TYPE"`
	QueueBindingArgs QueueBindingArgs `yaml:"queue_binding_args" envconfig:"AMQP_QUEUE_BINDING_ARGS"`
	BindingKey       string           `yaml:"binding_key" envconfig:"AMQP_BINDING_KEY"`
	PrefetchCount    int              `yaml:"prefetch_count" envconfig:"AMQP_PREFETCH_COUNT"`
}

// DynamoDBConfig wraps DynamoDB related configuration
type DynamoDBConfig struct {
	Config          *dynamodb.DynamoDB
	TaskStatesTable string `yaml:"task_states_table" envconfig:"TASK_STATES_TABLE"`
	GroupMetasTable string `yaml:"group_metas_table" envconfig:"GROUP_METAS_TABLE"`
}

// SQSConfig wraps SQS related configuration
type SQSConfig struct {
	Client          *sqs.SQS
	WaitTimeSeconds int `yaml:"receive_wait_time_seconds" envconfig:"SQS_WAIT_TIME_SECONDS"`
	// https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html
	// visibility timeout should default to nil to use the overall visibility timeout for the queue
	VisibilityTimeout *int `yaml:"receive_visibility_timeout" envconfig:"SQS_VISIBILITY_TIMEOUT"`
}

type RedisConfig struct {
	// Maximum number of idle connections in the pool.
	MaxIdle int `yaml:"max_idle" envconfig:"REDIS_MAX_IDLE"`

	// Maximum number of connections allocated by the pool at a given time.
	// When zero, there is no limit on the number of connections in the pool.
	MaxActive int `yaml:"max_active" envconfig:"REDIS_MAX_ACTIVE"`

	// Close connections after remaining idle for this duration in seconds. If the value
	// is zero, then idle connections are not closed. Applications should set
	// the timeout to a value less than the server's timeout.
	IdleTimeout int `yaml:"max_idle_timeout" envconfig:"REDIS_IDLE_TIMEOUT"`

	// If Wait is true and the pool is at the MaxActive limit, then Get() waits
	// for a connection to be returned to the pool before returning.
	Wait bool `yaml:"wait" envconfig:"REDIS_WAIT"`

	// ReadTimeout specifies the timeout in seconds for reading a single command reply.
	ReadTimeout int `yaml:"read_timeout" envconfig:"REDIS_READ_TIMEOUT"`

	// WriteTimeout specifies the timeout in seconds for writing a single command.
	WriteTimeout int `yaml:"write_timeout" envconfig:"REDIS_WRITE_TIMEOUT"`

	// ConnectTimeout specifies the timeout in seconds for connecting to the Redis server when
	// no DialNetDial option is specified.
	ConnectTimeout int `yaml:"connect_timeout" envconfig:"REDIS_CONNECT_TIMEOUT"`

	// DelayedTasksPollPeriod specifies the period in milliseconds when polling redis for delayed tasks
	DelayedTasksPollPeriod int `yaml:"delayed_tasks_poll_period" envconfig:"REDIS_DELAYED_TASKS_POLL_PERIOD"`
}

// Decode from yaml to map (any field whose type or pointer-to-type implements
// envconfig.Decoder can control its own deserialization)
func (args *QueueBindingArgs) Decode(value string) error {
	pairs := strings.Split(value, ",")
	mp := make(map[string]interface{}, len(pairs))
	for _, pair := range pairs {
		kvpair := strings.Split(pair, ":")
		if len(kvpair) != 2 {
			return fmt.Errorf("invalid map item: %q", pair)
		}
		mp[kvpair[0]] = kvpair[1]
	}
	*args = QueueBindingArgs(mp)
	return nil
}
<commit_msg>Format config using goimports<commit_after>package config

import (
	"crypto/tls"
	"fmt"
	"strings"
	"time"

	"github.com/aws/aws-sdk-go/service/dynamodb"

	"github.com/aws/aws-sdk-go/service/sqs"
)

var (
	// Start with sensible default values
	defaultCnf = &Config{
		Broker:          "amqp://guest:guest@localhost:5672/",
		DefaultQueue:    "machinery_tasks",
		ResultBackend:   "amqp://guest:guest@localhost:5672/",
		ResultsExpireIn: 3600,
		AMQP: &AMQPConfig{
			Exchange:      "machinery_exchange",
			ExchangeType:  "direct",
			BindingKey:    "machinery_task",
			PrefetchCount: 3,
		},
		DynamoDB: &DynamoDBConfig{
			TaskStatesTable: "task_states",
			GroupMetasTable: "group_metas",
		},
		Redis: &RedisConfig{
			MaxIdle:                3,
			IdleTimeout:            240,
			ReadTimeout:            15,
			WriteTimeout:           15,
			ConnectTimeout:         15,
			DelayedTasksPollPeriod: 20,
		},
	}

	reloadDelay = time.Second * 10
)

// Config holds all configuration for our program
type Config struct {
	Broker          string       `yaml:"broker" envconfig:"BROKER"`
	DefaultQueue    string       `yaml:"default_queue" envconfig:"DEFAULT_QUEUE"`
	ResultBackend   string       `yaml:"result_backend" envconfig:"RESULT_BACKEND"`
	ResultsExpireIn int          `yaml:"results_expire_in" envconfig:"RESULTS_EXPIRE_IN"`
	AMQP            *AMQPConfig  `yaml:"amqp"`
	SQS             *SQSConfig   `yaml:"sqs"`
	Redis           *RedisConfig `yaml:"redis"`
	TLSConfig       *tls.Config
	// NoUnixSignals - when set disables signal handling in machinery
	NoUnixSignals bool            `yaml:"no_unix_signals" envconfig:"NO_UNIX_SIGNALS"`
	DynamoDB      *DynamoDBConfig `yaml:"dynamodb"`
}

// QueueBindingArgs arguments which are used when binding to the exchange
type QueueBindingArgs map[string]interface{}

// AMQPConfig wraps RabbitMQ related configuration
type AMQPConfig struct {
	Exchange         string           `yaml:"exchange" envconfig:"AMQP_EXCHANGE"`
	ExchangeType     string           `yaml:"exchange_type" envconfig:"AMQP_EXCHANGE_TYPE"`
	QueueBindingArgs QueueBindingArgs `yaml:"queue_binding_args" envconfig:"AMQP_QUEUE_BINDING_ARGS"`
	BindingKey       string           `yaml:"binding_key" envconfig:"AMQP_BINDING_KEY"`
	PrefetchCount    int              `yaml:"prefetch_count" envconfig:"AMQP_PREFETCH_COUNT"`
}

// DynamoDBConfig wraps DynamoDB related configuration
type DynamoDBConfig struct {
	Config          *dynamodb.DynamoDB
	TaskStatesTable string `yaml:"task_states_table" envconfig:"TASK_STATES_TABLE"`
	GroupMetasTable string `yaml:"group_metas_table" envconfig:"GROUP_METAS_TABLE"`
}

// SQSConfig wraps SQS related configuration
type SQSConfig struct {
	Client          *sqs.SQS
	WaitTimeSeconds int `yaml:"receive_wait_time_seconds" envconfig:"SQS_WAIT_TIME_SECONDS"`
	// https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html
	// visibility timeout should default to nil to use the overall visibility timeout for the queue
	VisibilityTimeout *int `yaml:"receive_visibility_timeout" envconfig:"SQS_VISIBILITY_TIMEOUT"`
}

type RedisConfig struct {
	// Maximum number of idle connections in the pool.
	MaxIdle int `yaml:"max_idle" envconfig:"REDIS_MAX_IDLE"`

	// Maximum number of connections allocated by the pool at a given time.
	// When zero, there is no limit on the number of connections in the pool.
	MaxActive int `yaml:"max_active" envconfig:"REDIS_MAX_ACTIVE"`

	// Close connections after remaining idle for this duration in seconds. If the value
	// is zero, then idle connections are not closed. Applications should set
	// the timeout to a value less than the server's timeout.
	IdleTimeout int `yaml:"max_idle_timeout" envconfig:"REDIS_IDLE_TIMEOUT"`

	// If Wait is true and the pool is at the MaxActive limit, then Get() waits
	// for a connection to be returned to the pool before returning.
	Wait bool `yaml:"wait" envconfig:"REDIS_WAIT"`

	// ReadTimeout specifies the timeout in seconds for reading a single command reply.
	ReadTimeout int `yaml:"read_timeout" envconfig:"REDIS_READ_TIMEOUT"`

	// WriteTimeout specifies the timeout in seconds for writing a single command.
	WriteTimeout int `yaml:"write_timeout" envconfig:"REDIS_WRITE_TIMEOUT"`

	// ConnectTimeout specifies the timeout in seconds for connecting to the Redis server when
	// no DialNetDial option is specified.
	ConnectTimeout int `yaml:"connect_timeout" envconfig:"REDIS_CONNECT_TIMEOUT"`

	// DelayedTasksPollPeriod specifies the period in milliseconds when polling redis for delayed tasks
	DelayedTasksPollPeriod int `yaml:"delayed_tasks_poll_period" envconfig:"REDIS_DELAYED_TASKS_POLL_PERIOD"`
}

// Decode from yaml to map (any field whose type or pointer-to-type implements
// envconfig.Decoder can control its own deserialization)
func (args *QueueBindingArgs) Decode(value string) error {
	pairs := strings.Split(value, ",")
	mp := make(map[string]interface{}, len(pairs))
	for _, pair := range pairs {
		kvpair := strings.Split(pair, ":")
		if len(kvpair) != 2 {
			return fmt.Errorf("invalid map item: %q", pair)
		}
		mp[kvpair[0]] = kvpair[1]
	}
	*args = QueueBindingArgs(mp)
	return nil
}
<|endoftext|>


<commit_before>package glfw

/*
#include "glfw/include/GLFW/glfw3.h"
#include "glfw/src/internal.h"

GLFWAPI VkResult glfwCreateWindowSurface(VkInstance instance, GLFWwindow* window, const VkAllocationCallbacks* allocator, VkSurfaceKHR* surface);
GLFWAPI GLFWvkproc glfwGetInstanceProcAddress(VkInstance instance, const char* procname);

// Helper function for doing raw pointer arithmetic
static inline const char* getArrayIndex(const char** array, unsigned int index) {
	return array[index];
}

void* getVulkanProcAddr() {
	return glfwGetInstanceProcAddress;
}
*/
import "C"
import (
	"errors"
	"fmt"
	"reflect"
	"unsafe"
)

// VulkanSupported reports whether the Vulkan loader has been found. This check is performed by Init.
//
// The availability of a Vulkan loader does not by itself guarantee that window surface creation or
// even device creation is possible. Call GetRequiredInstanceExtensions to check whether the
// extensions necessary for Vulkan surface creation are available and GetPhysicalDevicePresentationSupport
// to check whether a queue family of a physical device supports image presentation.
func VulkanSupported() bool {
	return glfwbool(C.glfwVulkanSupported())
}

// GetVulkanGetInstanceProcAddress returns the function pointer used to find Vulkan core or
// extension functions. The return value of this function can be passed to the Vulkan library.
//
// Note that this function does not work the same way as the glfwGetInstanceProcAddress.
func GetVulkanGetInstanceProcAddress() unsafe.Pointer {
	return C.getVulkanProcAddr()
}

// GetRequiredInstanceExtensions returns a slice of Vulkan instance extension names required
// by GLFW for creating Vulkan surfaces for GLFW windows. If successful, the list will always
// contain VK_KHR_surface, so if you don't require any additional extensions you can pass this list
// directly to the VkInstanceCreateInfo struct.
//
// If Vulkan is not available on the machine, this function returns nil. Call
// VulkanSupported to check whether Vulkan is available.
//
// If Vulkan is available but no set of extensions allowing window surface creation was found, this
// function returns nil. You may still use Vulkan for off-screen rendering and compute work.
func (window *Window) GetRequiredInstanceExtensions() []string {
	var count C.uint32_t
	strarr := C.glfwGetRequiredInstanceExtensions(&count)
	if count == 0 {
		return nil
	}

	extensions := make([]string, count)
	for i := uint(0); i < uint(count); i++ {
		extensions[i] = C.GoString(C.getArrayIndex(strarr, C.uint(i)))
	}
	return extensions
}

// CreateWindowSurface creates a Vulkan surface for this window.
func (window *Window) CreateWindowSurface(instance interface{}, allocCallbacks unsafe.Pointer) (surface uintptr, err error) {
	if instance == nil {
		return 0, errors.New("vulkan: instance is nil")
	}
	val := reflect.ValueOf(instance)
	if val.Kind() != reflect.Ptr {
		return 0, fmt.Errorf("vulkan: instance is not a VkInstance (expected kind Ptr, got %s)", val.Kind())
	}
	var vulkanSurface C.VkSurfaceKHR
	ret := C.glfwCreateWindowSurface(
		(C.VkInstance)(unsafe.Pointer(reflect.ValueOf(instance).Pointer())), window.data,
		(*C.VkAllocationCallbacks)(allocCallbacks), (*C.VkSurfaceKHR)(unsafe.Pointer(&vulkanSurface)))
	if ret != C.VK_SUCCESS {
		return 0, fmt.Errorf("vulkan: error creating window surface: %d", ret)
	}
	return uintptr(unsafe.Pointer(&vulkanSurface)), nil
}
<commit_msg>Use only the internal header<commit_after>package glfw

/*
#include "glfw/src/internal.h"

GLFWAPI VkResult glfwCreateWindowSurface(VkInstance instance, GLFWwindow* window, const VkAllocationCallbacks* allocator, VkSurfaceKHR* surface);
GLFWAPI GLFWvkproc glfwGetInstanceProcAddress(VkInstance instance, const char* procname);

// Helper function for doing raw pointer arithmetic
static inline const char* getArrayIndex(const char** array, unsigned int index) {
	return array[index];
}

void* getVulkanProcAddr() {
	return glfwGetInstanceProcAddress;
}
*/
import "C"
import (
	"errors"
	"fmt"
	"reflect"
	"unsafe"
)

// VulkanSupported reports whether the Vulkan loader has been found. This check is performed by Init.
//
// The availability of a Vulkan loader does not by itself guarantee that window surface creation or
// even device creation is possible. Call GetRequiredInstanceExtensions to check whether the
// extensions necessary for Vulkan surface creation are available and GetPhysicalDevicePresentationSupport
// to check whether a queue family of a physical device supports image presentation.
func VulkanSupported() bool {
	return glfwbool(C.glfwVulkanSupported())
}

// GetVulkanGetInstanceProcAddress returns the function pointer used to find Vulkan core or
// extension functions. The return value of this function can be passed to the Vulkan library.
//
// Note that this function does not work the same way as the glfwGetInstanceProcAddress.
func GetVulkanGetInstanceProcAddress() unsafe.Pointer {
	return C.getVulkanProcAddr()
}

// GetRequiredInstanceExtensions returns a slice of Vulkan instance extension names required
// by GLFW for creating Vulkan surfaces for GLFW windows. If successful, the list will always
// contain VK_KHR_surface, so if you don't require any additional extensions you can pass this list
// directly to the VkInstanceCreateInfo struct.
//
// If Vulkan is not available on the machine, this function returns nil. Call
// VulkanSupported to check whether Vulkan is available.
//
// If Vulkan is available but no set of extensions allowing window surface creation was found, this
// function returns nil. You may still use Vulkan for off-screen rendering and compute work.
func (window *Window) GetRequiredInstanceExtensions() []string {
	var count C.uint32_t
	strarr := C.glfwGetRequiredInstanceExtensions(&count)
	if count == 0 {
		return nil
	}

	extensions := make([]string, count)
	for i := uint(0); i < uint(count); i++ {
		extensions[i] = C.GoString(C.getArrayIndex(strarr, C.uint(i)))
	}
	return extensions
}

// CreateWindowSurface creates a Vulkan surface for this window.
func (window *Window) CreateWindowSurface(instance interface{}, allocCallbacks unsafe.Pointer) (surface uintptr, err error) {
	if instance == nil {
		return 0, errors.New("vulkan: instance is nil")
	}
	val := reflect.ValueOf(instance)
	if val.Kind() != reflect.Ptr {
		return 0, fmt.Errorf("vulkan: instance is not a VkInstance (expected kind Ptr, got %s)", val.Kind())
	}
	var vulkanSurface C.VkSurfaceKHR
	ret := C.glfwCreateWindowSurface(
		(C.VkInstance)(unsafe.Pointer(reflect.ValueOf(instance).Pointer())), window.data,
		(*C.VkAllocationCallbacks)(allocCallbacks), (*C.VkSurfaceKHR)(unsafe.Pointer(&vulkanSurface)))
	if ret != C.VK_SUCCESS {
		return 0, fmt.Errorf("vulkan: error creating window surface: %d", ret)
	}
	return uintptr(unsafe.Pointer(&vulkanSurface)), nil
}
<|endoftext|>


<commit_before>package v3

import (
	"encoding/json"
	"fmt"

	. "github.com/cloudfoundry/cf-acceptance-tests/cats_suite_helpers"

	"github.com/cloudfoundry-incubator/cf-test-helpers/cf"
	"github.com/cloudfoundry-incubator/cf-test-helpers/helpers"
	"github.com/cloudfoundry/cf-acceptance-tests/helpers/assets"
	"github.com/cloudfoundry/cf-acceptance-tests/helpers/random_name"
	. "github.com/cloudfoundry/cf-acceptance-tests/helpers/v3_helpers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gexec"
)

var _ = V3Describe("route_mapping", func() {
	type RouteList struct {
		Resources []struct {
			Metadata struct {
				Guid string `json:"guid"`
			} `json:"metadata"`
		} `json:"resources"`
	}

	var (
		appName     string
		appGuid     string
		packageGuid string
		spaceGuid   string
		spaceName   string
		token       string
		webProcess  Process
	)

	BeforeEach(func() {
		appName = random_name.CATSRandomName("APP")
		spaceName = TestSetup.RegularUserContext().Space
		spaceGuid = GetSpaceGuidFromName(spaceName)
		appGuid = CreateApp(appName, spaceGuid, `{"foo":"bar"}`)
		packageGuid = CreatePackage(appGuid)
		token = GetAuthToken()
		uploadUrl := fmt.Sprintf("%s%s/v3/packages/%s/upload", Config.Protocol(), Config.GetApiEndpoint(), packageGuid)

		UploadPackage(uploadUrl, assets.NewAssets().DoraZip, token)
		WaitForPackageToBeReady(packageGuid)

		dropletGuid := StageBuildpackPackage(packageGuid, Config.GetRubyBuildpackName())
		WaitForDropletToStage(dropletGuid)
		AssignDropletToApp(appGuid, dropletGuid)

		processes := GetProcesses(appGuid, appName)
		webProcess = GetProcessByType(processes, "web")

		CreateRoute(spaceName, Config.GetAppsDomain(), appName)
	})

	AfterEach(func() {
		FetchRecentLogs(appGuid, token, Config)
		DeleteApp(appGuid)
	})

	Describe("Route mapping lifecycle", func() {
		It("creates a route mapping on a specified port", func() {
			updateProcessPath := fmt.Sprintf("/v3/processes/%s", webProcess.Guid)
			setPortBody := `{"ports": [1234], "health_check": {"type": "process"}}`

			Expect(cf.Cf("curl", updateProcessPath, "-X", "PATCH", "-d", setPortBody).Wait(Config.DefaultTimeoutDuration())).To(Exit(0))

			getRoutePath := fmt.Sprintf("/v2/routes?q=host:%s", appName)
			routeBody := cf.Cf("curl", getRoutePath).Wait(Config.DefaultTimeoutDuration()).Out.Contents()

			var routeJSON RouteList
			json.Unmarshal([]byte(routeBody), &routeJSON)
			routeGuid := routeJSON.Resources[0].Metadata.Guid
			addRouteBody := fmt.Sprintf(`
				{
					"relationships": {
						"app":   {"guid": "%s"},
						"route": {"guid": "%s"}
					},
					"app_port": 1234
				}`, appGuid, routeGuid)

			Expect(cf.Cf("curl", "/v3/route_mappings", "-X", "POST", "-d", addRouteBody).Wait(Config.DefaultTimeoutDuration())).To(Exit(0))

			StartApp(appGuid)
			Expect(string(cf.Cf("apps").Wait(Config.DefaultTimeoutDuration()).Out.Contents())).To(MatchRegexp(fmt.Sprintf("(v3-)?(%s)*(-web)?(\\s)+(started)", webProcess.Name)))

			Eventually(func() string {
				return helpers.CurlAppRoot(Config, appName)
			}, Config.DefaultTimeoutDuration()).Should(ContainSubstring("Hi, I'm Dora!"))
		})
	})
})
<commit_msg>update v3 route mapping test to not request ports in processes and route mappings<commit_after>package v3

import (
	"encoding/json"
	"fmt"

	. "github.com/cloudfoundry/cf-acceptance-tests/cats_suite_helpers"

	"github.com/cloudfoundry-incubator/cf-test-helpers/cf"
	"github.com/cloudfoundry-incubator/cf-test-helpers/helpers"
	"github.com/cloudfoundry/cf-acceptance-tests/helpers/assets"
	"github.com/cloudfoundry/cf-acceptance-tests/helpers/random_name"
	. "github.com/cloudfoundry/cf-acceptance-tests/helpers/v3_helpers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gexec"
)

var _ = V3Describe("route_mapping", func() {
	type RouteList struct {
		Resources []struct {
			Metadata struct {
				Guid string `json:"guid"`
			} `json:"metadata"`
		} `json:"resources"`
	}

	var (
		appName     string
		appGuid     string
		packageGuid string
		spaceGuid   string
		spaceName   string
		token       string
		webProcess  Process
	)

	BeforeEach(func() {
		appName = random_name.CATSRandomName("APP")
		spaceName = TestSetup.RegularUserContext().Space
		spaceGuid = GetSpaceGuidFromName(spaceName)
		appGuid = CreateApp(appName, spaceGuid, `{"foo":"bar"}`)
		packageGuid = CreatePackage(appGuid)
		token = GetAuthToken()
		uploadUrl := fmt.Sprintf("%s%s/v3/packages/%s/upload", Config.Protocol(), Config.GetApiEndpoint(), packageGuid)

		UploadPackage(uploadUrl, assets.NewAssets().DoraZip, token)
		WaitForPackageToBeReady(packageGuid)

		dropletGuid := StageBuildpackPackage(packageGuid, Config.GetRubyBuildpackName())
		WaitForDropletToStage(dropletGuid)
		AssignDropletToApp(appGuid, dropletGuid)

		processes := GetProcesses(appGuid, appName)
		webProcess = GetProcessByType(processes, "web")

		CreateRoute(spaceName, Config.GetAppsDomain(), appName)
	})

	AfterEach(func() {
		FetchRecentLogs(appGuid, token, Config)
		DeleteApp(appGuid)
	})

	Describe("Route mapping lifecycle", func() {
		It("creates a route mapping", func() {
			updateProcessPath := fmt.Sprintf("/v3/processes/%s", webProcess.Guid)
			setHealthCheckBody := `{"health_check": {"type": "process"}}`

			Expect(cf.Cf("curl", updateProcessPath, "-X", "PATCH", "-d", setHealthCheckBody).Wait(Config.DefaultTimeoutDuration())).To(Exit(0))

			getRoutePath := fmt.Sprintf("/v2/routes?q=host:%s", appName)
			routeBody := cf.Cf("curl", getRoutePath).Wait(Config.DefaultTimeoutDuration()).Out.Contents()

			var routeJSON RouteList
			json.Unmarshal([]byte(routeBody), &routeJSON)
			routeGuid := routeJSON.Resources[0].Metadata.Guid
			addRouteBody := fmt.Sprintf(`
				{
					"relationships": {
						"app":   {"guid": "%s"},
						"route": {"guid": "%s"}
					}
				}`, appGuid, routeGuid)

			Expect(cf.Cf("curl", "/v3/route_mappings", "-X", "POST", "-d", addRouteBody).Wait(Config.DefaultTimeoutDuration())).To(Exit(0))

			StartApp(appGuid)
			Expect(string(cf.Cf("apps").Wait(Config.DefaultTimeoutDuration()).Out.Contents())).To(MatchRegexp(fmt.Sprintf("(v3-)?(%s)*(-web)?(\\s)+(started)", webProcess.Name)))

			Eventually(func() string {
				return helpers.CurlAppRoot(Config, appName)
			}, Config.DefaultTimeoutDuration()).Should(ContainSubstring("Hi, I'm Dora!"))
		})
	})
})
<|endoftext|>