<commit_before>package client_fakes

import (
	"bytes"
	"errors"
	"fmt"
	"os"
	"path/filepath"

	services "github.com/maximilien/softlayer-go/services"
	softlayer "github.com/maximilien/softlayer-go/softlayer"
)

const (
	SOFTLAYER_API_URL  = "api.softlayer.com/rest/v3"
	TEMPLATE_ROOT_PATH = "templates"
)

type FakeSoftLayerClient struct {
	Username string
	ApiKey   string

	TemplatePath string

	SoftLayerServices map[string]softlayer.Service

	DoRawHttpRequestResponseCount int

	DoRawHttpRequestResponse       []byte
	DoRawHttpRequestResponses      [][]byte
	DoRawHttpRequestResponsesIndex int
	DoRawHttpRequestError          error
	DoRawHttpRequestPath           string
	DoRawHttpRequestRequestType    string

	GenerateRequestBodyBuffer *bytes.Buffer
	GenerateRequestBodyError  error

	HasErrorsError, CheckForHttpResponseError error
}

func NewFakeSoftLayerClient(username, apiKey string) *FakeSoftLayerClient {
	pwd, _ := os.Getwd()
	fslc := &FakeSoftLayerClient{
		Username: username,
		ApiKey:   apiKey,

		TemplatePath: filepath.Join(pwd, TEMPLATE_ROOT_PATH),

		SoftLayerServices: map[string]softlayer.Service{},

		DoRawHttpRequestResponseCount: 0,

		DoRawHttpRequestResponse:       nil,
		DoRawHttpRequestResponses:      [][]byte{},
		DoRawHttpRequestResponsesIndex: 0,
		DoRawHttpRequestError:          nil,
		DoRawHttpRequestPath:           "",
		DoRawHttpRequestRequestType:    "",

		GenerateRequestBodyBuffer: new(bytes.Buffer),
		GenerateRequestBodyError:  nil,

		HasErrorsError:            nil,
		CheckForHttpResponseError: nil,
	}

	fslc.initSoftLayerServices()

	return fslc
}

//softlayer.Client interface methods

func (fslc *FakeSoftLayerClient) GetService(serviceName string) (softlayer.Service, error) {
	slService, ok := fslc.SoftLayerServices[serviceName]
	if !ok {
		return nil, errors.New(fmt.Sprintf("softlayer-go does not support service '%s'", serviceName))
	}

	return slService, nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Account_Service() (softlayer.SoftLayer_Account_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Account")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Account_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Virtual_Guest_Service() (softlayer.SoftLayer_Virtual_Guest_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Virtual_Guest")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Virtual_Guest_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Dns_Domain_Service() (softlayer.SoftLayer_Dns_Domain_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Dns_Domain")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Dns_Domain_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Virtual_Disk_Image_Service() (softlayer.SoftLayer_Virtual_Disk_Image_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Virtual_Disk_Image")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Virtual_Disk_Image_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Security_Ssh_Key_Service() (softlayer.SoftLayer_Security_Ssh_Key_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Security_Ssh_Key")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Security_Ssh_Key_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Network_Storage_Service() (softlayer.SoftLayer_Network_Storage_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Network_Storage")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Network_Storage_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Network_Storage_Allowed_Host_Service() (softlayer.SoftLayer_Network_Storage_Allowed_Host_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Network_Storage_Allowed_Host")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Network_Storage_Allowed_Host_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Product_Order_Service() (softlayer.SoftLayer_Product_Order_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Product_Order")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Product_Order_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Product_Package_Service() (softlayer.SoftLayer_Product_Package_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Product_Package")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Product_Package_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Billing_Item_Cancellation_Request_Service() (softlayer.SoftLayer_Billing_Item_Cancellation_Request_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Billing_Item_Cancellation_Request")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Billing_Item_Cancellation_Request_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Virtual_Guest_Block_Device_Template_Group_Service() (softlayer.SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Virtual_Guest_Block_Device_Template_Group")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Hardware_Service() (softlayer.SoftLayer_Hardware_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Hardware")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Hardware_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Dns_Domain_Record_Service() (softlayer.SoftLayer_Dns_Domain_Record_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Dns_Domain_ResourceRecord")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Dns_Domain_Record_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_SoftLayer_Dns_Domain_Record_SRV_Service() (softlayer.SoftLayer_Dns_Domain_Record_SRV_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Dns_Domain_ResourceRecord_SrvType")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Dns_Domain_Record_SRV_Service), nil
}

//Public methods
func (fslc *FakeSoftLayerClient) DoRawHttpRequestWithObjectMask(path string, masks []string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
	fslc.DoRawHttpRequestPath = path
	fslc.DoRawHttpRequestRequestType = requestType

	fslc.DoRawHttpRequestResponseCount += 1

	if fslc.DoRawHttpRequestError != nil {
		return []byte{}, fslc.DoRawHttpRequestError
	}

	if fslc.DoRawHttpRequestResponse != nil {
		return fslc.DoRawHttpRequestResponse, fslc.DoRawHttpRequestError
	} else {
		fslc.DoRawHttpRequestResponsesIndex = fslc.DoRawHttpRequestResponsesIndex + 1
		return fslc.DoRawHttpRequestResponses[fslc.DoRawHttpRequestResponsesIndex-1], fslc.DoRawHttpRequestError
	}
}

func (fslc *FakeSoftLayerClient) DoRawHttpRequestWithObjectFilter(path string, filters string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
	fslc.DoRawHttpRequestPath = path
	fslc.DoRawHttpRequestRequestType = requestType

	fslc.DoRawHttpRequestResponseCount += 1

	if fslc.DoRawHttpRequestError != nil {
		return []byte{}, fslc.DoRawHttpRequestError
	}

	if fslc.DoRawHttpRequestResponse != nil {
		return fslc.DoRawHttpRequestResponse, fslc.DoRawHttpRequestError
	} else {
		fslc.DoRawHttpRequestResponsesIndex = fslc.DoRawHttpRequestResponsesIndex + 1
		return fslc.DoRawHttpRequestResponses[fslc.DoRawHttpRequestResponsesIndex-1], fslc.DoRawHttpRequestError
	}
}

func (fslc *FakeSoftLayerClient) DoRawHttpRequestWithObjectFilterAndObjectMask(path string, masks []string, filters string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
	fslc.DoRawHttpRequestPath = path
	fslc.DoRawHttpRequestRequestType = requestType

	fslc.DoRawHttpRequestResponseCount += 1

	if fslc.DoRawHttpRequestError != nil {
		return []byte{}, fslc.DoRawHttpRequestError
	}

	if fslc.DoRawHttpRequestResponse != nil {
		return fslc.DoRawHttpRequestResponse, fslc.DoRawHttpRequestError
	} else {
		fslc.DoRawHttpRequestResponsesIndex = fslc.DoRawHttpRequestResponsesIndex + 1
		return fslc.DoRawHttpRequestResponses[fslc.DoRawHttpRequestResponsesIndex-1], fslc.DoRawHttpRequestError
	}
}

func (fslc *FakeSoftLayerClient) DoRawHttpRequest(path string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
	fslc.DoRawHttpRequestPath = path
	fslc.DoRawHttpRequestRequestType = requestType

	fslc.DoRawHttpRequestResponseCount += 1

	if fslc.DoRawHttpRequestError != nil {
		return []byte{}, fslc.DoRawHttpRequestError
	}

	if fslc.DoRawHttpRequestResponse != nil {
		return fslc.DoRawHttpRequestResponse, fslc.DoRawHttpRequestError
	} else {
		fslc.DoRawHttpRequestResponsesIndex = fslc.DoRawHttpRequestResponsesIndex + 1
		return fslc.DoRawHttpRequestResponses[fslc.DoRawHttpRequestResponsesIndex-1], fslc.DoRawHttpRequestError
	}
}

func (fslc *FakeSoftLayerClient) GenerateRequestBody(templateData interface{}) (*bytes.Buffer, error) {
	return fslc.GenerateRequestBodyBuffer, fslc.GenerateRequestBodyError
}

func (fslc *FakeSoftLayerClient) HasErrors(body map[string]interface{}) error {
	return fslc.HasErrorsError
}

func (fslc *FakeSoftLayerClient) CheckForHttpResponseErrors(data []byte) error {
	return fslc.CheckForHttpResponseError
}

//Private methods

func (fslc *FakeSoftLayerClient) initSoftLayerServices() {
	fslc.SoftLayerServices["SoftLayer_Account"] = services.NewSoftLayer_Account_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Virtual_Guest"] = services.NewSoftLayer_Virtual_Guest_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Virtual_Disk_Image"] = services.NewSoftLayer_Virtual_Disk_Image_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Security_Ssh_Key"] = services.NewSoftLayer_Security_Ssh_Key_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Network_Storage"] = services.NewSoftLayer_Network_Storage_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Network_Storage_Allowed_Host"] = services.NewSoftLayer_Network_Storage_Allowed_Host_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Product_Order"] = services.NewSoftLayer_Product_Order_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Product_Package"] = services.NewSoftLayer_Product_Package_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Billing_Item_Cancellation_Request"] = services.NewSoftLayer_Billing_Item_Cancellation_Request_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Virtual_Guest_Block_Device_Template_Group"] = services.NewSoftLayer_Virtual_Guest_Block_Device_Template_Group_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Hardware"] = services.NewSoftLayer_Hardware_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Dns_Domain"] = services.NewSoftLayer_Dns_Domain_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Dns_Domain_ResourceRecord"] = services.NewSoftLayer_Dns_Domain_Record_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Dns_Domain_ResourceRecord_SrvType"] = services.NewSoftLayer_Dns_Domain_Record_SRV_Service(fslc)
}
<commit_msg>Update softlayer_client_fake.go<commit_after>package client_fakes

import (
	"bytes"
	"errors"
	"fmt"
	"os"
	"path/filepath"

	services "github.com/maximilien/softlayer-go/services"
	softlayer "github.com/maximilien/softlayer-go/softlayer"
)

const (
	SOFTLAYER_API_URL  = "api.softlayer.com/rest/v3"
	TEMPLATE_ROOT_PATH = "templates"
)

type FakeSoftLayerClient struct {
	Username string
	ApiKey   string

	TemplatePath string

	SoftLayerServices map[string]softlayer.Service

	DoRawHttpRequestResponseCount int

	DoRawHttpRequestResponse       []byte
	DoRawHttpRequestResponses      [][]byte
	DoRawHttpRequestResponsesIndex int
	DoRawHttpRequestError          error
	DoRawHttpRequestPath           string
	DoRawHttpRequestRequestType    string

	GenerateRequestBodyBuffer *bytes.Buffer
	GenerateRequestBodyError  error

	HasErrorsError, CheckForHttpResponseError error
}

func NewFakeSoftLayerClient(username, apiKey string) *FakeSoftLayerClient {
	pwd, _ := os.Getwd()
	fslc := &FakeSoftLayerClient{
		Username: username,
		ApiKey:   apiKey,

		TemplatePath: filepath.Join(pwd, TEMPLATE_ROOT_PATH),

		SoftLayerServices: map[string]softlayer.Service{},

		DoRawHttpRequestResponseCount: 0,

		DoRawHttpRequestResponse:       nil,
		DoRawHttpRequestResponses:      [][]byte{},
		DoRawHttpRequestResponsesIndex: 0,
		DoRawHttpRequestError:          nil,
		DoRawHttpRequestPath:           "",
		DoRawHttpRequestRequestType:    "",

		GenerateRequestBodyBuffer: new(bytes.Buffer),
		GenerateRequestBodyError:  nil,

		HasErrorsError:            nil,
		CheckForHttpResponseError: nil,
	}

	fslc.initSoftLayerServices()

	return fslc
}

//softlayer.Client interface methods

func (fslc *FakeSoftLayerClient) GetService(serviceName string) (softlayer.Service, error) {
	slService, ok := fslc.SoftLayerServices[serviceName]
	if !ok {
		return nil, errors.New(fmt.Sprintf("softlayer-go does not support service '%s'", serviceName))
	}

	return slService, nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Account_Service() (softlayer.SoftLayer_Account_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Account")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Account_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Virtual_Guest_Service() (softlayer.SoftLayer_Virtual_Guest_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Virtual_Guest")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Virtual_Guest_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Dns_Domain_Service() (softlayer.SoftLayer_Dns_Domain_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Dns_Domain")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Dns_Domain_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Virtual_Disk_Image_Service() (softlayer.SoftLayer_Virtual_Disk_Image_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Virtual_Disk_Image")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Virtual_Disk_Image_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Security_Ssh_Key_Service() (softlayer.SoftLayer_Security_Ssh_Key_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Security_Ssh_Key")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Security_Ssh_Key_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Network_Storage_Service() (softlayer.SoftLayer_Network_Storage_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Network_Storage")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Network_Storage_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Network_Storage_Allowed_Host_Service() (softlayer.SoftLayer_Network_Storage_Allowed_Host_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Network_Storage_Allowed_Host")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Network_Storage_Allowed_Host_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Product_Order_Service() (softlayer.SoftLayer_Product_Order_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Product_Order")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Product_Order_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Product_Package_Service() (softlayer.SoftLayer_Product_Package_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Product_Package")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Product_Package_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Billing_Item_Cancellation_Request_Service() (softlayer.SoftLayer_Billing_Item_Cancellation_Request_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Billing_Item_Cancellation_Request")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Billing_Item_Cancellation_Request_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Virtual_Guest_Block_Device_Template_Group_Service() (softlayer.SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Virtual_Guest_Block_Device_Template_Group")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Virtual_Guest_Block_Device_Template_Group_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Hardware_Service() (softlayer.SoftLayer_Hardware_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Hardware")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Hardware_Service), nil
}

func (fslc *FakeSoftLayerClient) GetSoftLayer_Dns_Domain_Record_Service() (softlayer.SoftLayer_Dns_Domain_Record_Service, error) {
	slService, err := fslc.GetService("SoftLayer_Dns_Domain_ResourceRecord")
	if err != nil {
		return nil, err
	}

	return slService.(softlayer.SoftLayer_Dns_Domain_Record_Service), nil
}

//Public methods
func (fslc *FakeSoftLayerClient) DoRawHttpRequestWithObjectMask(path string, masks []string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
	fslc.DoRawHttpRequestPath = path
	fslc.DoRawHttpRequestRequestType = requestType

	fslc.DoRawHttpRequestResponseCount += 1

	if fslc.DoRawHttpRequestError != nil {
		return []byte{}, fslc.DoRawHttpRequestError
	}

	if fslc.DoRawHttpRequestResponse != nil {
		return fslc.DoRawHttpRequestResponse, fslc.DoRawHttpRequestError
	} else {
		fslc.DoRawHttpRequestResponsesIndex = fslc.DoRawHttpRequestResponsesIndex + 1
		return fslc.DoRawHttpRequestResponses[fslc.DoRawHttpRequestResponsesIndex-1], fslc.DoRawHttpRequestError
	}
}

func (fslc *FakeSoftLayerClient) DoRawHttpRequestWithObjectFilter(path string, filters string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
	fslc.DoRawHttpRequestPath = path
	fslc.DoRawHttpRequestRequestType = requestType

	fslc.DoRawHttpRequestResponseCount += 1

	if fslc.DoRawHttpRequestError != nil {
		return []byte{}, fslc.DoRawHttpRequestError
	}

	if fslc.DoRawHttpRequestResponse != nil {
		return fslc.DoRawHttpRequestResponse, fslc.DoRawHttpRequestError
	} else {
		fslc.DoRawHttpRequestResponsesIndex = fslc.DoRawHttpRequestResponsesIndex + 1
		return fslc.DoRawHttpRequestResponses[fslc.DoRawHttpRequestResponsesIndex-1], fslc.DoRawHttpRequestError
	}
}

func (fslc *FakeSoftLayerClient) DoRawHttpRequestWithObjectFilterAndObjectMask(path string, masks []string, filters string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
	fslc.DoRawHttpRequestPath = path
	fslc.DoRawHttpRequestRequestType = requestType

	fslc.DoRawHttpRequestResponseCount += 1

	if fslc.DoRawHttpRequestError != nil {
		return []byte{}, fslc.DoRawHttpRequestError
	}

	if fslc.DoRawHttpRequestResponse != nil {
		return fslc.DoRawHttpRequestResponse, fslc.DoRawHttpRequestError
	} else {
		fslc.DoRawHttpRequestResponsesIndex = fslc.DoRawHttpRequestResponsesIndex + 1
		return fslc.DoRawHttpRequestResponses[fslc.DoRawHttpRequestResponsesIndex-1], fslc.DoRawHttpRequestError
	}
}

func (fslc *FakeSoftLayerClient) DoRawHttpRequest(path string, requestType string, requestBody *bytes.Buffer) ([]byte, error) {
	fslc.DoRawHttpRequestPath = path
	fslc.DoRawHttpRequestRequestType = requestType

	fslc.DoRawHttpRequestResponseCount += 1

	if fslc.DoRawHttpRequestError != nil {
		return []byte{}, fslc.DoRawHttpRequestError
	}

	if fslc.DoRawHttpRequestResponse != nil {
		return fslc.DoRawHttpRequestResponse, fslc.DoRawHttpRequestError
	} else {
		fslc.DoRawHttpRequestResponsesIndex = fslc.DoRawHttpRequestResponsesIndex + 1
		return fslc.DoRawHttpRequestResponses[fslc.DoRawHttpRequestResponsesIndex-1], fslc.DoRawHttpRequestError
	}
}

func (fslc *FakeSoftLayerClient) GenerateRequestBody(templateData interface{}) (*bytes.Buffer, error) {
	return fslc.GenerateRequestBodyBuffer, fslc.GenerateRequestBodyError
}

func (fslc *FakeSoftLayerClient) HasErrors(body map[string]interface{}) error {
	return fslc.HasErrorsError
}

func (fslc *FakeSoftLayerClient) CheckForHttpResponseErrors(data []byte) error {
	return fslc.CheckForHttpResponseError
}

//Private methods

func (fslc *FakeSoftLayerClient) initSoftLayerServices() {
	fslc.SoftLayerServices["SoftLayer_Account"] = services.NewSoftLayer_Account_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Virtual_Guest"] = services.NewSoftLayer_Virtual_Guest_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Virtual_Disk_Image"] = services.NewSoftLayer_Virtual_Disk_Image_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Security_Ssh_Key"] = services.NewSoftLayer_Security_Ssh_Key_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Network_Storage"] = services.NewSoftLayer_Network_Storage_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Network_Storage_Allowed_Host"] = services.NewSoftLayer_Network_Storage_Allowed_Host_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Product_Order"] = services.NewSoftLayer_Product_Order_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Product_Package"] = services.NewSoftLayer_Product_Package_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Billing_Item_Cancellation_Request"] = services.NewSoftLayer_Billing_Item_Cancellation_Request_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Virtual_Guest_Block_Device_Template_Group"] = services.NewSoftLayer_Virtual_Guest_Block_Device_Template_Group_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Hardware"] = services.NewSoftLayer_Hardware_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Dns_Domain"] = services.NewSoftLayer_Dns_Domain_Service(fslc)
	fslc.SoftLayerServices["SoftLayer_Dns_Domain_ResourceRecord"] = services.NewSoftLayer_Dns_Domain_Record_Service(fslc)
}
<|endoftext|>


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

// Package main contains a simple command line tool for DistanceMatrix
// Directions docs: https://developers.google.com/maps/documentation/distancematrix/
package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"

	"github.com/kr/pretty"
	"google.golang.org/maps"
)

var (
	apiKey                   = flag.String("key", "", "API Key for using Google Maps API.")
	origins                  = flag.String("origins", "", "One or more addresses and/or textual latitude/longitude values, separated with the pipe (|) character, from which to calculate distance and time.")
	destinations             = flag.String("destinations", "", "One or more addresses and/or textual latitude/longitude values, separated with the pipe (|) character, to which to calculate distance and time.")
	mode                     = flag.String("mode", "", "Specifies the mode of transport to use when calculating distance.")
	language                 = flag.String("language", "", "The language in which to return results.")
	avoid                    = flag.String("avoid", "", "Introduces restrictions to the route.")
	units                    = flag.String("units", "", "Specifies the unit system to use when expressing distance as text.")
	departureTime            = flag.String("departure_time", "", "The desired time of departure.")
	arrivalTime              = flag.String("arrival_time", "", "Specifies the desired time of arrival.")
	transitMode              = flag.String("transit_mode", "", "Specifies one or more preferred modes of transit.")
	transitRoutingPreference = flag.String("transit_routing_preference", "", "Specifies preferences for transit requests.")
)

func usageAndExit(msg string) {
	fmt.Fprintln(os.Stderr, msg)
	fmt.Println("Flags:")
	flag.PrintDefaults()
	os.Exit(2)
}

func main() {
	flag.Parse()
	client := &http.Client{}
	if *apiKey == "" {
		usageAndExit("Please specify an API Key.")
	}
	ctx := maps.NewContext(*apiKey, client)

	r := &maps.DistanceMatrixRequest{
		Language:      *language,
		DepartureTime: *departureTime,
		ArrivalTime:   *arrivalTime,
	}

	if *origins != "" {
		r.Origins = strings.Split(*origins, "|")
	}
	if *destinations != "" {
		r.Destinations = strings.Split(*destinations, "|")
	}

	lookupMode(*mode, r)
	lookupAvoid(*avoid, r)
	lookupUnits(*units, r)
	lookupTransitMode(*transitMode, r)
	lookupTransitRoutingPreference(*transitRoutingPreference, r)

	pretty.Println(r)

	resp, err := r.Get(ctx)
	if err != nil {
		log.Fatalf("Fatal error: %s", err)
	}

	pretty.Println(resp)
}

func lookupMode(mode string, r *maps.DistanceMatrixRequest) {
	if mode != "" {
		switch {
		case mode == "driving":
			r.Mode = maps.TravelModeDriving
		case mode == "walking":
			r.Mode = maps.TravelModeWalking
		case mode == "bicycling":
			r.Mode = maps.TravelModeBicycling
		case mode == "transit":
			r.Mode = maps.TravelModeTransit
		default:
			log.Fatalf("Unknown mode %s", mode)
		}
	}
}

func lookupAvoid(avoid string, r *maps.DistanceMatrixRequest) {
	if avoid != "" {
		switch {
		case avoid == "tolls":
			r.Avoid = maps.AvoidTolls
		case avoid == "highways":
			r.Avoid = maps.AvoidHighways
		case avoid == "ferries":
			r.Avoid = maps.AvoidFerries
		default:
			log.Fatalf("Unknown avoid restriction %s", avoid)
		}
	}
}

func lookupUnits(units string, r *maps.DistanceMatrixRequest) {
	if units != "" {
		switch {
		case units == "metric":
			r.Units = maps.UnitsMetric
		case units == "imperial":
			r.Units = maps.UnitsImperial
		default:
			log.Fatalf("Unknown units %s", units)
		}
	}
}

func lookupTransitMode(transitMode string, r *maps.DistanceMatrixRequest) {
	if transitMode != "" {
		switch {
		case transitMode == "bus":
			r.TransitMode = maps.TransitModeBus
		case transitMode == "subway":
			r.TransitMode = maps.TransitModeSubway
		case transitMode == "train":
			r.TransitMode = maps.TransitModeTrain
		case transitMode == "tram":
			r.TransitMode = maps.TransitModeTram
		case transitMode == "rail":
			r.TransitMode = maps.TransitModeRail
		default:
			log.Fatalf("Unknown transit_mode %s", transitMode)
		}
	}
}

func lookupTransitRoutingPreference(transitRoutingPreference string, r *maps.DistanceMatrixRequest) {
	if transitRoutingPreference != "" {
		switch {
		case transitRoutingPreference == "fewer_transfers":
			r.TransitRoutingPreference = maps.TransitRoutingPreferenceFewerTransfers
		case transitRoutingPreference == "less_walking":
			r.TransitRoutingPreference = maps.TransitRoutingPreferenceLessWalking
		default:
			log.Fatalf("Unknown transit_routing_preference %s", transitRoutingPreference)
		}
	}
}
<commit_msg>Minor cleanup<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package main contains a simple command line tool for DistanceMatrix
// Directions docs: https://developers.google.com/maps/documentation/distancematrix/
package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"

	"github.com/kr/pretty"
	"google.golang.org/maps"
)

var (
	apiKey                   = flag.String("key", "", "API Key for using Google Maps API.")
	origins                  = flag.String("origins", "", "One or more addresses and/or textual latitude/longitude values, separated with the pipe (|) character, from which to calculate distance and time.")
	destinations             = flag.String("destinations", "", "One or more addresses and/or textual latitude/longitude values, separated with the pipe (|) character, to which to calculate distance and time.")
	mode                     = flag.String("mode", "", "Specifies the mode of transport to use when calculating distance.")
	language                 = flag.String("language", "", "The language in which to return results.")
	avoid                    = flag.String("avoid", "", "Introduces restrictions to the route.")
	units                    = flag.String("units", "", "Specifies the unit system to use when expressing distance as text.")
	departureTime            = flag.String("departure_time", "", "The desired time of departure.")
	arrivalTime              = flag.String("arrival_time", "", "Specifies the desired time of arrival.")
	transitMode              = flag.String("transit_mode", "", "Specifies one or more preferred modes of transit.")
	transitRoutingPreference = flag.String("transit_routing_preference", "", "Specifies preferences for transit requests.")
)

func usageAndExit(msg string) {
	fmt.Fprintln(os.Stderr, msg)
	fmt.Println("Flags:")
	flag.PrintDefaults()
	os.Exit(2)
}

func main() {
	flag.Parse()
	client := &http.Client{}
	if *apiKey == "" {
		usageAndExit("Please specify an API Key.")
	}
	ctx := maps.NewContext(*apiKey, client)

	r := &maps.DistanceMatrixRequest{
		Language:      *language,
		DepartureTime: *departureTime,
		ArrivalTime:   *arrivalTime,
	}

	if *origins != "" {
		r.Origins = strings.Split(*origins, "|")
	}
	if *destinations != "" {
		r.Destinations = strings.Split(*destinations, "|")
	}

	lookupMode(*mode, r)
	lookupAvoid(*avoid, r)
	lookupUnits(*units, r)
	lookupTransitMode(*transitMode, r)
	lookupTransitRoutingPreference(*transitRoutingPreference, r)

	pretty.Println(r)

	resp, err := r.Get(ctx)
	if err != nil {
		log.Fatalf("fatal error: %s", err)
	}

	pretty.Println(resp)
}

func lookupMode(mode string, r *maps.DistanceMatrixRequest) {
	if mode != "" {
		switch {
		case mode == "driving":
			r.Mode = maps.TravelModeDriving
		case mode == "walking":
			r.Mode = maps.TravelModeWalking
		case mode == "bicycling":
			r.Mode = maps.TravelModeBicycling
		case mode == "transit":
			r.Mode = maps.TravelModeTransit
		default:
			log.Fatalf("Unknown mode %s", mode)
		}
	}
}

func lookupAvoid(avoid string, r *maps.DistanceMatrixRequest) {
	if avoid != "" {
		switch {
		case avoid == "tolls":
			r.Avoid = maps.AvoidTolls
		case avoid == "highways":
			r.Avoid = maps.AvoidHighways
		case avoid == "ferries":
			r.Avoid = maps.AvoidFerries
		default:
			log.Fatalf("Unknown avoid restriction %s", avoid)
		}
	}
}

func lookupUnits(units string, r *maps.DistanceMatrixRequest) {
	if units != "" {
		switch {
		case units == "metric":
			r.Units = maps.UnitsMetric
		case units == "imperial":
			r.Units = maps.UnitsImperial
		default:
			log.Fatalf("Unknown units %s", units)
		}
	}
}

func lookupTransitMode(transitMode string, r *maps.DistanceMatrixRequest) {
	if transitMode != "" {
		switch {
		case transitMode == "bus":
			r.TransitMode = maps.TransitModeBus
		case transitMode == "subway":
			r.TransitMode = maps.TransitModeSubway
		case transitMode == "train":
			r.TransitMode = maps.TransitModeTrain
		case transitMode == "tram":
			r.TransitMode = maps.TransitModeTram
		case transitMode == "rail":
			r.TransitMode = maps.TransitModeRail
		default:
			log.Fatalf("Unknown transit_mode %s", transitMode)
		}
	}
}

func lookupTransitRoutingPreference(transitRoutingPreference string, r *maps.DistanceMatrixRequest) {
	if transitRoutingPreference != "" {
		switch {
		case transitRoutingPreference == "fewer_transfers":
			r.TransitRoutingPreference = maps.TransitRoutingPreferenceFewerTransfers
		case transitRoutingPreference == "less_walking":
			r.TransitRoutingPreference = maps.TransitRoutingPreferenceLessWalking
		default:
			log.Fatalf("Unknown transit_routing_preference %s", transitRoutingPreference)
		}
	}
}
<|endoftext|>


<commit_before>// Router for Upwork API
//
// Licensed under the Upwork's API Terms of Use;
// you may not use this file except in compliance with the Terms.
//
// 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.
//
// Author::    Maksym Novozhylov (mnovozhilov@upwork.com)
// Copyright:: Copyright 2016(c) Upwork.com
// License::   See LICENSE.txt and TOS - https://developers.upwork.com/api-tos.html
package messages

import (
    "net/http"
    "github.com/upwork/golang-upwork/api"
)

const (
    EntryPoint = "api"
)

type a struct {
    client api.ApiClient
}

// Constructor
func New(c api.ApiClient) (a) {
    var r a
    c.SetEntryPoint(EntryPoint)
    r.client = c

    return r
}

// Retrive rooms information
func (r a) GetRooms(company string) (*http.Response, []byte) {
    return r.client.Get("/messages/v3/" + company + "/rooms", nil)
}

// Get a specific room information
func (r a) GetRoomDetails(company string, roomId string, params map[string]string) (*http.Response, []byte) {
    return r.client.Get("/messages/v3/" + company + "/rooms/" + roomId, params)
}

// Get a specific room by offer ID
func (r a) GetRoomByOffer(company string, offerId string, params map[string]string) (*http.Response, []byte) {
    return r.client.Get("/messages/v3/" + company + "/rooms/offers/" + offerId, params)
}

// Get a specific room by application ID
func (r a) GetRoomByApplication(company string, applicationId string, params map[string]string) (*http.Response, []byte) {
    return r.client.Get("/messages/v3/" + company + "/rooms/applications/" + applicationId, params)
}

// Get a specific room by contract ID
func (r a) GetRoomByContract(company string, contractId string, params map[string]string) (*http.Response, []byte) {
    return r.client.Get("/messages/v3/" + company + "/rooms/contracts/" + contractId, params)
}

// Create a new room
func (r a) CreateRoom(company string, params map[string]string) (*http.Response, []byte) {
    return r.client.Post("/messages/v3/" + company + "/rooms", params)
}

// Send a message to a room
func (r a) SendMessageToRoom(company string, roomId string, params map[string]string) (*http.Response, []byte) {
    return r.client.Post("/messages/v3/" + company + "/rooms/" + roomId + "/stories", params)
}

// Update a room settings
func (r a) UpdateRoomSettings(company string, roomId string, username string, params map[string]string) (*http.Response, []byte) {
    return r.client.Put("/messages/v3/" + company + "/rooms/" + roomId + "/users/" + username, params)
}

// Update the metadata of a room
func (r a) UpdateRoomMetadata(company string, roomId string, params map[string]string) (*http.Response, []byte) {
    return r.client.Put("/messages/v3/" + company + "/rooms/" + roomId, params)
}
<commit_msg>v1.2.0<commit_after>// Router for Upwork API
//
// Licensed under the Upwork's API Terms of Use;
// you may not use this file except in compliance with the Terms.
//
// 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.
//
// Author::    Maksym Novozhylov (mnovozhilov@upwork.com)
// Copyright:: Copyright 2016(c) Upwork.com
// License::   See LICENSE.txt and TOS - https://developers.upwork.com/api-tos.html
package messages

import (
    "net/http"
    "github.com/upwork/golang-upwork/api"
)

const (
    EntryPoint = "api"
)

type a struct {
    client api.ApiClient
}

// Constructor
func New(c api.ApiClient) (a) {
    var r a
    c.SetEntryPoint(EntryPoint)
    r.client = c

    return r
}

// Retrieve rooms information
func (r a) GetRooms(company string, params map[string]string) (*http.Response, []byte) {
    return r.client.Get("/messages/v3/" + company + "/rooms", params)
}

// Get a specific room information
func (r a) GetRoomDetails(company string, roomId string, params map[string]string) (*http.Response, []byte) {
    return r.client.Get("/messages/v3/" + company + "/rooms/" + roomId, params)
}

// Get a specific room by offer ID
func (r a) GetRoomByOffer(company string, offerId string, params map[string]string) (*http.Response, []byte) {
    return r.client.Get("/messages/v3/" + company + "/rooms/offers/" + offerId, params)
}

// Get a specific room by application ID
func (r a) GetRoomByApplication(company string, applicationId string, params map[string]string) (*http.Response, []byte) {
    return r.client.Get("/messages/v3/" + company + "/rooms/applications/" + applicationId, params)
}

// Get a specific room by contract ID
func (r a) GetRoomByContract(company string, contractId string, params map[string]string) (*http.Response, []byte) {
    return r.client.Get("/messages/v3/" + company + "/rooms/contracts/" + contractId, params)
}

// Create a new room
func (r a) CreateRoom(company string, params map[string]string) (*http.Response, []byte) {
    return r.client.Post("/messages/v3/" + company + "/rooms", params)
}

// Send a message to a room
func (r a) SendMessageToRoom(company string, roomId string, params map[string]string) (*http.Response, []byte) {
    return r.client.Post("/messages/v3/" + company + "/rooms/" + roomId + "/stories", params)
}

// Update a room settings
func (r a) UpdateRoomSettings(company string, roomId string, username string, params map[string]string) (*http.Response, []byte) {
    return r.client.Put("/messages/v3/" + company + "/rooms/" + roomId + "/users/" + username, params)
}

// Update the metadata of a room
func (r a) UpdateRoomMetadata(company string, roomId string, params map[string]string) (*http.Response, []byte) {
    return r.client.Put("/messages/v3/" + company + "/rooms/" + roomId, params)
}
<|endoftext|>


<commit_before>package acceptance_test

import (
	"cf-pusher/cf_cli_adapter"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"strings"

	"github.com/cloudfoundry-incubator/cf-test-helpers/cf"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gexec"
	"os"
)

var _ = Describe("external connectivity", func() {
	var (
		appA      string
		orgName   string
		spaceName string
		appRoute  string
		cli       *cf_cli_adapter.Adapter
	)

	BeforeEach(func() {
		if testConfig.Internetless {
			Skip("skipping egress policy tests")
		}

		cli = &cf_cli_adapter.Adapter{CfCliPath: "cf"}
		appA = fmt.Sprintf("appA-%d", rand.Int31())

		orgName = testConfig.Prefix + "egress-policy-org"
		spaceName = testConfig.Prefix + "space"
		setupOrgAndSpace(orgName, spaceName)

		By("unbinding all running ASGs")
		for _, sg := range testConfig.DefaultSecurityGroups {
			Expect(cf.Cf("unbind-running-security-group", sg).Wait(Timeout_Short)).To(gexec.Exit(0))
		}

		By("pushing the test app")
		pushProxy(appA)
		appRoute = fmt.Sprintf("http://%s.%s/", appA, config.AppsDomain)
	})

	AfterEach(func() {
		By("adding back all the original running ASGs")
		for _, sg := range testConfig.DefaultSecurityGroups {
			Expect(cf.Cf("bind-running-security-group", sg).Wait(Timeout_Short)).To(gexec.Exit(0))
		}

		By("deleting the test org")
		Expect(cf.Cf("delete-org", orgName, "-f").Wait(Timeout_Push)).To(gexec.Exit(0))
	})

	checkRequest := func(route string, expectedStatusCode int, expectedResponseSubstring string) error {
		resp, err := http.Get(route)
		if err != nil {
			return err
		}
		defer resp.Body.Close()

		respBytes, err := ioutil.ReadAll(resp.Body)
		Expect(err).NotTo(HaveOccurred())
		respBody := string(respBytes)

		if resp.StatusCode != expectedStatusCode {
			return fmt.Errorf("test http get to %s: expected response code %d but got %d.  response body:\n%s", route, expectedStatusCode, resp.StatusCode, respBody)
		}
		if !strings.Contains(respBody, expectedResponseSubstring) {
			return fmt.Errorf("test http get to %s: expected response to contain %q but instead saw:\n%s", route, expectedResponseSubstring, respBody)
		}
		return nil
	}

	canProxy := func() error {
		return checkRequest(appRoute+"proxy/example.com", 200, "Example Domain")
	}
	cannotProxy := func() error {
		return checkRequest(appRoute+"proxy/example.com", 500, "example.com")
	}

	Describe("egress policy connectivity", func() {
		It("the app can reach the internet when egress policy is present", func(done Done) {
			By("checking that the app cannot reach the internet using http and dns")
			Eventually(cannotProxy, "10s", "1s").Should(Succeed())
			Consistently(cannotProxy, "2s", "0.5s").Should(Succeed())

			By("creating egress policy")
			appAGuid, err := cli.AppGuid(appA)
			Expect(err).NotTo(HaveOccurred())
			createEgressPolicy(cli, fmt.Sprintf(testEgressPolicies, appAGuid))

			By("checking that the app can use dns and http to reach the internet")
			Eventually(canProxy, "10s", "1s").Should(Succeed())
			Consistently(canProxy, "2s", "0.5s").Should(Succeed())

			close(done)
		}, 180 /* <-- overall spec timeout in seconds */)
	})
})

func createEgressPolicy(cli *cf_cli_adapter.Adapter, payload string) {
	payloadFile, err := ioutil.TempFile("", "")
	Expect(err).NotTo(HaveOccurred())

	_, err = payloadFile.Write([]byte(payload))
	Expect(err).NotTo(HaveOccurred())

	err = payloadFile.Close()
	Expect(err).NotTo(HaveOccurred())

	_, err = cli.Curl("POST", "/networking/v1/external/policies", payloadFile.Name())
	Expect(err).NotTo(HaveOccurred())

	err = os.Remove(payloadFile.Name())
	Expect(err).NotTo(HaveOccurred())
}

var testEgressPolicies = `
	"egress_policies": [
		{
			"source": {"id": %q},
			"destination": {
				"protocol": "tcp",
				"ips": [
					"start": "0.0.0.0",
					"end": "255.255.255.255",
				]
			}
		}
	]
`
<commit_msg>Update test egress policy json<commit_after>package acceptance_test

import (
	"cf-pusher/cf_cli_adapter"
	"fmt"
	"io/ioutil"
	"math/rand"
	"net/http"
	"strings"

	"github.com/cloudfoundry-incubator/cf-test-helpers/cf"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gexec"
	"os"
)

var _ = Describe("external connectivity", func() {
	var (
		appA      string
		orgName   string
		spaceName string
		appRoute  string
		cli       *cf_cli_adapter.Adapter
	)

	BeforeEach(func() {
		if testConfig.Internetless {
			Skip("skipping egress policy tests")
		}

		cli = &cf_cli_adapter.Adapter{CfCliPath: "cf"}
		appA = fmt.Sprintf("appA-%d", rand.Int31())

		orgName = testConfig.Prefix + "egress-policy-org"
		spaceName = testConfig.Prefix + "space"
		setupOrgAndSpace(orgName, spaceName)

		By("unbinding all running ASGs")
		for _, sg := range testConfig.DefaultSecurityGroups {
			Expect(cf.Cf("unbind-running-security-group", sg).Wait(Timeout_Short)).To(gexec.Exit(0))
		}

		By("pushing the test app")
		pushProxy(appA)
		appRoute = fmt.Sprintf("http://%s.%s/", appA, config.AppsDomain)
	})

	AfterEach(func() {
		By("adding back all the original running ASGs")
		for _, sg := range testConfig.DefaultSecurityGroups {
			Expect(cf.Cf("bind-running-security-group", sg).Wait(Timeout_Short)).To(gexec.Exit(0))
		}

		By("deleting the test org")
		Expect(cf.Cf("delete-org", orgName, "-f").Wait(Timeout_Push)).To(gexec.Exit(0))
	})

	checkRequest := func(route string, expectedStatusCode int, expectedResponseSubstring string) error {
		resp, err := http.Get(route)
		if err != nil {
			return err
		}
		defer resp.Body.Close()

		respBytes, err := ioutil.ReadAll(resp.Body)
		Expect(err).NotTo(HaveOccurred())
		respBody := string(respBytes)

		if resp.StatusCode != expectedStatusCode {
			return fmt.Errorf("test http get to %s: expected response code %d but got %d.  response body:\n%s", route, expectedStatusCode, resp.StatusCode, respBody)
		}
		if !strings.Contains(respBody, expectedResponseSubstring) {
			return fmt.Errorf("test http get to %s: expected response to contain %q but instead saw:\n%s", route, expectedResponseSubstring, respBody)
		}
		return nil
	}

	canProxy := func() error {
		return checkRequest(appRoute+"proxy/example.com", 200, "Example Domain")
	}
	cannotProxy := func() error {
		return checkRequest(appRoute+"proxy/example.com", 500, "example.com")
	}

	Describe("egress policy connectivity", func() {
		It("the app can reach the internet when egress policy is present", func(done Done) {
			By("checking that the app cannot reach the internet using http and dns")
			Eventually(cannotProxy, "10s", "1s").Should(Succeed())
			Consistently(cannotProxy, "2s", "0.5s").Should(Succeed())

			By("creating egress policy")
			appAGuid, err := cli.AppGuid(appA)
			Expect(err).NotTo(HaveOccurred())
			createEgressPolicy(cli, fmt.Sprintf(testEgressPolicies, appAGuid))

			By("checking that the app can use dns and http to reach the internet")
			Eventually(canProxy, "10s", "1s").Should(Succeed())
			Consistently(canProxy, "2s", "0.5s").Should(Succeed())

			close(done)
		}, 180 /* <-- overall spec timeout in seconds */)
	})
})

func createEgressPolicy(cli *cf_cli_adapter.Adapter, payload string) {
	payloadFile, err := ioutil.TempFile("", "")
	Expect(err).NotTo(HaveOccurred())

	_, err = payloadFile.Write([]byte(payload))
	Expect(err).NotTo(HaveOccurred())

	err = payloadFile.Close()
	Expect(err).NotTo(HaveOccurred())

	_, err = cli.Curl("POST", "/networking/v1/external/policies", payloadFile.Name())
	Expect(err).NotTo(HaveOccurred())

	err = os.Remove(payloadFile.Name())
	Expect(err).NotTo(HaveOccurred())
}

var testEgressPolicies = `
{
  "egress_policies": [
    {
      "source": {
        "id": %q
      },
      "destination": {
        "protocol": "tcp",
        "ips": [
          {
            "start": "0.0.0.0",
            "end": "255.255.255.255"
          }
        ]
      }
    }
  ]
}`
<|endoftext|>


<commit_before>package hsup

import (
	"errors"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/exec"
	"syscall"
	"time"
)

var ErrNoSlugURL = errors.New("no slug specified")

const profileRunnerText = `#!/bin/bash
export PS1='\[\033[01;34m\]\w\[\033[00m\] \[\033[01;32m\]$ \[\033[00m\]'

if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi

if [ -d /app/.profile.d ]; then
  for i in /app/.profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi

rm $0
cmd="$@" # trick to disable word splitting
exec bash -c "$cmd"
`

type profileRunner struct {
	file *os.File
}

func (pr *profileRunner) Init() (err error) {
	if pr.file, err = ioutil.TempFile("", "pr_"); err != nil {
		return err
	}

	if _, err = pr.file.Write([]byte(profileRunnerText)); err != nil {
		return err
	}

	fi, err := os.Stat(pr.file.Name())
	if err != nil {
		return err
	}

	if err = os.Chmod(pr.file.Name(), fi.Mode()|0111); err != nil {
		return err
	}

	return pr.file.Close()
}

func (pr *profileRunner) Args(args []string) []string {
	return append([]string{pr.file.Name()}, args...)
}

type AbsPathDynoDriver struct{}

func (dd *AbsPathDynoDriver) fetch(release *Release) error {
	if release.slugURL == "" {
		return ErrNoSlugURL
	}

	switch release.Where() {
	case Local:
		// No-op: the slug is already available on the file
		// system.
	case HTTP:
		log.Printf("fetching slug URL %q", release.slugURL)

		resp, err := http.Get(release.slugURL)
		if err != nil {
			return err
		}
		defer resp.Body.Close()

		out, err := os.Create("/tmp/slug.tgz")
		if err != nil {
			return err
		}
		defer out.Close()

		if _, err := io.Copy(out, resp.Body); err != nil {
			return err
		}

		release.slugURL = "/tmp/slug.tgz"
	}

	return nil
}

func (dd *AbsPathDynoDriver) unpack(release *Release) error {
	if release.slugURL == "" {
		return nil
	}

	if release.Where() != Local {
		panic("by unpack, expect release slugURL to be " +
			"transmogrified to a local path")
	}

	cmd := exec.Command("/bin/tar", "-C", "/app", "--strip-components=2", "-zxf",
		release.slugURL)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		return err
	}

	return nil
}

func (dd *AbsPathDynoDriver) Build(release *Release) (err error) {
	if release.Where() == HTTP {
		if err = dd.fetch(release); err != nil {
			return err
		}
	}

	if err = dd.unpack(release); err != nil {
		return err
	}

	return nil
}

func (dd *AbsPathDynoDriver) Start(ex *Executor) (err error) {
	var pr profileRunner
	if err = pr.Init(); err != nil {
		return err
	}

	args := pr.Args(ex.Args)
	ex.cmd = exec.Command(args[0], args[1:]...)

	ex.cmd.Stdin = os.Stdin
	ex.cmd.Stdout = os.Stdout
	ex.cmd.Stderr = os.Stderr

	// Tee stdout and stderr to Logplex.
	if ex.LogplexURL != nil {
		var rStdout, rStderr io.Reader
		ex.logsRelay, err = newRelay(ex.LogplexURL, ex.Name())
		if err != nil {
			return err
		}

		rStdout, ex.cmd.Stdout = teePipe(os.Stdout)
		rStderr, ex.cmd.Stderr = teePipe(os.Stderr)

		go ex.logsRelay.run(rStdout)
		go ex.logsRelay.run(rStderr)
	}

	ex.cmd.Dir = "/app"

	// Fill environment vector from Heroku configuration, with a
	// default $PATH.
	ex.cmd.Env = []string{"PATH=/usr/local/sbin:/usr/local/bin:" +
		"/usr/sbin:/usr/bin:/sbin:/bin",
		"HOME=/app", "DYNO=" + ex.Name(), "PORT=5000"}

	for k, v := range ex.Release.config {
		ex.cmd.Env = append(ex.cmd.Env, k+"="+v)
	}

	ex.cmd.SysProcAttr = &syscall.SysProcAttr{
		Setpgid: true,
	}

	if err = ex.cmd.Start(); err != nil {
		return err
	}

	ex.waiting = make(chan struct{})
	return nil
}

func (dd *AbsPathDynoDriver) Wait(ex *Executor) (s *ExitStatus) {
	s = &ExitStatus{}
	err := ex.cmd.Wait()
	if err != nil {
		if eErr, ok := err.(*exec.ExitError); ok {
			if status, ok := eErr.Sys().(syscall.WaitStatus); ok {
				s.Code = status.ExitStatus()
				if status.Signaled() {
					s.Code = 128 + int(status.Signal())
				}
			}
		} else {
			// Non ExitErrors are propagated: they are
			// liable to be errors in starting the
			// process.
			s.Err = err
		}
	}

	if ex.logsRelay != nil {
		// wait until all buffered logs are delivered
		ex.logsRelay.stop()
	}
	go func() {
		ex.waiting <- struct{}{}
	}()

	return s
}

func (dd *AbsPathDynoDriver) Stop(ex *Executor) error {
	p := ex.cmd.Process

	group, err := os.FindProcess(-1 * p.Pid)
	if err != nil {
		return err
	}

	// Begin graceful shutdown via SIGTERM.
	group.Signal(syscall.SIGTERM)

	for {
		select {
		case <-time.After(10 * time.Second):
			log.Println("sigkill", group)
			group.Signal(syscall.SIGKILL)
		case <-ex.waiting:
			log.Println("waited", group)
			return nil
		}
		log.Println("spin", group)
		time.Sleep(1)
	}
}
<commit_msg>Use "$*" to run command without word splitting<commit_after>package hsup

import (
	"errors"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/exec"
	"syscall"
	"time"
)

var ErrNoSlugURL = errors.New("no slug specified")

const profileRunnerText = `#!/bin/bash
export PS1='\[\033[01;34m\]\w\[\033[00m\] \[\033[01;32m\]$ \[\033[00m\]'

if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi

if [ -d /app/.profile.d ]; then
  for i in /app/.profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi

rm $0
exec bash -c "$*"
`

type profileRunner struct {
	file *os.File
}

func (pr *profileRunner) Init() (err error) {
	if pr.file, err = ioutil.TempFile("", "pr_"); err != nil {
		return err
	}

	if _, err = pr.file.Write([]byte(profileRunnerText)); err != nil {
		return err
	}

	fi, err := os.Stat(pr.file.Name())
	if err != nil {
		return err
	}

	if err = os.Chmod(pr.file.Name(), fi.Mode()|0111); err != nil {
		return err
	}

	return pr.file.Close()
}

func (pr *profileRunner) Args(args []string) []string {
	return append([]string{pr.file.Name()}, args...)
}

type AbsPathDynoDriver struct{}

func (dd *AbsPathDynoDriver) fetch(release *Release) error {
	if release.slugURL == "" {
		return ErrNoSlugURL
	}

	switch release.Where() {
	case Local:
		// No-op: the slug is already available on the file
		// system.
	case HTTP:
		log.Printf("fetching slug URL %q", release.slugURL)

		resp, err := http.Get(release.slugURL)
		if err != nil {
			return err
		}
		defer resp.Body.Close()

		out, err := os.Create("/tmp/slug.tgz")
		if err != nil {
			return err
		}
		defer out.Close()

		if _, err := io.Copy(out, resp.Body); err != nil {
			return err
		}

		release.slugURL = "/tmp/slug.tgz"
	}

	return nil
}

func (dd *AbsPathDynoDriver) unpack(release *Release) error {
	if release.slugURL == "" {
		return nil
	}

	if release.Where() != Local {
		panic("by unpack, expect release slugURL to be " +
			"transmogrified to a local path")
	}

	cmd := exec.Command("/bin/tar", "-C", "/app", "--strip-components=2", "-zxf",
		release.slugURL)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		return err
	}

	return nil
}

func (dd *AbsPathDynoDriver) Build(release *Release) (err error) {
	if release.Where() == HTTP {
		if err = dd.fetch(release); err != nil {
			return err
		}
	}

	if err = dd.unpack(release); err != nil {
		return err
	}

	return nil
}

func (dd *AbsPathDynoDriver) Start(ex *Executor) (err error) {
	var pr profileRunner
	if err = pr.Init(); err != nil {
		return err
	}

	args := pr.Args(ex.Args)
	ex.cmd = exec.Command(args[0], args[1:]...)

	ex.cmd.Stdin = os.Stdin
	ex.cmd.Stdout = os.Stdout
	ex.cmd.Stderr = os.Stderr

	// Tee stdout and stderr to Logplex.
	if ex.LogplexURL != nil {
		var rStdout, rStderr io.Reader
		ex.logsRelay, err = newRelay(ex.LogplexURL, ex.Name())
		if err != nil {
			return err
		}

		rStdout, ex.cmd.Stdout = teePipe(os.Stdout)
		rStderr, ex.cmd.Stderr = teePipe(os.Stderr)

		go ex.logsRelay.run(rStdout)
		go ex.logsRelay.run(rStderr)
	}

	ex.cmd.Dir = "/app"

	// Fill environment vector from Heroku configuration, with a
	// default $PATH.
	ex.cmd.Env = []string{"PATH=/usr/local/sbin:/usr/local/bin:" +
		"/usr/sbin:/usr/bin:/sbin:/bin",
		"HOME=/app", "DYNO=" + ex.Name(), "PORT=5000"}

	for k, v := range ex.Release.config {
		ex.cmd.Env = append(ex.cmd.Env, k+"="+v)
	}

	ex.cmd.SysProcAttr = &syscall.SysProcAttr{
		Setpgid: true,
	}

	if err = ex.cmd.Start(); err != nil {
		return err
	}

	ex.waiting = make(chan struct{})
	return nil
}

func (dd *AbsPathDynoDriver) Wait(ex *Executor) (s *ExitStatus) {
	s = &ExitStatus{}
	err := ex.cmd.Wait()
	if err != nil {
		if eErr, ok := err.(*exec.ExitError); ok {
			if status, ok := eErr.Sys().(syscall.WaitStatus); ok {
				s.Code = status.ExitStatus()
				if status.Signaled() {
					s.Code = 128 + int(status.Signal())
				}
			}
		} else {
			// Non ExitErrors are propagated: they are
			// liable to be errors in starting the
			// process.
			s.Err = err
		}
	}

	if ex.logsRelay != nil {
		// wait until all buffered logs are delivered
		ex.logsRelay.stop()
	}
	go func() {
		ex.waiting <- struct{}{}
	}()

	return s
}

func (dd *AbsPathDynoDriver) Stop(ex *Executor) error {
	p := ex.cmd.Process

	group, err := os.FindProcess(-1 * p.Pid)
	if err != nil {
		return err
	}

	// Begin graceful shutdown via SIGTERM.
	group.Signal(syscall.SIGTERM)

	for {
		select {
		case <-time.After(10 * time.Second):
			log.Println("sigkill", group)
			group.Signal(syscall.SIGKILL)
		case <-ex.waiting:
			log.Println("waited", group)
			return nil
		}
		log.Println("spin", group)
		time.Sleep(1)
	}
}
<|endoftext|>


<commit_before>package guest_fsresize

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"

	"github.com/vtolstov/go-ioctl"
)

func resizefs(path string) error {
	var err error
	var stdout io.ReadCloser
	var stdin bytes.Buffer

	partstart := 0
	partnum := 0
	device := "/tmp/resize_dev"
	partition := "/tmp/resize_part"
	active := false
	extended := false
	parttype := "Linux"
	devFs, err := findFs(path)
	if err != nil {
		return err
	}
	devBlk, err := findBlock("/sys/block", devFs)
	if err != nil {
		return err
	}
	os.Remove(device)
	if err = syscall.Mknod(device, uint32(os.ModeDevice|syscall.S_IFBLK|0600), devBlk.Int()); err != nil {
		return err
	}
	defer os.Remove(device)
	//	mbr := make([]byte, 446)

	/*
		f, err := os.OpenFile(device, os.O_RDONLY, os.FileMode(0400))
		if err != nil {
			return err
		}
		_, err = io.ReadFull(f, mbr)
		f.Close()
		if err != nil {
			return err
		}
	*/
	cmd := exec.Command("fdisk", "-l", "-u", device)
	stdout, err = cmd.StdoutPipe()
	if err != nil {
		log.Printf("failed to open %s via fdisk %s 2\n", device, err.Error())
		return err
	}
	r := bufio.NewReader(stdout)

	if err = cmd.Start(); err != nil {
		log.Printf("failed to open %s via fdisk %s 3\n", device, err.Error())
		return err
	}

	for {
		line, err := r.ReadString('\n')
		if err != nil {
			break
		}

		if strings.HasPrefix(line, device) {
			partnum += 1
			///test3        *  16384 204799  188416  92M  5 Extended
			ps := strings.Fields(line)
			if ps[1] == "*" {
				active = true
				partstart, _ = strconv.Atoi(ps[2])
				if len(ps) > 7 {
					parttype = ps[6]
					if ps[7] == "Extended" {
						extended = true
					}
				} else {
					parttype = ps[5]
					if ps[6] == "Extended" {
						extended = true
					}
				}
			} else {
				active = false
				partstart, _ = strconv.Atoi(ps[1])
				if len(ps) > 6 {
					parttype = ps[5]
					if ps[6] == "Extended" {
						extended = true
					}
				} else {
					parttype = ps[4]
					if ps[5] == "Extended" {
						extended = true
					}
				}
			}
		}
	}

	if err = cmd.Wait(); err != nil || partstart == 0 {
		return fmt.Errorf("failed to open %s via fdisk 4\n", device)
	}
	if partnum > 1 {
		stdin.Write([]byte("d\n" + fmt.Sprintf("%d", partnum) + "\n"))
	} else {
		stdin.Write([]byte("d\n"))
	}
	if extended {
		stdin.Write([]byte("n\nl\n" + fmt.Sprintf("%d", partnum) + "\n" + fmt.Sprintf("%d", partstart) + "\n\n"))
	} else {
		stdin.Write([]byte("n\np\n" + fmt.Sprintf("%d", partnum) + "\n" + fmt.Sprintf("%d", partstart) + "\n\n"))
	}
	if active {
		stdin.Write([]byte("a\n" + fmt.Sprintf("%d", partnum) + "\n"))
	}
	if partnum > 1 {
		stdin.Write([]byte("t\n" + fmt.Sprintf("%d", partnum) + "\n" + parttype + "\nw"))
	} else {
		stdin.Write([]byte("t\n" + parttype + "\nw"))
	}
	cmd = exec.Command("fdisk", "-u", device)
	cmd.Stdin = &stdin
	cmd.Run()
	stdin.Reset()

	w, err := os.OpenFile(device, os.O_WRONLY, 0600)
	if err != nil {
		return err
	}
	/*
		_, err = w.Write(mbr)
		if err != nil {
			return err
		}
		err = w.Sync()
		if err != nil {
			return err
		}
	*/
	blkerr := ioctl.BlkRRPart(w.Fd())
	err = w.Close()
	if err != nil {
		return err
	}
	if blkerr != nil {
		args := []string{}
		for _, name := range []string{"partx", "partprobe", "kpartx"} {
			if _, err = exec.LookPath(name); err == nil {
				switch name {
				case "partx":
					args = []string{"-u", device}
				default:
					args = []string{device}
				}
				log.Printf("update partition table via %s %s", name, strings.Join(args, " "))
				if err = exec.Command(name, args...).Run(); err == nil {
					break
				}
			}
		}
	}
	os.Remove(partition)
	if err = syscall.Mknod(partition, uint32(os.ModeDevice|syscall.S_IFBLK|0600), devFs.Int()); err != nil {
		return err
	}
	defer os.Remove(partition)
	log.Printf("resize filesystem via %s %s", "resize2fs", partition)
	buf, err := exec.Command("resize2fs", partition).CombinedOutput()
	if err != nil {
		log.Printf("resize2fs %s", buf)
		return err
	}
	return nil
}

type Dev struct {
	Major uint64
	Minor uint64
}

func (d *Dev) String() string {
	return fmt.Sprintf("%d:%d", d.Major, d.Minor)
}

func (d *Dev) Int() int {
	return int(d.Major*256 + d.Minor)
}

func findFs() (*Dev, error) {
	var st syscall.Stat_t

	err := syscall.Stat("/", &st)
	if err != nil {
		return nil, err
	}
	return &Dev{Major: uint64(st.Dev / 256), Minor: uint64(st.Dev % 256)}, nil
}

func findBlock(start string, s *Dev) (*Dev, error) {
	var err error
	fis, err := ioutil.ReadDir(start)
	if err != nil {
		return nil, err
	}
	for _, fi := range fis {
		switch fi.Name() {
		case "bdi", "subsystem", "device", "trace":
			continue
		}
		if _, err := os.Stat(filepath.Join(start, "dev")); err == nil {
			if buf, err := ioutil.ReadFile(filepath.Join(start, "dev")); err == nil {
				dev := strings.TrimSpace(string(buf))
				if s.String() == dev {
					if buf, err = ioutil.ReadFile(filepath.Join(filepath.Dir(start), "dev")); err == nil {
						majorminor := strings.Split(strings.TrimSpace(string(buf)), ":")
						major, _ := strconv.Atoi(majorminor[0])
						minor, _ := strconv.Atoi(majorminor[1])
						return &Dev{Major: uint64(major), Minor: uint64(minor)}, nil
					}
				}
			}
		}
		devBlk, err := findBlock(filepath.Join(start, fi.Name()), s)
		if err == nil {
			return devBlk, err
		}
	}
	return nil, errors.New("failed to find dev")
}
<commit_msg>fix build<commit_after>package guest_fsresize

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"syscall"

	"github.com/vtolstov/go-ioctl"
)

func resizefs(path string) error {
	var err error
	var stdout io.ReadCloser
	var stdin bytes.Buffer

	partstart := 0
	partnum := 0
	device := "/tmp/resize_dev"
	partition := "/tmp/resize_part"
	active := false
	extended := false
	parttype := "Linux"
	devFs, err := findFs(path)
	if err != nil {
		return err
	}
	devBlk, err := findBlock("/sys/block", devFs)
	if err != nil {
		return err
	}
	os.Remove(device)
	if err = syscall.Mknod(device, uint32(os.ModeDevice|syscall.S_IFBLK|0600), devBlk.Int()); err != nil {
		return err
	}
	defer os.Remove(device)
	//	mbr := make([]byte, 446)

	/*
		f, err := os.OpenFile(device, os.O_RDONLY, os.FileMode(0400))
		if err != nil {
			return err
		}
		_, err = io.ReadFull(f, mbr)
		f.Close()
		if err != nil {
			return err
		}
	*/
	cmd := exec.Command("fdisk", "-l", "-u", device)
	stdout, err = cmd.StdoutPipe()
	if err != nil {
		log.Printf("failed to open %s via fdisk %s 2\n", device, err.Error())
		return err
	}
	r := bufio.NewReader(stdout)

	if err = cmd.Start(); err != nil {
		log.Printf("failed to open %s via fdisk %s 3\n", device, err.Error())
		return err
	}

	for {
		line, err := r.ReadString('\n')
		if err != nil {
			break
		}

		if strings.HasPrefix(line, device) {
			partnum += 1
			///test3        *  16384 204799  188416  92M  5 Extended
			ps := strings.Fields(line)
			if ps[1] == "*" {
				active = true
				partstart, _ = strconv.Atoi(ps[2])
				if len(ps) > 7 {
					parttype = ps[6]
					if ps[7] == "Extended" {
						extended = true
					}
				} else {
					parttype = ps[5]
					if ps[6] == "Extended" {
						extended = true
					}
				}
			} else {
				active = false
				partstart, _ = strconv.Atoi(ps[1])
				if len(ps) > 6 {
					parttype = ps[5]
					if ps[6] == "Extended" {
						extended = true
					}
				} else {
					parttype = ps[4]
					if ps[5] == "Extended" {
						extended = true
					}
				}
			}
		}
	}

	if err = cmd.Wait(); err != nil || partstart == 0 {
		return fmt.Errorf("failed to open %s via fdisk 4\n", device)
	}
	if partnum > 1 {
		stdin.Write([]byte("d\n" + fmt.Sprintf("%d", partnum) + "\n"))
	} else {
		stdin.Write([]byte("d\n"))
	}
	if extended {
		stdin.Write([]byte("n\nl\n" + fmt.Sprintf("%d", partnum) + "\n" + fmt.Sprintf("%d", partstart) + "\n\n"))
	} else {
		stdin.Write([]byte("n\np\n" + fmt.Sprintf("%d", partnum) + "\n" + fmt.Sprintf("%d", partstart) + "\n\n"))
	}
	if active {
		stdin.Write([]byte("a\n" + fmt.Sprintf("%d", partnum) + "\n"))
	}
	if partnum > 1 {
		stdin.Write([]byte("t\n" + fmt.Sprintf("%d", partnum) + "\n" + parttype + "\nw"))
	} else {
		stdin.Write([]byte("t\n" + parttype + "\nw"))
	}
	cmd = exec.Command("fdisk", "-u", device)
	cmd.Stdin = &stdin
	cmd.Run()
	stdin.Reset()

	w, err := os.OpenFile(device, os.O_WRONLY, 0600)
	if err != nil {
		return err
	}
	/*
		_, err = w.Write(mbr)
		if err != nil {
			return err
		}
		err = w.Sync()
		if err != nil {
			return err
		}
	*/
	blkerr := ioctl.BlkRRPart(w.Fd())
	err = w.Close()
	if err != nil {
		return err
	}
	if blkerr != nil {
		args := []string{}
		for _, name := range []string{"partx", "partprobe", "kpartx"} {
			if _, err = exec.LookPath(name); err == nil {
				switch name {
				case "partx":
					args = []string{"-u", device}
				default:
					args = []string{device}
				}
				log.Printf("update partition table via %s %s", name, strings.Join(args, " "))
				if err = exec.Command(name, args...).Run(); err == nil {
					break
				}
			}
		}
	}
	os.Remove(partition)
	if err = syscall.Mknod(partition, uint32(os.ModeDevice|syscall.S_IFBLK|0600), devFs.Int()); err != nil {
		return err
	}
	defer os.Remove(partition)
	log.Printf("resize filesystem via %s %s", "resize2fs", partition)
	buf, err := exec.Command("resize2fs", partition).CombinedOutput()
	if err != nil {
		log.Printf("resize2fs %s", buf)
		return err
	}
	return nil
}

type Dev struct {
	Major uint64
	Minor uint64
}

func (d *Dev) String() string {
	return fmt.Sprintf("%d:%d", d.Major, d.Minor)
}

func (d *Dev) Int() int {
	return int(d.Major*256 + d.Minor)
}

func findFs(path string) (*Dev, error) {
	var st syscall.Stat_t

	err := syscall.Stat(path, &st)
	if err != nil {
		return nil, err
	}
	return &Dev{Major: uint64(st.Dev / 256), Minor: uint64(st.Dev % 256)}, nil
}

func findBlock(start string, s *Dev) (*Dev, error) {
	var err error
	fis, err := ioutil.ReadDir(start)
	if err != nil {
		return nil, err
	}
	for _, fi := range fis {
		switch fi.Name() {
		case "bdi", "subsystem", "device", "trace":
			continue
		}
		if _, err := os.Stat(filepath.Join(start, "dev")); err == nil {
			if buf, err := ioutil.ReadFile(filepath.Join(start, "dev")); err == nil {
				dev := strings.TrimSpace(string(buf))
				if s.String() == dev {
					if buf, err = ioutil.ReadFile(filepath.Join(filepath.Dir(start), "dev")); err == nil {
						majorminor := strings.Split(strings.TrimSpace(string(buf)), ":")
						major, _ := strconv.Atoi(majorminor[0])
						minor, _ := strconv.Atoi(majorminor[1])
						return &Dev{Major: uint64(major), Minor: uint64(minor)}, nil
					}
				}
			}
		}
		devBlk, err := findBlock(filepath.Join(start, fi.Name()), s)
		if err == nil {
			return devBlk, err
		}
	}
	return nil, errors.New("failed to find dev")
}
<|endoftext|>


<commit_before>package selector
<commit_msg>Added tests for GetSkillsOrder<commit_after>package selector

import "testing"
import "github.com/AxelUser/gowork/utils"

func TestGetSkillsOrder_PassOntology_SkillsAreInSameOrder(t *testing.T) {
	ontology := utils.CreateOntology([]string{"js", "css", "html"}, false, true)

	skillsInOrder := getSkillsOrder(ontology)

	for i := range ontology {
		if ontology[i].Alias != skillsInOrder[i] {
			t.Errorf("Expected skill <%s>, but was <%s>", ontology[i].Alias, skillsInOrder[i])
		}
	}
}

func TestGetSkillsOrder_PassOntology_SameLenght(t *testing.T) {
	ontology := utils.CreateOntology([]string{"js", "css", "html"}, false, true)

	skillsInOrder := getSkillsOrder(ontology)

	if len(ontology) != len(skillsInOrder) {
		t.Errorf("Expected length <%d>, but was <%d>", len(ontology), len(skillsInOrder))
	}
}
<|endoftext|>


<commit_before>// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package autocert

import (
	"context"
	"errors"
	"io/ioutil"
	"os"
	"path/filepath"
)

// ErrCacheMiss is returned when a certificate is not found in cache.
var ErrCacheMiss = errors.New("acme/autocert: certificate cache miss")

// Cache is used by Manager to store and retrieve previously obtained certificates
// and other account data as opaque blobs.
//
// Cache implementations should not rely on the key naming pattern. Keys can
// include any printable ASCII characters, except the following: \/:*?"<>|
type Cache interface {
	// Get returns a certificate data for the specified key.
	// If there's no such key, Get returns ErrCacheMiss.
	Get(ctx context.Context, key string) ([]byte, error)

	// Put stores the data in the cache under the specified key.
	// Underlying implementations may use any data storage format,
	// as long as the reverse operation, Get, results in the original data.
	Put(ctx context.Context, key string, data []byte) error

	// Delete removes a certificate data from the cache under the specified key.
	// If there's no such key in the cache, Delete returns nil.
	Delete(ctx context.Context, key string) error
}

// DirCache implements Cache using a directory on the local filesystem.
// If the directory does not exist, it will be created with 0700 permissions.
type DirCache string

// Get reads a certificate data from the specified file name.
func (d DirCache) Get(ctx context.Context, name string) ([]byte, error) {
	name = filepath.Join(string(d), name)
	var (
		data []byte
		err  error
		done = make(chan struct{})
	)
	go func() {
		data, err = ioutil.ReadFile(name)
		close(done)
	}()
	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	case <-done:
	}
	if os.IsNotExist(err) {
		return nil, ErrCacheMiss
	}
	return data, err
}

// Put writes the certificate data to the specified file name.
// The file will be created with 0600 permissions.
func (d DirCache) Put(ctx context.Context, name string, data []byte) error {
	if err := os.MkdirAll(string(d), 0700); err != nil {
		return err
	}

	done := make(chan struct{})
	var err error
	go func() {
		defer close(done)
		var tmp string
		if tmp, err = d.writeTempFile(name, data); err != nil {
			return
		}
		defer os.Remove(tmp)
		select {
		case <-ctx.Done():
			// Don't overwrite the file if the context was canceled.
		default:
			newName := filepath.Join(string(d), name)
			err = os.Rename(tmp, newName)
		}
	}()
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-done:
	}
	return err
}

// Delete removes the specified file name.
func (d DirCache) Delete(ctx context.Context, name string) error {
	name = filepath.Join(string(d), name)
	var (
		err  error
		done = make(chan struct{})
	)
	go func() {
		err = os.Remove(name)
		close(done)
	}()
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-done:
	}
	if err != nil && !os.IsNotExist(err) {
		return err
	}
	return nil
}

// writeTempFile writes b to a temporary file, closes the file and returns its path.
func (d DirCache) writeTempFile(prefix string, b []byte) (name string, reterr error) {
	// TempFile uses 0600 permissions
	f, err := ioutil.TempFile(string(d), prefix)
	if err != nil {
		return "", err
	}
	defer func() {
		if reterr != nil {
			os.Remove(f.Name())
		}
	}()
	if _, err := f.Write(b); err != nil {
		f.Close()
		return "", err
	}
	return f.Name(), f.Close()
}
<commit_msg>acme/autocert: properly clean DirCache paths<commit_after>// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package autocert

import (
	"context"
	"errors"
	"io/ioutil"
	"os"
	"path/filepath"
)

// ErrCacheMiss is returned when a certificate is not found in cache.
var ErrCacheMiss = errors.New("acme/autocert: certificate cache miss")

// Cache is used by Manager to store and retrieve previously obtained certificates
// and other account data as opaque blobs.
//
// Cache implementations should not rely on the key naming pattern. Keys can
// include any printable ASCII characters, except the following: \/:*?"<>|
type Cache interface {
	// Get returns a certificate data for the specified key.
	// If there's no such key, Get returns ErrCacheMiss.
	Get(ctx context.Context, key string) ([]byte, error)

	// Put stores the data in the cache under the specified key.
	// Underlying implementations may use any data storage format,
	// as long as the reverse operation, Get, results in the original data.
	Put(ctx context.Context, key string, data []byte) error

	// Delete removes a certificate data from the cache under the specified key.
	// If there's no such key in the cache, Delete returns nil.
	Delete(ctx context.Context, key string) error
}

// DirCache implements Cache using a directory on the local filesystem.
// If the directory does not exist, it will be created with 0700 permissions.
type DirCache string

// Get reads a certificate data from the specified file name.
func (d DirCache) Get(ctx context.Context, name string) ([]byte, error) {
	name = filepath.Join(string(d), filepath.Clean("/"+name))
	var (
		data []byte
		err  error
		done = make(chan struct{})
	)
	go func() {
		data, err = ioutil.ReadFile(name)
		close(done)
	}()
	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	case <-done:
	}
	if os.IsNotExist(err) {
		return nil, ErrCacheMiss
	}
	return data, err
}

// Put writes the certificate data to the specified file name.
// The file will be created with 0600 permissions.
func (d DirCache) Put(ctx context.Context, name string, data []byte) error {
	if err := os.MkdirAll(string(d), 0700); err != nil {
		return err
	}

	done := make(chan struct{})
	var err error
	go func() {
		defer close(done)
		var tmp string
		if tmp, err = d.writeTempFile(name, data); err != nil {
			return
		}
		defer os.Remove(tmp)
		select {
		case <-ctx.Done():
			// Don't overwrite the file if the context was canceled.
		default:
			newName := filepath.Join(string(d), filepath.Clean("/"+name))
			err = os.Rename(tmp, newName)
		}
	}()
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-done:
	}
	return err
}

// Delete removes the specified file name.
func (d DirCache) Delete(ctx context.Context, name string) error {
	name = filepath.Join(string(d), filepath.Clean("/"+name))
	var (
		err  error
		done = make(chan struct{})
	)
	go func() {
		err = os.Remove(name)
		close(done)
	}()
	select {
	case <-ctx.Done():
		return ctx.Err()
	case <-done:
	}
	if err != nil && !os.IsNotExist(err) {
		return err
	}
	return nil
}

// writeTempFile writes b to a temporary file, closes the file and returns its path.
func (d DirCache) writeTempFile(prefix string, b []byte) (name string, reterr error) {
	// TempFile uses 0600 permissions
	f, err := ioutil.TempFile(string(d), prefix)
	if err != nil {
		return "", err
	}
	defer func() {
		if reterr != nil {
			os.Remove(f.Name())
		}
	}()
	if _, err := f.Write(b); err != nil {
		f.Close()
		return "", err
	}
	return f.Name(), f.Close()
}
<|endoftext|>