// short docker id (12 char) is extended
func (d *docker) extendDockerId(shortId string) (string, error) {

	for _, cinfo := range d.containersInfo {
		if strings.HasPrefix(cinfo.Id, shortId) {
			return cinfo.Id, nil
		}
	}

	return "", errors.New(fmt.Sprintf("Could not find long docker id for %s\n", shortId))
}
Exemple #2
0
func (c *Client) Abandon(name string) error {
	sess, err := c.Session()
	if err != nil {
		return err
	}

	s, err := sess.Open()
	if err != nil {
		return err
	}

	defer s.Close()

	_, err = s.Write([]byte{uint8(AbandonType)})
	if err != nil {
		return c.checkError(err)
	}

	enc := codec.NewEncoder(s, &msgpack)

	msg := Abandon{
		Name: name,
	}

	err = enc.Encode(&msg)
	if err != nil {
		return c.checkError(err)
	}

	buf := []byte{0}

	_, err = io.ReadFull(s, buf)
	if err != nil {
		return c.checkError(err)
	}

	switch MessageType(buf[0]) {
	case ErrorType:
		var msgerr Error

		err = codec.NewDecoder(s, &msgpack).Decode(&msgerr)
		if err != nil {
			return c.checkError(err)
		}

		return errors.New(msgerr.Error)
	case SuccessType:
		return nil
	default:
		return c.checkError(EProtocolError)
	}
}
Exemple #3
0
func (c *Client) nack(id MessageId) error {
	sess, err := c.Session()
	if err != nil {
		return err
	}

	s, err := sess.Open()
	if err != nil {
		return err
	}

	defer s.Close()

	_, err = s.Write([]byte{uint8(NackType)})
	if err != nil {
		return c.checkError(err)
	}

	enc := codec.NewEncoder(s, &msgpack)

	msg := NackMessage{
		MessageId: id,
	}

	if err := enc.Encode(&msg); err != nil {
		return c.checkError(err)
	}

	buf := []byte{0}

	_, err = io.ReadFull(s, buf)
	if err != nil {
		return c.checkError(err)
	}

	switch MessageType(buf[0]) {
	case ErrorType:
		var msgerr Error

		err = codec.NewDecoder(s, &msgpack).Decode(&msgerr)
		if err != nil {
			return c.checkError(err)
		}

		return errors.New(msgerr.Error)
	case SuccessType:
		return nil
	default:
		return c.checkError(EProtocolError)
	}

}
Exemple #4
0
func (c *Client) Stats() (*ClientStats, error) {
	if c.conn == nil {
		return nil, nil
	}

	sess, err := c.Session()
	if err != nil {
		return nil, err
	}

	s, err := sess.Open()
	if err != nil {
		return nil, err
	}

	_, err = s.Write([]byte{uint8(StatsType)})

	buf := []byte{0}

	_, err = io.ReadFull(s, buf)
	if err != nil {
		return nil, err
	}

	switch MessageType(buf[0]) {
	case StatsResultType:
		dec := codec.NewDecoder(s, &msgpack)

		var res ClientStats

		if err := dec.Decode(&res); err != nil {
			return nil, c.checkError(err)
		}

		return &res, nil
	case ErrorType:
		var msgerr Error

		err = codec.NewDecoder(s, &msgpack).Decode(&msgerr)
		if err != nil {
			return nil, c.checkError(err)
		}

		return nil, errors.New(msgerr.Error)
	case SuccessType:
		return nil, nil
	default:
		return nil, c.checkError(EProtocolError)
	}
}
Exemple #5
0
func (c *Client) Close() (err error) {
	if c.conn == nil {
		return nil
	}

	sess, err := c.Session()
	if err != nil {
		return err
	}

	s, err := sess.Open()
	if err != nil {
		return err
	}

	_, err = s.Write([]byte{uint8(CloseType)})

	defer func() {
		s.Close()

		err = c.sess.Close()
		c.sess = nil
		c.conn = nil
	}()

	buf := []byte{0}

	io.ReadFull(s, buf)
	if err == nil {
		switch MessageType(buf[0]) {
		case ErrorType:
			var msgerr Error

			err = codec.NewDecoder(s, &msgpack).Decode(&msgerr)
			if err != nil {
				return c.checkError(err)
			}

			return errors.New(msgerr.Error)
		case SuccessType:
			return nil
		default:
			return c.checkError(EProtocolError)
		}
	}

	return err
}
Exemple #6
0
func (c *Client) Push(name string, body *Message) error {
	sess, err := c.Session()
	if err != nil {
		return err
	}

	s, err := sess.Open()
	if err != nil {
		return err
	}

	defer s.Close()

	_, err = s.Write([]byte{uint8(PushType)})
	if err != nil {
		return c.checkError(err)
	}

	enc := codec.NewEncoder(s, &msgpack)

	msg := Push{
		Name:    name,
		Message: body,
	}

	debugf("client %s: sending push request\n", c.addr)

	if err := enc.Encode(&msg); err != nil {
		return c.checkError(err)
	}

	buf := []byte{0}

	debugf("client %s: waiting for response\n", c.addr)

	_, err = io.ReadFull(s, buf)
	if err != nil {
		return c.checkError(err)
	}

	switch MessageType(buf[0]) {
	case ErrorType:
		debugf("client %s: got error\n", c.addr)

		var msgerr Error

		err = codec.NewDecoder(s, &msgpack).Decode(&msgerr)
		if err != nil {
			return c.checkError(err)
		}

		return errors.New(msgerr.Error)
	case SuccessType:
		debugf("client %s: got success\n", c.addr)

		return nil
	default:
		debugf("client %s: got protocol error\n", c.addr)

		return c.checkError(EProtocolError)
	}
}
Exemple #7
0
func (c *Client) LongPollCancelable(name string, til time.Duration, done chan struct{}) (*Delivery, error) {
	sess, err := c.Session()
	if err != nil {
		return nil, err
	}

	s, err := sess.Open()
	if err != nil {
		return nil, err
	}

	defer s.Close()

	_, err = s.Write([]byte{uint8(LongPollType)})
	if err != nil {
		return nil, c.checkError(err)
	}

	enc := codec.NewEncoder(s, &msgpack)

	msg := LongPoll{
		Name:     name,
		Duration: til.String(),
	}

	if err := enc.Encode(&msg); err != nil {
		return nil, c.checkError(err)
	}

	delivered := make(chan struct{})

	buf := []byte{0}

	go func() {
		_, err = io.ReadFull(s, buf)
		close(delivered)
	}()

	select {
	case <-done:
		return nil, nil
	case <-delivered:
		// do the rest
	}

	switch MessageType(buf[0]) {
	case ErrorType:
		var msgerr Error

		err = codec.NewDecoder(s, &msgpack).Decode(&msgerr)
		if err != nil {
			return nil, c.checkError(err)
		}

		return nil, errors.New(msgerr.Error)
	case PollResultType:
		dec := codec.NewDecoder(s, &msgpack)

		var res PollResult

		if err := dec.Decode(&res); err != nil {
			return nil, c.checkError(err)
		}

		if res.Message == nil {
			return nil, nil
		}

		del := &Delivery{
			Message: res.Message,
			Ack:     func() error { return c.ack(res.Message.MessageId) },
			Nack:    func() error { return c.nack(res.Message.MessageId) },
		}

		return del, nil
	default:
		return nil, c.checkError(EProtocolError)
	}
}
Exemple #8
0
func (c *Client) Poll(name string) (*Delivery, error) {
	sess, err := c.Session()
	if err != nil {
		return nil, err
	}

	s, err := sess.Open()
	if err != nil {
		return nil, err
	}

	defer s.Close()

	_, err = s.Write([]byte{uint8(PollType)})
	if err != nil {
		return nil, c.checkError(err)
	}

	enc := codec.NewEncoder(s, &msgpack)

	msg := Poll{
		Name: name,
	}

	if err := enc.Encode(&msg); err != nil {
		return nil, c.checkError(err)
	}

	buf := []byte{0}

	_, err = io.ReadFull(s, buf)
	if err != nil {
		return nil, c.checkError(err)
	}

	switch MessageType(buf[0]) {
	case ErrorType:
		var msgerr Error

		err = codec.NewDecoder(s, &msgpack).Decode(&msgerr)
		if err != nil {
			return nil, c.checkError(err)
		}

		return nil, errors.New(msgerr.Error)
	case PollResultType:
		dec := codec.NewDecoder(s, &msgpack)

		var res PollResult

		if err := dec.Decode(&res); err != nil {
			return nil, c.checkError(err)
		}

		if res.Message == nil {
			return nil, nil
		}

		del := &Delivery{
			Message: res.Message,
			Ack:     func() error { return c.ack(res.Message.MessageId) },
			Nack:    func() error { return c.nack(res.Message.MessageId) },
		}

		return del, nil
	default:
		return nil, c.checkError(EProtocolError)
	}
}
// Should pass
//
// * https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#Terminology
//   The OAuth 2.0 specification allows for registration of space-separated response_type parameter values.
//   If a Response Type contains one of more space characters (%20), it is compared as a space-delimited list of
//   values in which the order of values does not matter.
func TestNewAuthorizeRequest(t *testing.T) {
	ctrl := gomock.NewController(t)
	store := NewMockStorage(ctrl)
	defer ctrl.Finish()

	redir, _ := url.Parse("https://foo.bar/cb")
	for k, c := range []struct {
		desc          string
		conf          *Fosite
		r             *http.Request
		query         url.Values
		expectedError error
		mock          func()
		expect        *AuthorizeRequest
	}{
		/* empty request */
		{
			desc:          "empty request fails",
			conf:          &Fosite{Store: store},
			r:             &http.Request{},
			expectedError: ErrInvalidClient,
			mock: func() {
				store.EXPECT().GetClient(gomock.Any()).Return(nil, errors.New("foo"))
			},
		},
		/* invalid redirect uri */
		{
			desc:          "invalid redirect uri fails",
			conf:          &Fosite{Store: store},
			query:         url.Values{"redirect_uri": []string{"invalid"}},
			expectedError: ErrInvalidClient,
			mock: func() {
				store.EXPECT().GetClient(gomock.Any()).Return(nil, errors.New("foo"))
			},
		},
		/* invalid client */
		{
			desc:          "invalid client fails",
			conf:          &Fosite{Store: store},
			query:         url.Values{"redirect_uri": []string{"https://foo.bar/cb"}},
			expectedError: ErrInvalidClient,
			mock: func() {
				store.EXPECT().GetClient(gomock.Any()).Return(nil, errors.New("foo"))
			},
		},
		/* redirect client mismatch */
		{
			desc: "client and request redirects mismatch",
			conf: &Fosite{Store: store},
			query: url.Values{
				"client_id": []string{"1234"},
			},
			expectedError: ErrInvalidRequest,
			mock: func() {
				store.EXPECT().GetClient("1234").Return(&SecureClient{RedirectURIs: []string{"invalid"}}, nil)
			},
		},
		/* redirect client mismatch */
		{
			desc: "client and request redirects mismatch",
			conf: &Fosite{Store: store},
			query: url.Values{
				"redirect_uri": []string{""},
				"client_id":    []string{"1234"},
			},
			expectedError: ErrInvalidRequest,
			mock: func() {
				store.EXPECT().GetClient("1234").Return(&SecureClient{RedirectURIs: []string{"invalid"}}, nil)
			},
		},
		/* redirect client mismatch */
		{
			desc: "client and request redirects mismatch",
			conf: &Fosite{Store: store},
			query: url.Values{
				"redirect_uri": []string{"https://foo.bar/cb"},
				"client_id":    []string{"1234"},
			},
			expectedError: ErrInvalidRequest,
			mock: func() {
				store.EXPECT().GetClient("1234").Return(&SecureClient{RedirectURIs: []string{"invalid"}}, nil)
			},
		},
		/* no state */
		{
			desc: "no state",
			conf: &Fosite{Store: store},
			query: url.Values{
				"redirect_uri":  []string{"https://foo.bar/cb"},
				"client_id":     []string{"1234"},
				"response_type": []string{"code"},
			},
			expectedError: ErrInvalidState,
			mock: func() {
				store.EXPECT().GetClient("1234").Return(&SecureClient{RedirectURIs: []string{"https://foo.bar/cb"}}, nil)
			},
		},
		/* short state */
		{
			desc: "short state",
			conf: &Fosite{Store: store},
			query: url.Values{
				"redirect_uri":  {"https://foo.bar/cb"},
				"client_id":     {"1234"},
				"response_type": {"code"},
				"state":         {"short"},
			},
			expectedError: ErrInvalidState,
			mock: func() {
				store.EXPECT().GetClient("1234").Return(&SecureClient{RedirectURIs: []string{"https://foo.bar/cb"}}, nil)
			},
		},
		/* success case */
		{
			desc: "should pass",
			conf: &Fosite{Store: store},
			query: url.Values{
				"redirect_uri":  {"https://foo.bar/cb"},
				"client_id":     {"1234"},
				"response_type": {"code"},
				"state":         {"strong-state"},
				"scope":         {"foo bar"},
			},
			mock: func() {
				store.EXPECT().GetClient("1234").Return(&SecureClient{RedirectURIs: []string{"https://foo.bar/cb"}}, nil)
			},
			expectedError: ErrInvalidScope,
		},
		{
			desc: "should not pass because hybrid flow is not active",
			conf: &Fosite{Store: store},
			query: url.Values{
				"redirect_uri":  {"https://foo.bar/cb"},
				"client_id":     {"1234"},
				"response_type": {"code token"},
				"state":         {"strong-state"},
				"scope":         {DefaultRequiredScopeName + " foo bar"},
			},
			mock: func() {
				store.EXPECT().GetClient("1234").Return(&SecureClient{RedirectURIs: []string{"https://foo.bar/cb"}}, nil)
			},
			expectedError: ErrInvalidRequest,
		},
		{
			desc: "should not pass because hybrid flow is not active",
			conf: &Fosite{Store: store},
			query: url.Values{
				"redirect_uri":  {"https://foo.bar/cb"},
				"client_id":     {"1234"},
				"response_type": {"code"},
				"state":         {"strong-state"},
				"scope":         {DefaultRequiredScopeName + " foo bar"},
			},
			mock: func() {
				store.EXPECT().GetClient("1234").Return(&SecureClient{RedirectURIs: []string{"https://foo.bar/cb"}}, nil)
			},
			expect: &AuthorizeRequest{
				RedirectURI:   redir,
				ResponseTypes: []string{"code"},
				State:         "strong-state",
				Request: Request{
					Scopes: []string{DefaultRequiredScopeName, "foo", "bar"},
					Client: &SecureClient{RedirectURIs: []string{"https://foo.bar/cb"}},
				},
			},
		},
		{
			desc: "should pass",
			conf: &Fosite{Store: store, AllowHybridFlow: true},
			query: url.Values{
				"redirect_uri":  {"https://foo.bar/cb"},
				"client_id":     {"1234"},
				"response_type": {"code token"},
				"state":         {"strong-state"},
				"scope":         {DefaultRequiredScopeName + " foo bar"},
			},
			mock: func() {
				store.EXPECT().GetClient("1234").Return(&SecureClient{RedirectURIs: []string{"https://foo.bar/cb"}}, nil)
			},
			expect: &AuthorizeRequest{
				RedirectURI:   redir,
				ResponseTypes: []string{"code", "token"},
				State:         "strong-state",
				Request: Request{
					Client: &SecureClient{RedirectURIs: []string{"https://foo.bar/cb"}},
					Scopes: []string{DefaultRequiredScopeName, "foo", "bar"},
				},
			},
		},
	} {
		t.Logf("Joining test case %d", k)
		c.mock()
		if c.r == nil {
			c.r = &http.Request{Header: http.Header{}}
			if c.query != nil {
				c.r.URL = &url.URL{RawQuery: c.query.Encode()}
			}
		}

		ar, err := c.conf.NewAuthorizeRequest(context.Background(), c.r)
		assert.Equal(t, c.expectedError == nil, err == nil, "%d: %s\n%s", k, c.desc, err)
		if c.expectedError != nil {
			assert.Equal(t, err.Error(), c.expectedError.Error(), "%d: %s\n%s", k, c.desc, err)
		} else {
			pkg.AssertObjectKeysEqual(t, c.expect, ar, "ResponseTypes", "Scopes", "Client", "RedirectURI", "State")
			assert.NotNil(t, ar.GetRequestedAt())
		}
		t.Logf("Passed test case %d", k)
	}
}
			fsUtil.On("Mkdirs", mock.AnythingOfType("string")).Return(mkdirsError)
			fsUtil.On("Copy", mock.AnythingOfType("string"), mock.AnythingOfType("string")).Return(copyError)
			fsUtil.On("CopyAll", mock.AnythingOfType("string"), mock.AnythingOfType("string")).Return(copyAllError)
			if initMap {
				resMap = mapset.Init()
			}
			worker := new(common.ConfigWorker)
			worker.ResourceMap = resMap
			worker.FSUtil = fsUtil
			err := getter.GetLocalResources("", resources, "dest", "subfolder", recursively, worker, constants.Standards)
			assert.Equal(GinkgoT(), expectedError, err)
		},
			Entry("Bad input to reserve", false, true, []string{""}, nil, nil, nil, mapset.ErrEmptyInput),
			Entry("Successful recursive copy", true, true, []string{"res"}, nil, nil, nil, nil),
			Entry("Successful single copy", false, true, []string{"res"}, nil, nil, nil, nil),
			Entry("Failure of single copy", false, true, []string{"res"}, nil, errors.New("single copy fail"), nil, errors.New("single copy fail")),
			Entry("Mkdirs", false, true, []string{"res"}, errors.New("mkdirs error"), nil, nil, errors.New("mkdirs error")),
		)
	})
	Describe("GetRemoteResources", func() {
		DescribeTable("", func(downloadEntryError, tempDirError, openAndReadFileError, getResourcesError, parseV1_0_0Error, expectedError error) {
			entries := []common.Entry{
				{
					Path: "",
				},
			}
			getter := VCSAndLocalFSGetter{}
			worker := new(common.ConfigWorker)
			downloader := new(mocks.EntryDownloader)
			downloader.On("DownloadEntry", entries[0], mock.AnythingOfType("string")).Return(downloadEntryError)
			worker.Downloader = downloader
		Context("when the ParseV1_0_0 will not be called", func() {
			It("should not call it when passing in 1.0", func() {
				Parse(parser, []byte(`schema_version: "1.0"`))
				parser.AssertNotCalled(GinkgoT(), "ParseV1_0_0", data)
			})
		})
		Context("when the ParseV1_0_0 will is called", func() {
			BeforeEach(func() {
				data = []byte(`schema_version: "1.0.0"`)
			})
			Context("when ParseV1_0_0 is passed valid data", func() {
				It("should call ParseV1_0_0", func() {
					_, err = Parse(parser, data)
					parser.AssertCalled(GinkgoT(), "ParseV1_0_0", data)
					assert.Equal(GinkgoT(), expectedError, err)
				})
			})
			Context("when ParseV1_0_0 is passed invalid data", func() {
				BeforeEach(func() {
					expectedError = errors.New("can't parse yaml")
				})
				It("should call ParseV1_0_0 but return an error", func() {
					_, err = Parse(parser, data)
					parser.AssertCalled(GinkgoT(), "ParseV1_0_0", data)
					assert.Equal(GinkgoT(), expectedError, err)
				})
			})
		})
	})
})
Exemple #12
0
				return nil, nil
			}
		default:
		}

		if val == nil {
			return nil, nil
		}

		return NewDelivery(mailbox, val), nil
	case <-time.Tick(til):
		return nil, nil
	}
}

var ENoMailbox = errors.New("No such mailbox available")

func (r *Registry) Push(name string, value *Message) error {
	r.Lock()
	defer r.Unlock()

	if mailbox, ok := r.mailboxes[name]; ok {
		return mailbox.Push(value)
	}

	return errors.Subject(ENoMailbox, name)
}

func (r *Registry) Declare(name string) error {
	r.Lock()
	defer r.Unlock()
Exemple #13
0
// Init returns an initialized NestedMap
func Init() MapSet {
	return MapSet{mapOfSet: make(map[string]*set.Set)}
}

// Result is the result from any NestedMap operations
type Result struct {
	Value   string
	Error   error
	Success bool
}

var (
	// ErrEmptyInput represents that the input into the operation is not complete
	ErrEmptyInput = errors.New("One or more inputs are empty")
)

// Reserve will put a space into the map for the value given that key. Will return false if there is already an entry.
func (m *MapSet) Reserve(key string, value string) (result Result) {
	if key == "" || value == "" {
		result.Error = ErrEmptyInput
		return
	}
	var innerSet *set.Set
	if _, ok := m.mapOfSet[key]; !ok {
		innerSet = set.New()
		m.mapOfSet[key] = innerSet
	}
	if m.mapOfSet[key].Has(value) {
		result.Success = false
Exemple #14
0
package kbase

import (
	"github.com/gl-works/kbase/rpc"
	"github.com/vektra/errors"
	"golang.org/x/net/context"
)

var (
	emptyresponse *rpc.KeyResponse = &rpc.KeyResponse{}

	ErrMissingKspace = errors.New("ErrMissingKspace")
)

func (this *Kbase) HandleOffer(ctx context.Context, offer *rpc.Offer) (response *rpc.KeyResponse, err error) {
	if kspace, ok := this.kspaces[offer.Space]; ok {
		kspace.putOffer(offer.Key, offer.Server, offer.Value)
		response = emptyresponse
	} else {
		err = ErrMissingKspace
	}
	return
}

func (this *Kbase) HandlePoll(ctx context.Context, poll *rpc.Poll) (response *rpc.KeyResponse, err error) {
	if kspace, ok := this.kspaces[poll.Space]; ok {
		kspace.lockoffers.RLock()
		values := kspace.offers[poll.Key]
		kspace.lockoffers.RUnlock()
		response = &rpc.KeyResponse{Values: values}
	} else {
Exemple #15
0
	"net"
	"strings"
	"sync"
	"time"

	"github.com/hashicorp/yamux"
	"github.com/ugorji/go/codec"
	"github.com/vektra/errors"
	"github.com/vektra/seconn"
)

const DefaultPort = 8475

var msgpack codec.MsgpackHandle

var EProtocolError = errors.New("protocol error")

var muxConfig = yamux.DefaultConfig()

type Service struct {
	Address  string
	Registry Storage

	listener net.Listener

	wg     sync.WaitGroup
	closed bool

	shutdown chan struct{}
	lock     sync.Mutex
}
Exemple #16
0
	}

	g.printf("\n")
}

func (g *Generator) GeneratePrologueNote(note string) {
	if note != "" {
		g.printf("\n")
		for _, n := range strings.Split(note, "\\n") {
			g.printf("// %s\n", n)
		}
		g.printf("\n")
	}
}

var ErrNotInterface = errors.New("expression not an interface")

func (g *Generator) printf(s string, vals ...interface{}) {
	fmt.Fprintf(&g.buf, s, vals...)
}

var builtinTypes = map[string]bool{
	"ComplexType": true,
	"FloatType":   true,
	"IntegerType": true,
	"Type":        true,
	"Type1":       true,
	"bool":        true,
	"byte":        true,
	"complex128":  true,
	"complex64":   true,
Exemple #17
0
// Init returns an initialized NestedMap
func Init() MapSet {
	return MapSet{mapOfSet: make(map[string]*set.Set)}
}

// Result is the result from any NestedMap operations
type Result struct {
	Value   string
	Error   error
	Success bool
}

var (
	// ErrEmptyInput represents that the input into the operation is not complete
	ErrEmptyInput = errors.New("One or more inputs are empty")
	// ErrAlreadyExists represents when a value already exists in the set.
	ErrAlreadyExists = errors.New("Already exists")
)

// Reserve will put a space into the map for the value given that key. Will return false if there is already an entry.
func (m *MapSet) Reserve(key string, value string) (result Result) {
	if key == "" || value == "" {
		result.Error = ErrEmptyInput
		return
	}
	var innerSet *set.Set
	if _, ok := m.mapOfSet[key]; !ok {
		innerSet = set.New()
		m.mapOfSet[key] = innerSet
	}