<commit_before>package main_test

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"reflect"
	"testing"
	"time"

	"github.com/influxdb/influxdb/client"
	"github.com/influxdb/influxdb/influxql"

	main "github.com/influxdb/influxdb/cmd/influxd"
)

func Test_ServerSingleIntegration(t *testing.T) {
	var (
		join    = ""
		version = "x.x"
	)

	tmpDir := os.TempDir()
	tmpBrokerDir := filepath.Join(tmpDir, "broker")
	tmpDataDir := filepath.Join(tmpDir, "data")
	t.Logf("Using tmp directorie %q for broker\n", tmpBrokerDir)
	t.Logf("Using tmp directorie %q for data\n", tmpDataDir)
	// Sometimes if this test fails, it's because of a log.Fatal() in the program.
	// This prevents the defer from cleaning up directories.
	// To be safe, nuke them always before starting
	_ = os.RemoveAll(tmpBrokerDir)
	_ = os.RemoveAll(tmpDataDir)

	c := main.NewConfig()
	c.Broker.Dir = tmpBrokerDir
	c.Broker.Port = 8090
	c.Data.Dir = tmpDataDir
	c.Data.Port = 8090

	now := time.Now().UTC()

	s := main.Run(c, join, version, os.Stderr)

	defer func() {
		t.Log("Shutting down server and cleaning up tmp directories")
		if s != nil {
			s.Close()
		}

		err := os.RemoveAll(tmpBrokerDir)
		if err != nil {
			t.Logf("Failed to clean up %q: %s\n", tmpBrokerDir, err)
		}
		err = os.RemoveAll(tmpDataDir)
		if err != nil {
			t.Logf("Failed to clean up %q: %s\n", tmpDataDir, err)
		}
	}()

	if s == nil {
		t.Fatalf("Failed to open server")
	}

	// Create a database
	t.Log("Creating database")

	u := urlFor(c.BrokerURL(), "query", url.Values{"q": []string{"CREATE DATABASE foo"}})
	httpClient := http.Client{Timeout: 100 * time.Millisecond}

	resp, err := httpClient.Get(u.String())
	if err != nil {
		t.Fatalf("Couldn't create database: %s", err)
	}
	defer resp.Body.Close()

	var results client.Results
	err = json.NewDecoder(resp.Body).Decode(&results)
	if err != nil {
		t.Fatalf("Couldn't decode results: %v", err)
	}

	if results.Error() != nil {
		t.Logf("results.Error(): %q", results.Error().Error())
	}

	if resp.StatusCode != http.StatusOK {
		t.Fatalf("Create database failed.  Unexpected status code.  expected: %d, actual %d", http.StatusOK, resp.StatusCode)
	}

	if len(results.Results) != 1 {
		t.Fatalf("Create database failed.  Unexpected results length.  expected: %d, actual %d", 1, len(results.Results))
	}

	// Query the database exists
	u = urlFor(c.BrokerURL(), "query", url.Values{"q": []string{"SHOW DATABASES"}})

	resp, err = httpClient.Get(u.String())
	if err != nil {
		t.Fatalf("Couldn't query databases: %s", err)
	}
	defer resp.Body.Close()

	err = json.NewDecoder(resp.Body).Decode(&results)
	if err != nil {
		t.Fatalf("Couldn't decode results: %v", err)
	}

	if results.Error() != nil {
		t.Logf("results.Error(): %q", results.Error().Error())
	}

	if resp.StatusCode != http.StatusOK {
		t.Fatalf("show databases failed.  Unexpected status code.  expected: %d, actual %d", http.StatusOK, resp.StatusCode)
	}

	expectedResults := client.Results{
		Results: []client.Result{
			{Rows: []influxql.Row{
				influxql.Row{
					Columns: []string{"name"},
					Values:  [][]interface{}{{"foo"}},
				},
			}},
		},
	}
	if !reflect.DeepEqual(results, expectedResults) {
		t.Fatalf("show databases failed.  Unexpected results.  expected: %+v, actual %+v", expectedResults, results)
	}

	// Create a retention policy
	t.Log("Creating retention policy")

	u = urlFor(c.BrokerURL(), "query", url.Values{"q": []string{"CREATE RETENTION POLICY bar ON foo DURATION 1h REPLICATION 1 DEFAULT"}})

	resp, err = httpClient.Get(u.String())
	if err != nil {
		t.Fatalf("Couldn't create retention policy: %s", err)
	}
	defer resp.Body.Close()

	err = json.NewDecoder(resp.Body).Decode(&results)
	if err != nil {
		t.Fatalf("Couldn't decode results: %v", err)
	}

	if results.Error() != nil {
		t.Logf("results.Error(): %q", results.Error().Error())
	}

	if resp.StatusCode != http.StatusOK {
		t.Fatalf("Create retention policy failed.  Unexpected status code.  expected: %d, actual %d", http.StatusOK, resp.StatusCode)
	}

	if len(results.Results) != 1 {
		t.Fatalf("Create retention policy failed.  Unexpected results length.  expected: %d, actual %d", 1, len(results.Results))
	}

	// TODO corylanou: Query the retention policy exists

	// Write Data
	t.Log("Write data")

	u = urlFor(c.BrokerURL(), "write", url.Values{})

	buf := []byte(fmt.Sprintf(`{"database" : "foo", "retentionPolicy" : "bar", "points": [{"name": "cpu", "tags": {"host": "server01"},"timestamp": %d, "precision":"n","values": {"value": 100}}]}`, now.UnixNano()))
	t.Logf("Writing raw data: %s", string(buf))

	resp, err = httpClient.Post(u.String(), "application/json", bytes.NewReader(buf))
	if err != nil {
		t.Fatalf("Couldn't write data: %s", err)
	}
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("Write to database failed.  Unexpected status code.  expected: %d, actual %d", http.StatusOK, resp.StatusCode)
	}

	// Need some time for server to get consensus and write data
	// TODO corylanou query the status endpoint for the server and wait for the index to update to know the write was applied
	time.Sleep(100 * time.Millisecond)

	// Query the data exists
	t.Log("Query data")
	u = urlFor(c.BrokerURL(), "query", url.Values{"q": []string{`select value from "foo"."bar".cpu`}, "db": []string{"foo"}})

	resp, err = httpClient.Get(u.String())
	if err != nil {
		t.Fatalf("Couldn't query databases: %s", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatalf("Coulnd't read body of response: %s", err)
	}
	t.Logf("resp.Body: %s\n", string(body))

	dec := json.NewDecoder(bytes.NewReader(body))
	dec.UseNumber()
	err = dec.Decode(&results)
	if err != nil {
		t.Fatalf("Couldn't decode results: %v", err)
	}

	if results.Error() != nil {
		t.Logf("results.Error(): %q", results.Error().Error())
	}

	if resp.StatusCode != http.StatusOK {
		t.Fatalf("query databases failed.  Unexpected status code.  expected: %d, actual %d", http.StatusOK, resp.StatusCode)
	}

	expectedResults = client.Results{
		Results: []client.Result{
			{Rows: []influxql.Row{
				{
					Name:    "cpu",
					Columns: []string{"time", "value"},
					Values: [][]interface{}{
						[]interface{}{now.Format(time.RFC3339Nano), json.Number("100")},
					},
				}}},
		},
	}

	if !reflect.DeepEqual(results, expectedResults) {
		t.Logf("Expected:\n")
		t.Logf("%#v\n", expectedResults)
		t.Logf("Actual:\n")
		t.Logf("%#v\n", results)
		t.Fatalf("query databases failed.  Unexpected results.")
	}
}

func urlFor(u *url.URL, path string, params url.Values) *url.URL {
	u.Path = path
	u.RawQuery = params.Encode()
	return u
}
<commit_msg>Temporarily skip test.<commit_after>package main_test

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"reflect"
	"testing"
	"time"

	"github.com/influxdb/influxdb/client"
	"github.com/influxdb/influxdb/influxql"

	main "github.com/influxdb/influxdb/cmd/influxd"
)

func Test_ServerSingleIntegration(t *testing.T) {
	t.Skip("pending review")

	var (
		join    = ""
		version = "x.x"
	)

	tmpDir := os.TempDir()
	tmpBrokerDir := filepath.Join(tmpDir, "broker")
	tmpDataDir := filepath.Join(tmpDir, "data")
	t.Logf("Using tmp directorie %q for broker\n", tmpBrokerDir)
	t.Logf("Using tmp directorie %q for data\n", tmpDataDir)
	// Sometimes if this test fails, it's because of a log.Fatal() in the program.
	// This prevents the defer from cleaning up directories.
	// To be safe, nuke them always before starting
	_ = os.RemoveAll(tmpBrokerDir)
	_ = os.RemoveAll(tmpDataDir)

	c := main.NewConfig()
	c.Broker.Dir = tmpBrokerDir
	c.Broker.Port = 8090
	c.Data.Dir = tmpDataDir
	c.Data.Port = 8090

	now := time.Now().UTC()

	s := main.Run(c, join, version, os.Stderr)

	defer func() {
		t.Log("Shutting down server and cleaning up tmp directories")
		if s != nil {
			s.Close()
		}

		err := os.RemoveAll(tmpBrokerDir)
		if err != nil {
			t.Logf("Failed to clean up %q: %s\n", tmpBrokerDir, err)
		}
		err = os.RemoveAll(tmpDataDir)
		if err != nil {
			t.Logf("Failed to clean up %q: %s\n", tmpDataDir, err)
		}
	}()

	if s == nil {
		t.Fatalf("Failed to open server")
	}

	// Create a database
	t.Log("Creating database")

	u := urlFor(c.BrokerURL(), "query", url.Values{"q": []string{"CREATE DATABASE foo"}})
	httpClient := http.Client{Timeout: 100 * time.Millisecond}

	resp, err := httpClient.Get(u.String())
	if err != nil {
		t.Fatalf("Couldn't create database: %s", err)
	}
	defer resp.Body.Close()

	var results client.Results
	err = json.NewDecoder(resp.Body).Decode(&results)
	if err != nil {
		t.Fatalf("Couldn't decode results: %v", err)
	}

	if results.Error() != nil {
		t.Logf("results.Error(): %q", results.Error().Error())
	}

	if resp.StatusCode != http.StatusOK {
		t.Fatalf("Create database failed.  Unexpected status code.  expected: %d, actual %d", http.StatusOK, resp.StatusCode)
	}

	if len(results.Results) != 1 {
		t.Fatalf("Create database failed.  Unexpected results length.  expected: %d, actual %d", 1, len(results.Results))
	}

	// Query the database exists
	u = urlFor(c.BrokerURL(), "query", url.Values{"q": []string{"SHOW DATABASES"}})

	resp, err = httpClient.Get(u.String())
	if err != nil {
		t.Fatalf("Couldn't query databases: %s", err)
	}
	defer resp.Body.Close()

	err = json.NewDecoder(resp.Body).Decode(&results)
	if err != nil {
		t.Fatalf("Couldn't decode results: %v", err)
	}

	if results.Error() != nil {
		t.Logf("results.Error(): %q", results.Error().Error())
	}

	if resp.StatusCode != http.StatusOK {
		t.Fatalf("show databases failed.  Unexpected status code.  expected: %d, actual %d", http.StatusOK, resp.StatusCode)
	}

	expectedResults := client.Results{
		Results: []client.Result{
			{Rows: []influxql.Row{
				influxql.Row{
					Columns: []string{"name"},
					Values:  [][]interface{}{{"foo"}},
				},
			}},
		},
	}
	if !reflect.DeepEqual(results, expectedResults) {
		t.Fatalf("show databases failed.  Unexpected results.  expected: %+v, actual %+v", expectedResults, results)
	}

	// Create a retention policy
	t.Log("Creating retention policy")

	u = urlFor(c.BrokerURL(), "query", url.Values{"q": []string{"CREATE RETENTION POLICY bar ON foo DURATION 1h REPLICATION 1 DEFAULT"}})

	resp, err = httpClient.Get(u.String())
	if err != nil {
		t.Fatalf("Couldn't create retention policy: %s", err)
	}
	defer resp.Body.Close()

	err = json.NewDecoder(resp.Body).Decode(&results)
	if err != nil {
		t.Fatalf("Couldn't decode results: %v", err)
	}

	if results.Error() != nil {
		t.Logf("results.Error(): %q", results.Error().Error())
	}

	if resp.StatusCode != http.StatusOK {
		t.Fatalf("Create retention policy failed.  Unexpected status code.  expected: %d, actual %d", http.StatusOK, resp.StatusCode)
	}

	if len(results.Results) != 1 {
		t.Fatalf("Create retention policy failed.  Unexpected results length.  expected: %d, actual %d", 1, len(results.Results))
	}

	// TODO corylanou: Query the retention policy exists

	// Write Data
	t.Log("Write data")

	u = urlFor(c.BrokerURL(), "write", url.Values{})

	buf := []byte(fmt.Sprintf(`{"database" : "foo", "retentionPolicy" : "bar", "points": [{"name": "cpu", "tags": {"host": "server01"},"timestamp": %d, "precision":"n","values": {"value": 100}}]}`, now.UnixNano()))
	t.Logf("Writing raw data: %s", string(buf))

	resp, err = httpClient.Post(u.String(), "application/json", bytes.NewReader(buf))
	if err != nil {
		t.Fatalf("Couldn't write data: %s", err)
	}
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("Write to database failed.  Unexpected status code.  expected: %d, actual %d", http.StatusOK, resp.StatusCode)
	}

	// Need some time for server to get consensus and write data
	// TODO corylanou query the status endpoint for the server and wait for the index to update to know the write was applied
	time.Sleep(100 * time.Millisecond)

	// Query the data exists
	t.Log("Query data")
	u = urlFor(c.BrokerURL(), "query", url.Values{"q": []string{`select value from "foo"."bar".cpu`}, "db": []string{"foo"}})

	resp, err = httpClient.Get(u.String())
	if err != nil {
		t.Fatalf("Couldn't query databases: %s", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatalf("Coulnd't read body of response: %s", err)
	}
	t.Logf("resp.Body: %s\n", string(body))

	dec := json.NewDecoder(bytes.NewReader(body))
	dec.UseNumber()
	err = dec.Decode(&results)
	if err != nil {
		t.Fatalf("Couldn't decode results: %v", err)
	}

	if results.Error() != nil {
		t.Logf("results.Error(): %q", results.Error().Error())
	}

	if resp.StatusCode != http.StatusOK {
		t.Fatalf("query databases failed.  Unexpected status code.  expected: %d, actual %d", http.StatusOK, resp.StatusCode)
	}

	expectedResults = client.Results{
		Results: []client.Result{
			{Rows: []influxql.Row{
				{
					Name:    "cpu",
					Columns: []string{"time", "value"},
					Values: [][]interface{}{
						[]interface{}{now.Format(time.RFC3339Nano), json.Number("100")},
					},
				}}},
		},
	}

	if !reflect.DeepEqual(results, expectedResults) {
		t.Logf("Expected:\n")
		t.Logf("%#v\n", expectedResults)
		t.Logf("Actual:\n")
		t.Logf("%#v\n", results)
		t.Fatalf("query databases failed.  Unexpected results.")
	}
}

func urlFor(u *url.URL, path string, params url.Values) *url.URL {
	u.Path = path
	u.RawQuery = params.Encode()
	return u
}
<|endoftext|>


<commit_before>package resolves

import (
	"fmt"

	"github.com/wanliu/brain_data/database"
	"github.com/wanliu/flow/builtin/config"
	"github.com/wanliu/flow/context"
)

type CustomerCreation struct {
	Customer string
	Address  string
	Phone    string
	// OrderId uint
}

func (cc CustomerCreation) SetUp(ctx context.Context) {
	ctx.SetValue(config.CtxKeyConfirm, cc)
}

func (cc CustomerCreation) ClearUp(ctx context.Context) {
	ctx.SetValue(config.CtxKeyConfirm, nil)
}

func (cc CustomerCreation) Notice(ctx context.Context) string {
	return fmt.Sprintf("是否添加\"%v\"为新的客户？？", cc.Customer)
}

func (cc CustomerCreation) Cancel(ctx context.Context) string {
	cc.ClearUp(ctx)

	return fmt.Sprintf("已经取消添加\"%v\"为新客户的操作", cc.Customer)
}

func (cc CustomerCreation) Confirm(ctx context.Context) string {
	person := database.People{
		Name: cc.Customer,
	}

	err := database.CreatePerson(&person)

	if err == nil {
		oInt := ctx.Value(config.CtxKeyOrder)
		// confirm := ctx.Value(config.CtxKeyConfirm)

		if oInt != nil {
			order := oInt.(OrderResolve)

			if order.Expired(config.SesssionExpiredMinutes) {
				return fmt.Sprintf("添加了新的客户\"%v\", 当前没有正在进行中的订单", cc.Customer)
			}

			order.Customer = person.Name

			return fmt.Sprintf("添加了新的客户\"%v\"\n%v", cc.Customer, order.Answer(ctx))
		} else {
			return fmt.Sprintf("添加了新的客户\"%v\", 当前没有正在进行中的订单", cc.Customer)
		}
	} else {
		return fmt.Sprintf("添加新的客户\"%v\"失败，%v", cc.Customer, err.Error())
	}
}
<commit_msg>modify current order<commit_after>package resolves

import (
	"fmt"

	"github.com/wanliu/brain_data/database"
	"github.com/wanliu/flow/builtin/config"
	"github.com/wanliu/flow/context"
)

type CustomerCreation struct {
	Customer string
	Address  string
	Phone    string
	// OrderId uint
}

func (cc CustomerCreation) SetUp(ctx context.Context) {
	ctx.SetValue(config.CtxKeyConfirm, cc)
}

func (cc CustomerCreation) ClearUp(ctx context.Context) {
	ctx.SetValue(config.CtxKeyConfirm, nil)
}

func (cc CustomerCreation) Notice(ctx context.Context) string {
	return fmt.Sprintf("是否添加\"%v\"为新的客户？？", cc.Customer)
}

func (cc CustomerCreation) Cancel(ctx context.Context) string {
	cc.ClearUp(ctx)

	oInt := ctx.Value(config.CtxKeyOrder)
	// confirm := ctx.Value(config.CtxKeyConfirm)

	if oInt != nil {
		order := oInt.(OrderResolve)
		order.ExtractedCustomer = ""

		if order.Expired(config.SesssionExpiredMinutes) {
			return fmt.Sprintf("已经取消添加\"%v\"为新客户的操作", cc.Customer)
		}

		ctx.SetValue(config.CtxKeyOrder, order)
		return fmt.Sprintf("已经取消添加\"%v\"为新客户的操作\n%v", cc.Customer, order.Answer(ctx))
	} else {
		return fmt.Sprintf("已经取消添加\"%v\"为新客户的操作, 当前没有正在进行中的订单", cc.Customer)
	}

	return ""
}

func (cc CustomerCreation) Confirm(ctx context.Context) string {
	person := database.People{
		Name: cc.Customer,
	}

	err := database.CreatePerson(&person)

	if err == nil {
		oInt := ctx.Value(config.CtxKeyOrder)
		// confirm := ctx.Value(config.CtxKeyConfirm)

		if oInt != nil {
			order := oInt.(OrderResolve)

			order.Customer = person.Name

			if order.Expired(config.SesssionExpiredMinutes) {
				return fmt.Sprintf("添加了新的客户\"%v\", 当前没有正在进行中的订单", cc.Customer)
			}

			reply := fmt.Sprintf("添加了新的客户\"%v\"\n%v", cc.Customer, order.Answer(ctx))

			if order.Resolved() {
				ctx.SetValue(config.CtxKeyOrder, nil)
				ctx.SetValue(config.CtxKeyLastOrder, order)
			} else if order.Failed() {
				ctx.SetValue(config.CtxKeyOrder, nil)
			} else {
				ctx.SetValue(config.CtxKeyOrder, order)
			}

			return reply
		} else {
			return fmt.Sprintf("添加了新的客户\"%v\", 当前没有正在进行中的订单", cc.Customer)
		}
	} else {
		return fmt.Sprintf("添加新的客户\"%v\"失败，%v", cc.Customer, err.Error())
	}
}
<|endoftext|>


<commit_before>package rest

import (
	"encoding/json"
	"fmt"
	"socialapi/models"

	"labix.org/v2/mgo/bson"
)

func CreateChannelParticipants(channelId, accountId int64, c int) ([]*models.ChannelParticipant, error) {
	var participants []*models.ChannelParticipant
	for i := 0; i < c; i++ {
		participant, err := CreateChannelParticipant(channelId, accountId)
		if err != nil {
			return nil, err
		}

		participants = append(participants, participant)
	}

	return participants, nil
}

func CreateChannelParticipant(channelId, requesterId int64) (*models.ChannelParticipant, error) {
	account := models.NewAccount()
	account.OldId = bson.NewObjectId().Hex()
	account, _ = CreateAccount(account)
	return AddChannelParticipant(channelId, requesterId, account.Id)
}

func ListChannelParticipants(channelId, accountId int64) ([]*models.ChannelParticipant, error) {

	url := fmt.Sprintf("/channel/%d/participants?accountId=%d", channelId, accountId)
	res, err := sendRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	var participants []*models.ChannelParticipant
	err = json.Unmarshal(res, &participants)
	if err != nil {
		return nil, err
	}

	return participants, nil
}

func AddChannelParticipant(channelId, requesterId int64, accountIds ...int64) (*models.ChannelParticipant, error) {

	res := make([]*models.ChannelParticipant, 0)
	for _, accountId := range accountIds {
		c := models.NewChannelParticipant()
		c.AccountId = accountId
		res = append(res, c)
	}

	url := fmt.Sprintf("/channel/%d/participants/add?accountId=%d", channelId, requesterId)
	cps, err := sendModel("POST", url, &res)
	if err != nil {
		return nil, err
	}

	a := *(cps.(*[]*models.ChannelParticipant))

	return a[0], nil
}

func DeleteChannelParticipant(channelId int64, requesterId, accountId int64) (*models.ChannelParticipant, error) {
	c := models.NewChannelParticipant()
	c.AccountId = accountId

	res := []*models.ChannelParticipant{c}

	url := fmt.Sprintf("/channel/%d/participants/remove?accountId=%d", channelId, requesterId)
	cps, err := sendModel("POST", url, &res)
	if err != nil {
		return nil, err
	}

	a := *(cps.(*[]*models.ChannelParticipant))
	return a[0], nil
}
<commit_msg>Socialapi: generalize rest functions for channel participant operations<commit_after>package rest

import (
	"encoding/json"
	"fmt"
	"socialapi/models"

	"labix.org/v2/mgo/bson"
)

func CreateChannelParticipants(channelId, accountId int64, c int) ([]*models.ChannelParticipant, error) {
	var participants []*models.ChannelParticipant
	for i := 0; i < c; i++ {
		participant, err := CreateChannelParticipant(channelId, accountId)
		if err != nil {
			return nil, err
		}

		participants = append(participants, participant)
	}

	return participants, nil
}

func CreateChannelParticipant(channelId, requesterId int64) (*models.ChannelParticipant, error) {
	account := models.NewAccount()
	account.OldId = bson.NewObjectId().Hex()
	account, _ = CreateAccount(account)
	return AddChannelParticipant(channelId, requesterId, account.Id)
}

func ListChannelParticipants(channelId, accountId int64) ([]*models.ChannelParticipant, error) {

	url := fmt.Sprintf("/channel/%d/participants?accountId=%d", channelId, accountId)
	res, err := sendRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	var participants []*models.ChannelParticipant
	err = json.Unmarshal(res, &participants)
	if err != nil {
		return nil, err
	}

	return participants, nil
}

func AddChannelParticipant(channelId, requesterId int64, accountIds ...int64) (*models.ChannelParticipant, error) {
	url := fmt.Sprintf("/channel/%d/participants/add?accountId=%d", channelId, requesterId)
	return channelParticipantOp(
		url,
		channelId,
		requesterId,
		accountIds...,
	)
}

func DeleteChannelParticipant(channelId int64, requesterId, accountId ...int64) (*models.ChannelParticipant, error) {
	url := fmt.Sprintf("/channel/%d/participants/remove?accountId=%d", channelId, requesterId)
	return channelParticipantOp(
		url,
		channelId,
		requesterId,
		accountIds...,
	)
}

func BlockChannelParticipant(channelId int64, requesterId, accountId ...int64) (*models.ChannelParticipant, error) {
	url := fmt.Sprintf("/channel/%d/participants/block?accountId=%d", channelId, requesterId)
	return channelParticipantOp(
		url,
		channelId,
		requesterId,
		accountIds...,
	)
}

func UnblockChannelParticipant(channelId, requesterId int64, accountIds ...int64) (*models.ChannelParticipant, error) {
	url := fmt.Sprintf("/channel/%d/participants/unblock?accountId=%d", channelId, requesterId)
	return channelParticipantOp(
		url,
		channelId,
		requesterId,
		accountIds...,
	)
}

func channelParticipantOp(url string, channelId, requesterId int64, accountIds ...int64) (*models.ChannelParticipant, error) {

	res := make([]*models.ChannelParticipant, 0)
	for _, accountId := range accountIds {
		c := models.NewChannelParticipant()
		c.AccountId = accountId
		res = append(res, c)
	}

	cps, err := sendModel("POST", url, &res)
	if err != nil {
		return nil, err
	}

	a := *(cps.(*[]*models.ChannelParticipant))

	return a[0], nil
}
<|endoftext|>


<commit_before>package cwl

import (
	"fmt"

	//"github.com/davecgh/go-spew/spew"
	"reflect"

	"github.com/MG-RAST/AWE/lib/logger"
	"github.com/davecgh/go-spew/spew"
	"github.com/mitchellh/mapstructure"
)

type WorkflowStep struct {
	Id            string               `yaml:"id,omitempty" bson:"id,omitempty" json:"id,omitempty" mapstructure:"id,omitempty"`
	In            []WorkflowStepInput  `yaml:"in,omitempty" bson:"in,omitempty" json:"in,omitempty" mapstructure:"in,omitempty"` // array<WorkflowStepInput> | map<WorkflowStepInput.id, WorkflowStepInput.source> | map<WorkflowStepInput.id, WorkflowStepInput>
	Out           []WorkflowStepOutput `yaml:"out,omitempty" bson:"out,omitempty" json:"out,omitempty" mapstructure:"out,omitempty"`
	Run           interface{}          `yaml:"run,omitempty" bson:"run,omitempty" json:"run,omitempty" mapstructure:"run,omitempty"`                                     // (*Process) Specification unclear: string | CommandLineTool | ExpressionTool | Workflow
	Requirements  []interface{}        `yaml:"requirements,omitempty" bson:"requirements,omitempty" json:"requirements,omitempty" mapstructure:"requirements,omitempty"` //[]Requirement
	Hints         []interface{}        `yaml:"hints,omitempty" bson:"hints,omitempty" json:"hints,omitempty" mapstructure:"hints,omitempty"`                             //[]Requirement
	Label         string               `yaml:"label,omitempty" bson:"label,omitempty" json:"label,omitempty" mapstructure:"label,omitempty"`
	Doc           string               `yaml:"doc,omitempty" bson:"doc,omitempty" json:"doc,omitempty" mapstructure:"doc,omitempty"`
	Scatter       []string             `yaml:"scatter,omitempty" bson:"scatter,omitempty" json:"scatter,omitempty" mapstructure:"scatter,omitempty"`                         // ScatterFeatureRequirement
	ScatterMethod string               `yaml:"scatterMethod,omitempty" bson:"scatterMethod,omitempty" json:"scatterMethod,omitempty" mapstructure:"scatterMethod,omitempty"` // ScatterFeatureRequirement
}

func NewWorkflowStep(original interface{}, CwlVersion CWLVersion, injectedRequirements *[]Requirement) (w *WorkflowStep, schemata []CWLType_Type, err error) {
	var step WorkflowStep

	logger.Debug(3, "NewWorkflowStep starting")
	original, err = MakeStringMap(original)
	if err != nil {
		return
	}

	switch original.(type) {

	case map[string]interface{}:
		v_map := original.(map[string]interface{})
		//spew.Dump(v_map)

		step_in, ok := v_map["in"]
		if ok {
			v_map["in"], err = CreateWorkflowStepInputArray(step_in)
			if err != nil {
				return
			}
		}

		step_out, ok := v_map["out"]
		if ok {
			v_map["out"], err = NewWorkflowStepOutputArray(step_out)
			if err != nil {
				err = fmt.Errorf("(NewWorkflowStep) CreateWorkflowStepOutputArray %s", err.Error())
				return
			}
		}

		run, ok := v_map["run"]
		if ok {
			var schemata_new []CWLType_Type
			v_map["run"], schemata_new, err = NewProcess(run, CwlVersion)
			if err != nil {
				err = fmt.Errorf("(NewWorkflowStep) run %s", err.Error())
				return
			}
			for i, _ := range schemata_new {
				schemata = append(schemata, schemata_new[i])
			}
		}

		scatter, ok := v_map["scatter"]
		if ok {
			switch scatter.(type) {
			case string:
				var scatter_str string

				scatter_str, ok = scatter.(string)
				if !ok {
					err = fmt.Errorf("(NewWorkflowStep) expected string")
					return
				}
				v_map["scatter"] = []string{scatter_str}

			case []string:
				// all ok
			case []interface{}:
				scatter_array := scatter.([]interface{})
				scatter_string_array := []string{}
				for _, element := range scatter_array {
					var element_str string
					element_str, ok = element.(string)
					if !ok {
						err = fmt.Errorf("(NewWorkflowStep) Element of scatter array is not string (%s)", reflect.TypeOf(element))
						return
					}
					scatter_string_array = append(scatter_string_array, element_str)
				}
				v_map["scatter"] = scatter_string_array

			default:
				err = fmt.Errorf("(NewWorkflowStep) scatter has unsopported type: %s", reflect.TypeOf(scatter))
				return
			}
		}

		scatter, ok = v_map["scatter"]
		if ok {
			switch scatter.(type) {
			case []string:

			default:
				err = fmt.Errorf("(NewWorkflowStep) scatter is not []string: (type: %s)", reflect.TypeOf(scatter))
				return
			}
		}

		hints, ok := v_map["hints"]
		if ok {
			v_map["hints"], schemata, err = CreateRequirementArray(hints)
			if err != nil {
				err = fmt.Errorf("(NewWorkflowStep) CreateRequirementArray %s", err.Error())
				return
			}
		}

		var requirements_array *[]Requirement
		requirements, ok := v_map["requirements"]
		if ok {
			requirements_array, schemata, err = CreateRequirementArray(requirements)
			if err != nil {
				err = fmt.Errorf("(NewWorkflowStep) CreateRequirementArray %s", err.Error())
				return
			}

		}

		for _, r := range *injectedRequirements {
			var requirements_array *[]Requirement
			requirements_array = append(*requirements_array, r)

		}
		v_map["requirements"] = &requirements_array

		//spew.Dump(v_map["run"])
		err = mapstructure.Decode(original, &step)
		if err != nil {
			err = fmt.Errorf("(NewWorkflowStep) %s", err.Error())
			return
		}
		w = &step
		//spew.Dump(w.Run)

		//fmt.Println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")

	default:
		err = fmt.Errorf("(NewWorkflowStep) type %s unknown", reflect.TypeOf(original))

	}

	return
}

func (w WorkflowStep) GetOutput(id string) (output *WorkflowStepOutput, err error) {
	for _, o := range w.Out {
		// o is a WorkflowStepOutput
		if o.Id == id {
			output = &o
			return
		}
	}
	err = fmt.Errorf("WorkflowStepOutput %s not found in WorkflowStep", id)
	return
}

// CreateWorkflowStepsArray
func CreateWorkflowStepsArray(original interface{}, CwlVersion CWLVersion, injectedRequirements *[]Requirement) (schemata []CWLType_Type, array_ptr *[]WorkflowStep, err error) {

	array := []WorkflowStep{}

	if CwlVersion == "" {
		err = fmt.Errorf("(CreateWorkflowStepsArray) CwlVersion empty")
		return
	}
	switch original.(type) {

	case map[interface{}]interface{}:

		// iterate over workflow steps
		for k, v := range original.(map[interface{}]interface{}) {
			//fmt.Printf("A step\n")
			//spew.Dump(v)

			//fmt.Println("type: ")
			//fmt.Println(reflect.TypeOf(v))

			var schemata_new []CWLType_Type
			var step *WorkflowStep
			step, schemata_new, err = NewWorkflowStep(v, CwlVersion, injectedRequirements)
			if err != nil {
				err = fmt.Errorf("(CreateWorkflowStepsArray) NewWorkflowStep failed: %s", err.Error())
				return
			}

			step.Id = k.(string)

			//fmt.Printf("Last step\n")
			//spew.Dump(step)
			//fmt.Printf("C")
			array = append(array, *step)
			for i, _ := range schemata_new {
				schemata = append(schemata, schemata_new[i])
			}
			//fmt.Printf("D")

		}

		array_ptr = &array
		return
	case []interface{}:

		// iterate over workflow steps
		for _, v := range original.([]interface{}) {
			//fmt.Printf("A(2) step\n")
			//spew.Dump(v)

			//fmt.Println("type: ")
			//fmt.Println(reflect.TypeOf(v))
			var schemata_new []CWLType_Type
			var step *WorkflowStep
			step, schemata_new, err = NewWorkflowStep(v, CwlVersion, injectedRequirements)
			if err != nil {
				err = fmt.Errorf("(CreateWorkflowStepsArray) NewWorkflowStep failed: %s", err.Error())
				return
			}
			for i, _ := range schemata_new {
				schemata = append(schemata, schemata_new[i])
			}
			//step.Id = k.(string)

			//fmt.Printf("Last step\n")
			//spew.Dump(step)
			//fmt.Printf("C")
			array = append(array, *step)
			//fmt.Printf("D")

		}

		array_ptr = &array

	default:
		err = fmt.Errorf("(CreateWorkflowStepsArray) Type unknown")

	}
	//spew.Dump(new_array)
	return
}

// func (ws *WorkflowStep) GetInputType(name string) (result CWLType_Type, err error) {

// 	if ws.Run == nil {
// 		err = fmt.Errorf("(WorkflowStep/GetInputType) ws.Run == nil ")
// 		return
// 	}

// 	switch ws.Run.(type) {
// 	case *CommandLineTool:

// 		clt, ok := ws.Run.(*CommandLineTool)
// 		if !ok {
// 			err = fmt.Errorf("(WorkflowStep/GetInputType) type assertion error (%s)", reflect.TypeOf(ws.Run))
// 			return
// 		}
// 		_ = clt

// 		for _, input := range clt.Inputs {
// 			if input.Id == name {
// 				result = input.Type
// 			}

// 		}

// 	case *ExpressionTool:
// 		et, ok := ws.Run.(*ExpressionTool)
// 		if !ok {
// 			err = fmt.Errorf("(WorkflowStep/GetInputType) type assertion error (%s)", reflect.TypeOf(ws.Run))
// 			return
// 		}
// 		_ = et
// 	case *Workflow:
// 		wf, ok := ws.Run.(*Workflow)
// 		if !ok {
// 			err = fmt.Errorf("(WorkflowStep/GetInputType) type assertion error (%s)", reflect.TypeOf(ws.Run))
// 			return
// 		}
// 		_ = wf
// 	default:
// 		err = fmt.Errorf("(WorkflowStep/GetInputType) process type not supported (%s)", reflect.TypeOf(ws.Run))
// 		return
// 	}
// 	return
// }

func GetProcess(original interface{}, collection *CWL_collection, CwlVersion CWLVersion, input_schemata []CWLType_Type) (process interface{}, schemata []CWLType_Type, err error) {

	var p interface{}
	p, err = MakeStringMap(original)
	if err != nil {
		return
	}

	var clt *CommandLineTool
	var et *ExpressionTool
	var wfl *Workflow

	switch p.(type) {
	case string:

		process_name := p.(string)

		clt, err = collection.GetCommandLineTool(process_name)
		if err == nil {
			process = clt
			return
		}
		err = nil

		et, err = collection.GetExpressionTool(process_name)
		if err == nil {
			process = et
			return
		}
		err = nil

		wfl, err = collection.GetWorkflow(process_name)
		if err == nil {
			process = wfl
			return
		}
		err = nil
		spew.Dump(collection)
		err = fmt.Errorf("(GetProcess) Process %s not found ", process_name)

	case map[string]interface{}:

		//fmt.Println("GetProcess got:")
		//spew.Dump(p)

		p_map := p.(map[string]interface{})

		class_name_if, ok := p_map["class"]
		if ok {
			var class_name string
			class_name, ok = class_name_if.(string)
			if ok {
				switch class_name {
				case "CommandLineTool":

					clt, schemata, err = NewCommandLineTool(p, CwlVersion)
					process = clt
					return
				case "Workflow":
					wfl, schemata, err = NewWorkflow(p, CwlVersion)
					process = wfl
					return
				case "ExpressionTool":
					et, err = NewExpressionTool(p, "", input_schemata)
					process = et
					return
				default:
					err = fmt.Errorf("(GetProcess) class \"%s\" not a supported process", class_name)
					return
				}

			}
		}

		// in case of bson, check field "value"
		//process_name_interface, ok := p_map["value"]
		//if !ok {
		//	err = fmt.Errorf("(GetProcess) map did not hold a field named value")
		//	return
		//}
		//
		//process_name, ok = process_name_interface.(string)
		//if !ok {
		//	err = fmt.Errorf("(GetProcess) map value field is not a string")
		//	return
		//}

	default:
		err = fmt.Errorf("(GetProcess) Process type %s unknown", reflect.TypeOf(p))

	}

	return
}
<commit_msg>minor fix<commit_after>package cwl

import (
	"fmt"

	//"github.com/davecgh/go-spew/spew"
	"reflect"

	"github.com/MG-RAST/AWE/lib/logger"
	"github.com/davecgh/go-spew/spew"
	"github.com/mitchellh/mapstructure"
)

type WorkflowStep struct {
	Id            string               `yaml:"id,omitempty" bson:"id,omitempty" json:"id,omitempty" mapstructure:"id,omitempty"`
	In            []WorkflowStepInput  `yaml:"in,omitempty" bson:"in,omitempty" json:"in,omitempty" mapstructure:"in,omitempty"` // array<WorkflowStepInput> | map<WorkflowStepInput.id, WorkflowStepInput.source> | map<WorkflowStepInput.id, WorkflowStepInput>
	Out           []WorkflowStepOutput `yaml:"out,omitempty" bson:"out,omitempty" json:"out,omitempty" mapstructure:"out,omitempty"`
	Run           interface{}          `yaml:"run,omitempty" bson:"run,omitempty" json:"run,omitempty" mapstructure:"run,omitempty"`                                     // (*Process) Specification unclear: string | CommandLineTool | ExpressionTool | Workflow
	Requirements  []interface{}        `yaml:"requirements,omitempty" bson:"requirements,omitempty" json:"requirements,omitempty" mapstructure:"requirements,omitempty"` //[]Requirement
	Hints         []interface{}        `yaml:"hints,omitempty" bson:"hints,omitempty" json:"hints,omitempty" mapstructure:"hints,omitempty"`                             //[]Requirement
	Label         string               `yaml:"label,omitempty" bson:"label,omitempty" json:"label,omitempty" mapstructure:"label,omitempty"`
	Doc           string               `yaml:"doc,omitempty" bson:"doc,omitempty" json:"doc,omitempty" mapstructure:"doc,omitempty"`
	Scatter       []string             `yaml:"scatter,omitempty" bson:"scatter,omitempty" json:"scatter,omitempty" mapstructure:"scatter,omitempty"`                         // ScatterFeatureRequirement
	ScatterMethod string               `yaml:"scatterMethod,omitempty" bson:"scatterMethod,omitempty" json:"scatterMethod,omitempty" mapstructure:"scatterMethod,omitempty"` // ScatterFeatureRequirement
}

func NewWorkflowStep(original interface{}, CwlVersion CWLVersion, injectedRequirements *[]Requirement) (w *WorkflowStep, schemata []CWLType_Type, err error) {
	var step WorkflowStep

	logger.Debug(3, "NewWorkflowStep starting")
	original, err = MakeStringMap(original)
	if err != nil {
		return
	}

	switch original.(type) {

	case map[string]interface{}:
		v_map := original.(map[string]interface{})
		//spew.Dump(v_map)

		step_in, ok := v_map["in"]
		if ok {
			v_map["in"], err = CreateWorkflowStepInputArray(step_in)
			if err != nil {
				return
			}
		}

		step_out, ok := v_map["out"]
		if ok {
			v_map["out"], err = NewWorkflowStepOutputArray(step_out)
			if err != nil {
				err = fmt.Errorf("(NewWorkflowStep) CreateWorkflowStepOutputArray %s", err.Error())
				return
			}
		}

		run, ok := v_map["run"]
		if ok {
			var schemata_new []CWLType_Type
			v_map["run"], schemata_new, err = NewProcess(run, CwlVersion)
			if err != nil {
				err = fmt.Errorf("(NewWorkflowStep) run %s", err.Error())
				return
			}
			for i, _ := range schemata_new {
				schemata = append(schemata, schemata_new[i])
			}
		}

		scatter, ok := v_map["scatter"]
		if ok {
			switch scatter.(type) {
			case string:
				var scatter_str string

				scatter_str, ok = scatter.(string)
				if !ok {
					err = fmt.Errorf("(NewWorkflowStep) expected string")
					return
				}
				v_map["scatter"] = []string{scatter_str}

			case []string:
				// all ok
			case []interface{}:
				scatter_array := scatter.([]interface{})
				scatter_string_array := []string{}
				for _, element := range scatter_array {
					var element_str string
					element_str, ok = element.(string)
					if !ok {
						err = fmt.Errorf("(NewWorkflowStep) Element of scatter array is not string (%s)", reflect.TypeOf(element))
						return
					}
					scatter_string_array = append(scatter_string_array, element_str)
				}
				v_map["scatter"] = scatter_string_array

			default:
				err = fmt.Errorf("(NewWorkflowStep) scatter has unsopported type: %s", reflect.TypeOf(scatter))
				return
			}
		}

		scatter, ok = v_map["scatter"]
		if ok {
			switch scatter.(type) {
			case []string:

			default:
				err = fmt.Errorf("(NewWorkflowStep) scatter is not []string: (type: %s)", reflect.TypeOf(scatter))
				return
			}
		}

		hints, ok := v_map["hints"]
		if ok {
			v_map["hints"], schemata, err = CreateRequirementArray(hints)
			if err != nil {
				err = fmt.Errorf("(NewWorkflowStep) CreateRequirementArray %s", err.Error())
				return
			}
		}

		var requirements_array *[]Requirement
		requirements, ok := v_map["requirements"]
		if ok {
			requirements_array, schemata, err = CreateRequirementArray(requirements)
			if err != nil {
				err = fmt.Errorf("(NewWorkflowStep) CreateRequirementArray %s", err.Error())
				return
			}

		}

		//for _, r := range *injectedRequirements {
		//		var requirements_array *[]Requirement
		//		requirements_array = append(*requirements_array, r)
		//
		//		}
		v_map["requirements"] = &requirements_array

		//spew.Dump(v_map["run"])
		err = mapstructure.Decode(original, &step)
		if err != nil {
			err = fmt.Errorf("(NewWorkflowStep) %s", err.Error())
			return
		}
		w = &step
		//spew.Dump(w.Run)

		//fmt.Println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")

	default:
		err = fmt.Errorf("(NewWorkflowStep) type %s unknown", reflect.TypeOf(original))

	}

	return
}

func (w WorkflowStep) GetOutput(id string) (output *WorkflowStepOutput, err error) {
	for _, o := range w.Out {
		// o is a WorkflowStepOutput
		if o.Id == id {
			output = &o
			return
		}
	}
	err = fmt.Errorf("WorkflowStepOutput %s not found in WorkflowStep", id)
	return
}

// CreateWorkflowStepsArray
func CreateWorkflowStepsArray(original interface{}, CwlVersion CWLVersion, injectedRequirements *[]Requirement) (schemata []CWLType_Type, array_ptr *[]WorkflowStep, err error) {

	array := []WorkflowStep{}

	if CwlVersion == "" {
		err = fmt.Errorf("(CreateWorkflowStepsArray) CwlVersion empty")
		return
	}
	switch original.(type) {

	case map[interface{}]interface{}:

		// iterate over workflow steps
		for k, v := range original.(map[interface{}]interface{}) {
			//fmt.Printf("A step\n")
			//spew.Dump(v)

			//fmt.Println("type: ")
			//fmt.Println(reflect.TypeOf(v))

			var schemata_new []CWLType_Type
			var step *WorkflowStep
			step, schemata_new, err = NewWorkflowStep(v, CwlVersion, injectedRequirements)
			if err != nil {
				err = fmt.Errorf("(CreateWorkflowStepsArray) NewWorkflowStep failed: %s", err.Error())
				return
			}

			step.Id = k.(string)

			//fmt.Printf("Last step\n")
			//spew.Dump(step)
			//fmt.Printf("C")
			array = append(array, *step)
			for i, _ := range schemata_new {
				schemata = append(schemata, schemata_new[i])
			}
			//fmt.Printf("D")

		}

		array_ptr = &array
		return
	case []interface{}:

		// iterate over workflow steps
		for _, v := range original.([]interface{}) {
			//fmt.Printf("A(2) step\n")
			//spew.Dump(v)

			//fmt.Println("type: ")
			//fmt.Println(reflect.TypeOf(v))
			var schemata_new []CWLType_Type
			var step *WorkflowStep
			step, schemata_new, err = NewWorkflowStep(v, CwlVersion, injectedRequirements)
			if err != nil {
				err = fmt.Errorf("(CreateWorkflowStepsArray) NewWorkflowStep failed: %s", err.Error())
				return
			}
			for i, _ := range schemata_new {
				schemata = append(schemata, schemata_new[i])
			}
			//step.Id = k.(string)

			//fmt.Printf("Last step\n")
			//spew.Dump(step)
			//fmt.Printf("C")
			array = append(array, *step)
			//fmt.Printf("D")

		}

		array_ptr = &array

	default:
		err = fmt.Errorf("(CreateWorkflowStepsArray) Type unknown")

	}
	//spew.Dump(new_array)
	return
}

// func (ws *WorkflowStep) GetInputType(name string) (result CWLType_Type, err error) {

// 	if ws.Run == nil {
// 		err = fmt.Errorf("(WorkflowStep/GetInputType) ws.Run == nil ")
// 		return
// 	}

// 	switch ws.Run.(type) {
// 	case *CommandLineTool:

// 		clt, ok := ws.Run.(*CommandLineTool)
// 		if !ok {
// 			err = fmt.Errorf("(WorkflowStep/GetInputType) type assertion error (%s)", reflect.TypeOf(ws.Run))
// 			return
// 		}
// 		_ = clt

// 		for _, input := range clt.Inputs {
// 			if input.Id == name {
// 				result = input.Type
// 			}

// 		}

// 	case *ExpressionTool:
// 		et, ok := ws.Run.(*ExpressionTool)
// 		if !ok {
// 			err = fmt.Errorf("(WorkflowStep/GetInputType) type assertion error (%s)", reflect.TypeOf(ws.Run))
// 			return
// 		}
// 		_ = et
// 	case *Workflow:
// 		wf, ok := ws.Run.(*Workflow)
// 		if !ok {
// 			err = fmt.Errorf("(WorkflowStep/GetInputType) type assertion error (%s)", reflect.TypeOf(ws.Run))
// 			return
// 		}
// 		_ = wf
// 	default:
// 		err = fmt.Errorf("(WorkflowStep/GetInputType) process type not supported (%s)", reflect.TypeOf(ws.Run))
// 		return
// 	}
// 	return
// }

func GetProcess(original interface{}, collection *CWL_collection, CwlVersion CWLVersion, input_schemata []CWLType_Type) (process interface{}, schemata []CWLType_Type, err error) {

	var p interface{}
	p, err = MakeStringMap(original)
	if err != nil {
		return
	}

	var clt *CommandLineTool
	var et *ExpressionTool
	var wfl *Workflow

	switch p.(type) {
	case string:

		process_name := p.(string)

		clt, err = collection.GetCommandLineTool(process_name)
		if err == nil {
			process = clt
			return
		}
		err = nil

		et, err = collection.GetExpressionTool(process_name)
		if err == nil {
			process = et
			return
		}
		err = nil

		wfl, err = collection.GetWorkflow(process_name)
		if err == nil {
			process = wfl
			return
		}
		err = nil
		spew.Dump(collection)
		err = fmt.Errorf("(GetProcess) Process %s not found ", process_name)

	case map[string]interface{}:

		//fmt.Println("GetProcess got:")
		//spew.Dump(p)

		p_map := p.(map[string]interface{})

		class_name_if, ok := p_map["class"]
		if ok {
			var class_name string
			class_name, ok = class_name_if.(string)
			if ok {
				switch class_name {
				case "CommandLineTool":

					clt, schemata, err = NewCommandLineTool(p, CwlVersion)
					process = clt
					return
				case "Workflow":
					wfl, schemata, err = NewWorkflow(p, CwlVersion)
					process = wfl
					return
				case "ExpressionTool":
					et, err = NewExpressionTool(p, "", input_schemata)
					process = et
					return
				default:
					err = fmt.Errorf("(GetProcess) class \"%s\" not a supported process", class_name)
					return
				}

			}
		}

		// in case of bson, check field "value"
		//process_name_interface, ok := p_map["value"]
		//if !ok {
		//	err = fmt.Errorf("(GetProcess) map did not hold a field named value")
		//	return
		//}
		//
		//process_name, ok = process_name_interface.(string)
		//if !ok {
		//	err = fmt.Errorf("(GetProcess) map value field is not a string")
		//	return
		//}

	default:
		err = fmt.Errorf("(GetProcess) Process type %s unknown", reflect.TypeOf(p))

	}

	return
}
<|endoftext|>


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

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"syscall"

	vc "github.com/containers/virtcontainers"
	"github.com/containers/virtcontainers/pkg/oci"
	specs "github.com/opencontainers/runtime-spec/specs-go"
	"github.com/urfave/cli"
)

type execParams struct {
	ociProcess   oci.CompatOCIProcess
	cID          string
	pidFile      string
	console      string
	consoleSock  string
	detach       bool
	processLabel string
	noSubreaper  bool
}

var execCLICommand = cli.Command{
	Name:  "exec",
	Usage: "Execute new process inside the container",
	ArgsUsage: `<container-id> <command> [command options]  || -p process.json <container-id>

   <container-id> is the name for the instance of the container and <command>
   is the command to be executed in the container. <command> can't be empty
   unless a "-p" flag provided.

EXAMPLE:
   If the container is configured to run the linux ps command the following
   will output a list of processes running in the container:

       # ` + name + ` <container-id> ps`,
	Flags: []cli.Flag{
		cli.StringFlag{
			Name:  "console",
			Usage: "path to a pseudo terminal",
		},
		cli.StringFlag{
			Name:  "console-socket",
			Value: "",
			Usage: "path to an AF_UNIX socket which will receive a file descriptor referencing the master end of the console's pseudoterminal",
		},
		cli.StringFlag{
			Name:  "cwd",
			Usage: "current working directory in the container",
		},
		cli.StringSliceFlag{
			Name:  "env, e",
			Usage: "set environment variables",
		},
		cli.BoolFlag{
			Name:  "tty, t",
			Usage: "allocate a pseudo-TTY",
		},
		cli.StringFlag{
			Name:  "user, u",
			Usage: "UID (format: <uid>[:<gid>])",
		},
		cli.StringFlag{
			Name:  "process, p",
			Usage: "path to the process.json",
		},
		cli.BoolFlag{
			Name:  "detach,d",
			Usage: "detach from the container's process",
		},
		cli.StringFlag{
			Name:  "pid-file",
			Value: "",
			Usage: "specify the file to write the process id to",
		},
		cli.StringFlag{
			Name:  "process-label",
			Usage: "set the asm process label for the process commonly used with selinux",
		},
		cli.StringFlag{
			Name:  "apparmor",
			Usage: "set the apparmor profile for the process",
		},
		cli.BoolFlag{
			Name:  "no-new-privs",
			Usage: "set the no new privileges value for the process",
		},
		cli.StringSliceFlag{
			Name:  "cap, c",
			Value: &cli.StringSlice{},
			Usage: "add a capability to the bounding set for the process",
		},
		cli.BoolFlag{
			Name:   "no-subreaper",
			Usage:  "disable the use of the subreaper used to reap reparented processes",
			Hidden: true,
		},
	},
	Action: func(context *cli.Context) error {
		return execute(context)
	},
}

func generateExecParams(context *cli.Context, specProcess *oci.CompatOCIProcess) (execParams, error) {
	ctxArgs := context.Args()

	params := execParams{
		cID:          ctxArgs.First(),
		pidFile:      context.String("pid-file"),
		console:      context.String("console"),
		consoleSock:  context.String("console-socket"),
		detach:       context.Bool("detach"),
		processLabel: context.String("process-label"),
		noSubreaper:  context.Bool("no-subreaper"),
	}

	if context.String("process") != "" {
		var ociProcess oci.CompatOCIProcess

		fileContent, err := ioutil.ReadFile(context.String("process"))
		if err != nil {
			return execParams{}, err
		}

		if err := json.Unmarshal(fileContent, &ociProcess); err != nil {
			return execParams{}, err
		}

		params.ociProcess = ociProcess
	} else {
		params.ociProcess = *specProcess

		// Override terminal
		if context.IsSet("tty") {
			params.ociProcess.Terminal = context.Bool("tty")
		}

		// Override user
		if context.String("user") != "" {
			params.ociProcess.User = specs.User{
				Username: context.String("user"),
			}
		}

		// Override env
		params.ociProcess.Env = append(params.ociProcess.Env, context.StringSlice("env")...)

		// Override cwd
		if context.String("cwd") != "" {
			params.ociProcess.Cwd = context.String("cwd")
		}

		// Override no-new-privs
		if context.IsSet("no-new-privs") {
			params.ociProcess.NoNewPrivileges = context.Bool("no-new-privs")
		}

		// Override apparmor
		if context.String("apparmor") != "" {
			params.ociProcess.ApparmorProfile = context.String("apparmor")
		}

		params.ociProcess.Args = ctxArgs.Tail()
	}

	return params, nil
}

func execute(context *cli.Context) error {
	containerID := context.Args().First()
	status, podID, err := getExistingContainerInfo(containerID)
	if err != nil {
		return err
	}

	// Retrieve OCI spec configuration.
	ociSpec, err := oci.GetOCIConfig(status)
	if err != nil {
		return err
	}

	params, err := generateExecParams(context, ociSpec.Process)
	if err != nil {
		return err
	}

	params.cID = status.ID

	// container MUST be running
	if status.State.State != vc.StateRunning {
		return fmt.Errorf("Container %s is not running", params.cID)
	}

	envVars, err := oci.EnvVars(params.ociProcess.Env)
	if err != nil {
		return err
	}

	consolePath, err := setupConsole(params.console, params.consoleSock)
	if err != nil {
		return err
	}

	cmd := vc.Cmd{
		Args:        params.ociProcess.Args,
		Envs:        envVars,
		WorkDir:     params.ociProcess.Cwd,
		User:        params.ociProcess.User.Username,
		Interactive: params.ociProcess.Terminal,
		Console:     consolePath,
		Detach:      noNeedForOutput(params.detach, params.ociProcess.Terminal),
	}

	_, _, process, err := vci.EnterContainer(podID, params.cID, cmd)
	if err != nil {
		return err
	}

	// Creation of PID file has to be the last thing done in the exec
	// because containerd considers the exec to have finished starting
	// after this file is created.
	if err := createPIDFile(params.pidFile, process.Pid); err != nil {
		return err
	}

	if params.detach {
		return nil
	}

	p, err := os.FindProcess(process.Pid)
	if err != nil {
		return err
	}

	ps, err := p.Wait()
	if err != nil {
		return fmt.Errorf("Process state %s, container info %+v: %v",
			ps.String(), status, err)
	}

	// Exit code has to be forwarded in this case.
	return cli.NewExitError("", ps.Sys().(syscall.WaitStatus).ExitStatus())
}
<commit_msg>exec: Comments<commit_after>// Copyright (c) 2014,2015,2016 Docker, Inc.
// Copyright (c) 2017 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"syscall"

	vc "github.com/containers/virtcontainers"
	"github.com/containers/virtcontainers/pkg/oci"
	specs "github.com/opencontainers/runtime-spec/specs-go"
	"github.com/urfave/cli"
)

type execParams struct {
	ociProcess   oci.CompatOCIProcess
	cID          string
	pidFile      string
	console      string
	consoleSock  string
	detach       bool
	processLabel string
	noSubreaper  bool
}

var execCLICommand = cli.Command{
	Name:  "exec",
	Usage: "Execute new process inside the container",
	ArgsUsage: `<container-id> <command> [command options]  || -p process.json <container-id>

   <container-id> is the name for the instance of the container and <command>
   is the command to be executed in the container. <command> can't be empty
   unless a "-p" flag provided.

EXAMPLE:
   If the container is configured to run the linux ps command the following
   will output a list of processes running in the container:

       # ` + name + ` <container-id> ps`,
	Flags: []cli.Flag{
		cli.StringFlag{
			Name:  "console",
			Usage: "path to a pseudo terminal",
		},
		cli.StringFlag{
			Name:  "console-socket",
			Value: "",
			Usage: "path to an AF_UNIX socket which will receive a file descriptor referencing the master end of the console's pseudoterminal",
		},
		cli.StringFlag{
			Name:  "cwd",
			Usage: "current working directory in the container",
		},
		cli.StringSliceFlag{
			Name:  "env, e",
			Usage: "set environment variables",
		},
		cli.BoolFlag{
			Name:  "tty, t",
			Usage: "allocate a pseudo-TTY",
		},
		cli.StringFlag{
			Name:  "user, u",
			Usage: "UID (format: <uid>[:<gid>])",
		},
		cli.StringFlag{
			Name:  "process, p",
			Usage: "path to the process.json",
		},
		cli.BoolFlag{
			Name:  "detach,d",
			Usage: "detach from the container's process",
		},
		cli.StringFlag{
			Name:  "pid-file",
			Value: "",
			Usage: "specify the file to write the process id to",
		},
		cli.StringFlag{
			Name:  "process-label",
			Usage: "set the asm process label for the process commonly used with selinux",
		},
		cli.StringFlag{
			Name:  "apparmor",
			Usage: "set the apparmor profile for the process",
		},
		cli.BoolFlag{
			Name:  "no-new-privs",
			Usage: "set the no new privileges value for the process",
		},
		cli.StringSliceFlag{
			Name:  "cap, c",
			Value: &cli.StringSlice{},
			Usage: "add a capability to the bounding set for the process",
		},
		cli.BoolFlag{
			Name:   "no-subreaper",
			Usage:  "disable the use of the subreaper used to reap reparented processes",
			Hidden: true,
		},
	},
	Action: func(context *cli.Context) error {
		return execute(context)
	},
}

func generateExecParams(context *cli.Context, specProcess *oci.CompatOCIProcess) (execParams, error) {
	ctxArgs := context.Args()

	params := execParams{
		cID:          ctxArgs.First(),
		pidFile:      context.String("pid-file"),
		console:      context.String("console"),
		consoleSock:  context.String("console-socket"),
		detach:       context.Bool("detach"),
		processLabel: context.String("process-label"),
		noSubreaper:  context.Bool("no-subreaper"),
	}

	if context.String("process") != "" {
		var ociProcess oci.CompatOCIProcess

		fileContent, err := ioutil.ReadFile(context.String("process"))
		if err != nil {
			return execParams{}, err
		}

		if err := json.Unmarshal(fileContent, &ociProcess); err != nil {
			return execParams{}, err
		}

		params.ociProcess = ociProcess
	} else {
		params.ociProcess = *specProcess

		// Override terminal
		if context.IsSet("tty") {
			params.ociProcess.Terminal = context.Bool("tty")
		}

		// Override user
		if context.String("user") != "" {
			params.ociProcess.User = specs.User{
				// This field is a Windows-only field
				// according to the specification. However, it
				// is abused here to allow the username
				// specified in the OCI runtime configuration
				// file to be overridden by a CLI request.
				Username: context.String("user"),
			}
		}

		// Override env
		params.ociProcess.Env = append(params.ociProcess.Env, context.StringSlice("env")...)

		// Override cwd
		if context.String("cwd") != "" {
			params.ociProcess.Cwd = context.String("cwd")
		}

		// Override no-new-privs
		if context.IsSet("no-new-privs") {
			params.ociProcess.NoNewPrivileges = context.Bool("no-new-privs")
		}

		// Override apparmor
		if context.String("apparmor") != "" {
			params.ociProcess.ApparmorProfile = context.String("apparmor")
		}

		params.ociProcess.Args = ctxArgs.Tail()
	}

	return params, nil
}

func execute(context *cli.Context) error {
	containerID := context.Args().First()
	status, podID, err := getExistingContainerInfo(containerID)
	if err != nil {
		return err
	}

	// Retrieve OCI spec configuration.
	ociSpec, err := oci.GetOCIConfig(status)
	if err != nil {
		return err
	}

	params, err := generateExecParams(context, ociSpec.Process)
	if err != nil {
		return err
	}

	params.cID = status.ID

	// container MUST be running
	if status.State.State != vc.StateRunning {
		return fmt.Errorf("Container %s is not running", params.cID)
	}

	envVars, err := oci.EnvVars(params.ociProcess.Env)
	if err != nil {
		return err
	}

	consolePath, err := setupConsole(params.console, params.consoleSock)
	if err != nil {
		return err
	}

	cmd := vc.Cmd{
		Args:        params.ociProcess.Args,
		Envs:        envVars,
		WorkDir:     params.ociProcess.Cwd,
		User:        params.ociProcess.User.Username,
		Interactive: params.ociProcess.Terminal,
		Console:     consolePath,
		Detach:      noNeedForOutput(params.detach, params.ociProcess.Terminal),
	}

	_, _, process, err := vci.EnterContainer(podID, params.cID, cmd)
	if err != nil {
		return err
	}

	// Creation of PID file has to be the last thing done in the exec
	// because containerd considers the exec to have finished starting
	// after this file is created.
	if err := createPIDFile(params.pidFile, process.Pid); err != nil {
		return err
	}

	if params.detach {
		return nil
	}

	p, err := os.FindProcess(process.Pid)
	if err != nil {
		return err
	}

	ps, err := p.Wait()
	if err != nil {
		return fmt.Errorf("Process state %s, container info %+v: %v",
			ps.String(), status, err)
	}

	// Exit code has to be forwarded in this case.
	return cli.NewExitError("", ps.Sys().(syscall.WaitStatus).ExitStatus())
}
<|endoftext|>


<commit_before>package gate

import (
	"io/ioutil"
	"strings"
	"testing"

	"github.com/elpinal/coco3/config"
	"github.com/elpinal/coco3/editor"
)

func TestGate(t *testing.T) {
	in := strings.NewReader("echo 1" + string(editor.CharCtrlM) + string(editor.CharEscape) + "ka" + string(editor.CharBackspace) + "2" + string(editor.CharCtrlM))
	conf := new(config.Config)
	conf.Init()
	g := New(conf, in, ioutil.Discard, ioutil.Discard).(*gate)
	b, err := g.Read()
	if err != nil {
		t.Errorf("reading input: %v", err)
	}
	if want := "echo 1"; string(b) != want {
		t.Errorf("got %q, want %q", string(b), want)
	}
	b, err = g.Read()
	if err != nil {
		t.Errorf("reading input: %v", err)
	}
	if want := "echo 2"; string(b) != want {
		t.Errorf("got %q, want %q", string(b), want)
	}
	if l := len(g.history); l != 2 {
		t.Errorf("the lenght of history should be %v, got %v", 2, l)
	}
}
<commit_msg>Fix a typo<commit_after>package gate

import (
	"io/ioutil"
	"strings"
	"testing"

	"github.com/elpinal/coco3/config"
	"github.com/elpinal/coco3/editor"
)

func TestGate(t *testing.T) {
	in := strings.NewReader("echo 1" + string(editor.CharCtrlM) + string(editor.CharEscape) + "ka" + string(editor.CharBackspace) + "2" + string(editor.CharCtrlM))
	conf := new(config.Config)
	conf.Init()
	g := New(conf, in, ioutil.Discard, ioutil.Discard).(*gate)
	b, err := g.Read()
	if err != nil {
		t.Errorf("reading input: %v", err)
	}
	if want := "echo 1"; string(b) != want {
		t.Errorf("got %q, want %q", string(b), want)
	}
	b, err = g.Read()
	if err != nil {
		t.Errorf("reading input: %v", err)
	}
	if want := "echo 2"; string(b) != want {
		t.Errorf("got %q, want %q", string(b), want)
	}
	if l := len(g.history); l != 2 {
		t.Errorf("the length of history should be %v, got %v", 2, l)
	}
}
<|endoftext|>


<commit_before>package main // sctl-minion

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

	sctl "github.com/CzarSimon/sctl-common"
	"github.com/CzarSimon/util"
)

// ResetToken Updates the minion token
func (env *Env) ResetToken(res http.ResponseWriter, req *http.Request) {
	var newToken sctl.Token
	err := util.DecodeJSON(req.Body, &newToken)
	if err != nil {
		util.SendErrRes(res, err)
		return
	}
	env.token = newToken
	util.SendOK(res)
}

// LockHandler Handles locking and unlocking
func (env *Env) LockHandler(res http.ResponseWriter, req *http.Request) {
	switch req.URL.Path {
	case "/lock":
		env.lock.Close()
		util.SendOK(res)
		break
	case "/unlock":
		if env.Unlock(req) {
			util.SendOK(res)
		} else {
			util.SendUnauthorized(res)
		}
		break
	default:
		break
	}
}

// MinionLock Holds lock state
type MinionLock struct {
	Open               bool
	FailedAuthAttempts int
	MaxTokenAge        float64
	MaxAttempts        int
}

// NewLock Returns a new open lock with 1 auth attempt left
func NewLock(config LockConfig) MinionLock {
	return MinionLock{
		Open:               true,
		FailedAuthAttempts: config.MaxAttempts - 1,
		MaxTokenAge:        config.TokenMaxAge,
		MaxAttempts:        config.MaxAttempts,
	}
}

// Close Closes the MinionLock
func (lock *MinionLock) Close() {
	lock.Open = false
	lock.FailedAuthAttempts = lock.MaxAttempts + 1
}

// RegisterFail registers an authorization failure
func (lock *MinionLock) RegisterFail() {
	lock.FailedAuthAttempts++
	if lock.FailedAuthAttempts >= lock.MaxAttempts {
		lock.Close()
	}
}

// ValidToken Checks if request token equals the minion token
func (env *Env) ValidToken(req *http.Request) bool {
	if !env.token.Valid(env.lock.MaxTokenAge) {
		fmt.Println(env.token.Timestamp, "To Old")
		env.lock.Close()
		return false
	}
	authSuccess := env.token.Data == req.Header.Get("Authorization")
	if authSuccess {
		env.lock.FailedAuthAttempts = 0
	} else {
		env.lock.RegisterFail()
	}
	return authSuccess
}

// Unlock Compares a candidate token a against the master token and unlocks the minion if they match
func (env *Env) Unlock(req *http.Request) bool {
	var candidate sctl.TokenBundle
	err := util.DecodeJSON(req.Body, &candidate)
	success := err == nil && env.masterToken == candidate.Master
	if success {
		env.token = candidate.Auth
		env.lock.Open = true
		env.lock.FailedAuthAttempts = env.config.Lock.MaxAttempts - 1
	}
	return success
}

// CertificateCommand Creates the command for creation of an rsa certificate and key
func (ssl SSLConfig) CertificateCommand() sctl.Command {
	subject := "/C=SE/ST=Stockholm/L=Stockholm/O=sctl/OU=security/CN=sctl-minion"
	args := []string{
		"req", "-x509", "-newkey", "rsa:4096", "-keyout", ssl.Key,
		"-out", ssl.Cert, "-days", "100", "-nodes", "-subj", subject}
	return sctl.Command{
		Main: "openssl",
		Args: args,
	}
}

// CertGen Generates self-signed ssl certificates
func (ssl SSLConfig) CertGen() {
	err := os.MkdirAll(ssl.Folder, os.ModePerm)
	util.CheckErrFatal(err)
	_, err = ssl.CertificateCommand().Execute()
	util.CheckErrFatal(err)
}

// Auth Checks if a request is made with a valid token
func (env *Env) Auth(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
	return func(res http.ResponseWriter, req *http.Request) {
		if !env.lock.Open {
			logAuthStatus("request made to a locked node", req)
			util.SendErrRes(res, errors.New("node locked"))
		} else if env.ValidToken(req) {
			logAuthStatus("auth success", req)
			handler(res, req)
		} else {
			logAuthStatus("auth failue", req)
			util.SendUnauthorized(res)
		}
	}
}

// logAuthStatus Logs outcome of authorization challange
func logAuthStatus(msg string, req *http.Request) {
	log.Printf("%s from: %s, %s", req.URL.Path, req.RemoteAddr, msg)
}
<commit_msg>Changed valididty period on minion cert generation<commit_after>package main // sctl-minion

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

	sctl "github.com/CzarSimon/sctl-common"
	"github.com/CzarSimon/util"
)

// ResetToken Updates the minion token
func (env *Env) ResetToken(res http.ResponseWriter, req *http.Request) {
	var newToken sctl.Token
	err := util.DecodeJSON(req.Body, &newToken)
	if err != nil {
		util.SendErrRes(res, err)
		return
	}
	env.token = newToken
	util.SendOK(res)
}

// LockHandler Handles locking and unlocking
func (env *Env) LockHandler(res http.ResponseWriter, req *http.Request) {
	switch req.URL.Path {
	case "/lock":
		env.lock.Close()
		util.SendOK(res)
		break
	case "/unlock":
		if env.Unlock(req) {
			util.SendOK(res)
		} else {
			util.SendUnauthorized(res)
		}
		break
	default:
		break
	}
}

// MinionLock Holds lock state
type MinionLock struct {
	Open               bool
	FailedAuthAttempts int
	MaxTokenAge        float64
	MaxAttempts        int
}

// NewLock Returns a new open lock with 1 auth attempt left
func NewLock(config LockConfig) MinionLock {
	return MinionLock{
		Open:               true,
		FailedAuthAttempts: config.MaxAttempts - 1,
		MaxTokenAge:        config.TokenMaxAge,
		MaxAttempts:        config.MaxAttempts,
	}
}

// Close Closes the MinionLock
func (lock *MinionLock) Close() {
	lock.Open = false
	lock.FailedAuthAttempts = lock.MaxAttempts + 1
}

// RegisterFail registers an authorization failure
func (lock *MinionLock) RegisterFail() {
	lock.FailedAuthAttempts++
	if lock.FailedAuthAttempts >= lock.MaxAttempts {
		lock.Close()
	}
}

// ValidToken Checks if request token equals the minion token
func (env *Env) ValidToken(req *http.Request) bool {
	if !env.token.Valid(env.lock.MaxTokenAge) {
		fmt.Println(env.token.Timestamp, "To Old")
		env.lock.Close()
		return false
	}
	authSuccess := env.token.Data == req.Header.Get("Authorization")
	if authSuccess {
		env.lock.FailedAuthAttempts = 0
	} else {
		env.lock.RegisterFail()
	}
	return authSuccess
}

// Unlock Compares a candidate token a against the master token and unlocks the minion if they match
func (env *Env) Unlock(req *http.Request) bool {
	var candidate sctl.TokenBundle
	err := util.DecodeJSON(req.Body, &candidate)
	success := err == nil && env.masterToken == candidate.Master
	if success {
		env.token = candidate.Auth
		env.lock.Open = true
		env.lock.FailedAuthAttempts = env.config.Lock.MaxAttempts - 1
	}
	return success
}

// CertificateCommand Creates the command for creation of an rsa certificate and key
func (ssl SSLConfig) CertificateCommand() sctl.Command {
	subject := "/C=SE/ST=Stockholm/L=Stockholm/O=sctl/OU=security/CN=sctl-minion"
	args := []string{
		"req", "-x509", "-newkey", "rsa:4096", "-keyout", ssl.Key,
		"-out", ssl.Cert, "-days", "730", "-nodes", "-subj", subject}
	return sctl.Command{
		Main: "openssl",
		Args: args,
	}
}

// CertGen Generates self-signed ssl certificates
func (ssl SSLConfig) CertGen() {
	err := os.MkdirAll(ssl.Folder, os.ModePerm)
	util.CheckErrFatal(err)
	_, err = ssl.CertificateCommand().Execute()
	util.CheckErrFatal(err)
}

// Auth Checks if a request is made with a valid token
func (env *Env) Auth(handler func(http.ResponseWriter, *http.Request)) func(http.ResponseWriter, *http.Request) {
	return func(res http.ResponseWriter, req *http.Request) {
		if !env.lock.Open {
			logAuthStatus("request made to a locked node", req)
			util.SendErrRes(res, errors.New("node locked"))
		} else if env.ValidToken(req) {
			logAuthStatus("auth success", req)
			handler(res, req)
		} else {
			logAuthStatus("auth failue", req)
			util.SendUnauthorized(res)
		}
	}
}

// logAuthStatus Logs outcome of authorization challange
func logAuthStatus(msg string, req *http.Request) {
	log.Printf("%s from: %s, %s", req.URL.Path, req.RemoteAddr, msg)
}
<|endoftext|>


<commit_before>package openstack

import (
	"fmt"
	"os"
	"testing"

	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"

	"github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes"
	"github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip"
	"github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach"
	"github.com/rackspace/gophercloud/openstack/compute/v2/servers"
	"github.com/rackspace/gophercloud/pagination"
)

func TestAccComputeV2Instance_basic(t *testing.T) {
	var instance servers.Server
	var testAccComputeV2Instance_basic = fmt.Sprintf(`
		resource "openstack_compute_instance_v2" "foo" {
			name = "terraform-test"
			security_groups = ["default"]
			network {
				uuid = "%s"
			}
			metadata {
				foo = "bar"
			}
		}`,
		os.Getenv("OS_NETWORK_ID"))

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckComputeV2InstanceDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccComputeV2Instance_basic,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckComputeV2InstanceExists(t, "openstack_compute_instance_v2.foo", &instance),
					testAccCheckComputeV2InstanceMetadata(&instance, "foo", "bar"),
				),
			},
		},
	})
}

func TestAccComputeV2Instance_volumeAttach(t *testing.T) {
	var instance servers.Server
	var volume volumes.Volume

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckComputeV2InstanceDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccComputeV2Instance_volumeAttach,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckBlockStorageV1VolumeExists(t, "openstack_blockstorage_volume_v1.myvol", &volume),
					testAccCheckComputeV2InstanceExists(t, "openstack_compute_instance_v2.foo", &instance),
					testAccCheckComputeV2InstanceVolumeAttachment(&instance, &volume),
				),
			},
		},
	})
}

func TestAccComputeV2Instance_floatingIPAttach(t *testing.T) {
	var instance servers.Server
	var fip floatingip.FloatingIP
	var testAccComputeV2Instance_floatingIPAttach = fmt.Sprintf(`
		resource "openstack_compute_floatingip_v2" "myip" {
		}

		resource "openstack_compute_instance_v2" "foo" {
			name = "terraform-test"
			security_groups = ["default"]
			floating_ip = "${openstack_compute_floatingip_v2.myip.address}"

			network {
				uuid = "%s"
			}
		}`,
		os.Getenv("OS_NETWORK_ID"))

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckComputeV2InstanceDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccComputeV2Instance_floatingIPAttach,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckComputeV2FloatingIPExists(t, "openstack_compute_floatingip_v2.myip", &fip),
					testAccCheckComputeV2InstanceExists(t, "openstack_compute_instance_v2.foo", &instance),
					testAccCheckComputeV2InstanceFloatingIPAttach(&instance, &fip),
				),
			},
		},
	})
}

func testAccCheckComputeV2InstanceDestroy(s *terraform.State) error {
	config := testAccProvider.Meta().(*Config)
	computeClient, err := config.computeV2Client(OS_REGION_NAME)
	if err != nil {
		return fmt.Errorf("(testAccCheckComputeV2InstanceDestroy) Error creating OpenStack compute client: %s", err)
	}

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "openstack_compute_instance_v2" {
			continue
		}

		_, err := servers.Get(computeClient, rs.Primary.ID).Extract()
		if err == nil {
			return fmt.Errorf("Instance still exists")
		}
	}

	return nil
}

func testAccCheckComputeV2InstanceExists(t *testing.T, n string, instance *servers.Server) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No ID is set")
		}

		config := testAccProvider.Meta().(*Config)
		computeClient, err := config.computeV2Client(OS_REGION_NAME)
		if err != nil {
			return fmt.Errorf("(testAccCheckComputeV2InstanceExists) Error creating OpenStack compute client: %s", err)
		}

		found, err := servers.Get(computeClient, rs.Primary.ID).Extract()
		if err != nil {
			return err
		}

		if found.ID != rs.Primary.ID {
			return fmt.Errorf("Instance not found")
		}

		*instance = *found

		return nil
	}
}

func testAccCheckComputeV2InstanceMetadata(
	instance *servers.Server, k string, v string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		if instance.Metadata == nil {
			return fmt.Errorf("No metadata")
		}

		for key, value := range instance.Metadata {
			if k != key {
				continue
			}

			if v == value.(string) {
				return nil
			}

			return fmt.Errorf("Bad value for %s: %s", k, value)
		}

		return fmt.Errorf("Metadata not found: %s", k)
	}
}

func testAccCheckComputeV2InstanceVolumeAttachment(
	instance *servers.Server, volume *volumes.Volume) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		var attachments []volumeattach.VolumeAttachment

		config := testAccProvider.Meta().(*Config)
		computeClient, err := config.computeV2Client(OS_REGION_NAME)
		if err != nil {
			return err
		}
		err = volumeattach.List(computeClient, instance.ID).EachPage(func(page pagination.Page) (bool, error) {
			actual, err := volumeattach.ExtractVolumeAttachments(page)
			if err != nil {
				return false, fmt.Errorf("Unable to lookup attachment: %s", err)
			}

			attachments = actual
			return true, nil
		})

		for _, attachment := range attachments {
			if attachment.VolumeID == volume.ID {
				return nil
			}
		}

		return fmt.Errorf("Volume not found: %s", volume.ID)
	}
}

func testAccCheckComputeV2InstanceFloatingIPAttach(
	instance *servers.Server, fip *floatingip.FloatingIP) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		if fip.InstanceID == instance.ID {
			return nil
		}

		return fmt.Errorf("Floating IP %s was not attached to instance %s", fip.ID, instance.ID)

	}
}

var testAccComputeV2Instance_volumeAttach = fmt.Sprintf(`
  resource "openstack_blockstorage_volume_v1" "myvol" {
    name = "myvol"
    size = 1
  }

  resource "openstack_compute_instance_v2" "foo" {
    region = "%s"
    name = "terraform-test"
    security_groups = ["default"]
    volume {
      volume_id = "${openstack_blockstorage_volume_v1.myvol.id}"
    }
  }`,
	OS_REGION_NAME)
<commit_msg>provider/openstack: added acceptance test to test security group order<commit_after>package openstack

import (
	"fmt"
	"os"
	"testing"

	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"

	"github.com/rackspace/gophercloud/openstack/blockstorage/v1/volumes"
	"github.com/rackspace/gophercloud/openstack/compute/v2/extensions/floatingip"
	"github.com/rackspace/gophercloud/openstack/compute/v2/extensions/secgroups"
	"github.com/rackspace/gophercloud/openstack/compute/v2/extensions/volumeattach"
	"github.com/rackspace/gophercloud/openstack/compute/v2/servers"
	"github.com/rackspace/gophercloud/pagination"
)

func TestAccComputeV2Instance_basic(t *testing.T) {
	var instance servers.Server
	var testAccComputeV2Instance_basic = fmt.Sprintf(`
		resource "openstack_compute_instance_v2" "foo" {
			name = "terraform-test"
			security_groups = ["default"]
			network {
				uuid = "%s"
			}
			metadata {
				foo = "bar"
			}
		}`,
		os.Getenv("OS_NETWORK_ID"))

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckComputeV2InstanceDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccComputeV2Instance_basic,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckComputeV2InstanceExists(t, "openstack_compute_instance_v2.foo", &instance),
					testAccCheckComputeV2InstanceMetadata(&instance, "foo", "bar"),
				),
			},
		},
	})
}

func TestAccComputeV2Instance_volumeAttach(t *testing.T) {
	var instance servers.Server
	var volume volumes.Volume

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckComputeV2InstanceDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccComputeV2Instance_volumeAttach,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckBlockStorageV1VolumeExists(t, "openstack_blockstorage_volume_v1.myvol", &volume),
					testAccCheckComputeV2InstanceExists(t, "openstack_compute_instance_v2.foo", &instance),
					testAccCheckComputeV2InstanceVolumeAttachment(&instance, &volume),
				),
			},
		},
	})
}

func TestAccComputeV2Instance_floatingIPAttach(t *testing.T) {
	var instance servers.Server
	var fip floatingip.FloatingIP
	var testAccComputeV2Instance_floatingIPAttach = fmt.Sprintf(`
		resource "openstack_compute_floatingip_v2" "myip" {
		}

		resource "openstack_compute_instance_v2" "foo" {
			name = "terraform-test"
			security_groups = ["default"]
			floating_ip = "${openstack_compute_floatingip_v2.myip.address}"

			network {
				uuid = "%s"
			}
		}`,
		os.Getenv("OS_NETWORK_ID"))

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckComputeV2InstanceDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccComputeV2Instance_floatingIPAttach,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckComputeV2FloatingIPExists(t, "openstack_compute_floatingip_v2.myip", &fip),
					testAccCheckComputeV2InstanceExists(t, "openstack_compute_instance_v2.foo", &instance),
					testAccCheckComputeV2InstanceFloatingIPAttach(&instance, &fip),
				),
			},
		},
	})
}

func TestAccComputeV2Instance_multi_secgroups(t *testing.T) {
	var instance servers.Server
	var secgroup secgroups.SecurityGroup
	var testAccComputeV2Instance_multi_secgroups = fmt.Sprintf(`
		resource "openstack_compute_secgroup_v2" "foo" {
			name = "terraform-test"
			description = "a security group"
			rule {
				from_port = 22
				to_port = 22
				ip_protocol = "tcp"
				cidr = "0.0.0.0/0"
			}
		}

		resource "openstack_compute_instance_v2" "foo" {
			name = "terraform-test"
			security_groups = ["default", "${openstack_compute_secgroup_v2.foo.name}"]
			network {
				uuid = "%s"
			}
		}`,
		os.Getenv("OS_NETWORK_ID"))

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckComputeV2InstanceDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccComputeV2Instance_multi_secgroups,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckComputeV2SecGroupExists(t, "openstack_compute_secgroup_v2.foo", &secgroup),
					testAccCheckComputeV2InstanceExists(t, "openstack_compute_instance_v2.foo", &instance),
				),
			},
		},
	})
}

func testAccCheckComputeV2InstanceDestroy(s *terraform.State) error {
	config := testAccProvider.Meta().(*Config)
	computeClient, err := config.computeV2Client(OS_REGION_NAME)
	if err != nil {
		return fmt.Errorf("(testAccCheckComputeV2InstanceDestroy) Error creating OpenStack compute client: %s", err)
	}

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "openstack_compute_instance_v2" {
			continue
		}

		_, err := servers.Get(computeClient, rs.Primary.ID).Extract()
		if err == nil {
			return fmt.Errorf("Instance still exists")
		}
	}

	return nil
}

func testAccCheckComputeV2InstanceExists(t *testing.T, n string, instance *servers.Server) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No ID is set")
		}

		config := testAccProvider.Meta().(*Config)
		computeClient, err := config.computeV2Client(OS_REGION_NAME)
		if err != nil {
			return fmt.Errorf("(testAccCheckComputeV2InstanceExists) Error creating OpenStack compute client: %s", err)
		}

		found, err := servers.Get(computeClient, rs.Primary.ID).Extract()
		if err != nil {
			return err
		}

		if found.ID != rs.Primary.ID {
			return fmt.Errorf("Instance not found")
		}

		*instance = *found

		return nil
	}
}

func testAccCheckComputeV2InstanceMetadata(
	instance *servers.Server, k string, v string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		if instance.Metadata == nil {
			return fmt.Errorf("No metadata")
		}

		for key, value := range instance.Metadata {
			if k != key {
				continue
			}

			if v == value.(string) {
				return nil
			}

			return fmt.Errorf("Bad value for %s: %s", k, value)
		}

		return fmt.Errorf("Metadata not found: %s", k)
	}
}

func testAccCheckComputeV2InstanceVolumeAttachment(
	instance *servers.Server, volume *volumes.Volume) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		var attachments []volumeattach.VolumeAttachment

		config := testAccProvider.Meta().(*Config)
		computeClient, err := config.computeV2Client(OS_REGION_NAME)
		if err != nil {
			return err
		}
		err = volumeattach.List(computeClient, instance.ID).EachPage(func(page pagination.Page) (bool, error) {
			actual, err := volumeattach.ExtractVolumeAttachments(page)
			if err != nil {
				return false, fmt.Errorf("Unable to lookup attachment: %s", err)
			}

			attachments = actual
			return true, nil
		})

		for _, attachment := range attachments {
			if attachment.VolumeID == volume.ID {
				return nil
			}
		}

		return fmt.Errorf("Volume not found: %s", volume.ID)
	}
}

func testAccCheckComputeV2InstanceFloatingIPAttach(
	instance *servers.Server, fip *floatingip.FloatingIP) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		if fip.InstanceID == instance.ID {
			return nil
		}

		return fmt.Errorf("Floating IP %s was not attached to instance %s", fip.ID, instance.ID)

	}
}

var testAccComputeV2Instance_volumeAttach = fmt.Sprintf(`
  resource "openstack_blockstorage_volume_v1" "myvol" {
    name = "myvol"
    size = 1
  }

  resource "openstack_compute_instance_v2" "foo" {
    region = "%s"
    name = "terraform-test"
    security_groups = ["default"]
    volume {
      volume_id = "${openstack_blockstorage_volume_v1.myvol.id}"
    }
  }`,
	OS_REGION_NAME)
<|endoftext|>


<commit_before>package debugmutex

import (
	"fmt"
	"log"
	"runtime"
	"runtime/debug"
	"sync"
	"time"
)

// Mutex is debug mutex, which prints logs and traces for locks
// implements sync.Locker interface
type Mutex struct {
	retries  int
	mu       sync.Mutex
	myMu     sync.RWMutex
	lockedAt string
}

// New returns new debug mutex
// retries parameter specify number of retries acquiring Mutex before fatal
// exit, if <=0, then wait forever
func New(retries int) sync.Locker {
	return &Mutex{retries: retries}
}

// Lock tries to lock mutex. Interval between attempts is 1 second.
// On each attempt stack trace and file:lino of previous Lock will be printed.
// Lock does os.Exit(1) after last attempt.
func (m *Mutex) Lock() {
	_, file, line, _ := runtime.Caller(1)
	caller := fmt.Sprintf("%s:%d", file, line)
	log.Printf("Trying to acquire Lock at %s", caller)
	wait := make(chan struct{})
	go func() {
		m.mu.Lock()
		close(wait)
	}()
	seconds := 0
loop:
	for {
		select {
		case <-wait:
			break loop
		case <-time.After(1 * time.Second):
			m.myMu.RLock()
			seconds++
			if m.retries > 0 && seconds > m.retries {
				debug.PrintStack()
				log.Fatalf("Possible deadlock - can't acquire lock at %s for 5 second, locked by %s", caller, m.lockedAt)
			}
			log.Printf("Lock is stuck at %s, wait for lock from %s", caller, m.lockedAt)
			m.myMu.RUnlock()
		}
	}
	log.Printf("Lock acquired at %s", caller)
	debug.PrintStack()
	m.myMu.Lock()
	m.lockedAt = caller
	m.myMu.Unlock()
}

// Unlock unlocks mutex. It prints place in code where it was called and where
// mutex was locked.
func (m *Mutex) Unlock() {
	_, file, line, _ := runtime.Caller(1)
	caller := fmt.Sprintf("%s:%d", file, line)
	m.myMu.RLock()
	log.Printf("Release Lock locked at %s, at %s", m.lockedAt, caller)
	m.myMu.RUnlock()
	m.mu.Unlock()
}
<commit_msg>Use logrus and add fatal option<commit_after>package debugmutex

import (
	"fmt"
	"runtime"
	"sync"
	"time"

	"github.com/Sirupsen/logrus"
)

// Mutex is debug mutex, which prints logs and traces for locks
// implements sync.Locker interface
type Mutex struct {
	retries  int
	mu       sync.Mutex
	myMu     sync.RWMutex
	lockedAt string
	errFunc  func(format string, args ...interface{})
}

// New returns new debug mutex
// retries parameter specify number of retries acquiring Mutex before error
// message, if <=0, then wait forever
// if fatal is true, then program will exit by os.Exit(1)
func New(retries int, fatal bool) sync.Locker {
	var errF func(format string, args ...interface{})
	errF = logrus.Errorf
	if fatal {
		errF = logrus.Fatalf
	}
	return &Mutex{
		retries: retries,
		errFunc: errF,
	}
}

// Lock tries to lock mutex. Interval between attempts is 1 second.
// On each attempt stack trace and file:lino of previous Lock will be printed.
// Lock does os.Exit(1) after last attempt.
func (m *Mutex) Lock() {
	_, file, line, _ := runtime.Caller(1)
	caller := fmt.Sprintf("%s:%d", file, line)
	logrus.Debugf("Trying to acquire Lock at %s", caller)
	wait := make(chan struct{})
	go func() {
		m.mu.Lock()
		close(wait)
	}()
	seconds := 0
loop:
	for {
		select {
		case <-wait:
			break loop
		case <-time.After(1 * time.Second):
			m.myMu.RLock()
			seconds++
			if m.retries > 0 && seconds > m.retries {
				logrus.Errorf("Stack:\n%s", stack())
				m.errFunc("Possible deadlock - can't acquire lock at %s for 5 second, locked by %s", caller, m.lockedAt)
			}
			logrus.Debugf("Lock is stuck at %s, wait for lock from %s", caller, m.lockedAt)
			m.myMu.RUnlock()
		}
	}
	logrus.Debugf("Lock acquired at %s", caller)
	logrus.Debugf("Stack:\n%s", stack())
	m.myMu.Lock()
	m.lockedAt = caller
	m.myMu.Unlock()
}

// Unlock unlocks mutex. It prints place in code where it was called and where
// mutex was locked.
func (m *Mutex) Unlock() {
	_, file, line, _ := runtime.Caller(1)
	caller := fmt.Sprintf("%s:%d", file, line)
	m.myMu.RLock()
	logrus.Debugf("Release Lock locked at %s, at %s", m.lockedAt, caller)
	m.myMu.RUnlock()
	m.mu.Unlock()
}

func stack() string {
	var buf [2 << 10]byte
	return string(buf[:runtime.Stack(buf[:], false)])
}
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package definition

import (
	"errors"
	"fmt"
	"unicode/utf8"
)

// ELBPort ...
type ELBPort struct {
	FromPort int    `json:"from_port"`
	ToPort   int    `json:"to_port"`
	Protocol string `json:"protocol"`
	SSLCert  string `json:"ssl_cert"`
}

// ELB ...
type ELB struct {
	Name           string    `json:"name"`
	Private        bool      `json:"private"`
	Instances      []string  `json:"instances"`
	SecurityGroups []string  `json:"security_groups"`
	Ports          []ELBPort `json:"ports"`
}

// Validate checks if a Network is valid
func (e *ELB) Validate() error {
	if e.Name == "" {
		return errors.New("ELB name should not be null")
	}

	// Check if network name is > 50 characters
	if utf8.RuneCountInString(e.Name) > AWSMAXNAME {
		return fmt.Errorf("ELB name can't be greater than %d characters", AWSMAXNAME)
	}

	if len(e.Ports) < 1 {
		return errors.New("ELB must contain more than one ports")
	}

	for _, port := range e.Ports {
		if port.FromPort < 1 || port.FromPort > 65535 {
			return fmt.Errorf("From Port (%d) is out of range [1 - 65535]", port.FromPort)
		}

		if port.ToPort < 1 || port.ToPort > 65535 {
			return fmt.Errorf("From Port (%d) is out of range [1 - 65535]", port.ToPort)
		}

		if port.Protocol != "http" &&
			port.Protocol != "https" &&
			port.Protocol != "tcp" &&
			port.Protocol != "ssl" {
			return errors.New("ELB Protocol must be one of http, https, tcp or ssl")
		}

	}

	return nil
}
<commit_msg>remapping ports -> listeners on definition<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

package definition

import (
	"errors"
	"fmt"
	"unicode/utf8"
)

// ELBPort ...
type ELBPort struct {
	FromPort int    `json:"from_port"`
	ToPort   int    `json:"to_port"`
	Protocol string `json:"protocol"`
	SSLCert  string `json:"ssl_cert"`
}

// ELB ...
type ELB struct {
	Name           string    `json:"name"`
	Private        bool      `json:"private"`
	Instances      []string  `json:"instances"`
	SecurityGroups []string  `json:"security_groups"`
	Ports          []ELBPort `json:"listeners"`
}

// Validate checks if a Network is valid
func (e *ELB) Validate() error {
	if e.Name == "" {
		return errors.New("ELB name should not be null")
	}

	// Check if network name is > 50 characters
	if utf8.RuneCountInString(e.Name) > AWSMAXNAME {
		return fmt.Errorf("ELB name can't be greater than %d characters", AWSMAXNAME)
	}

	if len(e.Ports) < 1 {
		return errors.New("ELB must contain more than one ports")
	}

	for _, port := range e.Ports {
		if port.FromPort < 1 || port.FromPort > 65535 {
			return fmt.Errorf("From Port (%d) is out of range [1 - 65535]", port.FromPort)
		}

		if port.ToPort < 1 || port.ToPort > 65535 {
			return fmt.Errorf("From Port (%d) is out of range [1 - 65535]", port.ToPort)
		}

		if port.Protocol != "http" &&
			port.Protocol != "https" &&
			port.Protocol != "tcp" &&
			port.Protocol != "ssl" {
			return errors.New("ELB Protocol must be one of http, https, tcp or ssl")
		}

	}

	return nil
}
<|endoftext|>


<commit_before>package bloom_test

import (
	"strings"

	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
	"github.com/philharnish/forge/src/data/graph/bloom"
)

var _ = Describe("AlphabetMask",
	func() {
		It("Accepts all characters from ALPHABET",
			func() {
				for _, c := range bloom.ALPHABET {
					_, err := bloom.AlphabetMask(c)
					Expect(err).ShouldNot(HaveOccurred())
				}
			})

		It("Rejects characters outside of ALPHABET",
			func() {
				invalidCharacters := 0
				for i := 0; i < 200; i++ {
					c := rune(i)
					if strings.ContainsRune(bloom.ALPHABET, c) {
						continue
					}
					invalidCharacters++
					_, err := bloom.AlphabetMask(c)
					Expect(err).NotTo(BeNil())
				}
				Expect(invalidCharacters).To(BeNumerically(">", 0))
			})

		It("Returns unique masks for each character",
			func() {
				acc := bloom.BitMask(0)
				for _, c := range bloom.ALPHABET {
					mask, _ := bloom.AlphabetMask(c)
					Expect(mask).To(BeNumerically(">", 0))
					Expect(acc & mask).To(Equal(bloom.BitMask(0)))
					acc |= mask
				}
			})
	})

var _ = Describe("MaskAlphabet",
	func() {
		It("Returns empty string for 0",
			func() {
				Expect(bloom.MaskAlphabet(0b0, 0b0)).To(Equal(""))
			})

		It("Indicates provided characters",
			func() {
				Expect(bloom.MaskAlphabet(0b111, 0)).To(Equal("abc"))
			})

		It("Indicates required characters differently",
			func() {
				Expect(bloom.MaskAlphabet(0b111, 0b111)).To(Equal("ABC"))
			})

		It("Converts round-trip",
			func() {
				given := "it's an example"
				expected := "aeilmnpstx '"
				acc := bloom.BitMask(0)
				for _, c := range given {
					mask, _ := bloom.AlphabetMask(c)
					acc |= mask
				}
				Expect(bloom.MaskAlphabet(acc, 0)).To(Equal(expected))
			})
	})

/*

with description('mask defaults') as self:
  with before.each:
    self.subject = bloom_mask.BitMatchAnything()

  with it('is 0 initially'):
    expect(self.subject).to(equal(0))

  with it('bitwise ORs to itself'):
    expect(self.subject | 0b101).to(be(0b101))

  with it('bitwise ANDs to itself'):
    expect(self.subject & 0b101).to(be(0b101))

  with it('bitwise ANDs & assigns to itself'):
    self.subject &= 0b101
    expect(self.subject).to(be(0b101))

  with it('bitwise rORs to other'):
    expect(0b101 | self.subject).to(be(0b101))

  with it('bitwise rANDs to other'):
    expect(0b101 & self.subject).to(be(0b101))

  with it('bitwise rANDs & assigns to other'):
    x = 0b101
    x &= self.subject
    expect(x).to(be(0b101))

  with it('claims equality'):
    expect(0b101 & 0b0).to(equal(self.subject))

*/
<commit_msg>Delete TODO reference material. Done.<commit_after>package bloom_test

import (
	"strings"

	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
	"github.com/philharnish/forge/src/data/graph/bloom"
)

var _ = Describe("AlphabetMask",
	func() {
		It("Accepts all characters from ALPHABET",
			func() {
				for _, c := range bloom.ALPHABET {
					_, err := bloom.AlphabetMask(c)
					Expect(err).ShouldNot(HaveOccurred())
				}
			})

		It("Rejects characters outside of ALPHABET",
			func() {
				invalidCharacters := 0
				for i := 0; i < 200; i++ {
					c := rune(i)
					if strings.ContainsRune(bloom.ALPHABET, c) {
						continue
					}
					invalidCharacters++
					_, err := bloom.AlphabetMask(c)
					Expect(err).NotTo(BeNil())
				}
				Expect(invalidCharacters).To(BeNumerically(">", 0))
			})

		It("Returns unique masks for each character",
			func() {
				acc := bloom.BitMask(0)
				for _, c := range bloom.ALPHABET {
					mask, _ := bloom.AlphabetMask(c)
					Expect(mask).To(BeNumerically(">", 0))
					Expect(acc & mask).To(Equal(bloom.BitMask(0)))
					acc |= mask
				}
			})
	})

var _ = Describe("MaskAlphabet",
	func() {
		It("Returns empty string for 0",
			func() {
				Expect(bloom.MaskAlphabet(0b0, 0b0)).To(Equal(""))
			})

		It("Indicates provided characters",
			func() {
				Expect(bloom.MaskAlphabet(0b111, 0)).To(Equal("abc"))
			})

		It("Indicates required characters differently",
			func() {
				Expect(bloom.MaskAlphabet(0b111, 0b111)).To(Equal("ABC"))
			})

		It("Converts round-trip",
			func() {
				given := "it's an example"
				expected := "aeilmnpstx '"
				acc := bloom.BitMask(0)
				for _, c := range given {
					mask, _ := bloom.AlphabetMask(c)
					acc |= mask
				}
				Expect(bloom.MaskAlphabet(acc, 0)).To(Equal(expected))
			})
	})
<|endoftext|>


<commit_before>// Code generated by mockery v1.0.0
package mocks

import mock "github.com/stretchr/testify/mock"
import reflect "github.com/omniql/reflect"

// OType is an autogenerated mock type for the OType type
type OType struct {
	mock.Mock
}

// Application provides a mock function with given fields:
func (_m *OType) Application() reflect.ApplicationContainer {
	ret := _m.Called()

	var r0 reflect.ApplicationContainer
	if rf, ok := ret.Get(0).(func() reflect.ApplicationContainer); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(reflect.ApplicationContainer)
		}
	}

	return r0
}

// Enumeration provides a mock function with given fields:
func (_m *OType) Enumeration() reflect.EnumerationContainer {
	ret := _m.Called()

	var r0 reflect.EnumerationContainer
	if rf, ok := ret.Get(0).(func() reflect.EnumerationContainer); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(reflect.EnumerationContainer)
		}
	}

	return r0
}

// ExternalApplication provides a mock function with given fields:
func (_m *OType) ExternalApplication() reflect.ExternalApplicationContainer {
	ret := _m.Called()

	var r0 reflect.ExternalApplicationContainer
	if rf, ok := ret.Get(0).(func() reflect.ExternalApplicationContainer); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(reflect.ExternalApplicationContainer)
		}
	}

	return r0
}

// ExternalResource provides a mock function with given fields:
func (_m *OType) ExternalResource() reflect.ExternalResourceContainer {
	ret := _m.Called()

	var r0 reflect.ExternalResourceContainer
	if rf, ok := ret.Get(0).(func() reflect.ExternalResourceContainer); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(reflect.ExternalResourceContainer)
		}
	}

	return r0
}

// Kind provides a mock function with given fields:
func (_m *OType) Kind() reflect.OmniTypes {
	ret := _m.Called()

	var r0 reflect.OmniTypes
	if rf, ok := ret.Get(0).(func() reflect.OmniTypes); ok {
		r0 = rf()
	} else {
		r0 = ret.Get(0).(reflect.OmniTypes)
	}

	return r0
}

// Resource provides a mock function with given fields:
func (_m *OType) Resource() reflect.ResourceContainer {
	ret := _m.Called()

	var r0 reflect.ResourceContainer
	if rf, ok := ret.Get(0).(func() reflect.ResourceContainer); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(reflect.ResourceContainer)
		}
	}

	return r0
}

// Struct provides a mock function with given fields:
func (_m *OType) Struct() reflect.StructContainer {
	ret := _m.Called()

	var r0 reflect.StructContainer
	if rf, ok := ret.Get(0).(func() reflect.StructContainer); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(reflect.StructContainer)
		}
	}

	return r0
}

// Table provides a mock function with given fields:
func (_m *OType) Table() reflect.TableContainer {
	ret := _m.Called()

	var r0 reflect.TableContainer
	if rf, ok := ret.Get(0).(func() reflect.TableContainer); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(reflect.TableContainer)
		}
	}

	return r0
}

// Union provides a mock function with given fields:
func (_m *OType) Union() reflect.UnionContainer {
	ret := _m.Called()

	var r0 reflect.UnionContainer
	if rf, ok := ret.Get(0).(func() reflect.UnionContainer); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(reflect.UnionContainer)
		}
	}

	return r0
}
<commit_msg>end reflection interface<commit_after>// Code generated by mockery v1.0.0
package mocks

import mock "github.com/stretchr/testify/mock"
import reflect "github.com/omniql/reflect"

// OType is an autogenerated mock type for the OType type
type OType struct {
	mock.Mock
}

// Enumeration provides a mock function with given fields:
func (_m *OType) Enumeration() reflect.EnumerationContainer {
	ret := _m.Called()

	var r0 reflect.EnumerationContainer
	if rf, ok := ret.Get(0).(func() reflect.EnumerationContainer); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(reflect.EnumerationContainer)
		}
	}

	return r0
}

// ExternalResource provides a mock function with given fields:
func (_m *OType) ExternalResource() reflect.ExternalResourceContainer {
	ret := _m.Called()

	var r0 reflect.ExternalResourceContainer
	if rf, ok := ret.Get(0).(func() reflect.ExternalResourceContainer); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(reflect.ExternalResourceContainer)
		}
	}

	return r0
}

// Kind provides a mock function with given fields:
func (_m *OType) Kind() reflect.OmniTypes {
	ret := _m.Called()

	var r0 reflect.OmniTypes
	if rf, ok := ret.Get(0).(func() reflect.OmniTypes); ok {
		r0 = rf()
	} else {
		r0 = ret.Get(0).(reflect.OmniTypes)
	}

	return r0
}

// Resource provides a mock function with given fields:
func (_m *OType) Resource() reflect.ResourceContainer {
	ret := _m.Called()

	var r0 reflect.ResourceContainer
	if rf, ok := ret.Get(0).(func() reflect.ResourceContainer); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(reflect.ResourceContainer)
		}
	}

	return r0
}

// Struct provides a mock function with given fields:
func (_m *OType) Struct() reflect.StructContainer {
	ret := _m.Called()

	var r0 reflect.StructContainer
	if rf, ok := ret.Get(0).(func() reflect.StructContainer); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(reflect.StructContainer)
		}
	}

	return r0
}

// Table provides a mock function with given fields:
func (_m *OType) Table() reflect.TableContainer {
	ret := _m.Called()

	var r0 reflect.TableContainer
	if rf, ok := ret.Get(0).(func() reflect.TableContainer); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(reflect.TableContainer)
		}
	}

	return r0
}

// Union provides a mock function with given fields:
func (_m *OType) Union() reflect.UnionContainer {
	ret := _m.Called()

	var r0 reflect.UnionContainer
	if rf, ok := ret.Get(0).(func() reflect.UnionContainer); ok {
		r0 = rf()
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(reflect.UnionContainer)
		}
	}

	return r0
}
<|endoftext|>