├── examples ├── Godeps │ ├── _workspace │ │ ├── .gitignore │ │ └── src │ │ │ ├── github.com │ │ │ ├── stretchr │ │ │ │ ├── objx │ │ │ │ │ ├── value_test.go │ │ │ │ │ ├── README.md │ │ │ │ │ ├── security_test.go │ │ │ │ │ ├── map_for_test.go │ │ │ │ │ ├── security.go │ │ │ │ │ ├── .gitignore │ │ │ │ │ ├── value.go │ │ │ │ │ ├── constants.go │ │ │ │ │ ├── codegen │ │ │ │ │ │ ├── array-access.txt │ │ │ │ │ │ ├── types_list.txt │ │ │ │ │ │ └── index.html │ │ │ │ │ ├── tests.go │ │ │ │ │ ├── tests_test.go │ │ │ │ │ ├── LICENSE.md │ │ │ │ │ ├── simple_example_test.go │ │ │ │ │ ├── conversions_test.go │ │ │ │ │ ├── mutations_test.go │ │ │ │ │ ├── mutations.go │ │ │ │ │ ├── doc.go │ │ │ │ │ ├── fixture_test.go │ │ │ │ │ ├── conversions.go │ │ │ │ │ └── map_test.go │ │ │ │ └── testify │ │ │ │ │ ├── assert │ │ │ │ │ ├── errors.go │ │ │ │ │ └── http_assertions_test.go │ │ │ │ │ └── mock │ │ │ │ │ └── doc.go │ │ │ ├── pborman │ │ │ │ └── uuid │ │ │ │ │ ├── CONTRIBUTORS │ │ │ │ │ ├── doc.go │ │ │ │ │ ├── json_test.go │ │ │ │ │ ├── json.go │ │ │ │ │ ├── version4.go │ │ │ │ │ ├── version1.go │ │ │ │ │ ├── LICENSE │ │ │ │ │ ├── seq_test.go │ │ │ │ │ ├── hash.go │ │ │ │ │ ├── util.go │ │ │ │ │ ├── dce.go │ │ │ │ │ ├── node.go │ │ │ │ │ ├── time.go │ │ │ │ │ └── uuid.go │ │ │ ├── golang │ │ │ │ └── glog │ │ │ │ │ ├── README │ │ │ │ │ └── glog_file.go │ │ │ └── gogo │ │ │ │ └── protobuf │ │ │ │ └── proto │ │ │ │ ├── lib_gogo.go │ │ │ │ ├── testdata │ │ │ │ ├── Makefile │ │ │ │ └── golden_test.go │ │ │ │ ├── Makefile │ │ │ │ ├── text_gogo.go │ │ │ │ ├── size2_test.go │ │ │ │ ├── proto3_proto │ │ │ │ ├── proto3.proto │ │ │ │ └── proto3.pb.go │ │ │ │ ├── properties_gogo.go │ │ │ │ ├── message_set_test.go │ │ │ │ ├── skip_gogo.go │ │ │ │ ├── pointer_unsafe_gogo.go │ │ │ │ └── proto3_test.go │ │ │ └── golang.org │ │ │ └── x │ │ │ └── net │ │ │ └── context │ │ │ ├── ctxhttp │ │ │ ├── cancelreq.go │ │ │ ├── cancelreq_go14.go │ │ │ ├── ctxhttp_test.go │ │ │ └── ctxhttp.go │ │ │ └── withtimeout_test.go │ ├── Readme │ └── Godeps.json ├── Makefile ├── zkdetect │ └── main.go ├── README.md ├── flagcheck │ └── flagcheck.go └── executor │ └── main.go ├── upid ├── doc.go ├── upid_test.go └── upid.go ├── mesosutil ├── constants.go ├── process │ └── process.go └── node.go ├── detector ├── zoo │ ├── doc.go │ ├── plugin.go │ ├── plugin_test.go │ ├── types.go │ ├── client2.go │ ├── mock │ │ ├── conn.go │ │ └── mock.go │ └── detect_internal_test.go ├── doc.go ├── factory_test.go ├── interface.go ├── standalone_test.go └── factory.go ├── messenger ├── testmessage │ ├── Makefile │ ├── testmessage.proto │ └── generator.go ├── doc.go ├── sessionid │ └── sessionid.go ├── message.go ├── transporter.go ├── README.md └── mock │ └── messenger.go ├── mesos └── doc.go ├── executor ├── doc.go ├── testing.go └── mock │ └── mock.go ├── scheduler ├── plugins.go ├── doc.go ├── handler.go ├── mock │ └── scheduler.go ├── testing.go └── schedcache.go ├── auth ├── callback │ ├── name.go │ ├── password.go │ ├── interprocess.go │ └── interface.go ├── sasl │ ├── mock │ │ └── mock.go │ ├── mech │ │ ├── plugins.go │ │ ├── interface.go │ │ └── crammd5 │ │ │ └── mechanism.go │ ├── context.go │ └── authenticatee_test.go ├── interface.go └── login.go ├── mesosproto ├── Makefile ├── internal.proto ├── authentication.proto └── internal.pb.go ├── CHANGELOG ├── NOTICE ├── .travis.yml ├── .gitignore ├── healthchecker └── health_checker.go ├── CONTRIBUTING.md └── README.md /examples/Godeps/_workspace/.gitignore: -------------------------------------------------------------------------------- 1 | /pkg 2 | /bin 3 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/value_test.go: -------------------------------------------------------------------------------- 1 | package objx 2 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/pborman/uuid/CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | Paul Borman 2 | -------------------------------------------------------------------------------- /upid/doc.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package upid defines the UPID type and some utilities of the UPID. 3 | */ 4 | package upid 5 | -------------------------------------------------------------------------------- /mesosutil/constants.go: -------------------------------------------------------------------------------- 1 | package mesosutil 2 | 3 | const ( 4 | // MesosVersion indicates the supported mesos version. 5 | MesosVersion = "0.24.0" 6 | ) 7 | -------------------------------------------------------------------------------- /detector/zoo/doc.go: -------------------------------------------------------------------------------- 1 | // Zookeeper-based mesos-master leaderhip detection. 2 | // Implements support for optional detector.AllMasters interface. 3 | package zoo 4 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/README.md: -------------------------------------------------------------------------------- 1 | # objx 2 | 3 | * Jump into the [API Documentation](http://godoc.org/github.com/stretchr/objx) 4 | -------------------------------------------------------------------------------- /examples/Godeps/Readme: -------------------------------------------------------------------------------- 1 | This directory tree is generated automatically by godep. 2 | 3 | Please do not edit. 4 | 5 | See https://github.com/tools/godep for more information. 6 | -------------------------------------------------------------------------------- /messenger/testmessage/Makefile: -------------------------------------------------------------------------------- 1 | all: testmessage.proto 2 | protoc --proto_path=${GOPATH}/src:${GOPATH}/src/github.com/gogo/protobuf/protobuf:. --gogo_out=. testmessage.proto 3 | -------------------------------------------------------------------------------- /mesos/doc.go: -------------------------------------------------------------------------------- 1 | // This package was previously the home of the native bindings. Please use the 2 | // native branch if you need to build against the native bindings. 3 | package mesos 4 | -------------------------------------------------------------------------------- /executor/doc.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package executor includes the interfaces of the mesos executor and 3 | the mesos executor driver, as well as an implementation of the driver. 4 | */ 5 | package executor 6 | -------------------------------------------------------------------------------- /scheduler/plugins.go: -------------------------------------------------------------------------------- 1 | package scheduler 2 | 3 | import ( 4 | _ "github.com/mesos/mesos-go/auth/sasl" 5 | _ "github.com/mesos/mesos-go/auth/sasl/mech/crammd5" 6 | _ "github.com/mesos/mesos-go/detector/zoo" 7 | ) 8 | -------------------------------------------------------------------------------- /scheduler/doc.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package scheduler includes the interfaces for the mesos scheduler and 3 | the mesos executor driver. It also contains as well as an implementation 4 | of the driver that you can use in your code. 5 | */ 6 | package scheduler 7 | -------------------------------------------------------------------------------- /examples/Makefile: -------------------------------------------------------------------------------- 1 | BIN := persistent_scheduler scheduler executor zkdetect flagcheck 2 | RACE := -race 3 | 4 | .PHONY: 5 | .PHONY: all $(BIN) 6 | 7 | all: $(BIN) 8 | 9 | $(BIN): 10 | mkdir -p _output 11 | godep go build $(RACE) -o _output/$@ ./$@ 12 | -------------------------------------------------------------------------------- /messenger/doc.go: -------------------------------------------------------------------------------- 1 | /* 2 | Package messenger includes a messenger and a transporter. 3 | The messenger provides interfaces to send a protobuf message 4 | through the underlying transporter. It also dispatches messages 5 | to installed handlers. 6 | */ 7 | package messenger 8 | -------------------------------------------------------------------------------- /auth/callback/name.go: -------------------------------------------------------------------------------- 1 | package callback 2 | 3 | type Name struct { 4 | name string 5 | } 6 | 7 | func NewName() *Name { 8 | return &Name{} 9 | } 10 | 11 | func (cb *Name) Get() string { 12 | return cb.name 13 | } 14 | 15 | func (cb *Name) Set(name string) { 16 | cb.name = name 17 | } 18 | -------------------------------------------------------------------------------- /detector/zoo/plugin.go: -------------------------------------------------------------------------------- 1 | package zoo 2 | 3 | import ( 4 | "github.com/mesos/mesos-go/detector" 5 | ) 6 | 7 | func init() { 8 | detector.Register("zk://", detector.PluginFactory(func(spec string, options ...detector.Option) (detector.Master, error) { 9 | return NewMasterDetector(spec, options...) 10 | })) 11 | } 12 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/security_test.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestHashWithKey(t *testing.T) { 9 | 10 | assert.Equal(t, "0ce84d8d01f2c7b6e0882b784429c54d280ea2d9", HashWithKey("abc", "def")) 11 | 12 | } 13 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/map_for_test.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | var TestMap map[string]interface{} = map[string]interface{}{ 4 | "name": "Tyler", 5 | "address": map[string]interface{}{ 6 | "city": "Salt Lake City", 7 | "state": "UT", 8 | }, 9 | "numbers": []interface{}{"one", "two", "three", "four", "five"}, 10 | } 11 | -------------------------------------------------------------------------------- /mesosproto/Makefile: -------------------------------------------------------------------------------- 1 | PROTO_PATH := ${GOPATH}/src:. 2 | PROTO_PATH := ${PROTO_PATH}:${GOPATH}/src/github.com/gogo/protobuf/protobuf 3 | PROTO_PATH := ${PROTO_PATH}:${GOPATH}/src/github.com/gogo/protobuf/gogoproto 4 | 5 | .PHONY: all 6 | 7 | all: 8 | protoc --proto_path=${PROTO_PATH} --gogo_out=. *.proto 9 | protoc --proto_path=${PROTO_PATH} --gogo_out=. ./scheduler/*.proto 10 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/pborman/uuid/doc.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // The uuid package generates and inspects UUIDs. 6 | // 7 | // UUIDs are based on RFC 4122 and DCE 1.1: Authentication and Security Services. 8 | package uuid 9 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | 2015-09-20: v0.0.2 2 | Fixed a bunch of race conditions and most test flakes (#185, #189) 3 | Updated Protobufs to Mesos 0.24.0 (#192) 4 | Fixed path to executor in example-scheduler (#186) 5 | Fixed executor shutdown hang bug (#183) 6 | Fixed nil dereference bug (#181) 7 | 8 | 2015-09-15: v0.0.1 9 | First tagged release ever! 10 | Mesos 0.24.0 and 0.23.0 compatibility. 11 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/security.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | import ( 4 | "crypto/sha1" 5 | "encoding/hex" 6 | ) 7 | 8 | // HashWithKey hashes the specified string using the security 9 | // key. 10 | func HashWithKey(data, key string) string { 11 | hash := sha1.New() 12 | hash.Write([]byte(data + ":" + key)) 13 | return hex.EncodeToString(hash.Sum(nil)) 14 | } 15 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | 10 | # Architecture specific extensions/prefixes 11 | *.[568vq] 12 | [568vq].out 13 | 14 | *.cgo1.go 15 | *.cgo2.c 16 | _cgo_defun.c 17 | _cgo_gotypes.go 18 | _cgo_export.* 19 | 20 | _testmain.go 21 | 22 | *.exe 23 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/value.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | // Value provides methods for extracting interface{} data in various 4 | // types. 5 | type Value struct { 6 | // data contains the raw data being managed by this Value 7 | data interface{} 8 | } 9 | 10 | // Data returns the raw data contained by this Value 11 | func (v *Value) Data() interface{} { 12 | return v.data 13 | } 14 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/testify/assert/errors.go: -------------------------------------------------------------------------------- 1 | package assert 2 | 3 | import ( 4 | "errors" 5 | ) 6 | 7 | // AnError is an error instance useful for testing. If the code does not care 8 | // about error specifics, and only needs to return the error for example, this 9 | // error should be used to make the test code more readable. 10 | var AnError = errors.New("assert.AnError general error for testing") 11 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/constants.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | const ( 4 | // PathSeparator is the character used to separate the elements 5 | // of the keypath. 6 | // 7 | // For example, `location.address.city` 8 | PathSeparator string = "." 9 | 10 | // SignatureSeparator is the character that is used to 11 | // separate the Base64 string from the security signature. 12 | SignatureSeparator = "_" 13 | ) 14 | -------------------------------------------------------------------------------- /auth/callback/password.go: -------------------------------------------------------------------------------- 1 | package callback 2 | 3 | type Password struct { 4 | password []byte 5 | } 6 | 7 | func NewPassword() *Password { 8 | return &Password{} 9 | } 10 | 11 | func (cb *Password) Get() []byte { 12 | clone := make([]byte, len(cb.password)) 13 | copy(clone, cb.password) 14 | return clone 15 | } 16 | 17 | func (cb *Password) Set(password []byte) { 18 | cb.password = make([]byte, len(password)) 19 | copy(cb.password, password) 20 | } 21 | -------------------------------------------------------------------------------- /messenger/sessionid/sessionid.go: -------------------------------------------------------------------------------- 1 | package sessionid 2 | 3 | import ( 4 | "golang.org/x/net/context" 5 | ) 6 | 7 | type key int 8 | 9 | const sessionIDKey = 0 10 | 11 | func NewContext(ctx context.Context, sessionID string) context.Context { 12 | return context.WithValue(ctx, sessionIDKey, sessionID) 13 | } 14 | 15 | func FromContext(ctx context.Context) (string, bool) { 16 | sessionID, ok := ctx.Value(sessionIDKey).(string) 17 | return sessionID, ok 18 | } 19 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/codegen/array-access.txt: -------------------------------------------------------------------------------- 1 | case []{1}: 2 | a := object.([]{1}) 3 | if isSet { 4 | a[index] = value.({1}) 5 | } else { 6 | if index >= len(a) { 7 | if panics { 8 | panic(fmt.Sprintf("objx: Index %d is out of range because the []{1} only contains %d items.", index, len(a))) 9 | } 10 | return nil 11 | } else { 12 | return a[index] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/tests.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | // Has gets whether there is something at the specified selector 4 | // or not. 5 | // 6 | // If m is nil, Has will always return false. 7 | func (m Map) Has(selector string) bool { 8 | if m == nil { 9 | return false 10 | } 11 | return !m.Get(selector).IsNil() 12 | } 13 | 14 | // IsNil gets whether the data is nil or not. 15 | func (v *Value) IsNil() bool { 16 | return v == nil || v.data == nil 17 | } 18 | -------------------------------------------------------------------------------- /auth/sasl/mock/mock.go: -------------------------------------------------------------------------------- 1 | package mock 2 | 3 | import ( 4 | "github.com/gogo/protobuf/proto" 5 | mock_messenger "github.com/mesos/mesos-go/messenger/mock" 6 | "github.com/mesos/mesos-go/upid" 7 | "github.com/stretchr/testify/mock" 8 | "golang.org/x/net/context" 9 | ) 10 | 11 | type Transport struct { 12 | *mock_messenger.Messenger 13 | } 14 | 15 | func (m *Transport) Send(ctx context.Context, upid *upid.UPID, msg proto.Message) error { 16 | return m.Called(mock.Anything, upid, msg).Error(0) 17 | } 18 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/cancelreq.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build go1.5 6 | 7 | package ctxhttp 8 | 9 | import "net/http" 10 | 11 | func canceler(client *http.Client, req *http.Request) func() { 12 | ch := make(chan struct{}) 13 | req.Cancel = ch 14 | 15 | return func() { 16 | close(ch) 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /detector/zoo/plugin_test.go: -------------------------------------------------------------------------------- 1 | package zoo 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/mesos/mesos-go/detector" 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | // validate plugin registration for zk:// prefix is working 11 | func TestDectorFactoryNew_ZkPrefix(t *testing.T) { 12 | assert := assert.New(t) 13 | m, err := detector.New("zk://127.0.0.1:5050/mesos") 14 | assert.NoError(err) 15 | assert.IsType(&MasterDetector{}, m) 16 | md := m.(*MasterDetector) 17 | t.Logf("canceling detector") 18 | md.Cancel() 19 | } 20 | -------------------------------------------------------------------------------- /auth/callback/interprocess.go: -------------------------------------------------------------------------------- 1 | package callback 2 | 3 | import ( 4 | "github.com/mesos/mesos-go/upid" 5 | ) 6 | 7 | type Interprocess struct { 8 | client upid.UPID 9 | server upid.UPID 10 | } 11 | 12 | func NewInterprocess() *Interprocess { 13 | return &Interprocess{} 14 | } 15 | 16 | func (cb *Interprocess) Client() upid.UPID { 17 | return cb.client 18 | } 19 | 20 | func (cb *Interprocess) Server() upid.UPID { 21 | return cb.server 22 | } 23 | 24 | func (cb *Interprocess) Set(server, client upid.UPID) { 25 | cb.server = server 26 | cb.client = client 27 | } 28 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/tests_test.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestHas(t *testing.T) { 9 | 10 | m := New(TestMap) 11 | 12 | assert.True(t, m.Has("name")) 13 | assert.True(t, m.Has("address.state")) 14 | assert.True(t, m.Has("numbers[4]")) 15 | 16 | assert.False(t, m.Has("address.state.nope")) 17 | assert.False(t, m.Has("address.nope")) 18 | assert.False(t, m.Has("nope")) 19 | assert.False(t, m.Has("numbers[5]")) 20 | 21 | m = nil 22 | assert.False(t, m.Has("nothing")) 23 | 24 | } 25 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | Copyright 2013-2015, Mesosphere, Inc. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | -------------------------------------------------------------------------------- /mesosutil/process/process.go: -------------------------------------------------------------------------------- 1 | package process 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | ) 7 | 8 | var ( 9 | pidLock sync.Mutex 10 | pid uint64 11 | ) 12 | 13 | func nextPid() uint64 { 14 | pidLock.Lock() 15 | defer pidLock.Unlock() 16 | pid++ 17 | return pid 18 | } 19 | 20 | //TODO(jdef) add lifecycle funcs 21 | //TODO(jdef) add messaging funcs 22 | type Process struct { 23 | label string 24 | } 25 | 26 | func New(kind string) *Process { 27 | return &Process{ 28 | label: fmt.Sprintf("%s(%d)", kind, nextPid()), 29 | } 30 | } 31 | 32 | func (p *Process) Label() string { 33 | return p.label 34 | } 35 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/cancelreq_go14.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // +build !go1.5 6 | 7 | package ctxhttp 8 | 9 | import "net/http" 10 | 11 | type requestCanceler interface { 12 | CancelRequest(*http.Request) 13 | } 14 | 15 | func canceler(client *http.Client, req *http.Request) func() { 16 | rc, ok := client.Transport.(requestCanceler) 17 | if !ok { 18 | return func() {} 19 | } 20 | return func() { 21 | rc.CancelRequest(req) 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /auth/callback/interface.go: -------------------------------------------------------------------------------- 1 | package callback 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type Unsupported struct { 8 | Callback Interface 9 | } 10 | 11 | func (uc *Unsupported) Error() string { 12 | return fmt.Sprintf("Unsupported callback <%T>: %v", uc.Callback, uc.Callback) 13 | } 14 | 15 | type Interface interface { 16 | // marker interface 17 | } 18 | 19 | type Handler interface { 20 | // may return an Unsupported error on failure 21 | Handle(callbacks ...Interface) error 22 | } 23 | 24 | type HandlerFunc func(callbacks ...Interface) error 25 | 26 | func (f HandlerFunc) Handle(callbacks ...Interface) error { 27 | return f(callbacks...) 28 | } 29 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: go 3 | go: 4 | - 1.3 5 | - 1.4.2 6 | - 1.5.1 7 | - tip 8 | before_install: 9 | #these two lines help users who fork mesos-go. It's a noop when running from the mesos organization 10 | - RepoName=`basename $PWD`; SrcDir=`dirname $PWD`; DestDir="`dirname $SrcDir`/mesos" 11 | - if [[ "$SrcDir" != "$DestDir" ]]; then mv "$SrcDir" "$DestDir"; cd ../../mesos/$RepoName; export TRAVIS_BUILD_DIR=`dirname $TRAVIS_BUILD_DIR`/$RepoName; fi 12 | install: 13 | - go get -t -d -v ./... 14 | script: 15 | - ! gofmt -s -d . 2>&1 | read diff 16 | - go install -v ./... 17 | - flagcheck 18 | - go test -timeout 120s -race ./... 19 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/codegen/types_list.txt: -------------------------------------------------------------------------------- 1 | Interface,interface{},"something",nil,Inter 2 | Map,map[string]interface{},map[string]interface{}{"name":"Tyler"},nil,MSI 3 | ObjxMap,(Map),New(1),New(nil),ObjxMap 4 | Bool,bool,true,false,Bool 5 | String,string,"hello","",Str 6 | Int,int,1,0,Int 7 | Int8,int8,1,0,Int8 8 | Int16,int16,1,0,Int16 9 | Int32,int32,1,0,Int32 10 | Int64,int64,1,0,Int64 11 | Uint,uint,1,0,Uint 12 | Uint8,uint8,1,0,Uint8 13 | Uint16,uint16,1,0,Uint16 14 | Uint32,uint32,1,0,Uint32 15 | Uint64,uint64,1,0,Uint64 16 | Uintptr,uintptr,1,0,Uintptr 17 | Float32,float32,1,0,Float32 18 | Float64,float64,1,0,Float64 19 | Complex64,complex64,1,0,Complex64 20 | Complex128,complex128,1,0,Complex128 21 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/pborman/uuid/json_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import ( 8 | "encoding/json" 9 | "reflect" 10 | "testing" 11 | ) 12 | 13 | var testUUID = Parse("f47ac10b-58cc-0372-8567-0e02b2c3d479") 14 | 15 | func TestJSON(t *testing.T) { 16 | type S struct { 17 | ID1 UUID 18 | ID2 UUID 19 | } 20 | s1 := S{ID1: testUUID} 21 | data, err := json.Marshal(&s1) 22 | if err != nil { 23 | t.Fatal(err) 24 | } 25 | var s2 S 26 | if err := json.Unmarshal(data, &s2); err != nil { 27 | t.Fatal(err) 28 | } 29 | if !reflect.DeepEqual(&s1, &s2) { 30 | t.Errorf("got %#v, want %#v", s2, s1) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/golang.org/x/net/context/withtimeout_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package context_test 6 | 7 | import ( 8 | "fmt" 9 | "time" 10 | 11 | "golang.org/x/net/context" 12 | ) 13 | 14 | func ExampleWithTimeout() { 15 | // Pass a context with a timeout to tell a blocking function that it 16 | // should abandon its work after the timeout elapses. 17 | ctx, _ := context.WithTimeout(context.Background(), 100*time.Millisecond) 18 | select { 19 | case <-time.After(200 * time.Millisecond): 20 | fmt.Println("overslept") 21 | case <-ctx.Done(): 22 | fmt.Println(ctx.Err()) // prints "context deadline exceeded" 23 | } 24 | // Output: 25 | // context deadline exceeded 26 | } 27 | -------------------------------------------------------------------------------- /mesosutil/node.go: -------------------------------------------------------------------------------- 1 | package mesosutil 2 | 3 | import ( 4 | "os" 5 | "os/exec" 6 | "strings" 7 | 8 | log "github.com/golang/glog" 9 | ) 10 | 11 | //TODO(jdef) copied from kubernetes/pkg/util/node.go 12 | func GetHostname(hostnameOverride string) string { 13 | hostname := hostnameOverride 14 | if hostname == "" { 15 | // Note: We use exec here instead of os.Hostname() because we 16 | // want the FQDN, and this is the easiest way to get it. 17 | fqdn, err := exec.Command("hostname", "-f").Output() 18 | if err != nil || len(fqdn) == 0 { 19 | log.Errorf("Couldn't determine hostname fqdn, failing back to hostname: %v", err) 20 | hostname, err = os.Hostname() 21 | if err != nil { 22 | log.Fatalf("Error getting hostname: %v", err) 23 | } 24 | } else { 25 | hostname = string(fqdn) 26 | } 27 | } 28 | return strings.TrimSpace(hostname) 29 | } 30 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/pborman/uuid/json.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import "errors" 8 | 9 | func (u UUID) MarshalJSON() ([]byte, error) { 10 | if len(u) == 0 { 11 | return []byte(`""`), nil 12 | } 13 | return []byte(`"` + u.String() + `"`), nil 14 | } 15 | 16 | func (u *UUID) UnmarshalJSON(data []byte) error { 17 | if len(data) == 0 || string(data) == `""` { 18 | return nil 19 | } 20 | if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' { 21 | return errors.New("invalid UUID format") 22 | } 23 | data = data[1 : len(data)-1] 24 | uu := Parse(string(data)) 25 | if uu == nil { 26 | return errors.New("invalid UUID format") 27 | } 28 | *u = uu 29 | return nil 30 | } 31 | -------------------------------------------------------------------------------- /detector/zoo/types.go: -------------------------------------------------------------------------------- 1 | package zoo 2 | 3 | import ( 4 | "github.com/samuel/go-zookeeper/zk" 5 | ) 6 | 7 | // Connector Interface to facade zk.Conn type 8 | // since github.com/samuel/go-zookeeper/zk does not provide an interface 9 | // for the zk.Conn object, this allows for mocking and easier testing. 10 | type Connector interface { 11 | Close() 12 | Children(string) ([]string, *zk.Stat, error) 13 | ChildrenW(string) ([]string, *zk.Stat, <-chan zk.Event, error) 14 | Get(string) ([]byte, *zk.Stat, error) 15 | } 16 | 17 | //Factory is an adapter to trap the creation of zk.Conn instances 18 | //since the official zk API does not expose an interface for zk.Conn. 19 | type Factory interface { 20 | create() (Connector, <-chan zk.Event, error) 21 | } 22 | 23 | type asFactory func() (Connector, <-chan zk.Event, error) 24 | 25 | func (f asFactory) create() (Connector, <-chan zk.Event, error) { 26 | return f() 27 | } 28 | -------------------------------------------------------------------------------- /scheduler/handler.go: -------------------------------------------------------------------------------- 1 | package scheduler 2 | 3 | import ( 4 | "github.com/mesos/mesos-go/auth/callback" 5 | mesos "github.com/mesos/mesos-go/mesosproto" 6 | "github.com/mesos/mesos-go/upid" 7 | ) 8 | 9 | type CredentialHandler struct { 10 | pid *upid.UPID // the process to authenticate against (master) 11 | client *upid.UPID // the process to be authenticated (slave / framework) 12 | credential *mesos.Credential 13 | } 14 | 15 | func (h *CredentialHandler) Handle(callbacks ...callback.Interface) error { 16 | for _, cb := range callbacks { 17 | switch cb := cb.(type) { 18 | case *callback.Name: 19 | cb.Set(h.credential.GetPrincipal()) 20 | case *callback.Password: 21 | cb.Set(([]byte)(h.credential.GetSecret())) 22 | case *callback.Interprocess: 23 | cb.Set(*(h.pid), *(h.client)) 24 | default: 25 | return &callback.Unsupported{Callback: cb} 26 | } 27 | } 28 | return nil 29 | } 30 | -------------------------------------------------------------------------------- /messenger/testmessage/testmessage.proto: -------------------------------------------------------------------------------- 1 | package testmessage; 2 | 3 | import "github.com/gogo/protobuf/gogoproto/gogo.proto"; 4 | 5 | option (gogoproto.gostring_all) = true; 6 | option (gogoproto.equal_all) = true; 7 | option (gogoproto.verbose_equal_all) = true; 8 | option (gogoproto.goproto_stringer_all) = false; 9 | option (gogoproto.stringer_all) = true; 10 | option (gogoproto.populate_all) = true; 11 | option (gogoproto.testgen_all) = false; 12 | option (gogoproto.benchgen_all) = false; 13 | option (gogoproto.marshaler_all) = true; 14 | option (gogoproto.sizer_all) = true; 15 | option (gogoproto.unmarshaler_all) = true; 16 | 17 | message SmallMessage { 18 | repeated string Values = 1; 19 | } 20 | 21 | message MediumMessage { 22 | repeated string Values = 1; 23 | } 24 | 25 | message BigMessage { 26 | repeated string Values = 1; 27 | } 28 | 29 | message LargeMessage { 30 | repeated string Values = 1; 31 | } 32 | -------------------------------------------------------------------------------- /mesosproto/internal.proto: -------------------------------------------------------------------------------- 1 | package mesosproto; 2 | 3 | import "mesos.proto"; 4 | import "github.com/gogo/protobuf/gogoproto/gogo.proto"; 5 | 6 | // For use with detector callbacks 7 | message InternalMasterChangeDetected { 8 | // will be present if there's a new master, otherwise nil 9 | optional MasterInfo master = 1; 10 | } 11 | 12 | message InternalTryAuthentication { 13 | // empty message, serves as a signal to the scheduler bindings 14 | } 15 | 16 | message InternalAuthenticationResult { 17 | // true only if the authentication process completed and login was successful 18 | required bool success = 1; 19 | // true if the authentication process completed, successfully or not 20 | required bool completed = 2; 21 | // master pid that this result pertains to 22 | required string pid = 3; 23 | } 24 | 25 | message InternalNetworkError { 26 | // master pid that this event pertains to 27 | required string pid = 1; 28 | // driver session UUID 29 | optional string session = 2; 30 | } 31 | -------------------------------------------------------------------------------- /executor/testing.go: -------------------------------------------------------------------------------- 1 | package executor 2 | 3 | import ( 4 | "github.com/gogo/protobuf/proto" 5 | "github.com/mesos/mesos-go/messenger" 6 | "github.com/mesos/mesos-go/upid" 7 | "golang.org/x/net/context" 8 | ) 9 | 10 | type TestDriver struct { 11 | *MesosExecutorDriver 12 | } 13 | 14 | func (e *TestDriver) SetConnected(b bool) { 15 | e.guarded(func() { 16 | e.connected = b 17 | }) 18 | } 19 | 20 | func (e *TestDriver) SetMessenger(m messenger.Messenger) { 21 | e.messenger = m 22 | } 23 | 24 | func (e *TestDriver) Started() <-chan struct{} { 25 | return e.started 26 | } 27 | 28 | func (e *TestDriver) guarded(f func()) { 29 | e.lock.Lock() 30 | defer e.lock.Unlock() 31 | f() 32 | } 33 | 34 | func (e *TestDriver) Context() context.Context { 35 | return e.context() 36 | } 37 | 38 | func (e *TestDriver) StatusUpdateAcknowledgement(ctx context.Context, from *upid.UPID, msg proto.Message) { 39 | e.guarded(func() { 40 | e.statusUpdateAcknowledgement(ctx, from, msg) 41 | }) 42 | } 43 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/pborman/uuid/version4.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | // Random returns a Random (Version 4) UUID or panics. 8 | // 9 | // The strength of the UUIDs is based on the strength of the crypto/rand 10 | // package. 11 | // 12 | // A note about uniqueness derived from from the UUID Wikipedia entry: 13 | // 14 | // Randomly generated UUIDs have 122 random bits. One's annual risk of being 15 | // hit by a meteorite is estimated to be one chance in 17 billion, that 16 | // means the probability is about 0.00000000006 (6 × 10−11), 17 | // equivalent to the odds of creating a few tens of trillions of UUIDs in a 18 | // year and having one duplicate. 19 | func NewRandom() UUID { 20 | uuid := make([]byte, 16) 21 | randomBits([]byte(uuid)) 22 | uuid[6] = (uuid[6] & 0x0f) | 0x40 // Version 4 23 | uuid[8] = (uuid[8] & 0x3f) | 0x80 // Variant is 10 24 | return uuid 25 | } 26 | -------------------------------------------------------------------------------- /auth/sasl/mech/plugins.go: -------------------------------------------------------------------------------- 1 | package mech 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | 7 | log "github.com/golang/glog" 8 | ) 9 | 10 | var ( 11 | mechLock sync.Mutex 12 | supportedMechs = make(map[string]Factory) 13 | ) 14 | 15 | func Register(name string, f Factory) error { 16 | mechLock.Lock() 17 | defer mechLock.Unlock() 18 | 19 | if _, found := supportedMechs[name]; found { 20 | return fmt.Errorf("Mechanism registered twice: %s", name) 21 | } 22 | supportedMechs[name] = f 23 | log.V(1).Infof("Registered mechanism %s", name) 24 | return nil 25 | } 26 | 27 | func ListSupported() (list []string) { 28 | mechLock.Lock() 29 | defer mechLock.Unlock() 30 | 31 | for mechname := range supportedMechs { 32 | list = append(list, mechname) 33 | } 34 | return list 35 | } 36 | 37 | func SelectSupported(mechanisms []string) (selectedMech string, factory Factory) { 38 | mechLock.Lock() 39 | defer mechLock.Unlock() 40 | 41 | for _, m := range mechanisms { 42 | if f, ok := supportedMechs[m]; ok { 43 | selectedMech = m 44 | factory = f 45 | break 46 | } 47 | } 48 | return 49 | } 50 | -------------------------------------------------------------------------------- /detector/doc.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | /* 20 | The detector package houses implementation of master detectors. 21 | The default implementation is the zookeeper master detector. 22 | It uses zookeeper to detect the lead Mesos master during startup/failover. 23 | */ 24 | package detector 25 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/LICENSE.md: -------------------------------------------------------------------------------- 1 | objx - by Mat Ryer and Tyler Bunnell 2 | 3 | The MIT License (MIT) 4 | 5 | Copyright (c) 2014 Stretchr, Inc. 6 | 7 | Permission is hereby granted, free of charge, to any person obtaining a copy 8 | of this software and associated documentation files (the "Software"), to deal 9 | in the Software without restriction, including without limitation the rights 10 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | copies of the Software, and to permit persons to whom the Software is 12 | furnished to do so, subject to the following conditions: 13 | 14 | The above copyright notice and this permission notice shall be included in all 15 | copies or substantial portions of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 23 | SOFTWARE. 24 | -------------------------------------------------------------------------------- /messenger/testmessage/generator.go: -------------------------------------------------------------------------------- 1 | package testmessage 2 | 3 | import ( 4 | "math/rand" 5 | ) 6 | 7 | func generateRandomString(length int) string { 8 | b := make([]byte, length) 9 | for i := range b { 10 | b[i] = byte(rand.Int()) 11 | } 12 | return string(b) 13 | } 14 | 15 | // GenerateSmallMessage generates a small size message. 16 | func GenerateSmallMessage() *SmallMessage { 17 | v := make([]string, 3) 18 | for i := range v { 19 | v[i] = generateRandomString(5) 20 | } 21 | return &SmallMessage{Values: v} 22 | } 23 | 24 | // GenerateMediumMessage generates a medium size message. 25 | func GenerateMediumMessage() *MediumMessage { 26 | v := make([]string, 10) 27 | for i := range v { 28 | v[i] = generateRandomString(10) 29 | } 30 | return &MediumMessage{Values: v} 31 | } 32 | 33 | // GenerateBigMessage generates a big size message. 34 | func GenerateBigMessage() *BigMessage { 35 | v := make([]string, 20) 36 | for i := range v { 37 | v[i] = generateRandomString(20) 38 | } 39 | return &BigMessage{Values: v} 40 | } 41 | 42 | // GenerateLargeMessage generates a large size message. 43 | func GenerateLargeMessage() *LargeMessage { 44 | v := make([]string, 30) 45 | for i := range v { 46 | v[i] = generateRandomString(30) 47 | } 48 | return &LargeMessage{Values: v} 49 | } 50 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/simple_example_test.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestSimpleExample(t *testing.T) { 9 | 10 | // build a map from a JSON object 11 | o := MustFromJSON(`{"name":"Mat","foods":["indian","chinese"], "location":{"county":"hobbiton","city":"the shire"}}`) 12 | 13 | // Map can be used as a straight map[string]interface{} 14 | assert.Equal(t, o["name"], "Mat") 15 | 16 | // Get an Value object 17 | v := o.Get("name") 18 | assert.Equal(t, v, &Value{data: "Mat"}) 19 | 20 | // Test the contained value 21 | assert.False(t, v.IsInt()) 22 | assert.False(t, v.IsBool()) 23 | assert.True(t, v.IsStr()) 24 | 25 | // Get the contained value 26 | assert.Equal(t, v.Str(), "Mat") 27 | 28 | // Get a default value if the contained value is not of the expected type or does not exist 29 | assert.Equal(t, 1, v.Int(1)) 30 | 31 | // Get a value by using array notation 32 | assert.Equal(t, "indian", o.Get("foods[0]").Data()) 33 | 34 | // Set a value by using array notation 35 | o.Set("foods[0]", "italian") 36 | assert.Equal(t, "italian", o.Get("foods[0]").Str()) 37 | 38 | // Get a value by using dot notation 39 | assert.Equal(t, "hobbiton", o.Get("location.county").Str()) 40 | 41 | } 42 | -------------------------------------------------------------------------------- /auth/sasl/mech/interface.go: -------------------------------------------------------------------------------- 1 | package mech 2 | 3 | import ( 4 | "errors" 5 | 6 | "github.com/mesos/mesos-go/auth/callback" 7 | ) 8 | 9 | var ( 10 | IllegalStateErr = errors.New("illegal mechanism state") 11 | ) 12 | 13 | type Interface interface { 14 | Handler() callback.Handler 15 | Discard() // clean up resources or sensitive information; idempotent 16 | } 17 | 18 | // return a mechanism and it's initialization step (may be a noop that returns 19 | // a nil data blob and handle to the first "real" challenge step). 20 | type Factory func(h callback.Handler) (Interface, StepFunc, error) 21 | 22 | // StepFunc implementations should never return a nil StepFunc result. This 23 | // helps keep the logic in the SASL authticatee simpler: step functions are 24 | // never nil. Mechanisms that end up an error state (for example, some decoding 25 | // logic fails...) should return a StepFunc that represents an error state. 26 | // Some mechanisms may be able to recover from such. 27 | type StepFunc func(m Interface, data []byte) (StepFunc, []byte, error) 28 | 29 | // reflects an unrecoverable, illegal mechanism state; always returns IllegalState 30 | // as the next step along with an IllegalStateErr 31 | func IllegalState(m Interface, data []byte) (StepFunc, []byte, error) { 32 | return IllegalState, nil, IllegalStateErr 33 | } 34 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/pborman/uuid/version1.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import ( 8 | "encoding/binary" 9 | ) 10 | 11 | // NewUUID returns a Version 1 UUID based on the current NodeID and clock 12 | // sequence, and the current time. If the NodeID has not been set by SetNodeID 13 | // or SetNodeInterface then it will be set automatically. If the NodeID cannot 14 | // be set NewUUID returns nil. If clock sequence has not been set by 15 | // SetClockSequence then it will be set automatically. If GetTime fails to 16 | // return the current NewUUID returns nil. 17 | func NewUUID() UUID { 18 | if nodeID == nil { 19 | SetNodeInterface("") 20 | } 21 | 22 | now, seq, err := GetTime() 23 | if err != nil { 24 | return nil 25 | } 26 | 27 | uuid := make([]byte, 16) 28 | 29 | time_low := uint32(now & 0xffffffff) 30 | time_mid := uint16((now >> 32) & 0xffff) 31 | time_hi := uint16((now >> 48) & 0x0fff) 32 | time_hi |= 0x1000 // Version 1 33 | 34 | binary.BigEndian.PutUint32(uuid[0:], time_low) 35 | binary.BigEndian.PutUint16(uuid[4:], time_mid) 36 | binary.BigEndian.PutUint16(uuid[6:], time_hi) 37 | binary.BigEndian.PutUint16(uuid[8:], seq) 38 | copy(uuid[10:], nodeID) 39 | 40 | return uuid 41 | } 42 | -------------------------------------------------------------------------------- /upid/upid_test.go: -------------------------------------------------------------------------------- 1 | package upid 2 | 3 | import ( 4 | "testing" 5 | "testing/quick" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func TestUPIDParse(t *testing.T) { 11 | u, err := Parse("mesos@foo:bar") 12 | assert.Nil(t, u) 13 | assert.Error(t, err) 14 | 15 | u, err = Parse("mesoslocalhost5050") 16 | assert.Nil(t, u) 17 | assert.Error(t, err) 18 | 19 | u, err = Parse("mesos@localhost") 20 | assert.Nil(t, u) 21 | assert.Error(t, err) 22 | 23 | assert.Nil(t, quick.Check(func(s string) bool { 24 | u, err := Parse(s) 25 | return u == nil && err != nil 26 | }, &quick.Config{MaxCount: 100000})) 27 | } 28 | 29 | func TestUPIDString(t *testing.T) { 30 | u, err := Parse("mesos@localhost:5050") 31 | assert.NotNil(t, u) 32 | assert.NoError(t, err) 33 | assert.Equal(t, "mesos@localhost:5050", u.String()) 34 | } 35 | 36 | func TestUPIDEqual(t *testing.T) { 37 | u1, err := Parse("mesos@localhost:5050") 38 | u2, err := Parse("mesos@localhost:5050") 39 | u3, err := Parse("mesos1@localhost:5050") 40 | u4, err := Parse("mesos@mesos.com:5050") 41 | u5, err := Parse("mesos@localhost:5051") 42 | assert.NoError(t, err) 43 | 44 | assert.True(t, u1.Equal(u2)) 45 | assert.False(t, u1.Equal(u3)) 46 | assert.False(t, u1.Equal(u4)) 47 | assert.False(t, u1.Equal(u5)) 48 | assert.False(t, u1.Equal(nil)) 49 | assert.False(t, (*UPID)(nil).Equal(u5)) 50 | assert.True(t, (*UPID)(nil).Equal(nil)) 51 | } 52 | -------------------------------------------------------------------------------- /examples/zkdetect/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | 7 | log "github.com/golang/glog" 8 | "github.com/mesos/mesos-go/detector" 9 | _ "github.com/mesos/mesos-go/detector/zoo" 10 | mesos "github.com/mesos/mesos-go/mesosproto" 11 | ) 12 | 13 | type zkListener struct{} 14 | 15 | func (l *zkListener) OnMasterChanged(info *mesos.MasterInfo) { 16 | if info == nil { 17 | log.Infoln("master lost") 18 | } else { 19 | log.Infof("master changed: %s", masterString(info)) 20 | } 21 | } 22 | 23 | func (l *zkListener) UpdatedMasters(all []*mesos.MasterInfo) { 24 | for i, info := range all { 25 | log.Infof("master (%d): %s", i, masterString(info)) 26 | } 27 | } 28 | 29 | func masterString(info *mesos.MasterInfo) string { 30 | return fmt.Sprintf("Id %v Ip %v Hostname %v Port %v Version %v Pid %v", 31 | info.GetId(), info.GetIp(), info.GetHostname(), info.GetPort(), info.GetVersion(), info.GetPid()) 32 | } 33 | 34 | func main() { 35 | masters := flag.String("masters", "zk://localhost:2181/mesos", "ZK Mesos masters URI") 36 | flag.Parse() 37 | 38 | log.Infof("creating ZK detector for %q", *masters) 39 | 40 | m, err := detector.New(*masters) 41 | if err != nil { 42 | log.Fatalf("failed to create ZK listener for Mesos masters: %v", err) 43 | } 44 | 45 | log.Info("created ZK detector") 46 | err = m.Detect(&zkListener{}) 47 | if err != nil { 48 | log.Fatalf("failed to register ZK listener: %v", err) 49 | } 50 | 51 | log.Info("registered ZK listener") 52 | select {} // never stop 53 | } 54 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## generic files to ignore 2 | *~ 3 | *.lock 4 | *.DS_Store 5 | *.swp 6 | *.out 7 | 8 | # rails specific 9 | *.sqlite3 10 | config/database.yml 11 | log/* 12 | tmp/* 13 | 14 | # java specific 15 | *.class 16 | 17 | # python specific 18 | *.pyc 19 | 20 | # xcode/iphone specific 21 | build/* 22 | *.pbxuser 23 | *.mode2v3 24 | *.mode1v3 25 | *.perspective 26 | *.perspectivev3 27 | *~.nib 28 | 29 | # akka specific 30 | logs/* 31 | 32 | # sbt specific 33 | project/boot 34 | lib_managed/* 35 | project/build/target 36 | project/build/lib_managed 37 | project/build/src_managed 38 | project/plugins/lib_managed 39 | project/plugins/target 40 | project/plugins/src_managed 41 | project/plugins/project 42 | 43 | # eclipse specific 44 | .metadata 45 | jrebel.lic 46 | .idea/workspace.xml 47 | .idea/bashsupport_project.xml 48 | 49 | *.iml 50 | *.ipr 51 | *.iws 52 | 53 | target 54 | .idea 55 | .settings 56 | .classpath 57 | .project 58 | .ensime* 59 | *.sublime-* 60 | .cache 61 | .lib 62 | data 63 | .tags 64 | .tags_sorted_by_file 65 | atlassian-ide-plugin.xml 66 | node_modules 67 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 68 | *.o 69 | *.a 70 | *.so 71 | 72 | # Folders 73 | _obj 74 | _test 75 | 76 | # Architecture specific extensions/prefixes 77 | *.[568vq] 78 | [568vq].out 79 | 80 | *.cgo1.go 81 | *.cgo2.c 82 | _cgo_defun.c 83 | _cgo_gotypes.go 84 | _cgo_export.* 85 | 86 | _testmain.go 87 | 88 | *.exe 89 | *.test 90 | junit_* 91 | 92 | # mesos-go specific 93 | /examples/_output 94 | /vendor 95 | /example-scheduler 96 | 97 | #webide 98 | .c9 99 | -------------------------------------------------------------------------------- /scheduler/mock/scheduler.go: -------------------------------------------------------------------------------- 1 | package mock 2 | 3 | import ( 4 | log "github.com/golang/glog" 5 | mesos "github.com/mesos/mesos-go/mesosproto" 6 | "github.com/stretchr/testify/mock" 7 | 8 | . "github.com/mesos/mesos-go/scheduler" 9 | ) 10 | 11 | type MockScheduler struct { 12 | mock.Mock 13 | } 14 | 15 | func New() *MockScheduler { 16 | return &MockScheduler{} 17 | } 18 | 19 | func (sched *MockScheduler) Registered(SchedulerDriver, *mesos.FrameworkID, *mesos.MasterInfo) { 20 | sched.Called() 21 | } 22 | 23 | func (sched *MockScheduler) Reregistered(SchedulerDriver, *mesos.MasterInfo) { 24 | sched.Called() 25 | } 26 | 27 | func (sched *MockScheduler) Disconnected(SchedulerDriver) { 28 | sched.Called() 29 | } 30 | 31 | func (sched *MockScheduler) ResourceOffers(SchedulerDriver, []*mesos.Offer) { 32 | sched.Called() 33 | } 34 | 35 | func (sched *MockScheduler) OfferRescinded(SchedulerDriver, *mesos.OfferID) { 36 | sched.Called() 37 | } 38 | 39 | func (sched *MockScheduler) StatusUpdate(SchedulerDriver, *mesos.TaskStatus) { 40 | sched.Called() 41 | } 42 | 43 | func (sched *MockScheduler) FrameworkMessage(SchedulerDriver, *mesos.ExecutorID, *mesos.SlaveID, string) { 44 | sched.Called() 45 | } 46 | 47 | func (sched *MockScheduler) SlaveLost(SchedulerDriver, *mesos.SlaveID) { 48 | sched.Called() 49 | } 50 | 51 | func (sched *MockScheduler) ExecutorLost(SchedulerDriver, *mesos.ExecutorID, *mesos.SlaveID, int) { 52 | sched.Called() 53 | } 54 | 55 | func (sched *MockScheduler) Error(d SchedulerDriver, msg string) { 56 | log.Error(msg) 57 | sched.Called() 58 | } 59 | -------------------------------------------------------------------------------- /auth/sasl/context.go: -------------------------------------------------------------------------------- 1 | package sasl 2 | 3 | import ( 4 | "net" 5 | "strconv" 6 | 7 | "golang.org/x/net/context" 8 | ) 9 | 10 | // unexported to prevent collisions with context keys defined in 11 | // other packages. 12 | type _key int 13 | 14 | // If this package defined other context keys, they would have 15 | // different integer values. 16 | const ( 17 | statusKey _key = iota 18 | bindingAddressKey // bind address for login-related network ops 19 | bindingPortKey // port to bind auth listener if a specific port is needed 20 | ) 21 | 22 | func withStatus(ctx context.Context, s statusType) context.Context { 23 | return context.WithValue(ctx, statusKey, s) 24 | } 25 | 26 | func statusFrom(ctx context.Context) statusType { 27 | s, ok := ctx.Value(statusKey).(statusType) 28 | if !ok { 29 | panic("missing status in context") 30 | } 31 | return s 32 | } 33 | 34 | func WithBindingAddress(ctx context.Context, address net.IP) context.Context { 35 | return context.WithValue(ctx, bindingAddressKey, address) 36 | } 37 | 38 | func BindingAddressFrom(ctx context.Context) net.IP { 39 | obj := ctx.Value(bindingAddressKey) 40 | if addr, ok := obj.(net.IP); ok { 41 | return addr 42 | } else { 43 | return nil 44 | } 45 | } 46 | 47 | func WithBindingPort(ctx context.Context, port uint16) context.Context { 48 | return context.WithValue(ctx, bindingPortKey, port) 49 | } 50 | 51 | func BindingPortFrom(ctx context.Context) string { 52 | if port, ok := ctx.Value(bindingPortKey).(uint16); ok { 53 | return strconv.Itoa(int(port)) 54 | } 55 | return "0" 56 | } 57 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/golang/glog/README: -------------------------------------------------------------------------------- 1 | glog 2 | ==== 3 | 4 | Leveled execution logs for Go. 5 | 6 | This is an efficient pure Go implementation of leveled logs in the 7 | manner of the open source C++ package 8 | http://code.google.com/p/google-glog 9 | 10 | By binding methods to booleans it is possible to use the log package 11 | without paying the expense of evaluating the arguments to the log. 12 | Through the -vmodule flag, the package also provides fine-grained 13 | control over logging at the file level. 14 | 15 | The comment from glog.go introduces the ideas: 16 | 17 | Package glog implements logging analogous to the Google-internal 18 | C++ INFO/ERROR/V setup. It provides functions Info, Warning, 19 | Error, Fatal, plus formatting variants such as Infof. It 20 | also provides V-style logging controlled by the -v and 21 | -vmodule=file=2 flags. 22 | 23 | Basic examples: 24 | 25 | glog.Info("Prepare to repel boarders") 26 | 27 | glog.Fatalf("Initialization failed: %s", err) 28 | 29 | See the documentation for the V function for an explanation 30 | of these examples: 31 | 32 | if glog.V(2) { 33 | glog.Info("Starting transaction...") 34 | } 35 | 36 | glog.V(2).Infoln("Processed", nItems, "elements") 37 | 38 | 39 | The repository contains an open source version of the log package 40 | used inside Google. The master copy of the source lives inside 41 | Google, not here. The code in this repo is for export only and is not itself 42 | under development. Feature requests will be ignored. 43 | 44 | Send bug reports to golang-nuts@googlegroups.com. 45 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/pborman/uuid/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2009,2014 Google Inc. All rights reserved. 2 | 3 | Redistribution and use in source and binary forms, with or without 4 | modification, are permitted provided that the following conditions are 5 | met: 6 | 7 | * Redistributions of source code must retain the above copyright 8 | notice, this list of conditions and the following disclaimer. 9 | * Redistributions in binary form must reproduce the above 10 | copyright notice, this list of conditions and the following disclaimer 11 | in the documentation and/or other materials provided with the 12 | distribution. 13 | * Neither the name of Google Inc. nor the names of its 14 | contributors may be used to endorse or promote products derived from 15 | this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /healthchecker/health_checker.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package healthchecker 20 | 21 | import ( 22 | "time" 23 | 24 | "github.com/mesos/mesos-go/upid" 25 | ) 26 | 27 | // HealthChecker defines the interface of a health checker. 28 | type HealthChecker interface { 29 | // Start will start the health checker, and returns a notification channel. 30 | // if the checker thinks the slave is unhealthy, it will send the timestamp 31 | // via the channel. 32 | Start() <-chan time.Time 33 | // Pause will pause the slave health checker. 34 | Pause() 35 | // Continue will continue the slave health checker with a new slave upid. 36 | Continue(slaveUPID *upid.UPID) 37 | // Stop will stop the health checker. it should be called only once during 38 | // the life span of the checker. 39 | Stop() 40 | } 41 | -------------------------------------------------------------------------------- /examples/Godeps/Godeps.json: -------------------------------------------------------------------------------- 1 | { 2 | "ImportPath": "github.com/mesos/mesos-go", 3 | "GoVersion": "go1.4.2", 4 | "Packages": [ 5 | "./..." 6 | ], 7 | "Deps": [ 8 | { 9 | "ImportPath": "github.com/gogo/protobuf/proto", 10 | "Comment": "v0.1-55-g2093b57", 11 | "Rev": "2093b57e5ca2ccbee4626814100bc1aada691b18" 12 | }, 13 | { 14 | "ImportPath": "github.com/golang/glog", 15 | "Rev": "d1c4472bf2efd3826f2b5bdcc02d8416798d678c" 16 | }, 17 | { 18 | "ImportPath": "github.com/pborman/uuid", 19 | "Rev": "ca53cad383cad2479bbba7f7a1a05797ec1386e4" 20 | }, 21 | { 22 | "ImportPath": "github.com/samuel/go-zookeeper/zk", 23 | "Rev": "177002e16a0061912f02377e2dd8951a8b3551bc" 24 | }, 25 | { 26 | "ImportPath": "github.com/stretchr/objx", 27 | "Rev": "cbeaeb16a013161a98496fad62933b1d21786672" 28 | }, 29 | { 30 | "ImportPath": "github.com/stretchr/testify/assert", 31 | "Comment": "v1.0-21-gf552045", 32 | "Rev": "f5520455607c0233cb6d7b056f71b22c1d265ef1" 33 | }, 34 | { 35 | "ImportPath": "github.com/stretchr/testify/mock", 36 | "Comment": "v1.0-21-gf552045", 37 | "Rev": "f5520455607c0233cb6d7b056f71b22c1d265ef1" 38 | }, 39 | { 40 | "ImportPath": "github.com/stretchr/testify/require", 41 | "Comment": "v1.0-21-gf552045", 42 | "Rev": "f5520455607c0233cb6d7b056f71b22c1d265ef1" 43 | }, 44 | { 45 | "ImportPath": "github.com/stretchr/testify/suite", 46 | "Comment": "v1.0-21-gf552045", 47 | "Rev": "f5520455607c0233cb6d7b056f71b22c1d265ef1" 48 | }, 49 | { 50 | "ImportPath": "golang.org/x/net/context", 51 | "Rev": "cbcac7bb8415db9b6cb4d1ebab1dc9afbd688b97" 52 | } 53 | ] 54 | } 55 | -------------------------------------------------------------------------------- /detector/factory_test.go: -------------------------------------------------------------------------------- 1 | package detector 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | type testDetector string 10 | 11 | func (d testDetector) Start() error { return nil } 12 | func (d testDetector) Detect(f MasterChanged) error { return nil } 13 | 14 | func (d testDetector) Done() <-chan struct{} { return make(<-chan struct{}) } 15 | func (d testDetector) Cancel() {} 16 | 17 | // unregister a factory plugin according to its prefix. 18 | // this is part of the testing module on purpose: during normal execution there 19 | // should be no need to dynamically unregister plugins. 20 | func Unregister(prefix string) { 21 | pluginLock.Lock() 22 | defer pluginLock.Unlock() 23 | delete(plugins, prefix) 24 | } 25 | 26 | func TestDetectorFactoryRegister(t *testing.T) { 27 | prefix := "bbm:" 28 | Register(prefix, func(spec string, _ ...Option) (Master, error) { 29 | return testDetector("Hello!"), nil 30 | }) 31 | defer Unregister(prefix) 32 | 33 | f, ok := MatchingPlugin(prefix) 34 | 35 | assert.True(t, ok) 36 | assert.NotNil(t, f) 37 | } 38 | 39 | func TestDectorFactoryNew_EmptySpec(t *testing.T) { 40 | assert := assert.New(t) 41 | m, err := New("") 42 | assert.NotNil(err) 43 | assert.Nil(m) 44 | } 45 | 46 | func TestDectorFactoryNew_InvalidSpec(t *testing.T) { 47 | assert := assert.New(t) 48 | m, err := New("localhost") 49 | assert.NotNil(err) 50 | assert.Nil(m) 51 | } 52 | 53 | func TestDectorFactoryNew_TrivialSpec(t *testing.T) { 54 | assert := assert.New(t) 55 | m, err := New("localhost:1") 56 | assert.NoError(err) 57 | assert.NotNil(m) 58 | assert.IsType(&Standalone{}, m) 59 | } 60 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Examples 2 | 3 | ## Building 4 | ``` 5 | $ go get github.com/tools/godep 6 | $ make 7 | ``` 8 | 9 | ## Running 10 | ### Start Mesos 11 | You will need a running Mesos master and slaves to run the examples. For instance, start a local Mesos: 12 | ``` 13 | $ /bin/mesos-local --ip=127.0.0.1 --port=5050 --roles=golang 14 | ``` 15 | See http://mesos.apache.org/gettingstarted/ for getting started with Apache Mesos. 16 | 17 | ### Start the Go scheduler/executor examples 18 | ``` 19 | $ export EXECUTOR_BIN=$(pwd)/_output/executor 20 | $ ./_output/scheduler -master=127.0.0.1:5050 -executor="$EXECUTOR_BIN" -logtostderr=true 21 | ``` 22 | If all goes well, you should see output about task completion. 23 | You can also point your browser to the Mesos GUI http://127.0.0.1:5050/ to validate the framework activities. 24 | 25 | ### Start the Go scheduler with other executors 26 | You can also use the Go `example-scheduler` with executors written in other languages such as `Python` or `Java` for further validation (note: to use these executors requires a build of the mesos source code with `make check`): 27 | ``` 28 | $ ./_output/scheduler -master=127.0.0.1:5050 -executor="/src/examples/python/test-executor" -logtostderr=true 29 | ``` 30 | Similarly for the Java version: 31 | ``` 32 | $ ./_output/scheduler -master=127.0.0.1:5050 -executor="/src/examples/java/test-executor" -logtostderr=true 33 | ``` 34 | 35 | ### Start the Go persistent scheduler/executor examples 36 | ``` 37 | $ export EXECUTOR_BIN=$(pwd)/_output/executor 38 | $ ./_output/persistent_scheduler -master=127.0.0.1:5050 -executor="$EXECUTOR_BIN" -logtostderr=true -role=golang -mesos_authentication_principal=golang 39 | ``` 40 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/pborman/uuid/seq_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import ( 8 | "flag" 9 | "runtime" 10 | "testing" 11 | "time" 12 | ) 13 | 14 | // This test is only run when --regressions is passed on the go test line. 15 | var regressions = flag.Bool("regressions", false, "run uuid regression tests") 16 | 17 | // TestClockSeqRace tests for a particular race condition of returning two 18 | // identical Version1 UUIDs. The duration of 1 minute was chosen as the race 19 | // condition, before being fixed, nearly always occured in under 30 seconds. 20 | func TestClockSeqRace(t *testing.T) { 21 | if !*regressions { 22 | t.Skip("skipping regression tests") 23 | } 24 | duration := time.Minute 25 | 26 | done := make(chan struct{}) 27 | defer close(done) 28 | 29 | ch := make(chan UUID, 10000) 30 | ncpu := runtime.NumCPU() 31 | switch ncpu { 32 | case 0, 1: 33 | // We can't run the test effectively. 34 | t.Skip("skipping race test, only one CPU detected") 35 | return 36 | default: 37 | runtime.GOMAXPROCS(ncpu) 38 | } 39 | for i := 0; i < ncpu; i++ { 40 | go func() { 41 | for { 42 | select { 43 | case <-done: 44 | return 45 | case ch <- NewUUID(): 46 | } 47 | } 48 | }() 49 | } 50 | 51 | uuids := make(map[string]bool) 52 | cnt := 0 53 | start := time.Now() 54 | for u := range ch { 55 | s := u.String() 56 | if uuids[s] { 57 | t.Errorf("duplicate uuid after %d in %v: %s", cnt, time.Since(start), s) 58 | return 59 | } 60 | uuids[s] = true 61 | if time.Since(start) > duration { 62 | return 63 | } 64 | cnt++ 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /examples/flagcheck/flagcheck.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "os" 7 | 8 | // Import all non-testing packages to verify that flags are not added 9 | // to the command line. 10 | 11 | _ "github.com/mesos/mesos-go/auth" 12 | _ "github.com/mesos/mesos-go/auth/callback" 13 | _ "github.com/mesos/mesos-go/auth/sasl" 14 | _ "github.com/mesos/mesos-go/auth/sasl/mech" 15 | _ "github.com/mesos/mesos-go/auth/sasl/mech/crammd5" 16 | _ "github.com/mesos/mesos-go/detector" 17 | _ "github.com/mesos/mesos-go/detector/zoo" 18 | _ "github.com/mesos/mesos-go/executor" 19 | _ "github.com/mesos/mesos-go/healthchecker" 20 | _ "github.com/mesos/mesos-go/mesos" 21 | _ "github.com/mesos/mesos-go/mesosproto" 22 | _ "github.com/mesos/mesos-go/mesosproto/scheduler" 23 | _ "github.com/mesos/mesos-go/mesosutil" 24 | _ "github.com/mesos/mesos-go/mesosutil/process" 25 | _ "github.com/mesos/mesos-go/messenger" 26 | _ "github.com/mesos/mesos-go/messenger/sessionid" 27 | _ "github.com/mesos/mesos-go/scheduler" 28 | _ "github.com/mesos/mesos-go/upid" 29 | ) 30 | 31 | // Flags which are accepted from other packages. 32 | var allowedFlags = []string{ 33 | // Flags added from the glog package 34 | "logtostderr", 35 | "alsologtostderr", 36 | "v", 37 | "stderrthreshold", 38 | "vmodule", 39 | "log_backtrace_at", 40 | "log_dir", 41 | } 42 | 43 | func main() { 44 | expected := map[string]struct{}{} 45 | for _, f := range allowedFlags { 46 | expected[f] = struct{}{} 47 | } 48 | 49 | hasLeak := false 50 | flag.CommandLine.VisitAll(func(f *flag.Flag) { 51 | if _, ok := expected[f.Name]; !ok { 52 | fmt.Fprintf(os.Stderr, "Leaking flag %q: %q\n", f.Name, f.Usage) 53 | hasLeak = true 54 | } 55 | }) 56 | 57 | if hasLeak { 58 | os.Exit(1) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /messenger/message.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package messenger 20 | 21 | import ( 22 | "fmt" 23 | "strings" 24 | 25 | "github.com/gogo/protobuf/proto" 26 | "github.com/mesos/mesos-go/upid" 27 | ) 28 | 29 | // Message defines the type that passes in the Messenger. 30 | type Message struct { 31 | UPID *upid.UPID 32 | Name string 33 | ProtoMessage proto.Message 34 | Bytes []byte 35 | } 36 | 37 | // RequestURI returns the request URI of the message. 38 | func (m *Message) RequestURI() string { 39 | if m.isV1API() { 40 | return fmt.Sprintf("/api/v1/%s", m.Name) 41 | } 42 | 43 | return fmt.Sprintf("/%s/%s", m.UPID.ID, m.Name) 44 | } 45 | 46 | func (m *Message) isV1API() bool { 47 | return !strings.HasPrefix(m.Name, "mesos.internal") 48 | } 49 | 50 | // NOTE: This should not fail or panic. 51 | func extractNameFromRequestURI(requestURI string) string { 52 | return strings.Split(requestURI, "/")[2] 53 | } 54 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/testify/mock/doc.go: -------------------------------------------------------------------------------- 1 | // Provides a system by which it is possible to mock your objects and verify calls are happening as expected. 2 | // 3 | // Example Usage 4 | // 5 | // The mock package provides an object, Mock, that tracks activity on another object. It is usually 6 | // embedded into a test object as shown below: 7 | // 8 | // type MyTestObject struct { 9 | // // add a Mock object instance 10 | // mock.Mock 11 | // 12 | // // other fields go here as normal 13 | // } 14 | // 15 | // When implementing the methods of an interface, you wire your functions up 16 | // to call the Mock.Called(args...) method, and return the appropriate values. 17 | // 18 | // For example, to mock a method that saves the name and age of a person and returns 19 | // the year of their birth or an error, you might write this: 20 | // 21 | // func (o *MyTestObject) SavePersonDetails(firstname, lastname string, age int) (int, error) { 22 | // args := o.Called(firstname, lastname, age) 23 | // return args.Int(0), args.Error(1) 24 | // } 25 | // 26 | // The Int, Error and Bool methods are examples of strongly typed getters that take the argument 27 | // index position. Given this argument list: 28 | // 29 | // (12, true, "Something") 30 | // 31 | // You could read them out strongly typed like this: 32 | // 33 | // args.Int(0) 34 | // args.Bool(1) 35 | // args.String(2) 36 | // 37 | // For objects of your own type, use the generic Arguments.Get(index) method and make a type assertion: 38 | // 39 | // return args.Get(0).(*MyObject), args.Get(1).(*AnotherObjectOfMine) 40 | // 41 | // This may cause a panic if the object you are getting is nil (the type assertion will fail), in those 42 | // cases you should check for nil first. 43 | package mock 44 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | ## Issues 3 | When filing an issue, make sure to answer these five questions: 4 | 5 | 1. What version of the project are you using? 6 | 2. What operating system and processor architecture are you using? 7 | 3. What did you do? 8 | 4. What did you expect to see? 9 | 5. What did you see instead? 10 | 11 | ## Code 12 | ### Proposals 13 | Non trivial changes should be first discussed with the project maintainers by 14 | opening a Github issue with the "Proposal: " title prefix, clearly explaining 15 | rationale, context and implementation ideas. 16 | 17 | This separate step is encouraged but not required. 18 | 19 | ### Implementation 20 | Work should happen in an open pull request having a WIP prefix in its 21 | title which gives visibility to the development process and provides 22 | continuous integration feedback. 23 | 24 | The pull request description must be well written and provide the necessary 25 | context and background for review. If there's a proposal issue, it must be 26 | referenced. When ready, replace the WIP prefix with PTAL which will 27 | bring your contribution to the attention of project maintainers who will review 28 | your PR in a timely manner. 29 | 30 | Before review, keep in mind that: 31 | - Git commit messages should conform to [community standards](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html). 32 | - Git commits should represent meaningful milestones or units of work. 33 | - Changed or added code must be well tested. Different kinds of code 34 | require different testing strategies. 35 | - Changed or added code must pass the project's CI. 36 | - Changes to vendored files must be grouped into a single commit. 37 | 38 | Once comments and revisions on the implementation wind down, the reviewers will 39 | add the LGTM label which marks the PR as merge-able. 40 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/gogo/protobuf/proto/lib_gogo.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, Vastech SA (PTY) LTD. All rights reserved. 2 | // http://github.com/gogo/protobuf/gogoproto 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // 15 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 16 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 17 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 18 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 19 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 20 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 21 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 22 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 23 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | 27 | package proto 28 | 29 | import ( 30 | "encoding/json" 31 | "strconv" 32 | ) 33 | 34 | func MarshalJSONEnum(m map[int32]string, value int32) ([]byte, error) { 35 | s, ok := m[value] 36 | if !ok { 37 | s = strconv.Itoa(int(value)) 38 | } 39 | return json.Marshal(s) 40 | } 41 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/codegen/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Codegen 5 | 6 | 17 | 18 | 19 | 20 |

21 | Template 22 |

23 |

24 | Use {x} as a placeholder for each argument. 25 |

26 | 27 | 28 |

29 | Arguments (comma separated) 30 |

31 |

32 | One block per line 33 |

34 | 35 | 36 |

37 | Output 38 |

39 | 40 | 41 | 42 | 43 | 44 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /messenger/transporter.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package messenger 20 | 21 | import ( 22 | "github.com/mesos/mesos-go/upid" 23 | "golang.org/x/net/context" 24 | ) 25 | 26 | // Transporter defines methods for communicating with remote processes. 27 | type Transporter interface { 28 | //Send sends message to remote process. Must use context to determine 29 | //cancelled requests. Will stop sending when transport is stopped. 30 | Send(ctx context.Context, msg *Message) error 31 | 32 | //Rcvd receives and delegate message handling to installed handlers. 33 | //Will stop receiving when transport is stopped. 34 | Recv() (*Message, error) 35 | 36 | //Install mount an handler based on incoming message name. 37 | Install(messageName string) 38 | 39 | //Start starts the transporter and returns immediately. The error chan 40 | //is never nil. 41 | Start() (upid.UPID, <-chan error) 42 | 43 | //Stop kills the transporter. 44 | Stop(graceful bool) error 45 | 46 | //UPID returns the PID for transporter. 47 | UPID() upid.UPID 48 | } 49 | -------------------------------------------------------------------------------- /messenger/README.md: -------------------------------------------------------------------------------- 1 | ####Benchmark of the messenger. 2 | 3 | ```shell 4 | $ go test -v -run=Benckmark* -bench=. 5 | PASS 6 | BenchmarkMessengerSendSmallMessage 50000 70568 ns/op 7 | BenchmarkMessengerSendMediumMessage 50000 70265 ns/op 8 | BenchmarkMessengerSendBigMessage 50000 72693 ns/op 9 | BenchmarkMessengerSendLargeMessage 50000 72896 ns/op 10 | BenchmarkMessengerSendMixedMessage 50000 72631 ns/op 11 | BenchmarkMessengerSendRecvSmallMessage 20000 78409 ns/op 12 | BenchmarkMessengerSendRecvMediumMessage 20000 80471 ns/op 13 | BenchmarkMessengerSendRecvBigMessage 20000 82629 ns/op 14 | BenchmarkMessengerSendRecvLargeMessage 20000 85987 ns/op 15 | BenchmarkMessengerSendRecvMixedMessage 20000 83678 ns/op 16 | ok github.com/mesos/mesos-go/messenger 115.135s 17 | 18 | $ go test -v -run=Benckmark* -bench=. -cpu=4 -send-routines=4 2>/dev/null 19 | PASS 20 | BenchmarkMessengerSendSmallMessage-4 50000 35529 ns/op 21 | BenchmarkMessengerSendMediumMessage-4 50000 35997 ns/op 22 | BenchmarkMessengerSendBigMessage-4 50000 36871 ns/op 23 | BenchmarkMessengerSendLargeMessage-4 50000 37310 ns/op 24 | BenchmarkMessengerSendMixedMessage-4 50000 37419 ns/op 25 | BenchmarkMessengerSendRecvSmallMessage-4 50000 39320 ns/op 26 | BenchmarkMessengerSendRecvMediumMessage-4 50000 41990 ns/op 27 | BenchmarkMessengerSendRecvBigMessage-4 50000 42157 ns/op 28 | BenchmarkMessengerSendRecvLargeMessage-4 50000 45472 ns/op 29 | BenchmarkMessengerSendRecvMixedMessage-4 50000 47393 ns/op 30 | ok github.com/mesos/mesos-go/messenger 105.173s 31 | ``` 32 | 33 | ####environment: 34 | 35 | ``` 36 | OS: Linux yifan-laptop 3.13.0-32-generic #57-Ubuntu SMP Tue Jul 15 03:51:08 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux 37 | CPU: Intel(R) Core(TM) i5-3210M CPU @ 2.50GHz 38 | MEM: 4G DDR3 1600MHz 39 | ``` 40 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/pborman/uuid/hash.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import ( 8 | "crypto/md5" 9 | "crypto/sha1" 10 | "hash" 11 | ) 12 | 13 | // Well known Name Space IDs and UUIDs 14 | var ( 15 | NameSpace_DNS = Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8") 16 | NameSpace_URL = Parse("6ba7b811-9dad-11d1-80b4-00c04fd430c8") 17 | NameSpace_OID = Parse("6ba7b812-9dad-11d1-80b4-00c04fd430c8") 18 | NameSpace_X500 = Parse("6ba7b814-9dad-11d1-80b4-00c04fd430c8") 19 | NIL = Parse("00000000-0000-0000-0000-000000000000") 20 | ) 21 | 22 | // NewHash returns a new UUID dervied from the hash of space concatenated with 23 | // data generated by h. The hash should be at least 16 byte in length. The 24 | // first 16 bytes of the hash are used to form the UUID. The version of the 25 | // UUID will be the lower 4 bits of version. NewHash is used to implement 26 | // NewMD5 and NewSHA1. 27 | func NewHash(h hash.Hash, space UUID, data []byte, version int) UUID { 28 | h.Reset() 29 | h.Write(space) 30 | h.Write([]byte(data)) 31 | s := h.Sum(nil) 32 | uuid := make([]byte, 16) 33 | copy(uuid, s) 34 | uuid[6] = (uuid[6] & 0x0f) | uint8((version&0xf)<<4) 35 | uuid[8] = (uuid[8] & 0x3f) | 0x80 // RFC 4122 variant 36 | return uuid 37 | } 38 | 39 | // NewMD5 returns a new MD5 (Version 3) UUID based on the 40 | // supplied name space and data. 41 | // 42 | // NewHash(md5.New(), space, data, 3) 43 | func NewMD5(space UUID, data []byte) UUID { 44 | return NewHash(md5.New(), space, data, 3) 45 | } 46 | 47 | // NewSHA1 returns a new SHA1 (Version 5) UUID based on the 48 | // supplied name space and data. 49 | // 50 | // NewHash(sha1.New(), space, data, 5) 51 | func NewSHA1(space UUID, data []byte) UUID { 52 | return NewHash(sha1.New(), space, data, 5) 53 | } 54 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/Makefile: -------------------------------------------------------------------------------- 1 | # Go support for Protocol Buffers - Google's data interchange format 2 | # 3 | # Copyright 2010 The Go Authors. All rights reserved. 4 | # https://github.com/golang/protobuf 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # * Redistributions of source code must retain the above copyright 11 | # notice, this list of conditions and the following disclaimer. 12 | # * Redistributions in binary form must reproduce the above 13 | # copyright notice, this list of conditions and the following disclaimer 14 | # in the documentation and/or other materials provided with the 15 | # distribution. 16 | # * Neither the name of Google Inc. nor the names of its 17 | # contributors may be used to endorse or promote products derived from 18 | # this software without specific prior written permission. 19 | # 20 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 | # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | 32 | all: regenerate 33 | 34 | regenerate: 35 | go install github.com/gogo/protobuf/protoc-min-version 36 | protoc-min-version --version="3.0.0" --gogo_out=. test.proto 37 | 38 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package ctxhttp 6 | 7 | import ( 8 | "io/ioutil" 9 | "net/http" 10 | "net/http/httptest" 11 | "testing" 12 | "time" 13 | 14 | "golang.org/x/net/context" 15 | ) 16 | 17 | const ( 18 | requestDuration = 100 * time.Millisecond 19 | requestBody = "ok" 20 | ) 21 | 22 | func TestNoTimeout(t *testing.T) { 23 | ctx := context.Background() 24 | resp, err := doRequest(ctx) 25 | 26 | if resp == nil || err != nil { 27 | t.Fatalf("error received from client: %v %v", err, resp) 28 | } 29 | } 30 | func TestCancel(t *testing.T) { 31 | ctx, cancel := context.WithCancel(context.Background()) 32 | go func() { 33 | time.Sleep(requestDuration / 2) 34 | cancel() 35 | }() 36 | 37 | resp, err := doRequest(ctx) 38 | 39 | if resp != nil || err == nil { 40 | t.Fatalf("expected error, didn't get one. resp: %v", resp) 41 | } 42 | if err != ctx.Err() { 43 | t.Fatalf("expected error from context but got: %v", err) 44 | } 45 | } 46 | 47 | func TestCancelAfterRequest(t *testing.T) { 48 | ctx, cancel := context.WithCancel(context.Background()) 49 | 50 | resp, err := doRequest(ctx) 51 | 52 | // Cancel before reading the body. 53 | // Request.Body should still be readable after the context is canceled. 54 | cancel() 55 | 56 | b, err := ioutil.ReadAll(resp.Body) 57 | if err != nil || string(b) != requestBody { 58 | t.Fatalf("could not read body: %q %v", b, err) 59 | } 60 | } 61 | 62 | func doRequest(ctx context.Context) (*http.Response, error) { 63 | var okHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 64 | time.Sleep(requestDuration) 65 | w.Write([]byte(requestBody)) 66 | }) 67 | 68 | serv := httptest.NewServer(okHandler) 69 | defer serv.Close() 70 | 71 | return Get(ctx, nil, serv.URL) 72 | } 73 | -------------------------------------------------------------------------------- /upid/upid.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package upid 20 | 21 | import ( 22 | "fmt" 23 | "net" 24 | "strings" 25 | ) 26 | 27 | // UPID is a equivalent of the UPID in libprocess. 28 | type UPID struct { 29 | ID string 30 | Host string 31 | Port string 32 | } 33 | 34 | // Parse parses the UPID from the input string. 35 | func Parse(input string) (*UPID, error) { 36 | upid := new(UPID) 37 | 38 | splits := strings.Split(input, "@") 39 | if len(splits) != 2 { 40 | return nil, fmt.Errorf("Expect one `@' in the input") 41 | } 42 | upid.ID = splits[0] 43 | 44 | if _, err := net.ResolveTCPAddr("tcp4", splits[1]); err != nil { 45 | return nil, err 46 | } 47 | upid.Host, upid.Port, _ = net.SplitHostPort(splits[1]) 48 | return upid, nil 49 | } 50 | 51 | // String returns the string representation. 52 | func (u UPID) String() string { 53 | return fmt.Sprintf("%s@%s:%s", u.ID, u.Host, u.Port) 54 | } 55 | 56 | // Equal returns true if two upid is equal 57 | func (u *UPID) Equal(upid *UPID) bool { 58 | if u == nil { 59 | return upid == nil 60 | } else { 61 | return upid != nil && u.ID == upid.ID && u.Host == upid.Host && u.Port == upid.Port 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/conversions_test.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestConversionJSON(t *testing.T) { 9 | 10 | jsonString := `{"name":"Mat"}` 11 | o := MustFromJSON(jsonString) 12 | 13 | result, err := o.JSON() 14 | 15 | if assert.NoError(t, err) { 16 | assert.Equal(t, jsonString, result) 17 | } 18 | 19 | assert.Equal(t, jsonString, o.MustJSON()) 20 | 21 | } 22 | 23 | func TestConversionJSONWithError(t *testing.T) { 24 | 25 | o := MSI() 26 | o["test"] = func() {} 27 | 28 | assert.Panics(t, func() { 29 | o.MustJSON() 30 | }) 31 | 32 | _, err := o.JSON() 33 | 34 | assert.Error(t, err) 35 | 36 | } 37 | 38 | func TestConversionBase64(t *testing.T) { 39 | 40 | o := New(map[string]interface{}{"name": "Mat"}) 41 | 42 | result, err := o.Base64() 43 | 44 | if assert.NoError(t, err) { 45 | assert.Equal(t, "eyJuYW1lIjoiTWF0In0=", result) 46 | } 47 | 48 | assert.Equal(t, "eyJuYW1lIjoiTWF0In0=", o.MustBase64()) 49 | 50 | } 51 | 52 | func TestConversionBase64WithError(t *testing.T) { 53 | 54 | o := MSI() 55 | o["test"] = func() {} 56 | 57 | assert.Panics(t, func() { 58 | o.MustBase64() 59 | }) 60 | 61 | _, err := o.Base64() 62 | 63 | assert.Error(t, err) 64 | 65 | } 66 | 67 | func TestConversionSignedBase64(t *testing.T) { 68 | 69 | o := New(map[string]interface{}{"name": "Mat"}) 70 | 71 | result, err := o.SignedBase64("key") 72 | 73 | if assert.NoError(t, err) { 74 | assert.Equal(t, "eyJuYW1lIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6", result) 75 | } 76 | 77 | assert.Equal(t, "eyJuYW1lIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6", o.MustSignedBase64("key")) 78 | 79 | } 80 | 81 | func TestConversionSignedBase64WithError(t *testing.T) { 82 | 83 | o := MSI() 84 | o["test"] = func() {} 85 | 86 | assert.Panics(t, func() { 87 | o.MustSignedBase64("key") 88 | }) 89 | 90 | _, err := o.SignedBase64("key") 91 | 92 | assert.Error(t, err) 93 | 94 | } 95 | -------------------------------------------------------------------------------- /detector/zoo/client2.go: -------------------------------------------------------------------------------- 1 | package zoo 2 | 3 | import ( 4 | "sync" 5 | "time" 6 | 7 | "github.com/samuel/go-zookeeper/zk" 8 | ) 9 | 10 | const ( 11 | defaultSessionTimeout = 60 * time.Second 12 | CurrentPath = "." 13 | ) 14 | 15 | var zkSessionTimeout = defaultSessionTimeout 16 | 17 | type client2 struct { 18 | *zk.Conn 19 | path string 20 | done chan struct{} // signal chan, closes when the underlying connection terminates 21 | stopOnce sync.Once 22 | } 23 | 24 | func connect2(hosts []string, path string) (*client2, error) { 25 | c, ev, err := zk.Connect(hosts, zkSessionTimeout) 26 | if err != nil { 27 | return nil, err 28 | } 29 | done := make(chan struct{}) 30 | go func() { 31 | // close the 'done' chan when the zk event chan closes (signals termination of zk connection) 32 | defer close(done) 33 | for { 34 | if _, ok := <-ev; !ok { 35 | return 36 | } 37 | } 38 | }() 39 | return &client2{ 40 | Conn: c, 41 | path: path, 42 | done: done, 43 | }, nil 44 | } 45 | 46 | func (c *client2) Stopped() <-chan struct{} { 47 | return c.done 48 | } 49 | 50 | func (c *client2) Stop() { 51 | c.stopOnce.Do(c.Close) 52 | } 53 | 54 | func (c *client2) Data(path string) (data []byte, err error) { 55 | data, _, err = c.Get(path) 56 | return 57 | } 58 | 59 | func (c *client2) WatchChildren(path string) (string, <-chan []string, <-chan error) { 60 | errCh := make(chan error, 1) 61 | snap := make(chan []string) 62 | 63 | watchPath := c.path 64 | if path != "" && path != CurrentPath { 65 | watchPath = watchPath + path 66 | } 67 | go func() { 68 | defer close(errCh) 69 | for { 70 | children, _, ev, err := c.ChildrenW(watchPath) 71 | if err != nil { 72 | errCh <- err 73 | return 74 | } 75 | select { 76 | case snap <- children: 77 | case <-c.done: 78 | return 79 | } 80 | e := <-ev // wait for the next watch-related event 81 | if e.Err != nil { 82 | errCh <- e.Err 83 | return 84 | } 85 | } 86 | }() 87 | return watchPath, snap, errCh 88 | } 89 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/mutations_test.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestExclude(t *testing.T) { 9 | 10 | d := make(Map) 11 | d["name"] = "Mat" 12 | d["age"] = 29 13 | d["secret"] = "ABC" 14 | 15 | excluded := d.Exclude([]string{"secret"}) 16 | 17 | assert.Equal(t, d["name"], excluded["name"]) 18 | assert.Equal(t, d["age"], excluded["age"]) 19 | assert.False(t, excluded.Has("secret"), "secret should be excluded") 20 | 21 | } 22 | 23 | func TestCopy(t *testing.T) { 24 | 25 | d1 := make(map[string]interface{}) 26 | d1["name"] = "Tyler" 27 | d1["location"] = "UT" 28 | 29 | d1Obj := New(d1) 30 | d2Obj := d1Obj.Copy() 31 | 32 | d2Obj["name"] = "Mat" 33 | 34 | assert.Equal(t, d1Obj.Get("name").Str(), "Tyler") 35 | assert.Equal(t, d2Obj.Get("name").Str(), "Mat") 36 | 37 | } 38 | 39 | func TestMerge(t *testing.T) { 40 | 41 | d := make(map[string]interface{}) 42 | d["name"] = "Mat" 43 | 44 | d1 := make(map[string]interface{}) 45 | d1["name"] = "Tyler" 46 | d1["location"] = "UT" 47 | 48 | dObj := New(d) 49 | d1Obj := New(d1) 50 | 51 | merged := dObj.Merge(d1Obj) 52 | 53 | assert.Equal(t, merged.Get("name").Str(), d1Obj.Get("name").Str()) 54 | assert.Equal(t, merged.Get("location").Str(), d1Obj.Get("location").Str()) 55 | assert.Empty(t, dObj.Get("location").Str()) 56 | 57 | } 58 | 59 | func TestMergeHere(t *testing.T) { 60 | 61 | d := make(map[string]interface{}) 62 | d["name"] = "Mat" 63 | 64 | d1 := make(map[string]interface{}) 65 | d1["name"] = "Tyler" 66 | d1["location"] = "UT" 67 | 68 | dObj := New(d) 69 | d1Obj := New(d1) 70 | 71 | merged := dObj.MergeHere(d1Obj) 72 | 73 | assert.Equal(t, dObj, merged, "With MergeHere, it should return the first modified map") 74 | assert.Equal(t, merged.Get("name").Str(), d1Obj.Get("name").Str()) 75 | assert.Equal(t, merged.Get("location").Str(), d1Obj.Get("location").Str()) 76 | assert.Equal(t, merged.Get("location").Str(), dObj.Get("location").Str()) 77 | } 78 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/gogo/protobuf/proto/Makefile: -------------------------------------------------------------------------------- 1 | # Go support for Protocol Buffers - Google's data interchange format 2 | # 3 | # Copyright 2010 The Go Authors. All rights reserved. 4 | # https://github.com/golang/protobuf 5 | # 6 | # Redistribution and use in source and binary forms, with or without 7 | # modification, are permitted provided that the following conditions are 8 | # met: 9 | # 10 | # * Redistributions of source code must retain the above copyright 11 | # notice, this list of conditions and the following disclaimer. 12 | # * Redistributions in binary form must reproduce the above 13 | # copyright notice, this list of conditions and the following disclaimer 14 | # in the documentation and/or other materials provided with the 15 | # distribution. 16 | # * Neither the name of Google Inc. nor the names of its 17 | # contributors may be used to endorse or promote products derived from 18 | # this software without specific prior written permission. 19 | # 20 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 | # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 | # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 | # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | 32 | install: 33 | go install 34 | 35 | test: install generate-test-pbs 36 | go test 37 | 38 | 39 | generate-test-pbs: 40 | make install 41 | make -C testdata 42 | protoc-min-version --version="3.0.0" --proto_path=.:../../../../ --gogo_out=. proto3_proto/proto3.proto 43 | make 44 | -------------------------------------------------------------------------------- /auth/sasl/mech/crammd5/mechanism.go: -------------------------------------------------------------------------------- 1 | package crammd5 2 | 3 | import ( 4 | "crypto/hmac" 5 | "crypto/md5" 6 | "encoding/hex" 7 | "errors" 8 | "io" 9 | 10 | log "github.com/golang/glog" 11 | "github.com/mesos/mesos-go/auth/callback" 12 | "github.com/mesos/mesos-go/auth/sasl/mech" 13 | ) 14 | 15 | var ( 16 | Name = "CRAM-MD5" // name this mechanism is registered with 17 | 18 | //TODO(jdef) is this a generic SASL error? if so, move it up to mech 19 | challengeDataRequired = errors.New("challenge data may not be empty") 20 | ) 21 | 22 | func init() { 23 | mech.Register(Name, newInstance) 24 | } 25 | 26 | type mechanism struct { 27 | handler callback.Handler 28 | } 29 | 30 | func (m *mechanism) Handler() callback.Handler { 31 | return m.handler 32 | } 33 | 34 | func (m *mechanism) Discard() { 35 | // noop 36 | } 37 | 38 | func newInstance(h callback.Handler) (mech.Interface, mech.StepFunc, error) { 39 | m := &mechanism{ 40 | handler: h, 41 | } 42 | fn := func(m mech.Interface, data []byte) (mech.StepFunc, []byte, error) { 43 | // noop: no initialization needed 44 | return challengeResponse, nil, nil 45 | } 46 | return m, fn, nil 47 | } 48 | 49 | // algorithm lifted from wikipedia: http://en.wikipedia.org/wiki/CRAM-MD5 50 | // except that the SASL mechanism used by Mesos doesn't leverage base64 encoding 51 | func challengeResponse(m mech.Interface, data []byte) (mech.StepFunc, []byte, error) { 52 | if len(data) == 0 { 53 | return mech.IllegalState, nil, challengeDataRequired 54 | } 55 | decoded := string(data) 56 | log.V(4).Infof("challenge(decoded): %s", decoded) // for deep debugging only 57 | 58 | username := callback.NewName() 59 | secret := callback.NewPassword() 60 | 61 | if err := m.Handler().Handle(username, secret); err != nil { 62 | return mech.IllegalState, nil, err 63 | } 64 | hash := hmac.New(md5.New, secret.Get()) 65 | if _, err := io.WriteString(hash, decoded); err != nil { 66 | return mech.IllegalState, nil, err 67 | } 68 | 69 | codes := hex.EncodeToString(hash.Sum(nil)) 70 | msg := username.Get() + " " + codes 71 | return nil, []byte(msg), nil 72 | } 73 | -------------------------------------------------------------------------------- /scheduler/testing.go: -------------------------------------------------------------------------------- 1 | package scheduler 2 | 3 | import ( 4 | "github.com/gogo/protobuf/proto" 5 | mesos "github.com/mesos/mesos-go/mesosproto" 6 | "github.com/mesos/mesos-go/upid" 7 | "golang.org/x/net/context" 8 | ) 9 | 10 | type TestDriver struct { 11 | *MesosSchedulerDriver 12 | } 13 | 14 | func (t *TestDriver) SetConnected(b bool) { 15 | t.eventLock.Lock() 16 | defer t.eventLock.Unlock() 17 | t.connected = b 18 | } 19 | 20 | func (t *TestDriver) Started() <-chan struct{} { 21 | return t.started 22 | } 23 | 24 | func (t *TestDriver) Stopped() <-chan struct{} { 25 | return t.stopCh 26 | } 27 | 28 | func (t *TestDriver) Done() <-chan struct{} { 29 | return t.done 30 | } 31 | 32 | func (t *TestDriver) Framework() *mesos.FrameworkInfo { 33 | return t.frameworkInfo 34 | } 35 | 36 | func (t *TestDriver) UPID() *upid.UPID { 37 | return t.self 38 | } 39 | 40 | func (t *TestDriver) MasterPID() *upid.UPID { 41 | return t.masterPid 42 | } 43 | 44 | func (t *TestDriver) Fatal(ctx context.Context, msg string) { 45 | t.eventLock.Lock() 46 | defer t.eventLock.Unlock() 47 | t.fatal(ctx, msg) 48 | } 49 | 50 | func (t *TestDriver) OnDispatch(f func(ctx context.Context, upid *upid.UPID, msg proto.Message) error) { 51 | t.dispatch = f 52 | } 53 | 54 | func (t *TestDriver) HandleMasterChanged(ctx context.Context, from *upid.UPID, msg proto.Message) { 55 | t.eventLock.Lock() 56 | defer t.eventLock.Unlock() 57 | t.handleMasterChanged(ctx, from, msg) 58 | } 59 | 60 | func (t *TestDriver) CacheOffer(offer *mesos.Offer, pid *upid.UPID) { 61 | t.cache.putOffer(offer, pid) 62 | } 63 | 64 | func (t *TestDriver) Context() context.Context { 65 | return t.context() 66 | } 67 | 68 | func (t *TestDriver) FrameworkRegistered(ctx context.Context, from *upid.UPID, msg proto.Message) { 69 | t.eventLock.Lock() 70 | defer t.eventLock.Unlock() 71 | t.frameworkRegistered(ctx, from, msg) 72 | } 73 | 74 | func (t *TestDriver) FrameworkReregistered(ctx context.Context, from *upid.UPID, msg proto.Message) { 75 | t.eventLock.Lock() 76 | defer t.eventLock.Unlock() 77 | t.frameworkReregistered(ctx, from, msg) 78 | } 79 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/pborman/uuid/util.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import ( 8 | "io" 9 | ) 10 | 11 | // randomBits completely fills slice b with random data. 12 | func randomBits(b []byte) { 13 | if _, err := io.ReadFull(rander, b); err != nil { 14 | panic(err.Error()) // rand should never fail 15 | } 16 | } 17 | 18 | // xvalues returns the value of a byte as a hexadecimal digit or 255. 19 | var xvalues = []byte{ 20 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 21 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 22 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 23 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 255, 255, 255, 255, 255, 255, 24 | 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 25 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 26 | 255, 10, 11, 12, 13, 14, 15, 255, 255, 255, 255, 255, 255, 255, 255, 255, 27 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 28 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 29 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 30 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 31 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 32 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 33 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 34 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 35 | 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 36 | } 37 | 38 | // xtob converts the the first two hex bytes of x into a byte. 39 | func xtob(x string) (byte, bool) { 40 | b1 := xvalues[x[0]] 41 | b2 := xvalues[x[1]] 42 | return (b1 << 4) | b2, b1 != 255 && b2 != 255 43 | } 44 | -------------------------------------------------------------------------------- /mesosproto/authentication.proto: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package mesosproto; 20 | 21 | import "github.com/gogo/protobuf/gogoproto/gogo.proto"; 22 | 23 | option (gogoproto.gostring_all) = true; 24 | option (gogoproto.equal_all) = true; 25 | option (gogoproto.verbose_equal_all) = true; 26 | option (gogoproto.goproto_stringer_all) = false; 27 | option (gogoproto.stringer_all) = true; 28 | option (gogoproto.populate_all) = true; 29 | option (gogoproto.testgen_all) = true; 30 | option (gogoproto.benchgen_all) = true; 31 | option (gogoproto.marshaler_all) = true; 32 | option (gogoproto.sizer_all) = true; 33 | option (gogoproto.unmarshaler_all) = true; 34 | 35 | message AuthenticateMessage { 36 | required string pid = 1; // PID that needs to be authenticated. 37 | } 38 | 39 | 40 | message AuthenticationMechanismsMessage { 41 | repeated string mechanisms = 1; // List of available SASL mechanisms. 42 | } 43 | 44 | 45 | message AuthenticationStartMessage { 46 | required string mechanism = 1; 47 | optional bytes data = 2; 48 | } 49 | 50 | 51 | message AuthenticationStepMessage { 52 | required bytes data = 1; 53 | } 54 | 55 | 56 | message AuthenticationCompletedMessage {} 57 | 58 | 59 | message AuthenticationFailedMessage {} 60 | 61 | 62 | message AuthenticationErrorMessage { 63 | optional string error = 1; 64 | } 65 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/gogo/protobuf/proto/text_gogo.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, Vastech SA (PTY) LTD. All rights reserved. 2 | // http://github.com/gogo/protobuf/gogoproto 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // 15 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 16 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 17 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 18 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 19 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 20 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 21 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 22 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 23 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | 27 | package proto 28 | 29 | import ( 30 | "fmt" 31 | "reflect" 32 | ) 33 | 34 | func writeEnum(w *textWriter, v reflect.Value, props *Properties) error { 35 | m, ok := enumStringMaps[props.Enum] 36 | if !ok { 37 | if err := writeAny(w, v, props); err != nil { 38 | return err 39 | } 40 | } 41 | key := int32(0) 42 | if v.Kind() == reflect.Ptr { 43 | key = int32(v.Elem().Int()) 44 | } else { 45 | key = int32(v.Int()) 46 | } 47 | s, ok := m[key] 48 | if !ok { 49 | if err := writeAny(w, v, props); err != nil { 50 | return err 51 | } 52 | } 53 | _, err := fmt.Fprint(w, s) 54 | return err 55 | } 56 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Go bindings for Apache Mesos 2 | 3 | Very early version of a pure Go language bindings for Apache Mesos. As with other pure implementation, mesos-go uses the HTTP wire protocol to communicate directly with a running Mesos master and its slave instances. One of the objectives of this project is to provide an idiomatic Go API that makes it super easy to create Mesos frameworks using Go. 4 | 5 | [![Build Status](https://travis-ci.org/mesos/mesos-go.svg)](https://travis-ci.org/mesos/mesos-go) [![GoDoc] (https://godoc.org/github.com/mesos/mesos-go?status.png)](https://godoc.org/github.com/mesos/mesos-go) 6 | 7 | ## Status 8 | This project is undergoing a *complete* rewrite happening in the 9 | [next](https://github.com/mesos/mesos-go/tree/next) branch. These bindings will 10 | integrate exclusively with the new public Mesos HTTP API. 11 | 12 | The current version of the bindings are considered **alpha** and won't 13 | see any major development besides critical compatibility and bug fixes. 14 | 15 | We use [semantic versioning](http://semver.org/). 16 | 17 | ### Compatibility 18 | `mesos-N` tags mark the start of support for a specific Mesos version while 19 | maintaining backwards compatibility with the previous major version. 20 | 21 | ### Features 22 | - The SchedulerDriver API implemented 23 | - The ExecutorDriver API implemented 24 | - Stable API (based on the core Mesos code) 25 | - Plenty of unit and integrative of tests 26 | - Modular design for easy readability/extensibility 27 | - Example programs on how to use the API 28 | - Leading master detection 29 | - Authentication via SASL/CRAM-MD5 30 | 31 | ### Pre-Requisites 32 | - Go 1.3 or higher 33 | - A standard and working Go workspace setup 34 | - Apache Mesos 0.19 or newer 35 | 36 | ## Installing 37 | Users of this library are encouraged to vendor it. API stability isn't guaranteed 38 | at this stage. 39 | ```shell 40 | $ go get github.com/mesos/mesos-go 41 | ``` 42 | 43 | ## Testing 44 | ```shell 45 | $ go test -race ./... 46 | ``` 47 | 48 | ## Contributing 49 | Contributions are welcome. Please refer to [CONTRIBUTING.md](CONTRIBUTING.md) for 50 | guidelines. 51 | 52 | ## License 53 | This project is [Apache License 2.0](LICENSE). 54 | -------------------------------------------------------------------------------- /detector/zoo/mock/conn.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package mock 20 | 21 | import ( 22 | "github.com/samuel/go-zookeeper/zk" 23 | "github.com/stretchr/testify/mock" 24 | ) 25 | 26 | // Impersontates a zk.Connection 27 | // It implements interface Connector 28 | type Connector struct { 29 | mock.Mock 30 | } 31 | 32 | func NewConnector() *Connector { 33 | return new(Connector) 34 | } 35 | 36 | func (conn *Connector) Close() { 37 | conn.Called() 38 | } 39 | 40 | func (conn *Connector) ChildrenW(path string) ([]string, *zk.Stat, <-chan zk.Event, error) { 41 | args := conn.Called(path) 42 | var ( 43 | arg0 []string 44 | arg1 *zk.Stat 45 | arg2 <-chan zk.Event 46 | ) 47 | if args.Get(0) != nil { 48 | arg0 = args.Get(0).([]string) 49 | } 50 | if args.Get(1) != nil { 51 | arg1 = args.Get(1).(*zk.Stat) 52 | } 53 | if args.Get(2) != nil { 54 | arg2 = args.Get(2).(<-chan zk.Event) 55 | } 56 | return arg0, arg1, arg2, args.Error(3) 57 | } 58 | 59 | func (conn *Connector) Children(path string) ([]string, *zk.Stat, error) { 60 | args := conn.Called(path) 61 | return args.Get(0).([]string), 62 | args.Get(1).(*zk.Stat), 63 | args.Error(2) 64 | } 65 | 66 | func (conn *Connector) Get(path string) ([]byte, *zk.Stat, error) { 67 | args := conn.Called(path) 68 | return args.Get(0).([]byte), 69 | args.Get(1).(*zk.Stat), 70 | args.Error(2) 71 | } 72 | -------------------------------------------------------------------------------- /detector/zoo/mock/mock.go: -------------------------------------------------------------------------------- 1 | package mock 2 | 3 | import ( 4 | "sync" 5 | 6 | log "github.com/golang/glog" 7 | "github.com/mesos/mesos-go/detector/zoo" 8 | mesos "github.com/mesos/mesos-go/mesosproto" 9 | "github.com/stretchr/testify/mock" 10 | ) 11 | 12 | type Client struct { 13 | mock.Mock 14 | } 15 | 16 | func (m *Client) Stopped() (a <-chan struct{}) { 17 | args := m.Called() 18 | if x := args.Get(0); x != nil { 19 | a = x.(<-chan struct{}) 20 | } 21 | return 22 | } 23 | 24 | func (m *Client) Stop() { 25 | m.Called() 26 | } 27 | 28 | func (m *Client) Data(path string) (a []byte, b error) { 29 | args := m.Called(path) 30 | if x := args.Get(0); x != nil { 31 | a = x.([]byte) 32 | } 33 | b = args.Error(1) 34 | return 35 | } 36 | 37 | func (m *Client) WatchChildren(path string) (a string, b <-chan []string, c <-chan error) { 38 | args := m.Called(path) 39 | a = args.String(0) 40 | if x := args.Get(1); x != nil { 41 | b = x.(<-chan []string) 42 | } 43 | if x := args.Get(2); x != nil { 44 | c = x.(<-chan error) 45 | } 46 | return 47 | } 48 | 49 | // newMockZkClient returns a mocked implementation of ZKInterface that implements expectations 50 | // for Stop() and Stopped(); multiple calls to Stop() are safe. 51 | func NewClient(testZkPath string, initialChildren ...string) (mocked *Client, snaps chan []string, errs chan error) { 52 | var doneOnce sync.Once 53 | done := make(chan struct{}) 54 | 55 | mocked = &Client{} 56 | mocked.On("Stop").Return().Run(func(_ mock.Arguments) { doneOnce.Do(func() { close(done) }) }) 57 | mocked.On("Stopped").Return((<-chan struct{})(done)) 58 | 59 | if initialChildren != nil { 60 | errs = make(chan error) // this is purposefully unbuffered (some tests depend on this) 61 | snaps = make(chan []string, 1) 62 | snaps <- initialChildren[:] 63 | mocked.On("WatchChildren", zoo.CurrentPath).Return( 64 | testZkPath, (<-chan []string)(snaps), (<-chan error)(errs)).Run( 65 | func(_ mock.Arguments) { log.V(1).Infoln("WatchChildren invoked") }) 66 | } 67 | return 68 | } 69 | 70 | // implements MasterChanged and AllMasters extension 71 | type AllMastersListener struct { 72 | mock.Mock 73 | } 74 | 75 | func (a *AllMastersListener) OnMasterChanged(mi *mesos.MasterInfo) { 76 | a.Called(mi) 77 | } 78 | 79 | func (a *AllMastersListener) UpdatedMasters(mi []*mesos.MasterInfo) { 80 | a.Called(mi) 81 | } 82 | -------------------------------------------------------------------------------- /auth/interface.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "sync" 7 | 8 | log "github.com/golang/glog" 9 | "github.com/mesos/mesos-go/auth/callback" 10 | "golang.org/x/net/context" 11 | ) 12 | 13 | // SPI interface: login provider implementations support this interface, clients 14 | // do not authenticate against this directly, instead they should use Login() 15 | type Authenticatee interface { 16 | // Returns no errors if successfully authenticated, otherwise a single 17 | // error. 18 | Authenticate(ctx context.Context, handler callback.Handler) error 19 | } 20 | 21 | // Func adapter for interface: allow func's to implement the Authenticatee interface 22 | // as long as the func signature matches 23 | type AuthenticateeFunc func(ctx context.Context, handler callback.Handler) error 24 | 25 | func (f AuthenticateeFunc) Authenticate(ctx context.Context, handler callback.Handler) error { 26 | return f(ctx, handler) 27 | } 28 | 29 | var ( 30 | // Authentication was attempted and failed (likely due to incorrect credentials, too 31 | // many retries within a time window, etc). Distinctly different from authentication 32 | // errors (e.g. network errors, configuration errors, etc). 33 | AuthenticationFailed = errors.New("authentication failed") 34 | 35 | authenticateeProviders = make(map[string]Authenticatee) // authentication providers dict 36 | providerLock sync.Mutex 37 | ) 38 | 39 | // Register an authentication provider (aka "login provider"). packages that 40 | // provide Authenticatee implementations should invoke this func in their 41 | // init() to register. 42 | func RegisterAuthenticateeProvider(name string, auth Authenticatee) (err error) { 43 | providerLock.Lock() 44 | defer providerLock.Unlock() 45 | 46 | if _, found := authenticateeProviders[name]; found { 47 | err = fmt.Errorf("authentication provider already registered: %v", name) 48 | } else { 49 | authenticateeProviders[name] = auth 50 | log.V(1).Infof("registered authentication provider: %v", name) 51 | } 52 | return 53 | } 54 | 55 | // Look up an authentication provider by name, returns non-nil and true if such 56 | // a provider is found. 57 | func getAuthenticateeProvider(name string) (provider Authenticatee, ok bool) { 58 | providerLock.Lock() 59 | defer providerLock.Unlock() 60 | 61 | provider, ok = authenticateeProviders[name] 62 | return 63 | } 64 | -------------------------------------------------------------------------------- /detector/zoo/detect_internal_test.go: -------------------------------------------------------------------------------- 1 | package zoo 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | const ( 10 | zkurl = "zk://127.0.0.1:2181/mesos" 11 | ) 12 | 13 | func TestParseZk_single(t *testing.T) { 14 | hosts, path, err := parseZk(zkurl) 15 | assert.NoError(t, err) 16 | assert.Equal(t, 1, len(hosts)) 17 | assert.Equal(t, "/mesos", path) 18 | } 19 | 20 | func TestParseZk_multi(t *testing.T) { 21 | hosts, path, err := parseZk("zk://abc:1,def:2/foo") 22 | assert.NoError(t, err) 23 | assert.Equal(t, []string{"abc:1", "def:2"}, hosts) 24 | assert.Equal(t, "/foo", path) 25 | } 26 | 27 | func TestParseZk_multiIP(t *testing.T) { 28 | hosts, path, err := parseZk("zk://10.186.175.156:2181,10.47.50.94:2181,10.0.92.171:2181/mesos") 29 | assert.NoError(t, err) 30 | assert.Equal(t, []string{"10.186.175.156:2181", "10.47.50.94:2181", "10.0.92.171:2181"}, hosts) 31 | assert.Equal(t, "/mesos", path) 32 | } 33 | 34 | func TestMasterDetect_selectTopNode_none(t *testing.T) { 35 | assert := assert.New(t) 36 | nodeList := []string{} 37 | node := selectTopNodePrefix(nodeList, "foo") 38 | assert.Equal("", node) 39 | } 40 | 41 | func TestMasterDetect_selectTopNode_0000x(t *testing.T) { 42 | assert := assert.New(t) 43 | nodeList := []string{ 44 | "info_0000000046", 45 | "info_0000000032", 46 | "info_0000000058", 47 | "info_0000000061", 48 | "info_0000000008", 49 | } 50 | node := selectTopNodePrefix(nodeList, nodePrefix) 51 | assert.Equal("info_0000000008", node) 52 | } 53 | 54 | func TestMasterDetect_selectTopNode_mixJson(t *testing.T) { 55 | assert := assert.New(t) 56 | nodeList := []string{ 57 | nodePrefix + "0000000046", 58 | nodePrefix + "0000000032", 59 | nodeJSONPrefix + "0000000046", 60 | nodeJSONPrefix + "0000000032", 61 | } 62 | node := selectTopNodePrefix(nodeList, nodeJSONPrefix) 63 | assert.Equal(nodeJSONPrefix+"0000000032", node) 64 | 65 | node = selectTopNodePrefix(nodeList, nodePrefix) 66 | assert.Equal(nodePrefix+"0000000032", node) 67 | } 68 | 69 | func TestMasterDetect_selectTopNode_mixedEntries(t *testing.T) { 70 | assert := assert.New(t) 71 | nodeList := []string{ 72 | "info_0000000046", 73 | "info_0000000032", 74 | "foo_lskdjfglsdkfsdfgdfg", 75 | "info_0000000061", 76 | "log_replicas_fdgwsdfgsdf", 77 | "bar", 78 | } 79 | node := selectTopNodePrefix(nodeList, nodePrefix) 80 | assert.Equal("info_0000000032", node) 81 | } 82 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/pborman/uuid/dce.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import ( 8 | "encoding/binary" 9 | "fmt" 10 | "os" 11 | ) 12 | 13 | // A Domain represents a Version 2 domain 14 | type Domain byte 15 | 16 | // Domain constants for DCE Security (Version 2) UUIDs. 17 | const ( 18 | Person = Domain(0) 19 | Group = Domain(1) 20 | Org = Domain(2) 21 | ) 22 | 23 | // NewDCESecurity returns a DCE Security (Version 2) UUID. 24 | // 25 | // The domain should be one of Person, Group or Org. 26 | // On a POSIX system the id should be the users UID for the Person 27 | // domain and the users GID for the Group. The meaning of id for 28 | // the domain Org or on non-POSIX systems is site defined. 29 | // 30 | // For a given domain/id pair the same token may be returned for up to 31 | // 7 minutes and 10 seconds. 32 | func NewDCESecurity(domain Domain, id uint32) UUID { 33 | uuid := NewUUID() 34 | if uuid != nil { 35 | uuid[6] = (uuid[6] & 0x0f) | 0x20 // Version 2 36 | uuid[9] = byte(domain) 37 | binary.BigEndian.PutUint32(uuid[0:], id) 38 | } 39 | return uuid 40 | } 41 | 42 | // NewDCEPerson returns a DCE Security (Version 2) UUID in the person 43 | // domain with the id returned by os.Getuid. 44 | // 45 | // NewDCEPerson(Person, uint32(os.Getuid())) 46 | func NewDCEPerson() UUID { 47 | return NewDCESecurity(Person, uint32(os.Getuid())) 48 | } 49 | 50 | // NewDCEGroup returns a DCE Security (Version 2) UUID in the group 51 | // domain with the id returned by os.Getgid. 52 | // 53 | // NewDCEGroup(Group, uint32(os.Getgid())) 54 | func NewDCEGroup() UUID { 55 | return NewDCESecurity(Group, uint32(os.Getgid())) 56 | } 57 | 58 | // Domain returns the domain for a Version 2 UUID or false. 59 | func (uuid UUID) Domain() (Domain, bool) { 60 | if v, _ := uuid.Version(); v != 2 { 61 | return 0, false 62 | } 63 | return Domain(uuid[9]), true 64 | } 65 | 66 | // Id returns the id for a Version 2 UUID or false. 67 | func (uuid UUID) Id() (uint32, bool) { 68 | if v, _ := uuid.Version(); v != 2 { 69 | return 0, false 70 | } 71 | return binary.BigEndian.Uint32(uuid[0:4]), true 72 | } 73 | 74 | func (d Domain) String() string { 75 | switch d { 76 | case Person: 77 | return "Person" 78 | case Group: 79 | return "Group" 80 | case Org: 81 | return "Org" 82 | } 83 | return fmt.Sprintf("Domain%d", int(d)) 84 | } 85 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/mutations.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | // Exclude returns a new Map with the keys in the specified []string 4 | // excluded. 5 | func (d Map) Exclude(exclude []string) Map { 6 | 7 | excluded := make(Map) 8 | for k, v := range d { 9 | var shouldInclude bool = true 10 | for _, toExclude := range exclude { 11 | if k == toExclude { 12 | shouldInclude = false 13 | break 14 | } 15 | } 16 | if shouldInclude { 17 | excluded[k] = v 18 | } 19 | } 20 | 21 | return excluded 22 | } 23 | 24 | // Copy creates a shallow copy of the Obj. 25 | func (m Map) Copy() Map { 26 | copied := make(map[string]interface{}) 27 | for k, v := range m { 28 | copied[k] = v 29 | } 30 | return New(copied) 31 | } 32 | 33 | // Merge blends the specified map with a copy of this map and returns the result. 34 | // 35 | // Keys that appear in both will be selected from the specified map. 36 | // This method requires that the wrapped object be a map[string]interface{} 37 | func (m Map) Merge(merge Map) Map { 38 | return m.Copy().MergeHere(merge) 39 | } 40 | 41 | // Merge blends the specified map with this map and returns the current map. 42 | // 43 | // Keys that appear in both will be selected from the specified map. The original map 44 | // will be modified. This method requires that 45 | // the wrapped object be a map[string]interface{} 46 | func (m Map) MergeHere(merge Map) Map { 47 | 48 | for k, v := range merge { 49 | m[k] = v 50 | } 51 | 52 | return m 53 | 54 | } 55 | 56 | // Transform builds a new Obj giving the transformer a chance 57 | // to change the keys and values as it goes. This method requires that 58 | // the wrapped object be a map[string]interface{} 59 | func (m Map) Transform(transformer func(key string, value interface{}) (string, interface{})) Map { 60 | newMap := make(map[string]interface{}) 61 | for k, v := range m { 62 | modifiedKey, modifiedVal := transformer(k, v) 63 | newMap[modifiedKey] = modifiedVal 64 | } 65 | return New(newMap) 66 | } 67 | 68 | // TransformKeys builds a new map using the specified key mapping. 69 | // 70 | // Unspecified keys will be unaltered. 71 | // This method requires that the wrapped object be a map[string]interface{} 72 | func (m Map) TransformKeys(mapping map[string]string) Map { 73 | return m.Transform(func(key string, value interface{}) (string, interface{}) { 74 | 75 | if newKey, ok := mapping[key]; ok { 76 | return newKey, value 77 | } 78 | 79 | return key, value 80 | }) 81 | } 82 | -------------------------------------------------------------------------------- /executor/mock/mock.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package mock 20 | 21 | import ( 22 | "github.com/mesos/mesos-go/executor" 23 | "github.com/mesos/mesos-go/mesosproto" 24 | "github.com/stretchr/testify/mock" 25 | ) 26 | 27 | // Executor is used for testing the executor driver. 28 | type Executor struct { 29 | mock.Mock 30 | } 31 | 32 | // New returns a mocked executor. 33 | func New() *Executor { 34 | return &Executor{} 35 | } 36 | 37 | // Registered implements the Registered handler. 38 | func (e *Executor) Registered(executor.ExecutorDriver, *mesosproto.ExecutorInfo, *mesosproto.FrameworkInfo, *mesosproto.SlaveInfo) { 39 | e.Called() 40 | } 41 | 42 | // Reregistered implements the Reregistered handler. 43 | func (e *Executor) Reregistered(executor.ExecutorDriver, *mesosproto.SlaveInfo) { 44 | e.Called() 45 | } 46 | 47 | // Disconnected implements the Disconnected handler. 48 | func (e *Executor) Disconnected(executor.ExecutorDriver) { 49 | e.Called() 50 | } 51 | 52 | // LaunchTask implements the LaunchTask handler. 53 | func (e *Executor) LaunchTask(executor.ExecutorDriver, *mesosproto.TaskInfo) { 54 | e.Called() 55 | } 56 | 57 | // KillTask implements the KillTask handler. 58 | func (e *Executor) KillTask(executor.ExecutorDriver, *mesosproto.TaskID) { 59 | e.Called() 60 | } 61 | 62 | // FrameworkMessage implements the FrameworkMessage handler. 63 | func (e *Executor) FrameworkMessage(executor.ExecutorDriver, string) { 64 | e.Called() 65 | } 66 | 67 | // Shutdown implements the Shutdown handler. 68 | func (e *Executor) Shutdown(executor.ExecutorDriver) { 69 | e.Called() 70 | } 71 | 72 | // Error implements the Error handler. 73 | func (e *Executor) Error(executor.ExecutorDriver, string) { 74 | e.Called() 75 | } 76 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/gogo/protobuf/proto/size2_test.go: -------------------------------------------------------------------------------- 1 | // Go support for Protocol Buffers - Google's data interchange format 2 | // 3 | // Copyright 2012 The Go Authors. All rights reserved. 4 | // https://github.com/golang/protobuf 5 | // 6 | // Redistribution and use in source and binary forms, with or without 7 | // modification, are permitted provided that the following conditions are 8 | // met: 9 | // 10 | // * Redistributions of source code must retain the above copyright 11 | // notice, this list of conditions and the following disclaimer. 12 | // * Redistributions in binary form must reproduce the above 13 | // copyright notice, this list of conditions and the following disclaimer 14 | // in the documentation and/or other materials provided with the 15 | // distribution. 16 | // * Neither the name of Google Inc. nor the names of its 17 | // contributors may be used to endorse or promote products derived from 18 | // this software without specific prior written permission. 19 | // 20 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | 32 | package proto 33 | 34 | import ( 35 | "testing" 36 | ) 37 | 38 | // This is a separate file and package from size_test.go because that one uses 39 | // generated messages and thus may not be in package proto without having a circular 40 | // dependency, whereas this file tests unexported details of size.go. 41 | 42 | func TestVarintSize(t *testing.T) { 43 | // Check the edge cases carefully. 44 | testCases := []struct { 45 | n uint64 46 | size int 47 | }{ 48 | {0, 1}, 49 | {1, 1}, 50 | {127, 1}, 51 | {128, 2}, 52 | {16383, 2}, 53 | {16384, 3}, 54 | {1<<63 - 1, 9}, 55 | {1 << 63, 10}, 56 | } 57 | for _, tc := range testCases { 58 | size := sizeVarint(tc.n) 59 | if size != tc.size { 60 | t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size) 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp.go: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | // Package ctxhttp provides helper functions for performing context-aware HTTP requests. 6 | package ctxhttp 7 | 8 | import ( 9 | "io" 10 | "net/http" 11 | "net/url" 12 | "strings" 13 | 14 | "golang.org/x/net/context" 15 | ) 16 | 17 | // Do sends an HTTP request with the provided http.Client and returns an HTTP response. 18 | // If the client is nil, http.DefaultClient is used. 19 | // If the context is canceled or times out, ctx.Err() will be returned. 20 | func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { 21 | if client == nil { 22 | client = http.DefaultClient 23 | } 24 | 25 | // Request cancelation changed in Go 1.5, see cancelreq.go and cancelreq_go14.go. 26 | cancel := canceler(client, req) 27 | 28 | type responseAndError struct { 29 | resp *http.Response 30 | err error 31 | } 32 | result := make(chan responseAndError, 1) 33 | 34 | go func() { 35 | resp, err := client.Do(req) 36 | result <- responseAndError{resp, err} 37 | }() 38 | 39 | select { 40 | case <-ctx.Done(): 41 | cancel() 42 | return nil, ctx.Err() 43 | case r := <-result: 44 | return r.resp, r.err 45 | } 46 | } 47 | 48 | // Get issues a GET request via the Do function. 49 | func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) { 50 | req, err := http.NewRequest("GET", url, nil) 51 | if err != nil { 52 | return nil, err 53 | } 54 | return Do(ctx, client, req) 55 | } 56 | 57 | // Head issues a HEAD request via the Do function. 58 | func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) { 59 | req, err := http.NewRequest("HEAD", url, nil) 60 | if err != nil { 61 | return nil, err 62 | } 63 | return Do(ctx, client, req) 64 | } 65 | 66 | // Post issues a POST request via the Do function. 67 | func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { 68 | req, err := http.NewRequest("POST", url, body) 69 | if err != nil { 70 | return nil, err 71 | } 72 | req.Header.Set("Content-Type", bodyType) 73 | return Do(ctx, client, req) 74 | } 75 | 76 | // PostForm issues a POST request via the Do function. 77 | func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { 78 | return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) 79 | } 80 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/gogo/protobuf/proto/proto3_proto/proto3.proto: -------------------------------------------------------------------------------- 1 | // Go support for Protocol Buffers - Google's data interchange format 2 | // 3 | // Copyright 2014 The Go Authors. All rights reserved. 4 | // https://github.com/golang/protobuf 5 | // 6 | // Redistribution and use in source and binary forms, with or without 7 | // modification, are permitted provided that the following conditions are 8 | // met: 9 | // 10 | // * Redistributions of source code must retain the above copyright 11 | // notice, this list of conditions and the following disclaimer. 12 | // * Redistributions in binary form must reproduce the above 13 | // copyright notice, this list of conditions and the following disclaimer 14 | // in the documentation and/or other materials provided with the 15 | // distribution. 16 | // * Neither the name of Google Inc. nor the names of its 17 | // contributors may be used to endorse or promote products derived from 18 | // this software without specific prior written permission. 19 | // 20 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | 32 | syntax = "proto3"; 33 | 34 | package proto3_proto; 35 | 36 | import "github.com/gogo/protobuf/proto/testdata/test.proto"; 37 | 38 | message Message { 39 | enum Humour { 40 | UNKNOWN = 0; 41 | PUNS = 1; 42 | SLAPSTICK = 2; 43 | BILL_BAILEY = 3; 44 | } 45 | 46 | string name = 1; 47 | Humour hilarity = 2; 48 | uint32 height_in_cm = 3; 49 | bytes data = 4; 50 | int64 result_count = 7; 51 | bool true_scotsman = 8; 52 | float score = 9; 53 | 54 | repeated uint64 key = 5; 55 | Nested nested = 6; 56 | 57 | map terrain = 10; 58 | testdata.SubDefaults proto2_field = 11; 59 | map proto2_value = 13; 60 | } 61 | 62 | message Nested { 63 | string bunny = 1; 64 | } 65 | 66 | message MessageWithMap { 67 | map byte_mapping = 1; 68 | } 69 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/doc.go: -------------------------------------------------------------------------------- 1 | // objx - Go package for dealing with maps, slices, JSON and other data. 2 | // 3 | // Overview 4 | // 5 | // Objx provides the `objx.Map` type, which is a `map[string]interface{}` that exposes 6 | // a powerful `Get` method (among others) that allows you to easily and quickly get 7 | // access to data within the map, without having to worry too much about type assertions, 8 | // missing data, default values etc. 9 | // 10 | // Pattern 11 | // 12 | // Objx uses a preditable pattern to make access data from within `map[string]interface{}'s 13 | // easy. 14 | // 15 | // Call one of the `objx.` functions to create your `objx.Map` to get going: 16 | // 17 | // m, err := objx.FromJSON(json) 18 | // 19 | // NOTE: Any methods or functions with the `Must` prefix will panic if something goes wrong, 20 | // the rest will be optimistic and try to figure things out without panicking. 21 | // 22 | // Use `Get` to access the value you're interested in. You can use dot and array 23 | // notation too: 24 | // 25 | // m.Get("places[0].latlng") 26 | // 27 | // Once you have saught the `Value` you're interested in, you can use the `Is*` methods 28 | // to determine its type. 29 | // 30 | // if m.Get("code").IsStr() { /* ... */ } 31 | // 32 | // Or you can just assume the type, and use one of the strong type methods to 33 | // extract the real value: 34 | // 35 | // m.Get("code").Int() 36 | // 37 | // If there's no value there (or if it's the wrong type) then a default value 38 | // will be returned, or you can be explicit about the default value. 39 | // 40 | // Get("code").Int(-1) 41 | // 42 | // If you're dealing with a slice of data as a value, Objx provides many useful 43 | // methods for iterating, manipulating and selecting that data. You can find out more 44 | // by exploring the index below. 45 | // 46 | // Reading data 47 | // 48 | // A simple example of how to use Objx: 49 | // 50 | // // use MustFromJSON to make an objx.Map from some JSON 51 | // m := objx.MustFromJSON(`{"name": "Mat", "age": 30}`) 52 | // 53 | // // get the details 54 | // name := m.Get("name").Str() 55 | // age := m.Get("age").Int() 56 | // 57 | // // get their nickname (or use their name if they 58 | // // don't have one) 59 | // nickname := m.Get("nickname").Str(name) 60 | // 61 | // Ranging 62 | // 63 | // Since `objx.Map` is a `map[string]interface{}` you can treat it as such. For 64 | // example, to `range` the data, do what you would expect: 65 | // 66 | // m := objx.MustFromJSON(json) 67 | // for key, value := range m { 68 | // 69 | // /* ... do your magic ... */ 70 | // 71 | // } 72 | package objx 73 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/gogo/protobuf/proto/properties_gogo.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, Vastech SA (PTY) LTD. All rights reserved. 2 | // http://github.com/gogo/protobuf/gogoproto 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // 15 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 16 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 17 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 18 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 19 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 20 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 21 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 22 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 23 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | 27 | package proto 28 | 29 | import ( 30 | "fmt" 31 | "os" 32 | "reflect" 33 | ) 34 | 35 | func (p *Properties) setCustomEncAndDec(typ reflect.Type) { 36 | p.ctype = typ 37 | if p.Repeated { 38 | p.enc = (*Buffer).enc_custom_slice_bytes 39 | p.dec = (*Buffer).dec_custom_slice_bytes 40 | p.size = size_custom_slice_bytes 41 | } else if typ.Kind() == reflect.Ptr { 42 | p.enc = (*Buffer).enc_custom_bytes 43 | p.dec = (*Buffer).dec_custom_bytes 44 | p.size = size_custom_bytes 45 | } else { 46 | p.enc = (*Buffer).enc_custom_ref_bytes 47 | p.dec = (*Buffer).dec_custom_ref_bytes 48 | p.size = size_custom_ref_bytes 49 | } 50 | } 51 | 52 | func (p *Properties) setSliceOfNonPointerStructs(typ reflect.Type) { 53 | t2 := typ.Elem() 54 | p.sstype = typ 55 | p.stype = t2 56 | p.isMarshaler = isMarshaler(t2) 57 | p.isUnmarshaler = isUnmarshaler(t2) 58 | p.enc = (*Buffer).enc_slice_ref_struct_message 59 | p.dec = (*Buffer).dec_slice_ref_struct_message 60 | p.size = size_slice_ref_struct_message 61 | if p.Wire != "bytes" { 62 | fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T \n", typ, t2) 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/fixture_test.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | var fixtures = []struct { 9 | // name is the name of the fixture (used for reporting 10 | // failures) 11 | name string 12 | // data is the JSON data to be worked on 13 | data string 14 | // get is the argument(s) to pass to Get 15 | get interface{} 16 | // output is the expected output 17 | output interface{} 18 | }{ 19 | { 20 | name: "Simple get", 21 | data: `{"name": "Mat"}`, 22 | get: "name", 23 | output: "Mat", 24 | }, 25 | { 26 | name: "Get with dot notation", 27 | data: `{"address": {"city": "Boulder"}}`, 28 | get: "address.city", 29 | output: "Boulder", 30 | }, 31 | { 32 | name: "Deep get with dot notation", 33 | data: `{"one": {"two": {"three": {"four": "hello"}}}}`, 34 | get: "one.two.three.four", 35 | output: "hello", 36 | }, 37 | { 38 | name: "Get missing with dot notation", 39 | data: `{"one": {"two": {"three": {"four": "hello"}}}}`, 40 | get: "one.ten", 41 | output: nil, 42 | }, 43 | { 44 | name: "Get with array notation", 45 | data: `{"tags": ["one", "two", "three"]}`, 46 | get: "tags[1]", 47 | output: "two", 48 | }, 49 | { 50 | name: "Get with array and dot notation", 51 | data: `{"types": { "tags": ["one", "two", "three"]}}`, 52 | get: "types.tags[1]", 53 | output: "two", 54 | }, 55 | { 56 | name: "Get with array and dot notation - field after array", 57 | data: `{"tags": [{"name":"one"}, {"name":"two"}, {"name":"three"}]}`, 58 | get: "tags[1].name", 59 | output: "two", 60 | }, 61 | { 62 | name: "Complex get with array and dot notation", 63 | data: `{"tags": [{"list": [{"one":"pizza"}]}]}`, 64 | get: "tags[0].list[0].one", 65 | output: "pizza", 66 | }, 67 | { 68 | name: "Get field from within string should be nil", 69 | data: `{"name":"Tyler"}`, 70 | get: "name.something", 71 | output: nil, 72 | }, 73 | { 74 | name: "Get field from within string (using array accessor) should be nil", 75 | data: `{"numbers":["one", "two", "three"]}`, 76 | get: "numbers[0].nope", 77 | output: nil, 78 | }, 79 | } 80 | 81 | func TestFixtures(t *testing.T) { 82 | 83 | for _, fixture := range fixtures { 84 | 85 | m := MustFromJSON(fixture.data) 86 | 87 | // get the value 88 | t.Logf("Running get fixture: \"%s\" (%v)", fixture.name, fixture) 89 | value := m.Get(fixture.get.(string)) 90 | 91 | // make sure it matches 92 | assert.Equal(t, fixture.output, value.data, 93 | "Get fixture \"%s\" failed: %v", fixture.name, fixture, 94 | ) 95 | 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/gogo/protobuf/proto/message_set_test.go: -------------------------------------------------------------------------------- 1 | // Go support for Protocol Buffers - Google's data interchange format 2 | // 3 | // Copyright 2014 The Go Authors. All rights reserved. 4 | // https://github.com/golang/protobuf 5 | // 6 | // Redistribution and use in source and binary forms, with or without 7 | // modification, are permitted provided that the following conditions are 8 | // met: 9 | // 10 | // * Redistributions of source code must retain the above copyright 11 | // notice, this list of conditions and the following disclaimer. 12 | // * Redistributions in binary form must reproduce the above 13 | // copyright notice, this list of conditions and the following disclaimer 14 | // in the documentation and/or other materials provided with the 15 | // distribution. 16 | // * Neither the name of Google Inc. nor the names of its 17 | // contributors may be used to endorse or promote products derived from 18 | // this software without specific prior written permission. 19 | // 20 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | 32 | package proto 33 | 34 | import ( 35 | "bytes" 36 | "testing" 37 | ) 38 | 39 | func TestUnmarshalMessageSetWithDuplicate(t *testing.T) { 40 | // Check that a repeated message set entry will be concatenated. 41 | in := &MessageSet{ 42 | Item: []*_MessageSet_Item{ 43 | {TypeId: Int32(12345), Message: []byte("hoo")}, 44 | {TypeId: Int32(12345), Message: []byte("hah")}, 45 | }, 46 | } 47 | b, err := Marshal(in) 48 | if err != nil { 49 | t.Fatalf("Marshal: %v", err) 50 | } 51 | t.Logf("Marshaled bytes: %q", b) 52 | 53 | m := make(map[int32]Extension) 54 | if err := UnmarshalMessageSet(b, m); err != nil { 55 | t.Fatalf("UnmarshalMessageSet: %v", err) 56 | } 57 | ext, ok := m[12345] 58 | if !ok { 59 | t.Fatalf("Didn't retrieve extension 12345; map is %v", m) 60 | } 61 | // Skip wire type/field number and length varints. 62 | got := skipVarint(skipVarint(ext.enc)) 63 | if want := []byte("hoohah"); !bytes.Equal(got, want) { 64 | t.Errorf("Combined extension is %q, want %q", got, want) 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /detector/interface.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package detector 20 | 21 | import ( 22 | mesos "github.com/mesos/mesos-go/mesosproto" 23 | ) 24 | 25 | type MasterChanged interface { 26 | // Invoked when the master changes 27 | OnMasterChanged(*mesos.MasterInfo) 28 | } 29 | 30 | // AllMasters defines an optional interface that, if implemented by the same 31 | // struct as implements MasterChanged, will receive an additional callbacks 32 | // independently of leadership changes. it's possible that, as a result of a 33 | // leadership change, both the OnMasterChanged and UpdatedMasters callbacks 34 | // would be invoked. 35 | // 36 | // **NOTE:** Detector implementations are not required to support this optional 37 | // interface. Please RTFM of the detector implementation that you want to use. 38 | type AllMasters interface { 39 | // UpdatedMasters is invoked upon a change in the membership of mesos 40 | // masters, and is useful to clients that wish to know the entire set 41 | // of Mesos masters currently running. 42 | UpdatedMasters([]*mesos.MasterInfo) 43 | } 44 | 45 | // func/interface adapter 46 | type OnMasterChanged func(*mesos.MasterInfo) 47 | 48 | func (f OnMasterChanged) OnMasterChanged(mi *mesos.MasterInfo) { 49 | f(mi) 50 | } 51 | 52 | // An abstraction of a Master detector which can be used to 53 | // detect the leading master from a group. 54 | type Master interface { 55 | // Detect new master election. Every time a new master is elected, the 56 | // detector will alert the observer. The first call to Detect is expected 57 | // to kickstart any background detection processing (and not before then). 58 | // If detection startup fails, or the listener cannot be added, then an 59 | // error is returned. 60 | Detect(MasterChanged) error 61 | 62 | // returns a chan that, when closed, indicates the detector has terminated 63 | Done() <-chan struct{} 64 | 65 | // cancel the detector. it's ok to call this multiple times, or even if 66 | // Detect() hasn't been invoked yet. 67 | Cancel() 68 | } 69 | 70 | // functional option type for detectors 71 | type Option func(interface{}) Option 72 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/pborman/uuid/node.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import "net" 8 | 9 | var ( 10 | interfaces []net.Interface // cached list of interfaces 11 | ifname string // name of interface being used 12 | nodeID []byte // hardware for version 1 UUIDs 13 | ) 14 | 15 | // NodeInterface returns the name of the interface from which the NodeID was 16 | // derived. The interface "user" is returned if the NodeID was set by 17 | // SetNodeID. 18 | func NodeInterface() string { 19 | return ifname 20 | } 21 | 22 | // SetNodeInterface selects the hardware address to be used for Version 1 UUIDs. 23 | // If name is "" then the first usable interface found will be used or a random 24 | // Node ID will be generated. If a named interface cannot be found then false 25 | // is returned. 26 | // 27 | // SetNodeInterface never fails when name is "". 28 | func SetNodeInterface(name string) bool { 29 | if interfaces == nil { 30 | var err error 31 | interfaces, err = net.Interfaces() 32 | if err != nil && name != "" { 33 | return false 34 | } 35 | } 36 | 37 | for _, ifs := range interfaces { 38 | if len(ifs.HardwareAddr) >= 6 && (name == "" || name == ifs.Name) { 39 | if setNodeID(ifs.HardwareAddr) { 40 | ifname = ifs.Name 41 | return true 42 | } 43 | } 44 | } 45 | 46 | // We found no interfaces with a valid hardware address. If name 47 | // does not specify a specific interface generate a random Node ID 48 | // (section 4.1.6) 49 | if name == "" { 50 | if nodeID == nil { 51 | nodeID = make([]byte, 6) 52 | } 53 | randomBits(nodeID) 54 | return true 55 | } 56 | return false 57 | } 58 | 59 | // NodeID returns a slice of a copy of the current Node ID, setting the Node ID 60 | // if not already set. 61 | func NodeID() []byte { 62 | if nodeID == nil { 63 | SetNodeInterface("") 64 | } 65 | nid := make([]byte, 6) 66 | copy(nid, nodeID) 67 | return nid 68 | } 69 | 70 | // SetNodeID sets the Node ID to be used for Version 1 UUIDs. The first 6 bytes 71 | // of id are used. If id is less than 6 bytes then false is returned and the 72 | // Node ID is not set. 73 | func SetNodeID(id []byte) bool { 74 | if setNodeID(id) { 75 | ifname = "user" 76 | return true 77 | } 78 | return false 79 | } 80 | 81 | func setNodeID(id []byte) bool { 82 | if len(id) < 6 { 83 | return false 84 | } 85 | if nodeID == nil { 86 | nodeID = make([]byte, 6) 87 | } 88 | copy(nodeID, id) 89 | return true 90 | } 91 | 92 | // NodeID returns the 6 byte node id encoded in uuid. It returns nil if uuid is 93 | // not valid. The NodeID is only well defined for version 1 and 2 UUIDs. 94 | func (uuid UUID) NodeID() []byte { 95 | if len(uuid) != 16 { 96 | return nil 97 | } 98 | node := make([]byte, 6) 99 | copy(node, uuid[10:]) 100 | return node 101 | } 102 | -------------------------------------------------------------------------------- /scheduler/schedcache.go: -------------------------------------------------------------------------------- 1 | package scheduler 2 | 3 | import ( 4 | log "github.com/golang/glog" 5 | mesos "github.com/mesos/mesos-go/mesosproto" 6 | "github.com/mesos/mesos-go/upid" 7 | "sync" 8 | ) 9 | 10 | type cachedOffer struct { 11 | offer *mesos.Offer 12 | slavePid *upid.UPID 13 | } 14 | 15 | func newCachedOffer(offer *mesos.Offer, slavePid *upid.UPID) *cachedOffer { 16 | return &cachedOffer{offer: offer, slavePid: slavePid} 17 | } 18 | 19 | // schedCache a managed cache with backing maps to store offeres 20 | // and tasked slaves. 21 | type schedCache struct { 22 | lock sync.RWMutex 23 | savedOffers map[string]*cachedOffer // current offers key:OfferID 24 | savedSlavePids map[string]*upid.UPID // Current saved slaves, key:slaveId 25 | } 26 | 27 | func newSchedCache() *schedCache { 28 | return &schedCache{ 29 | savedOffers: make(map[string]*cachedOffer), 30 | savedSlavePids: make(map[string]*upid.UPID), 31 | } 32 | } 33 | 34 | // putOffer stores an offer and the slavePID associated with offer. 35 | func (cache *schedCache) putOffer(offer *mesos.Offer, pid *upid.UPID) { 36 | if offer == nil || pid == nil { 37 | log.V(3).Infoln("WARN: Offer not cached. The offer or pid cannot be nil") 38 | return 39 | } 40 | log.V(3).Infoln("Caching offer ", offer.Id.GetValue(), " with slavePID ", pid.String()) 41 | cache.lock.Lock() 42 | cache.savedOffers[offer.Id.GetValue()] = &cachedOffer{offer: offer, slavePid: pid} 43 | cache.lock.Unlock() 44 | } 45 | 46 | // getOffer returns cached offer 47 | func (cache *schedCache) getOffer(offerId *mesos.OfferID) *cachedOffer { 48 | if offerId == nil { 49 | log.V(3).Infoln("WARN: OfferId == nil, returning nil") 50 | return nil 51 | } 52 | cache.lock.RLock() 53 | defer cache.lock.RUnlock() 54 | return cache.savedOffers[offerId.GetValue()] 55 | } 56 | 57 | // containsOff test cache for offer(offerId) 58 | func (cache *schedCache) containsOffer(offerId *mesos.OfferID) bool { 59 | cache.lock.RLock() 60 | defer cache.lock.RUnlock() 61 | _, ok := cache.savedOffers[offerId.GetValue()] 62 | return ok 63 | } 64 | 65 | func (cache *schedCache) removeOffer(offerId *mesos.OfferID) { 66 | cache.lock.Lock() 67 | delete(cache.savedOffers, offerId.GetValue()) 68 | cache.lock.Unlock() 69 | } 70 | 71 | func (cache *schedCache) putSlavePid(slaveId *mesos.SlaveID, pid *upid.UPID) { 72 | cache.lock.Lock() 73 | cache.savedSlavePids[slaveId.GetValue()] = pid 74 | cache.lock.Unlock() 75 | } 76 | 77 | func (cache *schedCache) getSlavePid(slaveId *mesos.SlaveID) *upid.UPID { 78 | if slaveId == nil { 79 | log.V(3).Infoln("SlaveId == nil, returning empty UPID") 80 | return nil 81 | } 82 | return cache.savedSlavePids[slaveId.GetValue()] 83 | } 84 | 85 | func (cache *schedCache) containsSlavePid(slaveId *mesos.SlaveID) bool { 86 | cache.lock.RLock() 87 | defer cache.lock.RUnlock() 88 | _, ok := cache.savedSlavePids[slaveId.GetValue()] 89 | return ok 90 | } 91 | 92 | func (cache *schedCache) removeSlavePid(slaveId *mesos.SlaveID) { 93 | cache.lock.Lock() 94 | delete(cache.savedSlavePids, slaveId.GetValue()) 95 | cache.lock.Unlock() 96 | } 97 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/conversions.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | import ( 4 | "bytes" 5 | "encoding/base64" 6 | "encoding/json" 7 | "errors" 8 | "fmt" 9 | "net/url" 10 | ) 11 | 12 | // JSON converts the contained object to a JSON string 13 | // representation 14 | func (m Map) JSON() (string, error) { 15 | 16 | result, err := json.Marshal(m) 17 | 18 | if err != nil { 19 | err = errors.New("objx: JSON encode failed with: " + err.Error()) 20 | } 21 | 22 | return string(result), err 23 | 24 | } 25 | 26 | // MustJSON converts the contained object to a JSON string 27 | // representation and panics if there is an error 28 | func (m Map) MustJSON() string { 29 | result, err := m.JSON() 30 | if err != nil { 31 | panic(err.Error()) 32 | } 33 | return result 34 | } 35 | 36 | // Base64 converts the contained object to a Base64 string 37 | // representation of the JSON string representation 38 | func (m Map) Base64() (string, error) { 39 | 40 | var buf bytes.Buffer 41 | 42 | jsonData, err := m.JSON() 43 | if err != nil { 44 | return "", err 45 | } 46 | 47 | encoder := base64.NewEncoder(base64.StdEncoding, &buf) 48 | encoder.Write([]byte(jsonData)) 49 | encoder.Close() 50 | 51 | return buf.String(), nil 52 | 53 | } 54 | 55 | // MustBase64 converts the contained object to a Base64 string 56 | // representation of the JSON string representation and panics 57 | // if there is an error 58 | func (m Map) MustBase64() string { 59 | result, err := m.Base64() 60 | if err != nil { 61 | panic(err.Error()) 62 | } 63 | return result 64 | } 65 | 66 | // SignedBase64 converts the contained object to a Base64 string 67 | // representation of the JSON string representation and signs it 68 | // using the provided key. 69 | func (m Map) SignedBase64(key string) (string, error) { 70 | 71 | base64, err := m.Base64() 72 | if err != nil { 73 | return "", err 74 | } 75 | 76 | sig := HashWithKey(base64, key) 77 | 78 | return base64 + SignatureSeparator + sig, nil 79 | 80 | } 81 | 82 | // MustSignedBase64 converts the contained object to a Base64 string 83 | // representation of the JSON string representation and signs it 84 | // using the provided key and panics if there is an error 85 | func (m Map) MustSignedBase64(key string) string { 86 | result, err := m.SignedBase64(key) 87 | if err != nil { 88 | panic(err.Error()) 89 | } 90 | return result 91 | } 92 | 93 | /* 94 | URL Query 95 | ------------------------------------------------ 96 | */ 97 | 98 | // URLValues creates a url.Values object from an Obj. This 99 | // function requires that the wrapped object be a map[string]interface{} 100 | func (m Map) URLValues() url.Values { 101 | 102 | vals := make(url.Values) 103 | 104 | for k, v := range m { 105 | //TODO: can this be done without sprintf? 106 | vals.Set(k, fmt.Sprintf("%v", v)) 107 | } 108 | 109 | return vals 110 | } 111 | 112 | // URLQuery gets an encoded URL query representing the given 113 | // Obj. This function requires that the wrapped object be a 114 | // map[string]interface{} 115 | func (m Map) URLQuery() (string, error) { 116 | return m.URLValues().Encode(), nil 117 | } 118 | -------------------------------------------------------------------------------- /auth/sasl/authenticatee_test.go: -------------------------------------------------------------------------------- 1 | package sasl 2 | 3 | import ( 4 | "testing" 5 | "time" 6 | 7 | "github.com/gogo/protobuf/proto" 8 | "github.com/mesos/mesos-go/auth/callback" 9 | "github.com/mesos/mesos-go/auth/sasl/mech/crammd5" 10 | mock_sasl "github.com/mesos/mesos-go/auth/sasl/mock" 11 | mesos "github.com/mesos/mesos-go/mesosproto" 12 | "github.com/mesos/mesos-go/messenger" 13 | mock_messenger "github.com/mesos/mesos-go/messenger/mock" 14 | "github.com/mesos/mesos-go/upid" 15 | "github.com/stretchr/testify/assert" 16 | "github.com/stretchr/testify/mock" 17 | "golang.org/x/net/context" 18 | ) 19 | 20 | func TestAuthticatee_validLogin(t *testing.T) { 21 | assert := assert.New(t) 22 | ctx := context.TODO() 23 | client := upid.UPID{ 24 | ID: "someFramework", 25 | Host: "b.net", 26 | Port: "789", 27 | } 28 | server := upid.UPID{ 29 | ID: "serv", 30 | Host: "a.com", 31 | Port: "123", 32 | } 33 | tpid := upid.UPID{ 34 | ID: "sasl_transport", 35 | Host: "g.org", 36 | Port: "456", 37 | } 38 | handler := callback.HandlerFunc(func(cb ...callback.Interface) error { 39 | for _, c := range cb { 40 | switch c := c.(type) { 41 | case *callback.Name: 42 | c.Set("foo") 43 | case *callback.Password: 44 | c.Set([]byte("bar")) 45 | case *callback.Interprocess: 46 | c.Set(server, client) 47 | default: 48 | return &callback.Unsupported{Callback: c} 49 | } 50 | } 51 | return nil 52 | }) 53 | var transport *mock_sasl.Transport 54 | factory := transportFactoryFunc(func() messenger.Messenger { 55 | transport = &mock_sasl.Transport{mock_messenger.NewMessenger()} 56 | transport.On("Install").Return(nil) 57 | transport.On("UPID").Return(tpid) 58 | transport.On("Start").Return(nil) 59 | transport.On("Stop").Return(nil) 60 | 61 | mechMsg := make(chan struct{}) 62 | stepMsg := make(chan struct{}) 63 | 64 | transport.On("Send", mock.Anything, &server, &mesos.AuthenticateMessage{ 65 | Pid: proto.String(client.String()), 66 | }).Return(nil).Run(func(_ mock.Arguments) { 67 | defer close(mechMsg) 68 | transport.Recv(&server, &mesos.AuthenticationMechanismsMessage{ 69 | Mechanisms: []string{crammd5.Name}, 70 | }) 71 | }).Once() 72 | 73 | transport.On("Send", mock.Anything, &server, &mesos.AuthenticationStartMessage{ 74 | Mechanism: proto.String(crammd5.Name), 75 | }).Return(nil).Run(func(_ mock.Arguments) { 76 | defer close(stepMsg) 77 | <-mechMsg 78 | transport.Recv(&server, &mesos.AuthenticationStepMessage{ 79 | Data: []byte(`lsd;lfkgjs;dlfkgjs;dfklg`), 80 | }) 81 | }).Once() 82 | 83 | transport.On("Send", mock.Anything, &server, &mesos.AuthenticationStepMessage{ 84 | Data: []byte(`foo cc7fd96cd80123ea844a7dba29a594ed`), 85 | }).Return(nil).Run(func(_ mock.Arguments) { 86 | <-stepMsg 87 | transport.Recv(&server, &mesos.AuthenticationCompletedMessage{}) 88 | }).Once() 89 | 90 | return transport 91 | }) 92 | login, err := makeAuthenticatee(handler, factory) 93 | assert.Nil(err) 94 | 95 | err = login.Authenticate(ctx, handler) 96 | assert.Nil(err) 97 | assert.NotNil(transport) 98 | time.Sleep(1 * time.Second) // wait for the authenticator to shut down 99 | transport.AssertExpectations(t) 100 | } 101 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/gogo/protobuf/proto/testdata/golden_test.go: -------------------------------------------------------------------------------- 1 | // Go support for Protocol Buffers - Google's data interchange format 2 | // 3 | // Copyright 2012 The Go Authors. All rights reserved. 4 | // https://github.com/golang/protobuf 5 | // 6 | // Redistribution and use in source and binary forms, with or without 7 | // modification, are permitted provided that the following conditions are 8 | // met: 9 | // 10 | // * Redistributions of source code must retain the above copyright 11 | // notice, this list of conditions and the following disclaimer. 12 | // * Redistributions in binary form must reproduce the above 13 | // copyright notice, this list of conditions and the following disclaimer 14 | // in the documentation and/or other materials provided with the 15 | // distribution. 16 | // * Neither the name of Google Inc. nor the names of its 17 | // contributors may be used to endorse or promote products derived from 18 | // this software without specific prior written permission. 19 | // 20 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | 32 | // Verify that the compiler output for test.proto is unchanged. 33 | 34 | package testdata 35 | 36 | import ( 37 | "crypto/sha1" 38 | "fmt" 39 | "io/ioutil" 40 | "os" 41 | "os/exec" 42 | "path/filepath" 43 | "testing" 44 | ) 45 | 46 | // sum returns in string form (for easy comparison) the SHA-1 hash of the named file. 47 | func sum(t *testing.T, name string) string { 48 | data, err := ioutil.ReadFile(name) 49 | if err != nil { 50 | t.Fatal(err) 51 | } 52 | t.Logf("sum(%q): length is %d", name, len(data)) 53 | hash := sha1.New() 54 | _, err = hash.Write(data) 55 | if err != nil { 56 | t.Fatal(err) 57 | } 58 | return fmt.Sprintf("% x", hash.Sum(nil)) 59 | } 60 | 61 | func run(t *testing.T, name string, args ...string) { 62 | cmd := exec.Command(name, args...) 63 | cmd.Stdin = os.Stdin 64 | cmd.Stdout = os.Stdout 65 | cmd.Stderr = os.Stderr 66 | err := cmd.Run() 67 | if err != nil { 68 | t.Fatal(err) 69 | } 70 | } 71 | 72 | func TestGolden(t *testing.T) { 73 | // Compute the original checksum. 74 | goldenSum := sum(t, "test.pb.go") 75 | // Run the proto compiler. 76 | run(t, "protoc", "--gogo_out="+os.TempDir(), "test.proto") 77 | newFile := filepath.Join(os.TempDir(), "test.pb.go") 78 | defer os.Remove(newFile) 79 | // Compute the new checksum. 80 | newSum := sum(t, newFile) 81 | // Verify 82 | if newSum != goldenSum { 83 | run(t, "diff", "-u", "test.pb.go", newFile) 84 | t.Fatal("Code generated by protoc-gen-go has changed; update test.pb.go") 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /auth/login.go: -------------------------------------------------------------------------------- 1 | package auth 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "time" 7 | 8 | "github.com/mesos/mesos-go/auth/callback" 9 | "github.com/mesos/mesos-go/upid" 10 | "golang.org/x/net/context" 11 | ) 12 | 13 | var ( 14 | // No login provider name has been specified in a context.Context 15 | NoLoginProviderName = errors.New("missing login provider name in context") 16 | ) 17 | 18 | // Main client entrypoint into the authentication APIs: clients are expected to 19 | // invoke this func with a context containing a login provider name value. 20 | // This may be written as: 21 | // providerName := ... // the user has probably configured this via some flag 22 | // handler := ... // handlers provide data like usernames and passwords 23 | // ctx := ... // obtain some initial or timed context 24 | // err := auth.Login(auth.WithLoginProvider(ctx, providerName), handler) 25 | func Login(ctx context.Context, handler callback.Handler) error { 26 | name, ok := LoginProviderFrom(ctx) 27 | if !ok { 28 | return NoLoginProviderName 29 | } 30 | provider, ok := getAuthenticateeProvider(name) 31 | if !ok { 32 | return fmt.Errorf("unrecognized login provider name in context: %s", name) 33 | } 34 | return provider.Authenticate(ctx, handler) 35 | } 36 | 37 | // Unexported key type, avoids conflicts with other context-using packages. All 38 | // context items registered from this package should use keys of this type. 39 | type loginKeyType int 40 | 41 | const ( 42 | // name of login provider to use 43 | loginProviderNameKey loginKeyType = iota 44 | 45 | // upid.UPID of some parent process 46 | parentUpidKey 47 | 48 | // time.Duration that limits the overall duration of an auth attempt 49 | timeoutKey 50 | ) 51 | 52 | // Return a context that inherits all values from the parent ctx and specifies 53 | // the login provider name given here. Intended to be invoked before calls to 54 | // Login(). 55 | func WithLoginProvider(ctx context.Context, providerName string) context.Context { 56 | return context.WithValue(ctx, loginProviderNameKey, providerName) 57 | } 58 | 59 | // Return the name of the login provider specified in this context. 60 | func LoginProviderFrom(ctx context.Context) (name string, ok bool) { 61 | name, ok = ctx.Value(loginProviderNameKey).(string) 62 | return 63 | } 64 | 65 | // Return the name of the login provider specified in this context, or empty 66 | // string if none. 67 | func LoginProvider(ctx context.Context) string { 68 | name, _ := LoginProviderFrom(ctx) 69 | return name 70 | } 71 | 72 | func WithParentUPID(ctx context.Context, pid upid.UPID) context.Context { 73 | return context.WithValue(ctx, parentUpidKey, pid) 74 | } 75 | 76 | func ParentUPIDFrom(ctx context.Context) (pid upid.UPID, ok bool) { 77 | pid, ok = ctx.Value(parentUpidKey).(upid.UPID) 78 | return 79 | } 80 | 81 | func ParentUPID(ctx context.Context) (upid *upid.UPID) { 82 | if upid, ok := ParentUPIDFrom(ctx); ok { 83 | return &upid 84 | } 85 | return nil 86 | } 87 | 88 | func TimeoutFrom(ctx context.Context) (d time.Duration, ok bool) { 89 | d, ok = ctx.Value(timeoutKey).(time.Duration) 90 | return 91 | } 92 | 93 | func Timeout(ctx context.Context) (d time.Duration) { 94 | d, _ = TimeoutFrom(ctx) 95 | return 96 | } 97 | 98 | func WithTimeout(ctx context.Context, d time.Duration) context.Context { 99 | return context.WithValue(ctx, timeoutKey, d) 100 | } 101 | -------------------------------------------------------------------------------- /messenger/mock/messenger.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package mock 20 | 21 | import ( 22 | "reflect" 23 | 24 | "github.com/gogo/protobuf/proto" 25 | "github.com/mesos/mesos-go/messenger" 26 | "github.com/mesos/mesos-go/upid" 27 | "github.com/stretchr/testify/mock" 28 | "golang.org/x/net/context" 29 | ) 30 | 31 | type message struct { 32 | from *upid.UPID 33 | msg proto.Message 34 | } 35 | 36 | // Messenger is a messenger that returns error on every operation. 37 | type Messenger struct { 38 | mock.Mock 39 | messageQueue chan *message 40 | handlers map[string]messenger.MessageHandler 41 | stop chan struct{} 42 | } 43 | 44 | // NewMessenger returns a mocked messenger used for testing. 45 | func NewMessenger() *Messenger { 46 | return &Messenger{ 47 | messageQueue: make(chan *message, 1), 48 | handlers: make(map[string]messenger.MessageHandler), 49 | stop: make(chan struct{}), 50 | } 51 | } 52 | 53 | // Install is a mocked implementation. 54 | func (m *Messenger) Install(handler messenger.MessageHandler, msg proto.Message) error { 55 | m.handlers[reflect.TypeOf(msg).Elem().Name()] = handler 56 | return m.Called().Error(0) 57 | } 58 | 59 | // Send is a mocked implementation. 60 | func (m *Messenger) Send(ctx context.Context, upid *upid.UPID, msg proto.Message) error { 61 | return m.Called().Error(0) 62 | } 63 | 64 | func (m *Messenger) Route(ctx context.Context, upid *upid.UPID, msg proto.Message) error { 65 | return m.Called().Error(0) 66 | } 67 | 68 | // Start is a mocked implementation. 69 | func (m *Messenger) Start() error { 70 | go m.recvLoop() 71 | return m.Called().Error(0) 72 | } 73 | 74 | // Stop is a mocked implementation. 75 | func (m *Messenger) Stop() error { 76 | // don't close an already-closed channel 77 | select { 78 | case <-m.stop: 79 | // noop 80 | default: 81 | close(m.stop) 82 | } 83 | return m.Called().Error(0) 84 | } 85 | 86 | // UPID is a mocked implementation. 87 | func (m *Messenger) UPID() upid.UPID { 88 | return m.Called().Get(0).(upid.UPID) 89 | } 90 | 91 | func (m *Messenger) recvLoop() { 92 | for { 93 | select { 94 | case <-m.stop: 95 | return 96 | case msg := <-m.messageQueue: 97 | name := reflect.TypeOf(msg.msg).Elem().Name() 98 | m.handlers[name](msg.from, msg.msg) 99 | } 100 | } 101 | } 102 | 103 | // Recv receives a upid and a message, it will dispatch the message to its handler 104 | // with the upid. This is for testing. 105 | func (m *Messenger) Recv(from *upid.UPID, msg proto.Message) { 106 | m.messageQueue <- &message{from, msg} 107 | } 108 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/objx/map_test.go: -------------------------------------------------------------------------------- 1 | package objx 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | type Convertable struct { 9 | name string 10 | } 11 | 12 | func (c *Convertable) MSI() map[string]interface{} { 13 | return map[string]interface{}{"name": c.name} 14 | } 15 | 16 | type Unconvertable struct { 17 | name string 18 | } 19 | 20 | func TestMapCreation(t *testing.T) { 21 | 22 | o := New(nil) 23 | assert.Nil(t, o) 24 | 25 | o = New("Tyler") 26 | assert.Nil(t, o) 27 | 28 | unconvertable := &Unconvertable{name: "Tyler"} 29 | o = New(unconvertable) 30 | assert.Nil(t, o) 31 | 32 | convertable := &Convertable{name: "Tyler"} 33 | o = New(convertable) 34 | if assert.NotNil(t, convertable) { 35 | assert.Equal(t, "Tyler", o["name"], "Tyler") 36 | } 37 | 38 | o = MSI() 39 | if assert.NotNil(t, o) { 40 | assert.NotNil(t, o) 41 | } 42 | 43 | o = MSI("name", "Tyler") 44 | if assert.NotNil(t, o) { 45 | if assert.NotNil(t, o) { 46 | assert.Equal(t, o["name"], "Tyler") 47 | } 48 | } 49 | 50 | } 51 | 52 | func TestMapMustFromJSONWithError(t *testing.T) { 53 | 54 | _, err := FromJSON(`"name":"Mat"}`) 55 | assert.Error(t, err) 56 | 57 | } 58 | 59 | func TestMapFromJSON(t *testing.T) { 60 | 61 | o := MustFromJSON(`{"name":"Mat"}`) 62 | 63 | if assert.NotNil(t, o) { 64 | if assert.NotNil(t, o) { 65 | assert.Equal(t, "Mat", o["name"]) 66 | } 67 | } 68 | 69 | } 70 | 71 | func TestMapFromJSONWithError(t *testing.T) { 72 | 73 | var m Map 74 | 75 | assert.Panics(t, func() { 76 | m = MustFromJSON(`"name":"Mat"}`) 77 | }) 78 | 79 | assert.Nil(t, m) 80 | 81 | } 82 | 83 | func TestMapFromBase64String(t *testing.T) { 84 | 85 | base64String := "eyJuYW1lIjoiTWF0In0=" 86 | 87 | o, err := FromBase64(base64String) 88 | 89 | if assert.NoError(t, err) { 90 | assert.Equal(t, o.Get("name").Str(), "Mat") 91 | } 92 | 93 | assert.Equal(t, MustFromBase64(base64String).Get("name").Str(), "Mat") 94 | 95 | } 96 | 97 | func TestMapFromBase64StringWithError(t *testing.T) { 98 | 99 | base64String := "eyJuYW1lIjoiTWFasd0In0=" 100 | 101 | _, err := FromBase64(base64String) 102 | 103 | assert.Error(t, err) 104 | 105 | assert.Panics(t, func() { 106 | MustFromBase64(base64String) 107 | }) 108 | 109 | } 110 | 111 | func TestMapFromSignedBase64String(t *testing.T) { 112 | 113 | base64String := "eyJuYW1lIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6" 114 | 115 | o, err := FromSignedBase64(base64String, "key") 116 | 117 | if assert.NoError(t, err) { 118 | assert.Equal(t, o.Get("name").Str(), "Mat") 119 | } 120 | 121 | assert.Equal(t, MustFromSignedBase64(base64String, "key").Get("name").Str(), "Mat") 122 | 123 | } 124 | 125 | func TestMapFromSignedBase64StringWithError(t *testing.T) { 126 | 127 | base64String := "eyJuYW1lasdIjoiTWF0In0=_67ee82916f90b2c0d68c903266e8998c9ef0c3d6" 128 | 129 | _, err := FromSignedBase64(base64String, "key") 130 | 131 | assert.Error(t, err) 132 | 133 | assert.Panics(t, func() { 134 | MustFromSignedBase64(base64String, "key") 135 | }) 136 | 137 | } 138 | 139 | func TestMapFromURLQuery(t *testing.T) { 140 | 141 | m, err := FromURLQuery("name=tyler&state=UT") 142 | if assert.NoError(t, err) && assert.NotNil(t, m) { 143 | assert.Equal(t, "tyler", m.Get("name").Str()) 144 | assert.Equal(t, "UT", m.Get("state").Str()) 145 | } 146 | 147 | } 148 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/gogo/protobuf/proto/skip_gogo.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, Vastech SA (PTY) LTD. All rights reserved. 2 | // http://github.com/gogo/protobuf/gogoproto 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // 15 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 16 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 17 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 18 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 19 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 20 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 21 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 22 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 23 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | 27 | package proto 28 | 29 | import ( 30 | "fmt" 31 | "io" 32 | ) 33 | 34 | func Skip(data []byte) (n int, err error) { 35 | l := len(data) 36 | index := 0 37 | for index < l { 38 | var wire uint64 39 | for shift := uint(0); ; shift += 7 { 40 | if index >= l { 41 | return 0, io.ErrUnexpectedEOF 42 | } 43 | b := data[index] 44 | index++ 45 | wire |= (uint64(b) & 0x7F) << shift 46 | if b < 0x80 { 47 | break 48 | } 49 | } 50 | wireType := int(wire & 0x7) 51 | switch wireType { 52 | case 0: 53 | for { 54 | if index >= l { 55 | return 0, io.ErrUnexpectedEOF 56 | } 57 | index++ 58 | if data[index-1] < 0x80 { 59 | break 60 | } 61 | } 62 | return index, nil 63 | case 1: 64 | index += 8 65 | return index, nil 66 | case 2: 67 | var length int 68 | for shift := uint(0); ; shift += 7 { 69 | if index >= l { 70 | return 0, io.ErrUnexpectedEOF 71 | } 72 | b := data[index] 73 | index++ 74 | length |= (int(b) & 0x7F) << shift 75 | if b < 0x80 { 76 | break 77 | } 78 | } 79 | index += length 80 | return index, nil 81 | case 3: 82 | for { 83 | var innerWire uint64 84 | var start int = index 85 | for shift := uint(0); ; shift += 7 { 86 | if index >= l { 87 | return 0, io.ErrUnexpectedEOF 88 | } 89 | b := data[index] 90 | index++ 91 | innerWire |= (uint64(b) & 0x7F) << shift 92 | if b < 0x80 { 93 | break 94 | } 95 | } 96 | innerWireType := int(innerWire & 0x7) 97 | if innerWireType == 4 { 98 | break 99 | } 100 | next, err := Skip(data[start:]) 101 | if err != nil { 102 | return 0, err 103 | } 104 | index = start + next 105 | } 106 | return index, nil 107 | case 4: 108 | return index, nil 109 | case 5: 110 | index += 4 111 | return index, nil 112 | default: 113 | return 0, fmt.Errorf("proto: illegal wireType %d", wireType) 114 | } 115 | } 116 | panic("unreachable") 117 | } 118 | -------------------------------------------------------------------------------- /mesosproto/internal.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-gogo. 2 | // source: internal.proto 3 | // DO NOT EDIT! 4 | 5 | package mesosproto 6 | 7 | import proto "github.com/gogo/protobuf/proto" 8 | import fmt "fmt" 9 | import math "math" 10 | 11 | // discarding unused import gogoproto "github.com/gogo/protobuf/gogoproto" 12 | 13 | // Reference imports to suppress errors if they are not otherwise used. 14 | var _ = proto.Marshal 15 | var _ = fmt.Errorf 16 | var _ = math.Inf 17 | 18 | // For use with detector callbacks 19 | type InternalMasterChangeDetected struct { 20 | // will be present if there's a new master, otherwise nil 21 | Master *MasterInfo `protobuf:"bytes,1,opt,name=master" json:"master,omitempty"` 22 | XXX_unrecognized []byte `json:"-"` 23 | } 24 | 25 | func (m *InternalMasterChangeDetected) Reset() { *m = InternalMasterChangeDetected{} } 26 | func (m *InternalMasterChangeDetected) String() string { return proto.CompactTextString(m) } 27 | func (*InternalMasterChangeDetected) ProtoMessage() {} 28 | 29 | func (m *InternalMasterChangeDetected) GetMaster() *MasterInfo { 30 | if m != nil { 31 | return m.Master 32 | } 33 | return nil 34 | } 35 | 36 | type InternalTryAuthentication struct { 37 | XXX_unrecognized []byte `json:"-"` 38 | } 39 | 40 | func (m *InternalTryAuthentication) Reset() { *m = InternalTryAuthentication{} } 41 | func (m *InternalTryAuthentication) String() string { return proto.CompactTextString(m) } 42 | func (*InternalTryAuthentication) ProtoMessage() {} 43 | 44 | type InternalAuthenticationResult struct { 45 | // true only if the authentication process completed and login was successful 46 | Success *bool `protobuf:"varint,1,req,name=success" json:"success,omitempty"` 47 | // true if the authentication process completed, successfully or not 48 | Completed *bool `protobuf:"varint,2,req,name=completed" json:"completed,omitempty"` 49 | // master pid that this result pertains to 50 | Pid *string `protobuf:"bytes,3,req,name=pid" json:"pid,omitempty"` 51 | XXX_unrecognized []byte `json:"-"` 52 | } 53 | 54 | func (m *InternalAuthenticationResult) Reset() { *m = InternalAuthenticationResult{} } 55 | func (m *InternalAuthenticationResult) String() string { return proto.CompactTextString(m) } 56 | func (*InternalAuthenticationResult) ProtoMessage() {} 57 | 58 | func (m *InternalAuthenticationResult) GetSuccess() bool { 59 | if m != nil && m.Success != nil { 60 | return *m.Success 61 | } 62 | return false 63 | } 64 | 65 | func (m *InternalAuthenticationResult) GetCompleted() bool { 66 | if m != nil && m.Completed != nil { 67 | return *m.Completed 68 | } 69 | return false 70 | } 71 | 72 | func (m *InternalAuthenticationResult) GetPid() string { 73 | if m != nil && m.Pid != nil { 74 | return *m.Pid 75 | } 76 | return "" 77 | } 78 | 79 | type InternalNetworkError struct { 80 | // master pid that this event pertains to 81 | Pid *string `protobuf:"bytes,1,req,name=pid" json:"pid,omitempty"` 82 | // driver session UUID 83 | Session *string `protobuf:"bytes,2,opt,name=session" json:"session,omitempty"` 84 | XXX_unrecognized []byte `json:"-"` 85 | } 86 | 87 | func (m *InternalNetworkError) Reset() { *m = InternalNetworkError{} } 88 | func (m *InternalNetworkError) String() string { return proto.CompactTextString(m) } 89 | func (*InternalNetworkError) ProtoMessage() {} 90 | 91 | func (m *InternalNetworkError) GetPid() string { 92 | if m != nil && m.Pid != nil { 93 | return *m.Pid 94 | } 95 | return "" 96 | } 97 | 98 | func (m *InternalNetworkError) GetSession() string { 99 | if m != nil && m.Session != nil { 100 | return *m.Session 101 | } 102 | return "" 103 | } 104 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/stretchr/testify/assert/http_assertions_test.go: -------------------------------------------------------------------------------- 1 | package assert 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "net/url" 7 | "testing" 8 | ) 9 | 10 | func httpOK(w http.ResponseWriter, r *http.Request) { 11 | w.WriteHeader(http.StatusOK) 12 | } 13 | 14 | func httpRedirect(w http.ResponseWriter, r *http.Request) { 15 | w.WriteHeader(http.StatusTemporaryRedirect) 16 | } 17 | 18 | func httpError(w http.ResponseWriter, r *http.Request) { 19 | w.WriteHeader(http.StatusInternalServerError) 20 | } 21 | 22 | func TestHTTPStatuses(t *testing.T) { 23 | assert := New(t) 24 | mockT := new(testing.T) 25 | 26 | assert.Equal(HTTPSuccess(mockT, httpOK, "GET", "/", nil), true) 27 | assert.Equal(HTTPSuccess(mockT, httpRedirect, "GET", "/", nil), false) 28 | assert.Equal(HTTPSuccess(mockT, httpError, "GET", "/", nil), false) 29 | 30 | assert.Equal(HTTPRedirect(mockT, httpOK, "GET", "/", nil), false) 31 | assert.Equal(HTTPRedirect(mockT, httpRedirect, "GET", "/", nil), true) 32 | assert.Equal(HTTPRedirect(mockT, httpError, "GET", "/", nil), false) 33 | 34 | assert.Equal(HTTPError(mockT, httpOK, "GET", "/", nil), false) 35 | assert.Equal(HTTPError(mockT, httpRedirect, "GET", "/", nil), false) 36 | assert.Equal(HTTPError(mockT, httpError, "GET", "/", nil), true) 37 | } 38 | 39 | func TestHTTPStatusesWrapper(t *testing.T) { 40 | assert := New(t) 41 | mockAssert := New(new(testing.T)) 42 | 43 | assert.Equal(mockAssert.HTTPSuccess(httpOK, "GET", "/", nil), true) 44 | assert.Equal(mockAssert.HTTPSuccess(httpRedirect, "GET", "/", nil), false) 45 | assert.Equal(mockAssert.HTTPSuccess(httpError, "GET", "/", nil), false) 46 | 47 | assert.Equal(mockAssert.HTTPRedirect(httpOK, "GET", "/", nil), false) 48 | assert.Equal(mockAssert.HTTPRedirect(httpRedirect, "GET", "/", nil), true) 49 | assert.Equal(mockAssert.HTTPRedirect(httpError, "GET", "/", nil), false) 50 | 51 | assert.Equal(mockAssert.HTTPError(httpOK, "GET", "/", nil), false) 52 | assert.Equal(mockAssert.HTTPError(httpRedirect, "GET", "/", nil), false) 53 | assert.Equal(mockAssert.HTTPError(httpError, "GET", "/", nil), true) 54 | } 55 | 56 | func httpHelloName(w http.ResponseWriter, r *http.Request) { 57 | name := r.FormValue("name") 58 | w.Write([]byte(fmt.Sprintf("Hello, %s!", name))) 59 | } 60 | 61 | func TestHttpBody(t *testing.T) { 62 | assert := New(t) 63 | mockT := new(testing.T) 64 | 65 | assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) 66 | assert.True(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) 67 | assert.False(HTTPBodyContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) 68 | 69 | assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) 70 | assert.False(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) 71 | assert.True(HTTPBodyNotContains(mockT, httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) 72 | } 73 | 74 | func TestHttpBodyWrappers(t *testing.T) { 75 | assert := New(t) 76 | mockAssert := New(new(testing.T)) 77 | 78 | assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) 79 | assert.True(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) 80 | assert.False(mockAssert.HTTPBodyContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) 81 | 82 | assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!")) 83 | assert.False(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "World")) 84 | assert.True(mockAssert.HTTPBodyNotContains(httpHelloName, "GET", "/", url.Values{"name": []string{"World"}}, "world")) 85 | 86 | } 87 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/golang/glog/glog_file.go: -------------------------------------------------------------------------------- 1 | // Go support for leveled logs, analogous to https://code.google.com/p/google-glog/ 2 | // 3 | // Copyright 2013 Google Inc. All Rights Reserved. 4 | // 5 | // Licensed under the Apache License, Version 2.0 (the "License"); 6 | // you may not use this file except in compliance with the License. 7 | // You may obtain a copy of the License at 8 | // 9 | // http://www.apache.org/licenses/LICENSE-2.0 10 | // 11 | // Unless required by applicable law or agreed to in writing, software 12 | // distributed under the License is distributed on an "AS IS" BASIS, 13 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | // See the License for the specific language governing permissions and 15 | // limitations under the License. 16 | 17 | // File I/O for logs. 18 | 19 | package glog 20 | 21 | import ( 22 | "errors" 23 | "flag" 24 | "fmt" 25 | "os" 26 | "os/user" 27 | "path/filepath" 28 | "strings" 29 | "sync" 30 | "time" 31 | ) 32 | 33 | // MaxSize is the maximum size of a log file in bytes. 34 | var MaxSize uint64 = 1024 * 1024 * 1800 35 | 36 | // logDirs lists the candidate directories for new log files. 37 | var logDirs []string 38 | 39 | // If non-empty, overrides the choice of directory in which to write logs. 40 | // See createLogDirs for the full list of possible destinations. 41 | var logDir = flag.String("log_dir", "", "If non-empty, write log files in this directory") 42 | 43 | func createLogDirs() { 44 | if *logDir != "" { 45 | logDirs = append(logDirs, *logDir) 46 | } 47 | logDirs = append(logDirs, os.TempDir()) 48 | } 49 | 50 | var ( 51 | pid = os.Getpid() 52 | program = filepath.Base(os.Args[0]) 53 | host = "unknownhost" 54 | userName = "unknownuser" 55 | ) 56 | 57 | func init() { 58 | h, err := os.Hostname() 59 | if err == nil { 60 | host = shortHostname(h) 61 | } 62 | 63 | current, err := user.Current() 64 | if err == nil { 65 | userName = current.Username 66 | } 67 | 68 | // Sanitize userName since it may contain filepath separators on Windows. 69 | userName = strings.Replace(userName, `\`, "_", -1) 70 | } 71 | 72 | // shortHostname returns its argument, truncating at the first period. 73 | // For instance, given "www.google.com" it returns "www". 74 | func shortHostname(hostname string) string { 75 | if i := strings.Index(hostname, "."); i >= 0 { 76 | return hostname[:i] 77 | } 78 | return hostname 79 | } 80 | 81 | // logName returns a new log file name containing tag, with start time t, and 82 | // the name for the symlink for tag. 83 | func logName(tag string, t time.Time) (name, link string) { 84 | name = fmt.Sprintf("%s.%s.%s.log.%s.%04d%02d%02d-%02d%02d%02d.%d", 85 | program, 86 | host, 87 | userName, 88 | tag, 89 | t.Year(), 90 | t.Month(), 91 | t.Day(), 92 | t.Hour(), 93 | t.Minute(), 94 | t.Second(), 95 | pid) 96 | return name, program + "." + tag 97 | } 98 | 99 | var onceLogDirs sync.Once 100 | 101 | // create creates a new log file and returns the file and its filename, which 102 | // contains tag ("INFO", "FATAL", etc.) and t. If the file is created 103 | // successfully, create also attempts to update the symlink for that tag, ignoring 104 | // errors. 105 | func create(tag string, t time.Time) (f *os.File, filename string, err error) { 106 | onceLogDirs.Do(createLogDirs) 107 | if len(logDirs) == 0 { 108 | return nil, "", errors.New("log: no log dirs") 109 | } 110 | name, link := logName(tag, t) 111 | var lastErr error 112 | for _, dir := range logDirs { 113 | fname := filepath.Join(dir, name) 114 | f, err := os.Create(fname) 115 | if err == nil { 116 | symlink := filepath.Join(dir, link) 117 | os.Remove(symlink) // ignore err 118 | os.Symlink(name, symlink) // ignore err 119 | return f, fname, nil 120 | } 121 | lastErr = err 122 | } 123 | return nil, "", fmt.Errorf("log: cannot create log: %v", lastErr) 124 | } 125 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/pborman/uuid/time.go: -------------------------------------------------------------------------------- 1 | // Copyright 2014 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import ( 8 | "encoding/binary" 9 | "sync" 10 | "time" 11 | ) 12 | 13 | // A Time represents a time as the number of 100's of nanoseconds since 15 Oct 14 | // 1582. 15 | type Time int64 16 | 17 | const ( 18 | lillian = 2299160 // Julian day of 15 Oct 1582 19 | unix = 2440587 // Julian day of 1 Jan 1970 20 | epoch = unix - lillian // Days between epochs 21 | g1582 = epoch * 86400 // seconds between epochs 22 | g1582ns100 = g1582 * 10000000 // 100s of a nanoseconds between epochs 23 | ) 24 | 25 | var ( 26 | mu sync.Mutex 27 | lasttime uint64 // last time we returned 28 | clock_seq uint16 // clock sequence for this run 29 | 30 | timeNow = time.Now // for testing 31 | ) 32 | 33 | // UnixTime converts t the number of seconds and nanoseconds using the Unix 34 | // epoch of 1 Jan 1970. 35 | func (t Time) UnixTime() (sec, nsec int64) { 36 | sec = int64(t - g1582ns100) 37 | nsec = (sec % 10000000) * 100 38 | sec /= 10000000 39 | return sec, nsec 40 | } 41 | 42 | // GetTime returns the current Time (100s of nanoseconds since 15 Oct 1582) and 43 | // clock sequence as well as adjusting the clock sequence as needed. An error 44 | // is returned if the current time cannot be determined. 45 | func GetTime() (Time, uint16, error) { 46 | defer mu.Unlock() 47 | mu.Lock() 48 | return getTime() 49 | } 50 | 51 | func getTime() (Time, uint16, error) { 52 | t := timeNow() 53 | 54 | // If we don't have a clock sequence already, set one. 55 | if clock_seq == 0 { 56 | setClockSequence(-1) 57 | } 58 | now := uint64(t.UnixNano()/100) + g1582ns100 59 | 60 | // If time has gone backwards with this clock sequence then we 61 | // increment the clock sequence 62 | if now <= lasttime { 63 | clock_seq = ((clock_seq + 1) & 0x3fff) | 0x8000 64 | } 65 | lasttime = now 66 | return Time(now), clock_seq, nil 67 | } 68 | 69 | // ClockSequence returns the current clock sequence, generating one if not 70 | // already set. The clock sequence is only used for Version 1 UUIDs. 71 | // 72 | // The uuid package does not use global static storage for the clock sequence or 73 | // the last time a UUID was generated. Unless SetClockSequence a new random 74 | // clock sequence is generated the first time a clock sequence is requested by 75 | // ClockSequence, GetTime, or NewUUID. (section 4.2.1.1) sequence is generated 76 | // for 77 | func ClockSequence() int { 78 | defer mu.Unlock() 79 | mu.Lock() 80 | return clockSequence() 81 | } 82 | 83 | func clockSequence() int { 84 | if clock_seq == 0 { 85 | setClockSequence(-1) 86 | } 87 | return int(clock_seq & 0x3fff) 88 | } 89 | 90 | // SetClockSeq sets the clock sequence to the lower 14 bits of seq. Setting to 91 | // -1 causes a new sequence to be generated. 92 | func SetClockSequence(seq int) { 93 | defer mu.Unlock() 94 | mu.Lock() 95 | setClockSequence(seq) 96 | } 97 | 98 | func setClockSequence(seq int) { 99 | if seq == -1 { 100 | var b [2]byte 101 | randomBits(b[:]) // clock sequence 102 | seq = int(b[0])<<8 | int(b[1]) 103 | } 104 | old_seq := clock_seq 105 | clock_seq = uint16(seq&0x3fff) | 0x8000 // Set our variant 106 | if old_seq != clock_seq { 107 | lasttime = 0 108 | } 109 | } 110 | 111 | // Time returns the time in 100s of nanoseconds since 15 Oct 1582 encoded in 112 | // uuid. It returns false if uuid is not valid. The time is only well defined 113 | // for version 1 and 2 UUIDs. 114 | func (uuid UUID) Time() (Time, bool) { 115 | if len(uuid) != 16 { 116 | return 0, false 117 | } 118 | time := int64(binary.BigEndian.Uint32(uuid[0:4])) 119 | time |= int64(binary.BigEndian.Uint16(uuid[4:6])) << 32 120 | time |= int64(binary.BigEndian.Uint16(uuid[6:8])&0xfff) << 48 121 | return Time(time), true 122 | } 123 | 124 | // ClockSequence returns the clock sequence encoded in uuid. It returns false 125 | // if uuid is not valid. The clock sequence is only well defined for version 1 126 | // and 2 UUIDs. 127 | func (uuid UUID) ClockSequence() (int, bool) { 128 | if len(uuid) != 16 { 129 | return 0, false 130 | } 131 | return int(binary.BigEndian.Uint16(uuid[8:10])) & 0x3fff, true 132 | } 133 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/gogo/protobuf/proto/pointer_unsafe_gogo.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, Vastech SA (PTY) LTD. All rights reserved. 2 | // http://github.com/gogo/protobuf/gogoproto 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // 15 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 16 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 17 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 18 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 19 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 20 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 21 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 22 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 23 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 24 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | 27 | // +build !appengine 28 | 29 | // This file contains the implementation of the proto field accesses using package unsafe. 30 | 31 | package proto 32 | 33 | import ( 34 | "reflect" 35 | "unsafe" 36 | ) 37 | 38 | func structPointer_InterfaceAt(p structPointer, f field, t reflect.Type) interface{} { 39 | point := unsafe.Pointer(uintptr(p) + uintptr(f)) 40 | r := reflect.NewAt(t, point) 41 | return r.Interface() 42 | } 43 | 44 | func structPointer_InterfaceRef(p structPointer, f field, t reflect.Type) interface{} { 45 | point := unsafe.Pointer(uintptr(p) + uintptr(f)) 46 | r := reflect.NewAt(t, point) 47 | if r.Elem().IsNil() { 48 | return nil 49 | } 50 | return r.Elem().Interface() 51 | } 52 | 53 | func copyUintPtr(oldptr, newptr uintptr, size int) { 54 | oldbytes := make([]byte, 0) 55 | oldslice := (*reflect.SliceHeader)(unsafe.Pointer(&oldbytes)) 56 | oldslice.Data = oldptr 57 | oldslice.Len = size 58 | oldslice.Cap = size 59 | newbytes := make([]byte, 0) 60 | newslice := (*reflect.SliceHeader)(unsafe.Pointer(&newbytes)) 61 | newslice.Data = newptr 62 | newslice.Len = size 63 | newslice.Cap = size 64 | copy(newbytes, oldbytes) 65 | } 66 | 67 | func structPointer_Copy(oldptr structPointer, newptr structPointer, size int) { 68 | copyUintPtr(uintptr(oldptr), uintptr(newptr), size) 69 | } 70 | 71 | func appendStructPointer(base structPointer, f field, typ reflect.Type) structPointer { 72 | size := typ.Elem().Size() 73 | oldHeader := structPointer_GetSliceHeader(base, f) 74 | newLen := oldHeader.Len + 1 75 | slice := reflect.MakeSlice(typ, newLen, newLen) 76 | bas := toStructPointer(slice) 77 | for i := 0; i < oldHeader.Len; i++ { 78 | newElemptr := uintptr(bas) + uintptr(i)*size 79 | oldElemptr := oldHeader.Data + uintptr(i)*size 80 | copyUintPtr(oldElemptr, newElemptr, int(size)) 81 | } 82 | 83 | oldHeader.Data = uintptr(bas) 84 | oldHeader.Len = newLen 85 | oldHeader.Cap = newLen 86 | 87 | return structPointer(unsafe.Pointer(uintptr(unsafe.Pointer(bas)) + uintptr(uintptr(newLen-1)*size))) 88 | } 89 | 90 | func structPointer_FieldPointer(p structPointer, f field) structPointer { 91 | return structPointer(unsafe.Pointer(uintptr(p) + uintptr(f))) 92 | } 93 | 94 | func structPointer_GetRefStructPointer(p structPointer, f field) structPointer { 95 | return structPointer((*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f)))) 96 | } 97 | 98 | func structPointer_GetSliceHeader(p structPointer, f field) *reflect.SliceHeader { 99 | return (*reflect.SliceHeader)(unsafe.Pointer(uintptr(p) + uintptr(f))) 100 | } 101 | 102 | func structPointer_Add(p structPointer, size field) structPointer { 103 | return structPointer(unsafe.Pointer(uintptr(p) + uintptr(size))) 104 | } 105 | 106 | func structPointer_Len(p structPointer, f field) int { 107 | return len(*(*[]interface{})(unsafe.Pointer(structPointer_GetRefStructPointer(p, f)))) 108 | } 109 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/pborman/uuid/uuid.go: -------------------------------------------------------------------------------- 1 | // Copyright 2011 Google Inc. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package uuid 6 | 7 | import ( 8 | "bytes" 9 | "crypto/rand" 10 | "fmt" 11 | "io" 12 | "strings" 13 | ) 14 | 15 | // A UUID is a 128 bit (16 byte) Universal Unique IDentifier as defined in RFC 16 | // 4122. 17 | type UUID []byte 18 | 19 | // A Version represents a UUIDs version. 20 | type Version byte 21 | 22 | // A Variant represents a UUIDs variant. 23 | type Variant byte 24 | 25 | // Constants returned by Variant. 26 | const ( 27 | Invalid = Variant(iota) // Invalid UUID 28 | RFC4122 // The variant specified in RFC4122 29 | Reserved // Reserved, NCS backward compatibility. 30 | Microsoft // Reserved, Microsoft Corporation backward compatibility. 31 | Future // Reserved for future definition. 32 | ) 33 | 34 | var rander = rand.Reader // random function 35 | 36 | // New returns a new random (version 4) UUID as a string. It is a convenience 37 | // function for NewRandom().String(). 38 | func New() string { 39 | return NewRandom().String() 40 | } 41 | 42 | // Parse decodes s into a UUID or returns nil. Both the UUID form of 43 | // xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and 44 | // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded. 45 | func Parse(s string) UUID { 46 | if len(s) == 36+9 { 47 | if strings.ToLower(s[:9]) != "urn:uuid:" { 48 | return nil 49 | } 50 | s = s[9:] 51 | } else if len(s) != 36 { 52 | return nil 53 | } 54 | if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { 55 | return nil 56 | } 57 | uuid := make([]byte, 16) 58 | for i, x := range []int{ 59 | 0, 2, 4, 6, 60 | 9, 11, 61 | 14, 16, 62 | 19, 21, 63 | 24, 26, 28, 30, 32, 34} { 64 | if v, ok := xtob(s[x:]); !ok { 65 | return nil 66 | } else { 67 | uuid[i] = v 68 | } 69 | } 70 | return uuid 71 | } 72 | 73 | // Equal returns true if uuid1 and uuid2 are equal. 74 | func Equal(uuid1, uuid2 UUID) bool { 75 | return bytes.Equal(uuid1, uuid2) 76 | } 77 | 78 | // String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx 79 | // , or "" if uuid is invalid. 80 | func (uuid UUID) String() string { 81 | if uuid == nil || len(uuid) != 16 { 82 | return "" 83 | } 84 | b := []byte(uuid) 85 | return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", 86 | b[:4], b[4:6], b[6:8], b[8:10], b[10:]) 87 | } 88 | 89 | // URN returns the RFC 2141 URN form of uuid, 90 | // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, or "" if uuid is invalid. 91 | func (uuid UUID) URN() string { 92 | if uuid == nil || len(uuid) != 16 { 93 | return "" 94 | } 95 | b := []byte(uuid) 96 | return fmt.Sprintf("urn:uuid:%08x-%04x-%04x-%04x-%012x", 97 | b[:4], b[4:6], b[6:8], b[8:10], b[10:]) 98 | } 99 | 100 | // Variant returns the variant encoded in uuid. It returns Invalid if 101 | // uuid is invalid. 102 | func (uuid UUID) Variant() Variant { 103 | if len(uuid) != 16 { 104 | return Invalid 105 | } 106 | switch { 107 | case (uuid[8] & 0xc0) == 0x80: 108 | return RFC4122 109 | case (uuid[8] & 0xe0) == 0xc0: 110 | return Microsoft 111 | case (uuid[8] & 0xe0) == 0xe0: 112 | return Future 113 | default: 114 | return Reserved 115 | } 116 | panic("unreachable") 117 | } 118 | 119 | // Version returns the verison of uuid. It returns false if uuid is not 120 | // valid. 121 | func (uuid UUID) Version() (Version, bool) { 122 | if len(uuid) != 16 { 123 | return 0, false 124 | } 125 | return Version(uuid[6] >> 4), true 126 | } 127 | 128 | func (v Version) String() string { 129 | if v > 15 { 130 | return fmt.Sprintf("BAD_VERSION_%d", v) 131 | } 132 | return fmt.Sprintf("VERSION_%d", v) 133 | } 134 | 135 | func (v Variant) String() string { 136 | switch v { 137 | case RFC4122: 138 | return "RFC4122" 139 | case Reserved: 140 | return "Reserved" 141 | case Microsoft: 142 | return "Microsoft" 143 | case Future: 144 | return "Future" 145 | case Invalid: 146 | return "Invalid" 147 | } 148 | return fmt.Sprintf("BadVariant%d", int(v)) 149 | } 150 | 151 | // SetRand sets the random number generator to r, which implents io.Reader. 152 | // If r.Read returns an error when the package requests random data then 153 | // a panic will be issued. 154 | // 155 | // Calling SetRand with nil sets the random number generator to the default 156 | // generator. 157 | func SetRand(r io.Reader) { 158 | if r == nil { 159 | rander = rand.Reader 160 | return 161 | } 162 | rander = r 163 | } 164 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/gogo/protobuf/proto/proto3_test.go: -------------------------------------------------------------------------------- 1 | // Go support for Protocol Buffers - Google's data interchange format 2 | // 3 | // Copyright 2014 The Go Authors. All rights reserved. 4 | // https://github.com/golang/protobuf 5 | // 6 | // Redistribution and use in source and binary forms, with or without 7 | // modification, are permitted provided that the following conditions are 8 | // met: 9 | // 10 | // * Redistributions of source code must retain the above copyright 11 | // notice, this list of conditions and the following disclaimer. 12 | // * Redistributions in binary form must reproduce the above 13 | // copyright notice, this list of conditions and the following disclaimer 14 | // in the documentation and/or other materials provided with the 15 | // distribution. 16 | // * Neither the name of Google Inc. nor the names of its 17 | // contributors may be used to endorse or promote products derived from 18 | // this software without specific prior written permission. 19 | // 20 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | 32 | package proto_test 33 | 34 | import ( 35 | "testing" 36 | 37 | "github.com/gogo/protobuf/proto" 38 | pb "github.com/gogo/protobuf/proto/proto3_proto" 39 | tpb "github.com/gogo/protobuf/proto/testdata" 40 | ) 41 | 42 | func TestProto3ZeroValues(t *testing.T) { 43 | tests := []struct { 44 | desc string 45 | m proto.Message 46 | }{ 47 | {"zero message", &pb.Message{}}, 48 | {"empty bytes field", &pb.Message{Data: []byte{}}}, 49 | } 50 | for _, test := range tests { 51 | b, err := proto.Marshal(test.m) 52 | if err != nil { 53 | t.Errorf("%s: proto.Marshal: %v", test.desc, err) 54 | continue 55 | } 56 | if len(b) > 0 { 57 | t.Errorf("%s: Encoding is non-empty: %q", test.desc, b) 58 | } 59 | } 60 | } 61 | 62 | func TestRoundTripProto3(t *testing.T) { 63 | m := &pb.Message{ 64 | Name: "David", // (2 | 1<<3): 0x0a 0x05 "David" 65 | Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01 66 | HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01 67 | Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto" 68 | ResultCount: 47, // (0 | 7<<3): 0x38 0x2f 69 | TrueScotsman: true, // (0 | 8<<3): 0x40 0x01 70 | Score: 8.1, // (5 | 9<<3): 0x4d <8.1> 71 | 72 | Key: []uint64{1, 0xdeadbeef}, 73 | Nested: &pb.Nested{ 74 | Bunny: "Monty", 75 | }, 76 | } 77 | t.Logf(" m: %v", m) 78 | 79 | b, err := proto.Marshal(m) 80 | if err != nil { 81 | t.Fatalf("proto.Marshal: %v", err) 82 | } 83 | t.Logf(" b: %q", b) 84 | 85 | m2 := new(pb.Message) 86 | if err := proto.Unmarshal(b, m2); err != nil { 87 | t.Fatalf("proto.Unmarshal: %v", err) 88 | } 89 | t.Logf("m2: %v", m2) 90 | 91 | if !proto.Equal(m, m2) { 92 | t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2) 93 | } 94 | } 95 | 96 | func TestProto3SetDefaults(t *testing.T) { 97 | in := &pb.Message{ 98 | Terrain: map[string]*pb.Nested{ 99 | "meadow": new(pb.Nested), 100 | }, 101 | Proto2Field: new(tpb.SubDefaults), 102 | Proto2Value: map[string]*tpb.SubDefaults{ 103 | "badlands": new(tpb.SubDefaults), 104 | }, 105 | } 106 | 107 | got := proto.Clone(in).(*pb.Message) 108 | proto.SetDefaults(got) 109 | 110 | // There are no defaults in proto3. Everything should be the zero value, but 111 | // we need to remember to set defaults for nested proto2 messages. 112 | want := &pb.Message{ 113 | Terrain: map[string]*pb.Nested{ 114 | "meadow": new(pb.Nested), 115 | }, 116 | Proto2Field: &tpb.SubDefaults{N: proto.Int64(7)}, 117 | Proto2Value: map[string]*tpb.SubDefaults{ 118 | "badlands": {N: proto.Int64(7)}, 119 | }, 120 | } 121 | 122 | if !proto.Equal(got, want) { 123 | t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want) 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /examples/Godeps/_workspace/src/github.com/gogo/protobuf/proto/proto3_proto/proto3.pb.go: -------------------------------------------------------------------------------- 1 | // Code generated by protoc-gen-gogo. 2 | // source: proto3_proto/proto3.proto 3 | // DO NOT EDIT! 4 | 5 | /* 6 | Package proto3_proto is a generated protocol buffer package. 7 | 8 | It is generated from these files: 9 | proto3_proto/proto3.proto 10 | 11 | It has these top-level messages: 12 | Message 13 | Nested 14 | MessageWithMap 15 | */ 16 | package proto3_proto 17 | 18 | import proto "github.com/gogo/protobuf/proto" 19 | import fmt "fmt" 20 | import math "math" 21 | import testdata "github.com/gogo/protobuf/proto/testdata" 22 | 23 | // Reference imports to suppress errors if they are not otherwise used. 24 | var _ = proto.Marshal 25 | var _ = fmt.Errorf 26 | var _ = math.Inf 27 | 28 | type Message_Humour int32 29 | 30 | const ( 31 | Message_UNKNOWN Message_Humour = 0 32 | Message_PUNS Message_Humour = 1 33 | Message_SLAPSTICK Message_Humour = 2 34 | Message_BILL_BAILEY Message_Humour = 3 35 | ) 36 | 37 | var Message_Humour_name = map[int32]string{ 38 | 0: "UNKNOWN", 39 | 1: "PUNS", 40 | 2: "SLAPSTICK", 41 | 3: "BILL_BAILEY", 42 | } 43 | var Message_Humour_value = map[string]int32{ 44 | "UNKNOWN": 0, 45 | "PUNS": 1, 46 | "SLAPSTICK": 2, 47 | "BILL_BAILEY": 3, 48 | } 49 | 50 | func (x Message_Humour) String() string { 51 | return proto.EnumName(Message_Humour_name, int32(x)) 52 | } 53 | 54 | type Message struct { 55 | Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` 56 | Hilarity Message_Humour `protobuf:"varint,2,opt,name=hilarity,proto3,enum=proto3_proto.Message_Humour" json:"hilarity,omitempty"` 57 | HeightInCm uint32 `protobuf:"varint,3,opt,name=height_in_cm,proto3" json:"height_in_cm,omitempty"` 58 | Data []byte `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"` 59 | ResultCount int64 `protobuf:"varint,7,opt,name=result_count,proto3" json:"result_count,omitempty"` 60 | TrueScotsman bool `protobuf:"varint,8,opt,name=true_scotsman,proto3" json:"true_scotsman,omitempty"` 61 | Score float32 `protobuf:"fixed32,9,opt,name=score,proto3" json:"score,omitempty"` 62 | Key []uint64 `protobuf:"varint,5,rep,name=key" json:"key,omitempty"` 63 | Nested *Nested `protobuf:"bytes,6,opt,name=nested" json:"nested,omitempty"` 64 | Terrain map[string]*Nested `protobuf:"bytes,10,rep,name=terrain" json:"terrain,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"` 65 | Proto2Field *testdata.SubDefaults `protobuf:"bytes,11,opt,name=proto2_field" json:"proto2_field,omitempty"` 66 | Proto2Value map[string]*testdata.SubDefaults `protobuf:"bytes,13,rep,name=proto2_value" json:"proto2_value,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value"` 67 | } 68 | 69 | func (m *Message) Reset() { *m = Message{} } 70 | func (m *Message) String() string { return proto.CompactTextString(m) } 71 | func (*Message) ProtoMessage() {} 72 | 73 | func (m *Message) GetNested() *Nested { 74 | if m != nil { 75 | return m.Nested 76 | } 77 | return nil 78 | } 79 | 80 | func (m *Message) GetTerrain() map[string]*Nested { 81 | if m != nil { 82 | return m.Terrain 83 | } 84 | return nil 85 | } 86 | 87 | func (m *Message) GetProto2Field() *testdata.SubDefaults { 88 | if m != nil { 89 | return m.Proto2Field 90 | } 91 | return nil 92 | } 93 | 94 | func (m *Message) GetProto2Value() map[string]*testdata.SubDefaults { 95 | if m != nil { 96 | return m.Proto2Value 97 | } 98 | return nil 99 | } 100 | 101 | type Nested struct { 102 | Bunny string `protobuf:"bytes,1,opt,name=bunny,proto3" json:"bunny,omitempty"` 103 | } 104 | 105 | func (m *Nested) Reset() { *m = Nested{} } 106 | func (m *Nested) String() string { return proto.CompactTextString(m) } 107 | func (*Nested) ProtoMessage() {} 108 | 109 | type MessageWithMap struct { 110 | ByteMapping map[bool][]byte `protobuf:"bytes,1,rep,name=byte_mapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"` 111 | } 112 | 113 | func (m *MessageWithMap) Reset() { *m = MessageWithMap{} } 114 | func (m *MessageWithMap) String() string { return proto.CompactTextString(m) } 115 | func (*MessageWithMap) ProtoMessage() {} 116 | 117 | func (m *MessageWithMap) GetByteMapping() map[bool][]byte { 118 | if m != nil { 119 | return m.ByteMapping 120 | } 121 | return nil 122 | } 123 | 124 | func init() { 125 | proto.RegisterEnum("proto3_proto.Message_Humour", Message_Humour_name, Message_Humour_value) 126 | } 127 | -------------------------------------------------------------------------------- /examples/executor/main.go: -------------------------------------------------------------------------------- 1 | /** 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | package main 20 | 21 | import ( 22 | "flag" 23 | "fmt" 24 | "math/rand" 25 | "time" 26 | 27 | exec "github.com/mesos/mesos-go/executor" 28 | mesos "github.com/mesos/mesos-go/mesosproto" 29 | ) 30 | 31 | var ( 32 | slowTasks = flag.Bool("slow_tasks", false, "When true tasks will take several seconds before responding with TASK_FINISHED; useful for debugging failover") 33 | ) 34 | 35 | type exampleExecutor struct { 36 | tasksLaunched int 37 | } 38 | 39 | func newExampleExecutor() *exampleExecutor { 40 | return &exampleExecutor{tasksLaunched: 0} 41 | } 42 | 43 | func (exec *exampleExecutor) Registered(driver exec.ExecutorDriver, execInfo *mesos.ExecutorInfo, fwinfo *mesos.FrameworkInfo, slaveInfo *mesos.SlaveInfo) { 44 | fmt.Println("Registered Executor on slave ", slaveInfo.GetHostname()) 45 | } 46 | 47 | func (exec *exampleExecutor) Reregistered(driver exec.ExecutorDriver, slaveInfo *mesos.SlaveInfo) { 48 | fmt.Println("Re-registered Executor on slave ", slaveInfo.GetHostname()) 49 | } 50 | 51 | func (exec *exampleExecutor) Disconnected(driver exec.ExecutorDriver) { 52 | fmt.Println("Executor disconnected.") 53 | } 54 | 55 | func (exec *exampleExecutor) LaunchTask(driver exec.ExecutorDriver, taskInfo *mesos.TaskInfo) { 56 | fmt.Println("Launching task", taskInfo.GetName(), "with command", taskInfo.Command.GetValue()) 57 | 58 | runStatus := &mesos.TaskStatus{ 59 | TaskId: taskInfo.GetTaskId(), 60 | State: mesos.TaskState_TASK_RUNNING.Enum(), 61 | } 62 | _, err := driver.SendStatusUpdate(runStatus) 63 | if err != nil { 64 | fmt.Println("Got error", err) 65 | } 66 | 67 | exec.tasksLaunched++ 68 | fmt.Println("Total tasks launched ", exec.tasksLaunched) 69 | // 70 | // this is where one would perform the requested task 71 | // 72 | finishTask := func() { 73 | // finish task 74 | fmt.Println("Finishing task", taskInfo.GetName()) 75 | finStatus := &mesos.TaskStatus{ 76 | TaskId: taskInfo.GetTaskId(), 77 | State: mesos.TaskState_TASK_FINISHED.Enum(), 78 | } 79 | if _, err := driver.SendStatusUpdate(finStatus); err != nil { 80 | fmt.Println("error sending FINISHED", err) 81 | } 82 | fmt.Println("Task finished", taskInfo.GetName()) 83 | } 84 | if *slowTasks { 85 | starting := &mesos.TaskStatus{ 86 | TaskId: taskInfo.GetTaskId(), 87 | State: mesos.TaskState_TASK_STARTING.Enum(), 88 | } 89 | if _, err := driver.SendStatusUpdate(starting); err != nil { 90 | fmt.Println("error sending STARTING", err) 91 | } 92 | delay := time.Duration(rand.Intn(90)+10) * time.Second 93 | go func() { 94 | time.Sleep(delay) // TODO(jdef) add jitter 95 | finishTask() 96 | }() 97 | } else { 98 | finishTask() 99 | } 100 | } 101 | 102 | func (exec *exampleExecutor) KillTask(driver exec.ExecutorDriver, taskID *mesos.TaskID) { 103 | fmt.Println("Kill task") 104 | } 105 | 106 | func (exec *exampleExecutor) FrameworkMessage(driver exec.ExecutorDriver, msg string) { 107 | fmt.Println("Got framework message: ", msg) 108 | } 109 | 110 | func (exec *exampleExecutor) Shutdown(driver exec.ExecutorDriver) { 111 | fmt.Println("Shutting down the executor") 112 | } 113 | 114 | func (exec *exampleExecutor) Error(driver exec.ExecutorDriver, err string) { 115 | fmt.Println("Got error message:", err) 116 | } 117 | 118 | // -------------------------- func inits () ----------------- // 119 | func init() { 120 | flag.Parse() 121 | } 122 | 123 | func main() { 124 | fmt.Println("Starting Example Executor (Go)") 125 | 126 | dconfig := exec.DriverConfig{ 127 | Executor: newExampleExecutor(), 128 | } 129 | driver, err := exec.NewMesosExecutorDriver(dconfig) 130 | 131 | if err != nil { 132 | fmt.Println("Unable to create a ExecutorDriver ", err.Error()) 133 | } 134 | 135 | _, err = driver.Start() 136 | if err != nil { 137 | fmt.Println("Got error:", err) 138 | return 139 | } 140 | fmt.Println("Executor process has started and running.") 141 | _, err = driver.Join() 142 | if err != nil { 143 | fmt.Println("driver failed:", err) 144 | } 145 | fmt.Println("executor terminating") 146 | } 147 | -------------------------------------------------------------------------------- /detector/standalone_test.go: -------------------------------------------------------------------------------- 1 | package detector 2 | 3 | import ( 4 | "sync" 5 | "testing" 6 | "time" 7 | 8 | "github.com/gogo/protobuf/proto" 9 | mesos "github.com/mesos/mesos-go/mesosproto" 10 | "github.com/mesos/mesos-go/upid" 11 | "github.com/stretchr/testify/assert" 12 | "golang.org/x/net/context" 13 | ) 14 | 15 | const ( 16 | localhost = uint32(2130706433) // packed uint32 for 127.0.0.1 IPv4 17 | ) 18 | 19 | func TestStandalone_nil(t *testing.T) { 20 | d := NewStandalone(nil) 21 | select { 22 | case <-d.Done(): // expected 23 | t.Fatalf("expected detector to stay alive since we haven't done anything with it") 24 | case <-time.After(500 * time.Millisecond): 25 | } 26 | d.Detect(nil) 27 | select { 28 | case <-d.Done(): // expected 29 | case <-time.After(1 * time.Second): 30 | t.Fatalf("expected detector to shutdown since it has no master") 31 | } 32 | } 33 | 34 | func TestStandalone_pollerIncompleteInfo(t *testing.T) { 35 | d := NewStandalone(&mesos.MasterInfo{}) 36 | f := fetcherFunc(func(context.Context, string) (*upid.UPID, error) { 37 | return nil, nil 38 | }) 39 | ch := make(chan struct{}) 40 | go func() { 41 | defer close(ch) 42 | d.poller(f) 43 | }() 44 | select { 45 | case <-ch: // expected 46 | case <-time.After(1 * time.Second): 47 | t.Fatalf("expected poller to shutdown since master info is incomplete") 48 | } 49 | select { 50 | case <-d.Done(): // expected 51 | case <-time.After(1 * time.Second): 52 | t.Fatalf("expected detector to shutdown since it has no master") 53 | } 54 | } 55 | 56 | func TestStandalone_pollerFetched(t *testing.T) { 57 | assert := assert.New(t) 58 | // presence of IP address allows fecher to be called 59 | d := NewStandalone(&mesos.MasterInfo{Ip: proto.Uint32(localhost)}) 60 | defer d.Cancel() 61 | 62 | fetched := make(chan struct{}) 63 | pid := &upid.UPID{ 64 | ID: "foo@127.0.0.1:5050", 65 | Host: "127.0.0.1", 66 | Port: "5050", 67 | } 68 | f := fetcherFunc(func(ctx context.Context, addr string) (*upid.UPID, error) { 69 | defer close(fetched) 70 | assert.Equal("127.0.0.1:5050", addr) 71 | return pid, nil 72 | }) 73 | 74 | go d.poller(f) 75 | 76 | // fetch called 77 | select { 78 | case <-fetched: // expected 79 | case <-time.After(1 * time.Second): 80 | t.Fatalf("expected fetch") 81 | } 82 | 83 | // read MasterInfo 84 | select { 85 | case mi := <-d.ch: 86 | assert.Equal(mi, CreateMasterInfo(pid)) 87 | case <-time.After(1 * time.Second): 88 | t.Fatalf("expected poller to send master info") 89 | } 90 | } 91 | 92 | func TestStandalone_pollerFetchedMulti(t *testing.T) { 93 | assert := assert.New(t) 94 | // presence of IP address allows fecher to be called 95 | d := NewStandalone(&mesos.MasterInfo{Ip: proto.Uint32(localhost)}) 96 | defer d.Cancel() 97 | d.leaderSyncInterval = 500 * time.Millisecond 98 | 99 | i := 0 100 | var wg sync.WaitGroup 101 | wg.Add(4) 102 | f := fetcherFunc(func(ctx context.Context, addr string) (*upid.UPID, error) { 103 | defer func() { i++ }() 104 | switch i { 105 | case 0: 106 | wg.Done() 107 | assert.Equal("127.0.0.1:5050", addr) 108 | return &upid.UPID{ID: "foo@127.0.0.1:5050", Host: "127.0.0.1", Port: "5050"}, nil 109 | case 1: 110 | wg.Done() 111 | assert.Equal("127.0.0.1:5050", addr) 112 | return &upid.UPID{ID: "foo@127.0.0.2:5050", Host: "127.0.0.2", Port: "5050"}, nil 113 | case 2: 114 | wg.Done() 115 | return nil, context.DeadlineExceeded 116 | case 3: 117 | wg.Done() 118 | assert.Equal("127.0.0.1:5050", addr) 119 | return &upid.UPID{ID: "foo@127.0.0.3:5050", Host: "127.0.0.3", Port: "5050"}, nil 120 | default: 121 | d.Cancel() 122 | return nil, context.Canceled 123 | } 124 | }) 125 | 126 | go d.poller(f) 127 | 128 | // fetches complete 129 | ch := make(chan struct{}) 130 | go func() { 131 | defer close(ch) 132 | wg.Wait() 133 | }() 134 | 135 | changed := make(chan struct{}) 136 | go func() { 137 | defer close(changed) 138 | for i := 0; i < 4; i++ { 139 | if mi, ok := <-d.ch; !ok { 140 | t.Fatalf("failed to read master info on cycle %v", i) 141 | break 142 | } else { 143 | switch i { 144 | case 0: 145 | assert.Equal(CreateMasterInfo(&upid.UPID{ID: "foo@127.0.0.1:5050", Host: "127.0.0.1", Port: "5050"}), mi) 146 | case 1: 147 | assert.Equal(CreateMasterInfo(&upid.UPID{ID: "foo@127.0.0.2:5050", Host: "127.0.0.2", Port: "5050"}), mi) 148 | case 2: 149 | assert.Nil(mi) 150 | case 3: 151 | assert.Equal(CreateMasterInfo(&upid.UPID{ID: "foo@127.0.0.3:5050", Host: "127.0.0.3", Port: "5050"}), mi) 152 | } 153 | } 154 | } 155 | }() 156 | 157 | started := time.Now() 158 | select { 159 | case <-ch: // expected 160 | case <-time.After(3 * time.Second): 161 | t.Fatalf("expected fetches all complete") 162 | } 163 | 164 | select { 165 | case <-changed: // expected 166 | case <-time.After((3 * time.Second) - time.Now().Sub(started)): 167 | t.Fatalf("expected to have received all master info changes") 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /detector/factory.go: -------------------------------------------------------------------------------- 1 | package detector 2 | 3 | import ( 4 | "encoding/binary" 5 | "errors" 6 | "fmt" 7 | "io/ioutil" 8 | "net" 9 | "strconv" 10 | "strings" 11 | "sync" 12 | 13 | "github.com/gogo/protobuf/proto" 14 | log "github.com/golang/glog" 15 | mesos "github.com/mesos/mesos-go/mesosproto" 16 | util "github.com/mesos/mesos-go/mesosutil" 17 | "github.com/mesos/mesos-go/upid" 18 | ) 19 | 20 | var ( 21 | pluginLock sync.Mutex 22 | plugins = map[string]PluginFactory{} 23 | EmptySpecError = errors.New("empty master specification") 24 | 25 | defaultFactory = PluginFactory(func(spec string, _ ...Option) (Master, error) { 26 | if len(spec) == 0 { 27 | return nil, EmptySpecError 28 | } 29 | if strings.Index(spec, "@") < 0 { 30 | spec = "master@" + spec 31 | } 32 | if pid, err := upid.Parse(spec); err == nil { 33 | return NewStandalone(CreateMasterInfo(pid)), nil 34 | } else { 35 | return nil, err 36 | } 37 | }) 38 | ) 39 | 40 | type PluginFactory func(string, ...Option) (Master, error) 41 | 42 | // associates a plugin implementation with a Master specification prefix. 43 | // packages that provide plugins are expected to invoke this func within 44 | // their init() implementation. schedulers that wish to support plugins may 45 | // anonymously import ("_") a package the auto-registers said plugins. 46 | func Register(prefix string, f PluginFactory) error { 47 | if prefix == "" { 48 | return fmt.Errorf("illegal prefix: '%v'", prefix) 49 | } 50 | if f == nil { 51 | return fmt.Errorf("nil plugin factories are not allowed") 52 | } 53 | 54 | pluginLock.Lock() 55 | defer pluginLock.Unlock() 56 | 57 | if _, found := plugins[prefix]; found { 58 | return fmt.Errorf("detection plugin already registered for prefix '%s'", prefix) 59 | } 60 | plugins[prefix] = f 61 | return nil 62 | } 63 | 64 | // Create a new detector given the provided specification. Examples are: 65 | // 66 | // - file://{path_to_local_file} 67 | // - {ipaddress}:{port} 68 | // - master@{ip_address}:{port} 69 | // - master({id})@{ip_address}:{port} 70 | // 71 | // Support for the file:// prefix is intentionally hardcoded so that it may 72 | // not be inadvertently overridden by a custom plugin implementation. Custom 73 | // plugins are supported via the Register and MatchingPlugin funcs. 74 | // 75 | // Furthermore it is expected that master detectors returned from this func 76 | // are not yet running and will only begin to spawn requisite background 77 | // processing upon, or some time after, the first invocation of their Detect. 78 | // 79 | func New(spec string, options ...Option) (m Master, err error) { 80 | if strings.HasPrefix(spec, "file://") { 81 | var body []byte 82 | path := spec[7:] 83 | body, err = ioutil.ReadFile(path) 84 | if err != nil { 85 | log.V(1).Infof("failed to read from file at '%s'", path) 86 | } else { 87 | m, err = New(string(body), options...) 88 | } 89 | } else if f, ok := MatchingPlugin(spec); ok { 90 | m, err = f(spec, options...) 91 | } else { 92 | m, err = defaultFactory(spec, options...) 93 | } 94 | 95 | return 96 | } 97 | 98 | func MatchingPlugin(spec string) (PluginFactory, bool) { 99 | pluginLock.Lock() 100 | defer pluginLock.Unlock() 101 | 102 | for prefix, f := range plugins { 103 | if strings.HasPrefix(spec, prefix) { 104 | return f, true 105 | } 106 | } 107 | return nil, false 108 | } 109 | 110 | // Super-useful utility func that attempts to build a mesos.MasterInfo from a 111 | // upid.UPID specification. An attempt is made to determine the IP address of 112 | // the UPID's Host and any errors during such resolution will result in a nil 113 | // returned result. A nil result is also returned upon errors parsing the Port 114 | // specification of the UPID. 115 | // 116 | // TODO(jdef) make this a func of upid.UPID so that callers can invoke somePid.MasterInfo()? 117 | // 118 | func CreateMasterInfo(pid *upid.UPID) *mesos.MasterInfo { 119 | if pid == nil { 120 | return nil 121 | } 122 | port, err := strconv.Atoi(pid.Port) 123 | if err != nil { 124 | log.Errorf("failed to parse port: %v", err) 125 | return nil 126 | } 127 | //TODO(jdef) what about (future) ipv6 support? 128 | var ipv4 net.IP 129 | if ipv4 = net.ParseIP(pid.Host); ipv4 != nil { 130 | // This is needed for the people cross-compiling from macos to linux. 131 | // The cross-compiled version of net.LookupIP() fails to handle plain IPs. 132 | // See https://github.com/mesos/mesos-go/pull/117 133 | } else if addrs, err := net.LookupIP(pid.Host); err == nil { 134 | for _, ip := range addrs { 135 | if ip = ip.To4(); ip != nil { 136 | ipv4 = ip 137 | break 138 | } 139 | } 140 | if ipv4 == nil { 141 | log.Errorf("host does not resolve to an IPv4 address: %v", pid.Host) 142 | return nil 143 | } 144 | } else { 145 | log.Errorf("failed to lookup IPs for host '%v': %v", pid.Host, err) 146 | return nil 147 | } 148 | packedip := binary.BigEndian.Uint32(ipv4) // network byte order is big-endian 149 | mi := util.NewMasterInfo(pid.ID, packedip, uint32(port)) 150 | mi.Pid = proto.String(pid.String()) 151 | if pid.Host != "" { 152 | mi.Hostname = proto.String(pid.Host) 153 | } 154 | return mi 155 | } 156 | --------------------------------------------------------------------------------