From 40d966f00e21f6573cd3e26c35663491ba54080a Mon Sep 17 00:00:00 2001 From: Akihiro Suda Date: Mon, 20 Feb 2017 05:26:36 +0000 Subject: [PATCH] clean up unused nats code Signed-off-by: Akihiro Suda --- events/nats.go | 49 - vendor.conf | 12 - vendor/github.com/Sirupsen/logrus/README.md | 425 +++ vendor/github.com/beorn7/perks/README.md | 31 + .../crosbymichael/console/README.md | 44 + .../crosbymichael/go-runc/README.md | 42 + vendor/github.com/davecgh/go-spew/README.md | 205 ++ vendor/github.com/docker/docker/README.md | 304 ++ vendor/github.com/docker/docker/pkg/README.md | 11 + .../docker/docker/pkg/archive/README.md | 1 + .../github.com/docker/go-metrics/LICENSE.code | 191 ++ .../github.com/docker/go-metrics/LICENSE.docs | 425 +++ vendor/github.com/docker/go-metrics/README.md | 79 + vendor/github.com/docker/go-units/README.md | 16 + vendor/github.com/gogo/protobuf/README | 258 ++ vendor/github.com/gogo/protobuf/Readme.md | 116 + vendor/github.com/golang/protobuf/README.md | 241 ++ .../golang_protobuf_extensions/README.md | 20 + .../nats-io/go-nats-streaming/LICENSE | 20 - .../go-nats-streaming/pb/protocol.pb.go | 2794 ----------------- .../go-nats-streaming/pb/protocol.proto | 115 - .../nats-io/go-nats-streaming/stan.go | 476 --- .../nats-io/go-nats-streaming/sub.go | 376 --- vendor/github.com/nats-io/go-nats/LICENSE | 20 - vendor/github.com/nats-io/go-nats/enc.go | 249 -- vendor/github.com/nats-io/go-nats/nats.go | 2630 ---------------- vendor/github.com/nats-io/go-nats/netchan.go | 100 - vendor/github.com/nats-io/go-nats/parser.go | 470 --- vendor/github.com/nats-io/nats/LICENSE | 20 - .../nats/encoders/builtin/default_enc.go | 106 - .../nats-io/nats/encoders/builtin/gob_enc.go | 34 - .../nats-io/nats/encoders/builtin/json_enc.go | 45 - vendor/github.com/nats-io/nats/util/tls.go | 37 - .../github.com/nats-io/nats/util/tls_pre17.go | 35 - vendor/github.com/nats-io/nuid/LICENSE | 21 - vendor/github.com/nats-io/nuid/nuid.go | 124 - .../github.com/nightlyone/lockfile/README.md | 52 + .../opencontainers/go-digest/LICENSE.code | 191 ++ .../opencontainers/go-digest/LICENSE.docs | 425 +++ .../opencontainers/go-digest/README.md | 104 + .../opencontainers/image-spec/README.md | 172 + .../github.com/opencontainers/runc/README.md | 199 ++ .../runc/libcontainer/README.md | 251 ++ .../runc/libcontainer/nsenter/README.md | 44 + .../opencontainers/runtime-spec/README.md | 145 + vendor/github.com/pkg/errors/README.md | 52 + .../github.com/pmezard/go-difflib/README.md | 50 + .../prometheus/client_golang/README.md | 45 + .../client_golang/prometheus/README.md | 1 + .../prometheus/client_model/README.md | 26 + vendor/github.com/prometheus/common/README.md | 12 + .../bitbucket.org/ww/goautoneg/README.txt | 67 + vendor/github.com/prometheus/procfs/README.md | 10 + .../github.com/stevvooe/continuity/README.md | 16 + vendor/github.com/stevvooe/go-btrfs/README.md | 18 + vendor/github.com/stretchr/testify/README.md | 332 ++ vendor/github.com/tonistiigi/fifo/readme.md | 30 + vendor/github.com/urfave/cli/README.md | 1364 ++++++++ vendor/golang.org/x/net/README | 3 + vendor/golang.org/x/net/http2/README | 20 + vendor/golang.org/x/sync/README | 2 + vendor/golang.org/x/sys/README | 3 + vendor/google.golang.org/grpc/README.md | 57 + 63 files changed, 6100 insertions(+), 7733 deletions(-) delete mode 100644 events/nats.go create mode 100644 vendor/github.com/Sirupsen/logrus/README.md create mode 100644 vendor/github.com/beorn7/perks/README.md create mode 100644 vendor/github.com/crosbymichael/console/README.md create mode 100644 vendor/github.com/crosbymichael/go-runc/README.md create mode 100644 vendor/github.com/davecgh/go-spew/README.md create mode 100644 vendor/github.com/docker/docker/README.md create mode 100644 vendor/github.com/docker/docker/pkg/README.md create mode 100644 vendor/github.com/docker/docker/pkg/archive/README.md create mode 100644 vendor/github.com/docker/go-metrics/LICENSE.code create mode 100644 vendor/github.com/docker/go-metrics/LICENSE.docs create mode 100644 vendor/github.com/docker/go-metrics/README.md create mode 100644 vendor/github.com/docker/go-units/README.md create mode 100644 vendor/github.com/gogo/protobuf/README create mode 100644 vendor/github.com/gogo/protobuf/Readme.md create mode 100644 vendor/github.com/golang/protobuf/README.md create mode 100644 vendor/github.com/matttproud/golang_protobuf_extensions/README.md delete mode 100644 vendor/github.com/nats-io/go-nats-streaming/LICENSE delete mode 100644 vendor/github.com/nats-io/go-nats-streaming/pb/protocol.pb.go delete mode 100644 vendor/github.com/nats-io/go-nats-streaming/pb/protocol.proto delete mode 100644 vendor/github.com/nats-io/go-nats-streaming/stan.go delete mode 100644 vendor/github.com/nats-io/go-nats-streaming/sub.go delete mode 100644 vendor/github.com/nats-io/go-nats/LICENSE delete mode 100644 vendor/github.com/nats-io/go-nats/enc.go delete mode 100644 vendor/github.com/nats-io/go-nats/nats.go delete mode 100644 vendor/github.com/nats-io/go-nats/netchan.go delete mode 100644 vendor/github.com/nats-io/go-nats/parser.go delete mode 100644 vendor/github.com/nats-io/nats/LICENSE delete mode 100644 vendor/github.com/nats-io/nats/encoders/builtin/default_enc.go delete mode 100644 vendor/github.com/nats-io/nats/encoders/builtin/gob_enc.go delete mode 100644 vendor/github.com/nats-io/nats/encoders/builtin/json_enc.go delete mode 100644 vendor/github.com/nats-io/nats/util/tls.go delete mode 100644 vendor/github.com/nats-io/nats/util/tls_pre17.go delete mode 100644 vendor/github.com/nats-io/nuid/LICENSE delete mode 100644 vendor/github.com/nats-io/nuid/nuid.go create mode 100644 vendor/github.com/nightlyone/lockfile/README.md create mode 100644 vendor/github.com/opencontainers/go-digest/LICENSE.code create mode 100644 vendor/github.com/opencontainers/go-digest/LICENSE.docs create mode 100644 vendor/github.com/opencontainers/go-digest/README.md create mode 100644 vendor/github.com/opencontainers/image-spec/README.md create mode 100644 vendor/github.com/opencontainers/runc/README.md create mode 100644 vendor/github.com/opencontainers/runc/libcontainer/README.md create mode 100644 vendor/github.com/opencontainers/runc/libcontainer/nsenter/README.md create mode 100644 vendor/github.com/opencontainers/runtime-spec/README.md create mode 100644 vendor/github.com/pkg/errors/README.md create mode 100644 vendor/github.com/pmezard/go-difflib/README.md create mode 100644 vendor/github.com/prometheus/client_golang/README.md create mode 100644 vendor/github.com/prometheus/client_golang/prometheus/README.md create mode 100644 vendor/github.com/prometheus/client_model/README.md create mode 100644 vendor/github.com/prometheus/common/README.md create mode 100644 vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt create mode 100644 vendor/github.com/prometheus/procfs/README.md create mode 100644 vendor/github.com/stevvooe/continuity/README.md create mode 100644 vendor/github.com/stevvooe/go-btrfs/README.md create mode 100644 vendor/github.com/stretchr/testify/README.md create mode 100644 vendor/github.com/tonistiigi/fifo/readme.md create mode 100644 vendor/github.com/urfave/cli/README.md create mode 100644 vendor/golang.org/x/net/README create mode 100644 vendor/golang.org/x/net/http2/README create mode 100644 vendor/golang.org/x/sync/README create mode 100644 vendor/golang.org/x/sys/README create mode 100644 vendor/google.golang.org/grpc/README.md diff --git a/events/nats.go b/events/nats.go deleted file mode 100644 index d05a497..0000000 --- a/events/nats.go +++ /dev/null @@ -1,49 +0,0 @@ -package events - -import ( - "context" - "encoding/json" - "time" - - "github.com/Sirupsen/logrus" - "github.com/docker/containerd/log" - "github.com/nats-io/go-nats-streaming" - "github.com/pkg/errors" -) - -type natsPoster struct { - sc stan.Conn -} - -func NewNATSPoster(clusterID, clientID string) (Poster, error) { - sc, err := stan.Connect(clusterID, clientID, stan.ConnectWait(5*time.Second)) - if err != nil { - return nil, errors.Wrap(err, "failed to connect to nats streaming server") - } - return &natsPoster{sc}, nil - -} - -func (p *natsPoster) Post(ctx context.Context, e Event) { - topic := getTopic(ctx) - if topic == "" { - log.G(ctx).WithField("event", e).Warn("unable to post event, topic is empty") - return - } - - data, err := json.Marshal(e) - if err != nil { - log.G(ctx).WithError(err).WithFields(logrus.Fields{"event": e, "topic": topic}). - Warn("unable to marshal event") - return - } - - err = p.sc.Publish(topic, data) - if err != nil { - log.G(ctx).WithError(err).WithFields(logrus.Fields{"event": e, "topic": topic}). - Warn("unable to post event") - } - - log.G(ctx).WithFields(logrus.Fields{"event": e, "topic": topic}). - Debug("Posted event") -} diff --git a/vendor.conf b/vendor.conf index a9f14d1..4d563d2 100644 --- a/vendor.conf +++ b/vendor.conf @@ -22,16 +22,6 @@ github.com/docker/go-units v0.3.1 github.com/gogo/protobuf 06ec6c31ff1bac6ed4e205a547a3d72934813ef3 # golang support for protobufs - master as of 12/16/2016 github.com/golang/protobuf 8ee79997227bf9b34611aee7946ae64735e6fd93 -# nats/go-nats, latest release as of 12/16/2016 -github.com/nats-io/go-nats v1.2.2 -github.com/nats-io/nats v1.2.2 -# nats nuid package; latest release as of 12/16/2016 -github.com/nats-io/nuid v1.0.0 -# nats-streaming-server, latest release as of 12/16/2016 -github.com/nats-io/nats-streaming-server v0.3.4 -github.com/nats-io/go-nats-streaming v0.3.4 -# gnatsd; latest release as of 12/16/2016 -github.com/nats-io/gnatsd v0.9.6 # runc, latest release as of 12/16/2016 github.com/opencontainers/runc ce450bcc6c135cae93ee2a99d41a308c179ff6dc # OCI runtime spec, latest release as of 12/16/2016 @@ -52,8 +42,6 @@ github.com/tonistiigi/fifo fe870ccf293940774c2b44e23f6c71fff8f7547d github.com/urfave/cli v1.19.1 # extended Golang net package; upstream reported githash as of 12/16/2016 golang.org/x/net 8b4af36cd21a1f85a7484b49feb7c79363106d8e -# Golang x/crypto package; latest upstream reported githash as of 12/16/2016 -golang.org/x/crypto 01be46f62051d02cb6a36c9b47b37b24e5758c81 # Go gRPC support; latest release as of 12/16/2016 google.golang.org/grpc v1.0.5 # pkg/errors; latest release as of 12/16/2016 diff --git a/vendor/github.com/Sirupsen/logrus/README.md b/vendor/github.com/Sirupsen/logrus/README.md new file mode 100644 index 0000000..126cd1f --- /dev/null +++ b/vendor/github.com/Sirupsen/logrus/README.md @@ -0,0 +1,425 @@ +# Logrus :walrus: [![Build Status](https://travis-ci.org/Sirupsen/logrus.svg?branch=master)](https://travis-ci.org/Sirupsen/logrus) [![GoDoc](https://godoc.org/github.com/Sirupsen/logrus?status.svg)](https://godoc.org/github.com/Sirupsen/logrus) + +Logrus is a structured logger for Go (golang), completely API compatible with +the standard library logger. [Godoc][godoc]. **Please note the Logrus API is not +yet stable (pre 1.0). Logrus itself is completely stable and has been used in +many large deployments. The core API is unlikely to change much but please +version control your Logrus to make sure you aren't fetching latest `master` on +every build.** + +Nicely color-coded in development (when a TTY is attached, otherwise just +plain text): + +![Colored](http://i.imgur.com/PY7qMwd.png) + +With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash +or Splunk: + +```json +{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the +ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} + +{"level":"warning","msg":"The group's number increased tremendously!", +"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} + +{"animal":"walrus","level":"info","msg":"A giant walrus appears!", +"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} + +{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", +"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} + +{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, +"time":"2014-03-10 19:57:38.562543128 -0400 EDT"} +``` + +With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not +attached, the output is compatible with the +[logfmt](http://godoc.org/github.com/kr/logfmt) format: + +```text +time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 +time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 +time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true +time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 +time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 +time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true +exit status 1 +``` + +#### Example + +The simplest way to use Logrus is simply the package-level exported logger: + +```go +package main + +import ( + log "github.com/Sirupsen/logrus" +) + +func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + }).Info("A walrus appears") +} +``` + +Note that it's completely api-compatible with the stdlib logger, so you can +replace your `log` imports everywhere with `log "github.com/Sirupsen/logrus"` +and you'll now have the flexibility of Logrus. You can customize it all you +want: + +```go +package main + +import ( + "os" + log "github.com/Sirupsen/logrus" +) + +func init() { + // Log as JSON instead of the default ASCII formatter. + log.SetFormatter(&log.JSONFormatter{}) + + // Output to stderr instead of stdout, could also be a file. + log.SetOutput(os.Stderr) + + // Only log the warning severity or above. + log.SetLevel(log.WarnLevel) +} + +func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + "size": 10, + }).Info("A group of walrus emerges from the ocean") + + log.WithFields(log.Fields{ + "omg": true, + "number": 122, + }).Warn("The group's number increased tremendously!") + + log.WithFields(log.Fields{ + "omg": true, + "number": 100, + }).Fatal("The ice breaks!") + + // A common pattern is to re-use fields between logging statements by re-using + // the logrus.Entry returned from WithFields() + contextLogger := log.WithFields(log.Fields{ + "common": "this is a common field", + "other": "I also should be logged always", + }) + + contextLogger.Info("I'll be logged with common and other field") + contextLogger.Info("Me too") +} +``` + +For more advanced usage such as logging to multiple locations from the same +application, you can also create an instance of the `logrus` Logger: + +```go +package main + +import ( + "github.com/Sirupsen/logrus" +) + +// Create a new instance of the logger. You can have any number of instances. +var log = logrus.New() + +func main() { + // The API for setting attributes is a little different than the package level + // exported logger. See Godoc. + log.Out = os.Stderr + + log.WithFields(logrus.Fields{ + "animal": "walrus", + "size": 10, + }).Info("A group of walrus emerges from the ocean") +} +``` + +#### Fields + +Logrus encourages careful, structured logging though logging fields instead of +long, unparseable error messages. For example, instead of: `log.Fatalf("Failed +to send event %s to topic %s with key %d")`, you should log the much more +discoverable: + +```go +log.WithFields(log.Fields{ + "event": event, + "topic": topic, + "key": key, +}).Fatal("Failed to send event") +``` + +We've found this API forces you to think about logging in a way that produces +much more useful logging messages. We've been in countless situations where just +a single added field to a log statement that was already there would've saved us +hours. The `WithFields` call is optional. + +In general, with Logrus using any of the `printf`-family functions should be +seen as a hint you should add a field, however, you can still use the +`printf`-family functions with Logrus. + +#### Hooks + +You can add hooks for logging levels. For example to send errors to an exception +tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to +multiple places simultaneously, e.g. syslog. + +Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in +`init`: + +```go +import ( + log "github.com/Sirupsen/logrus" + "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "aibrake" + logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog" + "log/syslog" +) + +func init() { + + // Use the Airbrake hook to report errors that have Error severity or above to + // an exception tracker. You can create custom hooks, see the Hooks section. + log.AddHook(airbrake.NewHook(123, "xyz", "production")) + + hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") + if err != nil { + log.Error("Unable to connect to local syslog daemon") + } else { + log.AddHook(hook) + } +} +``` +Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md). + +| Hook | Description | +| ----- | ----------- | +| [Airbrake](https://github.com/gemnasium/logrus-airbrake-hook) | Send errors to the Airbrake API V3. Uses the official [`gobrake`](https://github.com/airbrake/gobrake) behind the scenes. | +| [Airbrake "legacy"](https://github.com/gemnasium/logrus-airbrake-legacy-hook) | Send errors to an exception tracking service compatible with the Airbrake API V2. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. | +| [Papertrail](https://github.com/polds/logrus-papertrail-hook) | Send errors to the [Papertrail](https://papertrailapp.com) hosted logging service via UDP. | +| [Syslog](https://github.com/Sirupsen/logrus/blob/master/hooks/syslog/syslog.go) | Send errors to remote syslog server. Uses standard library `log/syslog` behind the scenes. | +| [Bugsnag](https://github.com/Shopify/logrus-bugsnag/blob/master/bugsnag.go) | Send errors to the Bugsnag exception tracking service. | +| [Sentry](https://github.com/evalphobia/logrus_sentry) | Send errors to the Sentry error logging and aggregation service. | +| [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. | +| [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) | +| [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. | +| [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` | +| [Graylog](https://github.com/gemnasium/logrus-graylog-hook) | Hook for logging to [Graylog](http://graylog2.org/) | +| [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) | +| [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem | +| [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger | +| [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail | +| [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar | +| [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd | +| [Mongodb](https://github.com/weekface/mgorus) | Hook for logging to mongodb | +| [Influxus] (http://github.com/vlad-doru/influxus) | Hook for concurrently logging to [InfluxDB] (http://influxdata.com/) | +| [InfluxDB](https://github.com/Abramovic/logrus_influxdb) | Hook for logging to influxdb | +| [Octokit](https://github.com/dorajistyle/logrus-octokit-hook) | Hook for logging to github via octokit | +| [DeferPanic](https://github.com/deferpanic/dp-logrus) | Hook for logging to DeferPanic | +| [Redis-Hook](https://github.com/rogierlommers/logrus-redis-hook) | Hook for logging to a ELK stack (through Redis) | +| [Amqp-Hook](https://github.com/vladoatanasov/logrus_amqp) | Hook for logging to Amqp broker (Like RabbitMQ) | +| [KafkaLogrus](https://github.com/goibibo/KafkaLogrus) | Hook for logging to kafka | +| [Typetalk](https://github.com/dragon3/logrus-typetalk-hook) | Hook for logging to [Typetalk](https://www.typetalk.in/) | +| [ElasticSearch](https://github.com/sohlich/elogrus) | Hook for logging to ElasticSearch| +| [Sumorus](https://github.com/doublefree/sumorus) | Hook for logging to [SumoLogic](https://www.sumologic.com/)| +| [Scribe](https://github.com/sagar8192/logrus-scribe-hook) | Hook for logging to [Scribe](https://github.com/facebookarchive/scribe)| +| [Logstash](https://github.com/bshuster-repo/logrus-logstash-hook) | Hook for logging to [Logstash](https://www.elastic.co/products/logstash) | +| [logz.io](https://github.com/ripcurld00d/logrus-logzio-hook) | Hook for logging to [logz.io](https://logz.io), a Log as a Service using Logstash | +| [Logmatic.io](https://github.com/logmatic/logmatic-go) | Hook for logging to [Logmatic.io](http://logmatic.io/) | +| [Pushover](https://github.com/toorop/logrus_pushover) | Send error via [Pushover](https://pushover.net) | + + +#### Level logging + +Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic. + +```go +log.Debug("Useful debugging information.") +log.Info("Something noteworthy happened!") +log.Warn("You should probably take a look at this.") +log.Error("Something failed but I'm not quitting.") +// Calls os.Exit(1) after logging +log.Fatal("Bye.") +// Calls panic() after logging +log.Panic("I'm bailing.") +``` + +You can set the logging level on a `Logger`, then it will only log entries with +that severity or anything above it: + +```go +// Will log anything that is info or above (warn, error, fatal, panic). Default. +log.SetLevel(log.InfoLevel) +``` + +It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose +environment if your application has that. + +#### Entries + +Besides the fields added with `WithField` or `WithFields` some fields are +automatically added to all logging events: + +1. `time`. The timestamp when the entry was created. +2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after + the `AddFields` call. E.g. `Failed to send event.` +3. `level`. The logging level. E.g. `info`. + +#### Environments + +Logrus has no notion of environment. + +If you wish for hooks and formatters to only be used in specific environments, +you should handle that yourself. For example, if your application has a global +variable `Environment`, which is a string representation of the environment you +could do: + +```go +import ( + log "github.com/Sirupsen/logrus" +) + +init() { + // do something here to set environment depending on an environment variable + // or command-line flag + if Environment == "production" { + log.SetFormatter(&log.JSONFormatter{}) + } else { + // The TextFormatter is default, you don't actually have to do this. + log.SetFormatter(&log.TextFormatter{}) + } +} +``` + +This configuration is how `logrus` was intended to be used, but JSON in +production is mostly only useful if you do log aggregation with tools like +Splunk or Logstash. + +#### Formatters + +The built-in logging formatters are: + +* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise + without colors. + * *Note:* to force colored output when there is no TTY, set the `ForceColors` + field to `true`. To force no colored output even if there is a TTY set the + `DisableColors` field to `true` +* `logrus.JSONFormatter`. Logs fields as JSON. + +Third party logging formatters: + +* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events. +* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout. +* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦. + +You can define your formatter by implementing the `Formatter` interface, +requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a +`Fields` type (`map[string]interface{}`) with all your fields as well as the +default ones (see Entries section above): + +```go +type MyJSONFormatter struct { +} + +log.SetFormatter(new(MyJSONFormatter)) + +func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) { + // Note this doesn't include Time, Level and Message which are available on + // the Entry. Consult `godoc` on information about those fields or read the + // source of the official loggers. + serialized, err := json.Marshal(entry.Data) + if err != nil { + return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) + } + return append(serialized, '\n'), nil +} +``` + +#### Logger as an `io.Writer` + +Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it. + +```go +w := logger.Writer() +defer w.Close() + +srv := http.Server{ + // create a stdlib log.Logger that writes to + // logrus.Logger. + ErrorLog: log.New(w, "", 0), +} +``` + +Each line written to that writer will be printed the usual way, using formatters +and hooks. The level for those entries is `info`. + +#### Rotation + +Log rotation is not provided with Logrus. Log rotation should be done by an +external program (like `logrotate(8)`) that can compress and delete old log +entries. It should not be a feature of the application-level logger. + +#### Tools + +| Tool | Description | +| ---- | ----------- | +|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.| +|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper arround Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) | + +#### Testing + +Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides: + +* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook +* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any): + +```go +logger, hook := NewNullLogger() +logger.Error("Hello error") + +assert.Equal(1, len(hook.Entries)) +assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level) +assert.Equal("Hello error", hook.LastEntry().Message) + +hook.Reset() +assert.Nil(hook.LastEntry()) +``` + +#### Fatal handlers + +Logrus can register one or more functions that will be called when any `fatal` +level message is logged. The registered handlers will be executed before +logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need +to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted. + +``` +... +handler := func() { + // gracefully shutdown something... +} +logrus.RegisterExitHandler(handler) +... +``` + +#### Thread safty + +By default Logger is protected by mutex for concurrent writes, this mutex is invoked when calling hooks and writing logs. +If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking. + +Situation when locking is not needed includes: + +* You have no hooks registered, or hooks calling is already thread-safe. + +* Writing to logger.Out is already thread-safe, for example: + + 1) logger.Out is protected by locks. + + 2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing) + + (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/) diff --git a/vendor/github.com/beorn7/perks/README.md b/vendor/github.com/beorn7/perks/README.md new file mode 100644 index 0000000..fc05777 --- /dev/null +++ b/vendor/github.com/beorn7/perks/README.md @@ -0,0 +1,31 @@ +# Perks for Go (golang.org) + +Perks contains the Go package quantile that computes approximate quantiles over +an unbounded data stream within low memory and CPU bounds. + +For more information and examples, see: +http://godoc.org/github.com/bmizerany/perks + +A very special thank you and shout out to Graham Cormode (Rutgers University), +Flip Korn (AT&T Labs–Research), S. Muthukrishnan (Rutgers University), and +Divesh Srivastava (AT&T Labs–Research) for their research and publication of +[Effective Computation of Biased Quantiles over Data Streams](http://www.cs.rutgers.edu/~muthu/bquant.pdf) + +Thank you, also: +* Armon Dadgar (@armon) +* Andrew Gerrand (@nf) +* Brad Fitzpatrick (@bradfitz) +* Keith Rarick (@kr) + +FAQ: + +Q: Why not move the quantile package into the project root? +A: I want to add more packages to perks later. + +Copyright (C) 2013 Blake Mizerany + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/crosbymichael/console/README.md b/vendor/github.com/crosbymichael/console/README.md new file mode 100644 index 0000000..b2e38bb --- /dev/null +++ b/vendor/github.com/crosbymichael/console/README.md @@ -0,0 +1,44 @@ +# console + +[![Build Status](https://travis-ci.org/crosbymichael/console.svg?branch=master)](https://travis-ci.org/crosbymichael/console) + +Golang package for dealing with consoles. Light on deps and a simple API. + +## Modifying the current process + +```go +current := console.Current() +defer current.Reset() + +if err := current.SetRaw(); err != nil { +} +ws, err := current.Size() +current.Resize(ws) +``` + +## License - MIT + +Copyright (c) 2017-infinity Michael Crosby. crosbymichael@gmail.com + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, copy, +modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH +THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/crosbymichael/go-runc/README.md b/vendor/github.com/crosbymichael/go-runc/README.md new file mode 100644 index 0000000..bf57843 --- /dev/null +++ b/vendor/github.com/crosbymichael/go-runc/README.md @@ -0,0 +1,42 @@ +# go-runc + +[![Build Status](https://travis-ci.org/crosbymichael/go-runc.svg?branch=master)](https://travis-ci.org/crosbymichael/go-runc) + + +This is a package for consuming the [runc](https://github.com/opencontainers/runc) binary in your Go applications. +It tries to expose all the settings and features of the runc CLI. If there is something missing then add it, its opensource! + +This needs runc @ [a9610f2c0](https://github.com/opencontainers/runc/commit/a9610f2c0237d2636d05a031ec8659a70e75ffeb) +or greater. + +## Docs + +Docs can be found at [godoc.org](https://godoc.org/github.com/crosbymichael/go-runc). + + +## LICENSE - MIT + +Copyright (c) 2016 Michael Crosby. crosbymichael@gmail.com + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, copy, +modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, +INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH +THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/davecgh/go-spew/README.md b/vendor/github.com/davecgh/go-spew/README.md new file mode 100644 index 0000000..2624304 --- /dev/null +++ b/vendor/github.com/davecgh/go-spew/README.md @@ -0,0 +1,205 @@ +go-spew +======= + +[![Build Status](https://img.shields.io/travis/davecgh/go-spew.svg)] +(https://travis-ci.org/davecgh/go-spew) [![ISC License] +(http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) [![Coverage Status] +(https://img.shields.io/coveralls/davecgh/go-spew.svg)] +(https://coveralls.io/r/davecgh/go-spew?branch=master) + + +Go-spew implements a deep pretty printer for Go data structures to aid in +debugging. A comprehensive suite of tests with 100% test coverage is provided +to ensure proper functionality. See `test_coverage.txt` for the gocov coverage +report. Go-spew is licensed under the liberal ISC license, so it may be used in +open source or commercial projects. + +If you're interested in reading about how this package came to life and some +of the challenges involved in providing a deep pretty printer, there is a blog +post about it +[here](https://web.archive.org/web/20160304013555/https://blog.cyphertite.com/go-spew-a-journey-into-dumping-go-data-structures/). + +## Documentation + +[![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)] +(http://godoc.org/github.com/davecgh/go-spew/spew) + +Full `go doc` style documentation for the project can be viewed online without +installing this package by using the excellent GoDoc site here: +http://godoc.org/github.com/davecgh/go-spew/spew + +You can also view the documentation locally once the package is installed with +the `godoc` tool by running `godoc -http=":6060"` and pointing your browser to +http://localhost:6060/pkg/github.com/davecgh/go-spew/spew + +## Installation + +```bash +$ go get -u github.com/davecgh/go-spew/spew +``` + +## Quick Start + +Add this import line to the file you're working in: + +```Go +import "github.com/davecgh/go-spew/spew" +``` + +To dump a variable with full newlines, indentation, type, and pointer +information use Dump, Fdump, or Sdump: + +```Go +spew.Dump(myVar1, myVar2, ...) +spew.Fdump(someWriter, myVar1, myVar2, ...) +str := spew.Sdump(myVar1, myVar2, ...) +``` + +Alternatively, if you would prefer to use format strings with a compacted inline +printing style, use the convenience wrappers Printf, Fprintf, etc with %v (most +compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types +and pointer addresses): + +```Go +spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) +spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) +spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) +spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) +``` + +## Debugging a Web Application Example + +Here is an example of how you can use `spew.Sdump()` to help debug a web application. Please be sure to wrap your output using the `html.EscapeString()` function for safety reasons. You should also only use this debugging technique in a development environment, never in production. + +```Go +package main + +import ( + "fmt" + "html" + "net/http" + + "github.com/davecgh/go-spew/spew" +) + +func handler(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html") + fmt.Fprintf(w, "Hi there, %s!", r.URL.Path[1:]) + fmt.Fprintf(w, "") +} + +func main() { + http.HandleFunc("/", handler) + http.ListenAndServe(":8080", nil) +} +``` + +## Sample Dump Output + +``` +(main.Foo) { + unexportedField: (*main.Bar)(0xf84002e210)({ + flag: (main.Flag) flagTwo, + data: (uintptr) + }), + ExportedField: (map[interface {}]interface {}) { + (string) "one": (bool) true + } +} +([]uint8) { + 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | + 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| + 00000020 31 32 |12| +} +``` + +## Sample Formatter Output + +Double pointer to a uint8: +``` + %v: <**>5 + %+v: <**>(0xf8400420d0->0xf8400420c8)5 + %#v: (**uint8)5 + %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 +``` + +Pointer to circular struct with a uint8 field and a pointer to itself: +``` + %v: <*>{1 <*>} + %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} + %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} + %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} +``` + +## Configuration Options + +Configuration of spew is handled by fields in the ConfigState type. For +convenience, all of the top-level functions use a global state available via the +spew.Config global. + +It is also possible to create a ConfigState instance that provides methods +equivalent to the top-level functions. This allows concurrent configuration +options. See the ConfigState documentation for more details. + +``` +* Indent + String to use for each indentation level for Dump functions. + It is a single space by default. A popular alternative is "\t". + +* MaxDepth + Maximum number of levels to descend into nested data structures. + There is no limit by default. + +* DisableMethods + Disables invocation of error and Stringer interface methods. + Method invocation is enabled by default. + +* DisablePointerMethods + Disables invocation of error and Stringer interface methods on types + which only accept pointer receivers from non-pointer variables. This option + relies on access to the unsafe package, so it will not have any effect when + running in environments without access to the unsafe package such as Google + App Engine or with the "safe" build tag specified. + Pointer method invocation is enabled by default. + +* DisablePointerAddresses + DisablePointerAddresses specifies whether to disable the printing of + pointer addresses. This is useful when diffing data structures in tests. + +* DisableCapacities + DisableCapacities specifies whether to disable the printing of capacities + for arrays, slices, maps and channels. This is useful when diffing data + structures in tests. + +* ContinueOnMethod + Enables recursion into types after invoking error and Stringer interface + methods. Recursion after method invocation is disabled by default. + +* SortKeys + Specifies map keys should be sorted before being printed. Use + this to have a more deterministic, diffable output. Note that + only native types (bool, int, uint, floats, uintptr and string) + and types which implement error or Stringer interfaces are supported, + with other types sorted according to the reflect.Value.String() output + which guarantees display stability. Natural map order is used by + default. + +* SpewKeys + SpewKeys specifies that, as a last resort attempt, map keys should be + spewed to strings and sorted by those strings. This is only considered + if SortKeys is true. + +``` + +## Unsafe Package Dependency + +This package relies on the unsafe package to perform some of the more advanced +features, however it also supports a "limited" mode which allows it to work in +environments where the unsafe package is not available. By default, it will +operate in this mode on Google App Engine and when compiled with GopherJS. The +"safe" build tag may also be specified to force the package to build without +using the unsafe package. + +## License + +Go-spew is licensed under the [copyfree](http://copyfree.org) ISC License. diff --git a/vendor/github.com/docker/docker/README.md b/vendor/github.com/docker/docker/README.md new file mode 100644 index 0000000..0b33bdc --- /dev/null +++ b/vendor/github.com/docker/docker/README.md @@ -0,0 +1,304 @@ +Docker: the container engine [![Release](https://img.shields.io/github/release/docker/docker.svg)](https://github.com/docker/docker/releases/latest) +============================ + +Docker is an open source project to pack, ship and run any application +as a lightweight container. + +Docker containers are both *hardware-agnostic* and *platform-agnostic*. +This means they can run anywhere, from your laptop to the largest +cloud compute instance and everything in between - and they don't require +you to use a particular language, framework or packaging system. That +makes them great building blocks for deploying and scaling web apps, +databases, and backend services without depending on a particular stack +or provider. + +Docker began as an open-source implementation of the deployment engine which +powered [dotCloud](http://web.archive.org/web/20130530031104/https://www.dotcloud.com/), +a popular Platform-as-a-Service. It benefits directly from the experience +accumulated over several years of large-scale operation and support of hundreds +of thousands of applications and databases. + +![Docker logo](docs/static_files/docker-logo-compressed.png "Docker") + +## Security Disclosure + +Security is very important to us. If you have any issue regarding security, +please disclose the information responsibly by sending an email to +security@docker.com and not by creating a GitHub issue. + +## Better than VMs + +A common method for distributing applications and sandboxing their +execution is to use virtual machines, or VMs. Typical VM formats are +VMware's vmdk, Oracle VirtualBox's vdi, and Amazon EC2's ami. In theory +these formats should allow every developer to automatically package +their application into a "machine" for easy distribution and deployment. +In practice, that almost never happens, for a few reasons: + + * *Size*: VMs are very large which makes them impractical to store + and transfer. + * *Performance*: running VMs consumes significant CPU and memory, + which makes them impractical in many scenarios, for example local + development of multi-tier applications, and large-scale deployment + of cpu and memory-intensive applications on large numbers of + machines. + * *Portability*: competing VM environments don't play well with each + other. Although conversion tools do exist, they are limited and + add even more overhead. + * *Hardware-centric*: VMs were designed with machine operators in + mind, not software developers. As a result, they offer very + limited tooling for what developers need most: building, testing + and running their software. For example, VMs offer no facilities + for application versioning, monitoring, configuration, logging or + service discovery. + +By contrast, Docker relies on a different sandboxing method known as +*containerization*. Unlike traditional virtualization, containerization +takes place at the kernel level. Most modern operating system kernels +now support the primitives necessary for containerization, including +Linux with [openvz](https://openvz.org), +[vserver](http://linux-vserver.org) and more recently +[lxc](https://linuxcontainers.org/), Solaris with +[zones](https://docs.oracle.com/cd/E26502_01/html/E29024/preface-1.html#scrolltoc), +and FreeBSD with +[Jails](https://www.freebsd.org/doc/handbook/jails.html). + +Docker builds on top of these low-level primitives to offer developers a +portable format and runtime environment that solves all four problems. +Docker containers are small (and their transfer can be optimized with +layers), they have basically zero memory and cpu overhead, they are +completely portable, and are designed from the ground up with an +application-centric design. + +Perhaps best of all, because Docker operates at the OS level, it can still be +run inside a VM! + +## Plays well with others + +Docker does not require you to buy into a particular programming +language, framework, packaging system, or configuration language. + +Is your application a Unix process? Does it use files, tcp connections, +environment variables, standard Unix streams and command-line arguments +as inputs and outputs? Then Docker can run it. + +Can your application's build be expressed as a sequence of such +commands? Then Docker can build it. + +## Escape dependency hell + +A common problem for developers is the difficulty of managing all +their application's dependencies in a simple and automated way. + +This is usually difficult for several reasons: + + * *Cross-platform dependencies*. Modern applications often depend on + a combination of system libraries and binaries, language-specific + packages, framework-specific modules, internal components + developed for another project, etc. These dependencies live in + different "worlds" and require different tools - these tools + typically don't work well with each other, requiring awkward + custom integrations. + + * *Conflicting dependencies*. Different applications may depend on + different versions of the same dependency. Packaging tools handle + these situations with various degrees of ease - but they all + handle them in different and incompatible ways, which again forces + the developer to do extra work. + + * *Custom dependencies*. A developer may need to prepare a custom + version of their application's dependency. Some packaging systems + can handle custom versions of a dependency, others can't - and all + of them handle it differently. + + +Docker solves the problem of dependency hell by giving the developer a simple +way to express *all* their application's dependencies in one place, while +streamlining the process of assembling them. If this makes you think of +[XKCD 927](https://xkcd.com/927/), don't worry. Docker doesn't +*replace* your favorite packaging systems. It simply orchestrates +their use in a simple and repeatable way. How does it do that? With +layers. + +Docker defines a build as running a sequence of Unix commands, one +after the other, in the same container. Build commands modify the +contents of the container (usually by installing new files on the +filesystem), the next command modifies it some more, etc. Since each +build command inherits the result of the previous commands, the +*order* in which the commands are executed expresses *dependencies*. + +Here's a typical Docker build process: + +```bash +FROM ubuntu:12.04 +RUN apt-get update && apt-get install -y python python-pip curl +RUN curl -sSL https://github.com/shykes/helloflask/archive/master.tar.gz | tar -xzv +RUN cd helloflask-master && pip install -r requirements.txt +``` + +Note that Docker doesn't care *how* dependencies are built - as long +as they can be built by running a Unix command in a container. + + +Getting started +=============== + +Docker can be installed either on your computer for building applications or +on servers for running them. To get started, [check out the installation +instructions in the +documentation](https://docs.docker.com/engine/installation/). + +Usage examples +============== + +Docker can be used to run short-lived commands, long-running daemons +(app servers, databases, etc.), interactive shell sessions, etc. + +You can find a [list of real-world +examples](https://docs.docker.com/engine/examples/) in the +documentation. + +Under the hood +-------------- + +Under the hood, Docker is built on the following components: + +* The + [cgroups](https://www.kernel.org/doc/Documentation/cgroup-v1/cgroups.txt) + and + [namespaces](http://man7.org/linux/man-pages/man7/namespaces.7.html) + capabilities of the Linux kernel +* The [Go](https://golang.org) programming language +* The [Docker Image Specification](https://github.com/docker/docker/blob/master/image/spec/v1.md) +* The [Libcontainer Specification](https://github.com/opencontainers/runc/blob/master/libcontainer/SPEC.md) + +Contributing to Docker [![GoDoc](https://godoc.org/github.com/docker/docker?status.svg)](https://godoc.org/github.com/docker/docker) +====================== + +| **Master** (Linux) | **Experimental** (Linux) | **Windows** | **FreeBSD** | +|------------------|----------------------|---------|---------| +| [![Jenkins Build Status](https://jenkins.dockerproject.org/view/Docker/job/Docker%20Master/badge/icon)](https://jenkins.dockerproject.org/view/Docker/job/Docker%20Master/) | [![Jenkins Build Status](https://jenkins.dockerproject.org/view/Docker/job/Docker%20Master%20%28experimental%29/badge/icon)](https://jenkins.dockerproject.org/view/Docker/job/Docker%20Master%20%28experimental%29/) | [![Build Status](http://jenkins.dockerproject.org/job/Docker%20Master%20(windows)/badge/icon)](http://jenkins.dockerproject.org/job/Docker%20Master%20(windows)/) | [![Build Status](http://jenkins.dockerproject.org/job/Docker%20Master%20(freebsd)/badge/icon)](http://jenkins.dockerproject.org/job/Docker%20Master%20(freebsd)/) | + +Want to hack on Docker? Awesome! We have [instructions to help you get +started contributing code or documentation](https://docs.docker.com/opensource/project/who-written-for/). + +These instructions are probably not perfect, please let us know if anything +feels wrong or incomplete. Better yet, submit a PR and improve them yourself. + +Getting the development builds +============================== + +Want to run Docker from a master build? You can download +master builds at [master.dockerproject.org](https://master.dockerproject.org). +They are updated with each commit merged into the master branch. + +Don't know how to use that super cool new feature in the master build? Check +out the master docs at +[docs.master.dockerproject.org](http://docs.master.dockerproject.org). + +How the project is run +====================== + +Docker is a very, very active project. If you want to learn more about how it is run, +or want to get more involved, the best place to start is [the project directory](https://github.com/docker/docker/tree/master/project). + +We are always open to suggestions on process improvements, and are always looking for more maintainers. + +### Talking to other Docker users and contributors + + + + + + + + + + + + + + + + + + + + + + + + +
Internet Relay Chat (IRC) +

+ IRC is a direct line to our most knowledgeable Docker users; we have + both the #docker and #docker-dev group on + irc.freenode.net. + IRC is a rich chat protocol but it can overwhelm new users. You can search + our chat archives. +

+ Read our IRC quickstart guide for an easy way to get started. +
Docker Community Forums + The Docker Engine + group is for users of the Docker Engine project. +
Google Groups + The docker-dev group is for contributors and other people + contributing to the Docker project. You can join this group without a + Google account by sending an email to docker-dev+subscribe@googlegroups.com. + You'll receive a join-request message; simply reply to the message to + confirm your subscription. +
Twitter + You can follow Docker's Twitter feed + to get updates on our products. You can also tweet us questions or just + share blogs or stories. +
Stack Overflow + Stack Overflow has over 7000 Docker questions listed. We regularly + monitor Docker questions + and so do many other knowledgeable Docker users. +
+ +### Legal + +*Brought to you courtesy of our legal counsel. For more context, +please see the [NOTICE](https://github.com/docker/docker/blob/master/NOTICE) document in this repo.* + +Use and transfer of Docker may be subject to certain restrictions by the +United States and other governments. + +It is your responsibility to ensure that your use and/or transfer does not +violate applicable laws. + +For more information, please see https://www.bis.doc.gov + + +Licensing +========= +Docker is licensed under the Apache License, Version 2.0. See +[LICENSE](https://github.com/docker/docker/blob/master/LICENSE) for the full +license text. + +Other Docker Related Projects +============================= +There are a number of projects under development that are based on Docker's +core technology. These projects expand the tooling built around the +Docker platform to broaden its application and utility. + +* [Docker Registry](https://github.com/docker/distribution): Registry +server for Docker (hosting/delivery of repositories and images) +* [Docker Machine](https://github.com/docker/machine): Machine management +for a container-centric world +* [Docker Swarm](https://github.com/docker/swarm): A Docker-native clustering +system +* [Docker Compose](https://github.com/docker/compose) (formerly Fig): +Define and run multi-container apps +* [Kitematic](https://github.com/docker/kitematic): The easiest way to use +Docker on Mac and Windows + +If you know of another project underway that should be listed here, please help +us keep this list up-to-date by submitting a PR. + +Awesome-Docker +============== +You can find more projects, tools and articles related to Docker on the [awesome-docker list](https://github.com/veggiemonk/awesome-docker). Add your project there. diff --git a/vendor/github.com/docker/docker/pkg/README.md b/vendor/github.com/docker/docker/pkg/README.md new file mode 100644 index 0000000..c4b78a8 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/README.md @@ -0,0 +1,11 @@ +pkg/ is a collection of utility packages used by the Docker project without being specific to its internals. + +Utility packages are kept separate from the docker core codebase to keep it as small and concise as possible. +If some utilities grow larger and their APIs stabilize, they may be moved to their own repository under the +Docker organization, to facilitate re-use by other projects. However that is not the priority. + +The directory `pkg` is named after the same directory in the camlistore project. Since Brad is a core +Go maintainer, we thought it made sense to copy his methods for organizing Go code :) Thanks Brad! + +Because utility packages are small and neatly separated from the rest of the codebase, they are a good +place to start for aspiring maintainers and contributors. Get in touch if you want to help maintain them! diff --git a/vendor/github.com/docker/docker/pkg/archive/README.md b/vendor/github.com/docker/docker/pkg/archive/README.md new file mode 100644 index 0000000..7307d96 --- /dev/null +++ b/vendor/github.com/docker/docker/pkg/archive/README.md @@ -0,0 +1 @@ +This code provides helper functions for dealing with archive files. diff --git a/vendor/github.com/docker/go-metrics/LICENSE.code b/vendor/github.com/docker/go-metrics/LICENSE.code new file mode 100644 index 0000000..8f3fee6 --- /dev/null +++ b/vendor/github.com/docker/go-metrics/LICENSE.code @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2013-2016 Docker, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/docker/go-metrics/LICENSE.docs b/vendor/github.com/docker/go-metrics/LICENSE.docs new file mode 100644 index 0000000..e26cd4f --- /dev/null +++ b/vendor/github.com/docker/go-metrics/LICENSE.docs @@ -0,0 +1,425 @@ +Attribution-ShareAlike 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-ShareAlike 4.0 International Public +License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-ShareAlike 4.0 International Public License ("Public +License"). To the extent this Public License may be interpreted as a +contract, You are granted the Licensed Rights in consideration of Your +acceptance of these terms and conditions, and the Licensor grants You +such rights in consideration of benefits the Licensor receives from +making the Licensed Material available under these terms and +conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. BY-SA Compatible License means a license listed at + creativecommons.org/compatiblelicenses, approved by Creative + Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + e. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name + of a Creative Commons Public License. The License Elements of this + Public License are Attribution and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + i. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + k. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + l. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + m. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. Additional offer from the Licensor -- Adapted Material. + Every recipient of Adapted Material from You + automatically receives an offer from the Licensor to + exercise the Licensed Rights in the Adapted Material + under the conditions of the Adapter's License You apply. + + c. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + b. ShareAlike. + + In addition to the conditions in Section 3(a), if You Share + Adapted Material You produce, the following conditions also apply. + + 1. The Adapter's License You apply must be a Creative Commons + license with the same License Elements, this version or + later, or a BY-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the + Adapter's License You apply. You may satisfy this condition + in any reasonable manner based on the medium, means, and + context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms + or conditions on, or apply any Effective Technological + Measures to, Adapted Material that restrict exercise of the + rights granted under the Adapter's License You apply. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material, + + including for purposes of Section 3(b); and + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public licenses. +Notwithstanding, Creative Commons may elect to apply one of its public +licenses to material it publishes and in those instances will be +considered the "Licensor." Except for the limited purpose of indicating +that material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the public +licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/vendor/github.com/docker/go-metrics/README.md b/vendor/github.com/docker/go-metrics/README.md new file mode 100644 index 0000000..fdf7fb7 --- /dev/null +++ b/vendor/github.com/docker/go-metrics/README.md @@ -0,0 +1,79 @@ +# go-metrics [![GoDoc](https://godoc.org/github.com/docker/go-metrics?status.svg)](https://godoc.org/github.com/docker/go-metrics) ![Badge Badge](http://doyouevenbadge.com/github.com/docker/go-metrics) + +This package is small wrapper around the prometheus go client to help enforce convention and best practices for metrics collection in Docker projects. + +## Best Practices + +This packages is meant to be used for collecting metrics in Docker projects. +It is not meant to be used as a replacement for the prometheus client but to help enforce consistent naming across metrics collected. +If you have not already read the prometheus best practices around naming and labels you can read the page [here](https://prometheus.io/docs/practices/naming/). + +The following are a few Docker specific rules that will help you name and work with metrics in your project. + +1. Namespace and Subsystem + +This package provides you with a namespace type that allows you to specify the same namespace and subsystem for your metrics. + +```go +ns := metrics.NewNamespace("engine", "daemon", metrics.Labels{ + "version": dockerversion.Version, + "commit": dockerversion.GitCommit, +}) +``` + +In the example above we are creating metrics for the Docker engine's daemon package. +`engine` would be the namespace in this example where `daemon` is the subsystem or package where we are collecting the metrics. + +A namespace also allows you to attach constant labels to the metrics such as the git commit and version that it is collecting. + +2. Declaring your Metrics + +Try to keep all your metric declarations in one file. +This makes it easy for others to see what constant labels are defined on the namespace and what labels are defined on the metrics when they are created. + +3. Use labels instead of multiple metrics + +Labels allow you to define one metric such as the time it takes to perform a certain action on an object. +If we wanted to collect timings on various container actions such as create, start, and delete then we can define one metric called `container_actions` and use labels to specify the type of action. + + +```go +containerActions = ns.NewLabeledTimer("container_actions", "The number of milliseconds it takes to process each container action", "action") +``` + +The last parameter is the label name or key. +When adding a data point to the metric you will use the `WithValues` function to specify the `action` that you are collecting for. + +```go +containerActions.WithValues("create").UpdateSince(start) +``` + +4. Always use a unit + +The metric name should describe what you are measuring but you also need to provide the unit that it is being measured with. +For a timer, the standard unit is seconds and a counter's standard unit is a total. +For gauges you must provide the unit. +This package provides a standard set of units for use within the Docker projects. + +```go +Nanoseconds Unit = "nanoseconds" +Seconds Unit = "seconds" +Bytes Unit = "bytes" +Total Unit = "total" +``` + +If you need to use a unit but it is not defined in the package please open a PR to add it but first try to see if one of the already created units will work for your metric, i.e. seconds or nanoseconds vs adding milliseconds. + +## Docs + +Package documentation can be found [here](https://godoc.org/github.com/docker/go-metrics). + +## Additional Metrics + +Additional metrics are also defined here that are not avaliable in the prometheus client. +If you need a custom metrics and it is generic enough to be used by multiple projects, define it here. + + +## Copyright and license + +Copyright © 2016 Docker, Inc. All rights reserved, except as follows. Code is released under the Apache 2.0 license. The README.md file, and files in the "docs" folder are licensed under the Creative Commons Attribution 4.0 International License under the terms and conditions set forth in the file "LICENSE.docs". You may obtain a duplicate copy of the same license, titled CC-BY-SA-4.0, at http://creativecommons.org/licenses/by/4.0/. diff --git a/vendor/github.com/docker/go-units/README.md b/vendor/github.com/docker/go-units/README.md new file mode 100644 index 0000000..4f70a4e --- /dev/null +++ b/vendor/github.com/docker/go-units/README.md @@ -0,0 +1,16 @@ +[![GoDoc](https://godoc.org/github.com/docker/go-units?status.svg)](https://godoc.org/github.com/docker/go-units) + +# Introduction + +go-units is a library to transform human friendly measurements into machine friendly values. + +## Usage + +See the [docs in godoc](https://godoc.org/github.com/docker/go-units) for examples and documentation. + +## Copyright and license + +Copyright © 2015 Docker, Inc. + +go-units is licensed under the Apache License, Version 2.0. +See [LICENSE](LICENSE) for the full text of the license. diff --git a/vendor/github.com/gogo/protobuf/README b/vendor/github.com/gogo/protobuf/README new file mode 100644 index 0000000..0ad5136 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/README @@ -0,0 +1,258 @@ +GoGoProtobuf http://github.com/gogo/protobuf extends +GoProtobuf http://github.com/golang/protobuf + +# Go support for Protocol Buffers + +Google's data interchange format. +Copyright 2010 The Go Authors. +https://github.com/golang/protobuf + +This package and the code it generates requires at least Go 1.4. + +This software implements Go bindings for protocol buffers. For +information about protocol buffers themselves, see + https://developers.google.com/protocol-buffers/ + +## Installation ## + +To use this software, you must: +- Install the standard C++ implementation of protocol buffers from + https://developers.google.com/protocol-buffers/ +- Of course, install the Go compiler and tools from + https://golang.org/ + See + https://golang.org/doc/install + for details or, if you are using gccgo, follow the instructions at + https://golang.org/doc/install/gccgo +- Grab the code from the repository and install the proto package. + The simplest way is to run `go get -u github.com/golang/protobuf/{proto,protoc-gen-go}`. + The compiler plugin, protoc-gen-go, will be installed in $GOBIN, + defaulting to $GOPATH/bin. It must be in your $PATH for the protocol + compiler, protoc, to find it. + +This software has two parts: a 'protocol compiler plugin' that +generates Go source files that, once compiled, can access and manage +protocol buffers; and a library that implements run-time support for +encoding (marshaling), decoding (unmarshaling), and accessing protocol +buffers. + +There is support for gRPC in Go using protocol buffers. +See the note at the bottom of this file for details. + +There are no insertion points in the plugin. + +GoGoProtobuf provides extensions for protocol buffers and GoProtobuf +see http://github.com/gogo/protobuf/gogoproto/doc.go + +## Using protocol buffers with Go ## + +Once the software is installed, there are two steps to using it. +First you must compile the protocol buffer definitions and then import +them, with the support library, into your program. + +To compile the protocol buffer definition, run protoc with the --gogo_out +parameter set to the directory you want to output the Go code to. + + protoc --gogo_out=. *.proto + +The generated files will be suffixed .pb.go. See the Test code below +for an example using such a file. + +The package comment for the proto library contains text describing +the interface provided in Go for protocol buffers. Here is an edited +version. + +If you are using any gogo.proto extensions you will need to specify the +proto_path to include the descriptor.proto and gogo.proto. +gogo.proto is located in github.com/gogo/protobuf/gogoproto +This should be fine, since your import is the same. +descriptor.proto is located in either github.com/gogo/protobuf/protobuf +or code.google.com/p/protobuf/trunk/src/ +Its import is google/protobuf/descriptor.proto so it might need some help. + + protoc --gogo_out=. -I=.:github.com/gogo/protobuf/protobuf *.proto + +========== + +The proto package converts data structures to and from the +wire format of protocol buffers. It works in concert with the +Go source code generated for .proto files by the protocol compiler. + +A summary of the properties of the protocol buffer interface +for a protocol buffer variable v: + + - Names are turned from camel_case to CamelCase for export. + - There are no methods on v to set fields; just treat + them as structure fields. + - There are getters that return a field's value if set, + and return the field's default value if unset. + The getters work even if the receiver is a nil message. + - The zero value for a struct is its correct initialization state. + All desired fields must be set before marshaling. + - A Reset() method will restore a protobuf struct to its zero state. + - Non-repeated fields are pointers to the values; nil means unset. + That is, optional or required field int32 f becomes F *int32. + - Repeated fields are slices. + - Helper functions are available to aid the setting of fields. + Helpers for getting values are superseded by the + GetFoo methods and their use is deprecated. + msg.Foo = proto.String("hello") // set field + - Constants are defined to hold the default values of all fields that + have them. They have the form Default_StructName_FieldName. + Because the getter methods handle defaulted values, + direct use of these constants should be rare. + - Enums are given type names and maps from names to values. + Enum values are prefixed with the enum's type name. Enum types have + a String method, and a Enum method to assist in message construction. + - Nested groups and enums have type names prefixed with the name of + the surrounding message type. + - Extensions are given descriptor names that start with E_, + followed by an underscore-delimited list of the nested messages + that contain it (if any) followed by the CamelCased name of the + extension field itself. HasExtension, ClearExtension, GetExtension + and SetExtension are functions for manipulating extensions. + - Oneof field sets are given a single field in their message, + with distinguished wrapper types for each possible field value. + - Marshal and Unmarshal are functions to encode and decode the wire format. + +When the .proto file specifies `syntax="proto3"`, there are some differences: + + - Non-repeated fields of non-message type are values instead of pointers. + - Getters are only generated for message and oneof fields. + - Enum types do not get an Enum method. + +Consider file test.proto, containing + +```proto + package example; + + enum FOO { X = 17; }; + + message Test { + required string label = 1; + optional int32 type = 2 [default=77]; + repeated int64 reps = 3; + optional group OptionalGroup = 4 { + required string RequiredField = 5; + } + } +``` + +To create and play with a Test object from the example package, + +```go + package main + + import ( + "log" + + "github.com/gogo/protobuf/proto" + "path/to/example" + ) + + func main() { + test := &example.Test { + Label: proto.String("hello"), + Type: proto.Int32(17), + Reps: []int64{1, 2, 3}, + Optionalgroup: &example.Test_OptionalGroup { + RequiredField: proto.String("good bye"), + }, + } + data, err := proto.Marshal(test) + if err != nil { + log.Fatal("marshaling error: ", err) + } + newTest := &example.Test{} + err = proto.Unmarshal(data, newTest) + if err != nil { + log.Fatal("unmarshaling error: ", err) + } + // Now test and newTest contain the same data. + if test.GetLabel() != newTest.GetLabel() { + log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) + } + // etc. + } +``` + + +## Parameters ## + +To pass extra parameters to the plugin, use a comma-separated +parameter list separated from the output directory by a colon: + + + protoc --gogo_out=plugins=grpc,import_path=mypackage:. *.proto + + +- `import_prefix=xxx` - a prefix that is added onto the beginning of + all imports. Useful for things like generating protos in a + subdirectory, or regenerating vendored protobufs in-place. +- `import_path=foo/bar` - used as the package if no input files + declare `go_package`. If it contains slashes, everything up to the + rightmost slash is ignored. +- `plugins=plugin1+plugin2` - specifies the list of sub-plugins to + load. The only plugin in this repo is `grpc`. +- `Mfoo/bar.proto=quux/shme` - declares that foo/bar.proto is + associated with Go package quux/shme. This is subject to the + import_prefix parameter. + +## gRPC Support ## + +If a proto file specifies RPC services, protoc-gen-go can be instructed to +generate code compatible with gRPC (http://www.grpc.io/). To do this, pass +the `plugins` parameter to protoc-gen-go; the usual way is to insert it into +the --go_out argument to protoc: + + protoc --gogo_out=plugins=grpc:. *.proto + +## Compatibility ## + +The library and the generated code are expected to be stable over time. +However, we reserve the right to make breaking changes without notice for the +following reasons: + +- Security. A security issue in the specification or implementation may come to + light whose resolution requires breaking compatibility. We reserve the right + to address such security issues. +- Unspecified behavior. There are some aspects of the Protocol Buffers + specification that are undefined. Programs that depend on such unspecified + behavior may break in future releases. +- Specification errors or changes. If it becomes necessary to address an + inconsistency, incompleteness, or change in the Protocol Buffers + specification, resolving the issue could affect the meaning or legality of + existing programs. We reserve the right to address such issues, including + updating the implementations. +- Bugs. If the library has a bug that violates the specification, a program + that depends on the buggy behavior may break if the bug is fixed. We reserve + the right to fix such bugs. +- Adding methods or fields to generated structs. These may conflict with field + names that already exist in a schema, causing applications to break. When the + code generator encounters a field in the schema that would collide with a + generated field or method name, the code generator will append an underscore + to the generated field or method name. +- Adding, removing, or changing methods or fields in generated structs that + start with `XXX`. These parts of the generated code are exported out of + necessity, but should not be considered part of the public API. +- Adding, removing, or changing unexported symbols in generated code. + +Any breaking changes outside of these will be announced 6 months in advance to +protobuf@googlegroups.com. + +You should, whenever possible, use generated code created by the `protoc-gen-go` +tool built at the same commit as the `proto` package. The `proto` package +declares package-level constants in the form `ProtoPackageIsVersionX`. +Application code and generated code may depend on one of these constants to +ensure that compilation will fail if the available version of the proto library +is too old. Whenever we make a change to the generated code that requires newer +library support, in the same commit we will increment the version number of the +generated code and declare a new package-level constant whose name incorporates +the latest version number. Removing a compatibility constant is considered a +breaking change and would be subject to the announcement policy stated above. + +## Plugins ## + +The `protoc-gen-go/generator` package exposes a plugin interface, +which is used by the gRPC code generation. This interface is not +supported and is subject to incompatible changes without notice. diff --git a/vendor/github.com/gogo/protobuf/Readme.md b/vendor/github.com/gogo/protobuf/Readme.md new file mode 100644 index 0000000..7da3263 --- /dev/null +++ b/vendor/github.com/gogo/protobuf/Readme.md @@ -0,0 +1,116 @@ +# Protocol Buffers for Go with Gadgets + +[![Build Status](https://travis-ci.org/gogo/protobuf.svg?branch=master)](https://travis-ci.org/gogo/protobuf) + +gogoprotobuf is a fork of golang/protobuf with extra code generation features. + +This code generation is used to achieve: + + - fast marshalling and unmarshalling + - more canonical Go structures + - goprotobuf compatibility + - less typing by optionally generating extra helper code + - peace of mind by optionally generating test and benchmark code + - other serialization formats + +Keeping track of how up to date gogoprotobuf is relative to golang/protobuf is done in this +issue + +## Users + +These projects use gogoprotobuf: + + - etcd - blog - sample proto file + - spacemonkey - blog + - badoo - sample proto file + - mesos-go - sample proto file + - heka - the switch from golang/protobuf to gogo/protobuf when it was still on code.google.com + - cockroachdb - sample proto file + - go-ipfs - sample proto file + - rkive-go - sample proto file + - dropbox + - srclib - sample proto file + - adyoulike + - cloudfoundry - sample proto file + - kubernetes - go2idl built on top of gogoprotobuf + - dgraph - release notes - benchmarks + - centrifugo - release notes - blog + - docker swarmkit - sample proto file + - nats.io - go-nats-streaming + - tidb - Communication between tidb and tikv + +Please lets us know if you are using gogoprotobuf by posting on our GoogleGroup. + +### Mentioned + + - Cloudflare - go serialization talk - Albert Strasheim + - gophercon + - alecthomas' go serialization benchmarks + +## Getting Started + +There are several ways to use gogoprotobuf, but for all you need to install go and protoc. +After that you can choose: + + - Speed + - More Speed and more generated code + - Most Speed and most customization + +### Installation + +To install it, you must first have Go (at least version 1.3.3) installed (see [http://golang.org/doc/install](http://golang.org/doc/install)). Go 1.7.1 is continuously tested. + +Next, install the standard protocol buffer implementation from [https://github.com/google/protobuf](https://github.com/google/protobuf). +Most versions from 2.3.1 should not give any problems, but 2.6.1, 3.0.2 and 3.1.0 are continuously tested. + +### Speed + +Install the protoc-gen-gofast binary + + go get github.com/gogo/protobuf/protoc-gen-gofast + +Use it to generate faster marshaling and unmarshaling go code for your protocol buffers. + + protoc --gofast_out=. myproto.proto + +This does not allow you to use any of the other gogoprotobuf [extensions](https://github.com/gogo/protobuf/blob/master/extensions.md). + +### More Speed and more generated code + +Fields without pointers cause less time in the garbage collector. +More code generation results in more convenient methods. + +Other binaries are also included: + + protoc-gen-gogofast (same as gofast, but imports gogoprotobuf) + protoc-gen-gogofaster (same as gogofast, without XXX_unrecognized, less pointer fields) + protoc-gen-gogoslick (same as gogofaster, but with generated string, gostring and equal methods) + +Installing any of these binaries is easy. Simply run: + + go get github.com/gogo/protobuf/proto + go get github.com/gogo/protobuf/{binary} + go get github.com/gogo/protobuf/gogoproto + +These binaries allow you to using gogoprotobuf [extensions](https://github.com/gogo/protobuf/blob/master/extensions.md). + +### Most Speed and most customization + +Customizing the fields of the messages to be the fields that you actually want to use removes the need to copy between the structs you use and structs you use to serialize. +gogoprotobuf also offers more serialization formats and generation of tests and even more methods. + +Please visit the [extensions](https://github.com/gogo/protobuf/blob/master/extensions.md) page for more documentation. + +Install protoc-gen-gogo: + + go get github.com/gogo/protobuf/proto + go get github.com/gogo/protobuf/jsonpb + go get github.com/gogo/protobuf/protoc-gen-gogo + go get github.com/gogo/protobuf/gogoproto + +## GRPC + +It works the same as golang/protobuf, simply specify the plugin. +Here is an example using gofast: + + protoc --gofast_out=plugins=grpc:. my.proto diff --git a/vendor/github.com/golang/protobuf/README.md b/vendor/github.com/golang/protobuf/README.md new file mode 100644 index 0000000..037fc7c --- /dev/null +++ b/vendor/github.com/golang/protobuf/README.md @@ -0,0 +1,241 @@ +# Go support for Protocol Buffers + +Google's data interchange format. +Copyright 2010 The Go Authors. +https://github.com/golang/protobuf + +This package and the code it generates requires at least Go 1.4. + +This software implements Go bindings for protocol buffers. For +information about protocol buffers themselves, see + https://developers.google.com/protocol-buffers/ + +## Installation ## + +To use this software, you must: +- Install the standard C++ implementation of protocol buffers from + https://developers.google.com/protocol-buffers/ +- Of course, install the Go compiler and tools from + https://golang.org/ + See + https://golang.org/doc/install + for details or, if you are using gccgo, follow the instructions at + https://golang.org/doc/install/gccgo +- Grab the code from the repository and install the proto package. + The simplest way is to run `go get -u github.com/golang/protobuf/{proto,protoc-gen-go}`. + The compiler plugin, protoc-gen-go, will be installed in $GOBIN, + defaulting to $GOPATH/bin. It must be in your $PATH for the protocol + compiler, protoc, to find it. + +This software has two parts: a 'protocol compiler plugin' that +generates Go source files that, once compiled, can access and manage +protocol buffers; and a library that implements run-time support for +encoding (marshaling), decoding (unmarshaling), and accessing protocol +buffers. + +There is support for gRPC in Go using protocol buffers. +See the note at the bottom of this file for details. + +There are no insertion points in the plugin. + + +## Using protocol buffers with Go ## + +Once the software is installed, there are two steps to using it. +First you must compile the protocol buffer definitions and then import +them, with the support library, into your program. + +To compile the protocol buffer definition, run protoc with the --go_out +parameter set to the directory you want to output the Go code to. + + protoc --go_out=. *.proto + +The generated files will be suffixed .pb.go. See the Test code below +for an example using such a file. + + +The package comment for the proto library contains text describing +the interface provided in Go for protocol buffers. Here is an edited +version. + +========== + +The proto package converts data structures to and from the +wire format of protocol buffers. It works in concert with the +Go source code generated for .proto files by the protocol compiler. + +A summary of the properties of the protocol buffer interface +for a protocol buffer variable v: + + - Names are turned from camel_case to CamelCase for export. + - There are no methods on v to set fields; just treat + them as structure fields. + - There are getters that return a field's value if set, + and return the field's default value if unset. + The getters work even if the receiver is a nil message. + - The zero value for a struct is its correct initialization state. + All desired fields must be set before marshaling. + - A Reset() method will restore a protobuf struct to its zero state. + - Non-repeated fields are pointers to the values; nil means unset. + That is, optional or required field int32 f becomes F *int32. + - Repeated fields are slices. + - Helper functions are available to aid the setting of fields. + Helpers for getting values are superseded by the + GetFoo methods and their use is deprecated. + msg.Foo = proto.String("hello") // set field + - Constants are defined to hold the default values of all fields that + have them. They have the form Default_StructName_FieldName. + Because the getter methods handle defaulted values, + direct use of these constants should be rare. + - Enums are given type names and maps from names to values. + Enum values are prefixed with the enum's type name. Enum types have + a String method, and a Enum method to assist in message construction. + - Nested groups and enums have type names prefixed with the name of + the surrounding message type. + - Extensions are given descriptor names that start with E_, + followed by an underscore-delimited list of the nested messages + that contain it (if any) followed by the CamelCased name of the + extension field itself. HasExtension, ClearExtension, GetExtension + and SetExtension are functions for manipulating extensions. + - Oneof field sets are given a single field in their message, + with distinguished wrapper types for each possible field value. + - Marshal and Unmarshal are functions to encode and decode the wire format. + +When the .proto file specifies `syntax="proto3"`, there are some differences: + + - Non-repeated fields of non-message type are values instead of pointers. + - Getters are only generated for message and oneof fields. + - Enum types do not get an Enum method. + +Consider file test.proto, containing + +```proto + package example; + + enum FOO { X = 17; }; + + message Test { + required string label = 1; + optional int32 type = 2 [default=77]; + repeated int64 reps = 3; + optional group OptionalGroup = 4 { + required string RequiredField = 5; + } + } +``` + +To create and play with a Test object from the example package, + +```go + package main + + import ( + "log" + + "github.com/golang/protobuf/proto" + "path/to/example" + ) + + func main() { + test := &example.Test { + Label: proto.String("hello"), + Type: proto.Int32(17), + Reps: []int64{1, 2, 3}, + Optionalgroup: &example.Test_OptionalGroup { + RequiredField: proto.String("good bye"), + }, + } + data, err := proto.Marshal(test) + if err != nil { + log.Fatal("marshaling error: ", err) + } + newTest := &example.Test{} + err = proto.Unmarshal(data, newTest) + if err != nil { + log.Fatal("unmarshaling error: ", err) + } + // Now test and newTest contain the same data. + if test.GetLabel() != newTest.GetLabel() { + log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel()) + } + // etc. + } +``` + +## Parameters ## + +To pass extra parameters to the plugin, use a comma-separated +parameter list separated from the output directory by a colon: + + + protoc --go_out=plugins=grpc,import_path=mypackage:. *.proto + + +- `import_prefix=xxx` - a prefix that is added onto the beginning of + all imports. Useful for things like generating protos in a + subdirectory, or regenerating vendored protobufs in-place. +- `import_path=foo/bar` - used as the package if no input files + declare `go_package`. If it contains slashes, everything up to the + rightmost slash is ignored. +- `plugins=plugin1+plugin2` - specifies the list of sub-plugins to + load. The only plugin in this repo is `grpc`. +- `Mfoo/bar.proto=quux/shme` - declares that foo/bar.proto is + associated with Go package quux/shme. This is subject to the + import_prefix parameter. + +## gRPC Support ## + +If a proto file specifies RPC services, protoc-gen-go can be instructed to +generate code compatible with gRPC (http://www.grpc.io/). To do this, pass +the `plugins` parameter to protoc-gen-go; the usual way is to insert it into +the --go_out argument to protoc: + + protoc --go_out=plugins=grpc:. *.proto + +## Compatibility ## + +The library and the generated code are expected to be stable over time. +However, we reserve the right to make breaking changes without notice for the +following reasons: + +- Security. A security issue in the specification or implementation may come to + light whose resolution requires breaking compatibility. We reserve the right + to address such security issues. +- Unspecified behavior. There are some aspects of the Protocol Buffers + specification that are undefined. Programs that depend on such unspecified + behavior may break in future releases. +- Specification errors or changes. If it becomes necessary to address an + inconsistency, incompleteness, or change in the Protocol Buffers + specification, resolving the issue could affect the meaning or legality of + existing programs. We reserve the right to address such issues, including + updating the implementations. +- Bugs. If the library has a bug that violates the specification, a program + that depends on the buggy behavior may break if the bug is fixed. We reserve + the right to fix such bugs. +- Adding methods or fields to generated structs. These may conflict with field + names that already exist in a schema, causing applications to break. When the + code generator encounters a field in the schema that would collide with a + generated field or method name, the code generator will append an underscore + to the generated field or method name. +- Adding, removing, or changing methods or fields in generated structs that + start with `XXX`. These parts of the generated code are exported out of + necessity, but should not be considered part of the public API. +- Adding, removing, or changing unexported symbols in generated code. + +Any breaking changes outside of these will be announced 6 months in advance to +protobuf@googlegroups.com. + +You should, whenever possible, use generated code created by the `protoc-gen-go` +tool built at the same commit as the `proto` package. The `proto` package +declares package-level constants in the form `ProtoPackageIsVersionX`. +Application code and generated code may depend on one of these constants to +ensure that compilation will fail if the available version of the proto library +is too old. Whenever we make a change to the generated code that requires newer +library support, in the same commit we will increment the version number of the +generated code and declare a new package-level constant whose name incorporates +the latest version number. Removing a compatibility constant is considered a +breaking change and would be subject to the announcement policy stated above. + +The `protoc-gen-go/generator` package exposes a plugin interface, +which is used by the gRPC code generation. This interface is not +supported and is subject to incompatible changes without notice. diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/README.md b/vendor/github.com/matttproud/golang_protobuf_extensions/README.md new file mode 100644 index 0000000..751ee69 --- /dev/null +++ b/vendor/github.com/matttproud/golang_protobuf_extensions/README.md @@ -0,0 +1,20 @@ +# Overview +This repository provides various Protocol Buffer extensions for the Go +language (golang), namely support for record length-delimited message +streaming. + +| Java | Go | +| ------------------------------ | --------------------- | +| MessageLite#parseDelimitedFrom | pbutil.ReadDelimited | +| MessageLite#writeDelimitedTo | pbutil.WriteDelimited | + +Because [Code Review 9102043](https://codereview.appspot.com/9102043/) is +destined to never be merged into mainline (i.e., never be promoted to formal +[goprotobuf features](https://github.com/golang/protobuf)), this repository +will live here in the wild. + +# Documentation +We have [generated Go Doc documentation](http://godoc.org/github.com/matttproud/golang_protobuf_extensions/pbutil) here. + +# Testing +[![Build Status](https://travis-ci.org/matttproud/golang_protobuf_extensions.png?branch=master)](https://travis-ci.org/matttproud/golang_protobuf_extensions) diff --git a/vendor/github.com/nats-io/go-nats-streaming/LICENSE b/vendor/github.com/nats-io/go-nats-streaming/LICENSE deleted file mode 100644 index d5cf6aa..0000000 --- a/vendor/github.com/nats-io/go-nats-streaming/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Apcera Inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/nats-io/go-nats-streaming/pb/protocol.pb.go b/vendor/github.com/nats-io/go-nats-streaming/pb/protocol.pb.go deleted file mode 100644 index e0a3da5..0000000 --- a/vendor/github.com/nats-io/go-nats-streaming/pb/protocol.pb.go +++ /dev/null @@ -1,2794 +0,0 @@ -// Code generated by protoc-gen-gogo. -// source: protocol.proto -// DO NOT EDIT! - -/* - Package pb is a generated protocol buffer package. - - It is generated from these files: - protocol.proto - - It has these top-level messages: - PubMsg - PubAck - MsgProto - Ack - ConnectRequest - ConnectResponse - SubscriptionRequest - SubscriptionResponse - UnsubscribeRequest - CloseRequest - CloseResponse -*/ -package pb - -import proto "github.com/gogo/protobuf/proto" -import fmt "fmt" -import math "math" -import _ "github.com/gogo/protobuf/gogoproto" - -import io "io" - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// Enum for start position type. -type StartPosition int32 - -const ( - StartPosition_NewOnly StartPosition = 0 - StartPosition_LastReceived StartPosition = 1 - StartPosition_TimeDeltaStart StartPosition = 2 - StartPosition_SequenceStart StartPosition = 3 - StartPosition_First StartPosition = 4 -) - -var StartPosition_name = map[int32]string{ - 0: "NewOnly", - 1: "LastReceived", - 2: "TimeDeltaStart", - 3: "SequenceStart", - 4: "First", -} -var StartPosition_value = map[string]int32{ - "NewOnly": 0, - "LastReceived": 1, - "TimeDeltaStart": 2, - "SequenceStart": 3, - "First": 4, -} - -func (x StartPosition) String() string { - return proto.EnumName(StartPosition_name, int32(x)) -} - -// How messages are delivered to the STAN cluster -type PubMsg struct { - ClientID string `protobuf:"bytes,1,opt,name=clientID,proto3" json:"clientID,omitempty"` - Guid string `protobuf:"bytes,2,opt,name=guid,proto3" json:"guid,omitempty"` - Subject string `protobuf:"bytes,3,opt,name=subject,proto3" json:"subject,omitempty"` - Reply string `protobuf:"bytes,4,opt,name=reply,proto3" json:"reply,omitempty"` - Data []byte `protobuf:"bytes,5,opt,name=data,proto3" json:"data,omitempty"` - Sha256 []byte `protobuf:"bytes,10,opt,name=sha256,proto3" json:"sha256,omitempty"` -} - -func (m *PubMsg) Reset() { *m = PubMsg{} } -func (m *PubMsg) String() string { return proto.CompactTextString(m) } -func (*PubMsg) ProtoMessage() {} - -// Used to ACK to publishers -type PubAck struct { - Guid string `protobuf:"bytes,1,opt,name=guid,proto3" json:"guid,omitempty"` - Error string `protobuf:"bytes,2,opt,name=error,proto3" json:"error,omitempty"` -} - -func (m *PubAck) Reset() { *m = PubAck{} } -func (m *PubAck) String() string { return proto.CompactTextString(m) } -func (*PubAck) ProtoMessage() {} - -// Msg struct. Sequence is assigned for global ordering by -// the cluster after the publisher has been acknowledged. -type MsgProto struct { - Sequence uint64 `protobuf:"varint,1,opt,name=sequence,proto3" json:"sequence,omitempty"` - Subject string `protobuf:"bytes,2,opt,name=subject,proto3" json:"subject,omitempty"` - Reply string `protobuf:"bytes,3,opt,name=reply,proto3" json:"reply,omitempty"` - Data []byte `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"` - Timestamp int64 `protobuf:"varint,5,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - Redelivered bool `protobuf:"varint,6,opt,name=redelivered,proto3" json:"redelivered,omitempty"` - CRC32 uint32 `protobuf:"varint,10,opt,name=CRC32,proto3" json:"CRC32,omitempty"` -} - -func (m *MsgProto) Reset() { *m = MsgProto{} } -func (m *MsgProto) String() string { return proto.CompactTextString(m) } -func (*MsgProto) ProtoMessage() {} - -// Ack will deliver an ack for a delivered msg. -type Ack struct { - Subject string `protobuf:"bytes,1,opt,name=subject,proto3" json:"subject,omitempty"` - Sequence uint64 `protobuf:"varint,2,opt,name=sequence,proto3" json:"sequence,omitempty"` -} - -func (m *Ack) Reset() { *m = Ack{} } -func (m *Ack) String() string { return proto.CompactTextString(m) } -func (*Ack) ProtoMessage() {} - -// Connection Request -type ConnectRequest struct { - ClientID string `protobuf:"bytes,1,opt,name=clientID,proto3" json:"clientID,omitempty"` - HeartbeatInbox string `protobuf:"bytes,2,opt,name=heartbeatInbox,proto3" json:"heartbeatInbox,omitempty"` -} - -func (m *ConnectRequest) Reset() { *m = ConnectRequest{} } -func (m *ConnectRequest) String() string { return proto.CompactTextString(m) } -func (*ConnectRequest) ProtoMessage() {} - -// Response to a client connect -type ConnectResponse struct { - PubPrefix string `protobuf:"bytes,1,opt,name=pubPrefix,proto3" json:"pubPrefix,omitempty"` - SubRequests string `protobuf:"bytes,2,opt,name=subRequests,proto3" json:"subRequests,omitempty"` - UnsubRequests string `protobuf:"bytes,3,opt,name=unsubRequests,proto3" json:"unsubRequests,omitempty"` - CloseRequests string `protobuf:"bytes,4,opt,name=closeRequests,proto3" json:"closeRequests,omitempty"` - Error string `protobuf:"bytes,5,opt,name=error,proto3" json:"error,omitempty"` - SubCloseRequests string `protobuf:"bytes,6,opt,name=subCloseRequests,proto3" json:"subCloseRequests,omitempty"` - PublicKey string `protobuf:"bytes,100,opt,name=publicKey,proto3" json:"publicKey,omitempty"` -} - -func (m *ConnectResponse) Reset() { *m = ConnectResponse{} } -func (m *ConnectResponse) String() string { return proto.CompactTextString(m) } -func (*ConnectResponse) ProtoMessage() {} - -// Protocol for a client to subscribe -type SubscriptionRequest struct { - ClientID string `protobuf:"bytes,1,opt,name=clientID,proto3" json:"clientID,omitempty"` - Subject string `protobuf:"bytes,2,opt,name=subject,proto3" json:"subject,omitempty"` - QGroup string `protobuf:"bytes,3,opt,name=qGroup,proto3" json:"qGroup,omitempty"` - Inbox string `protobuf:"bytes,4,opt,name=inbox,proto3" json:"inbox,omitempty"` - MaxInFlight int32 `protobuf:"varint,5,opt,name=maxInFlight,proto3" json:"maxInFlight,omitempty"` - AckWaitInSecs int32 `protobuf:"varint,6,opt,name=ackWaitInSecs,proto3" json:"ackWaitInSecs,omitempty"` - DurableName string `protobuf:"bytes,7,opt,name=durableName,proto3" json:"durableName,omitempty"` - StartPosition StartPosition `protobuf:"varint,10,opt,name=startPosition,proto3,enum=pb.StartPosition" json:"startPosition,omitempty"` - StartSequence uint64 `protobuf:"varint,11,opt,name=startSequence,proto3" json:"startSequence,omitempty"` - StartTimeDelta int64 `protobuf:"varint,12,opt,name=startTimeDelta,proto3" json:"startTimeDelta,omitempty"` -} - -func (m *SubscriptionRequest) Reset() { *m = SubscriptionRequest{} } -func (m *SubscriptionRequest) String() string { return proto.CompactTextString(m) } -func (*SubscriptionRequest) ProtoMessage() {} - -// Response for SubscriptionRequest and UnsubscribeRequests -type SubscriptionResponse struct { - AckInbox string `protobuf:"bytes,2,opt,name=ackInbox,proto3" json:"ackInbox,omitempty"` - Error string `protobuf:"bytes,3,opt,name=error,proto3" json:"error,omitempty"` -} - -func (m *SubscriptionResponse) Reset() { *m = SubscriptionResponse{} } -func (m *SubscriptionResponse) String() string { return proto.CompactTextString(m) } -func (*SubscriptionResponse) ProtoMessage() {} - -// Protocol for a clients to unsubscribe. Will return a SubscriptionResponse -type UnsubscribeRequest struct { - ClientID string `protobuf:"bytes,1,opt,name=clientID,proto3" json:"clientID,omitempty"` - Subject string `protobuf:"bytes,2,opt,name=subject,proto3" json:"subject,omitempty"` - Inbox string `protobuf:"bytes,3,opt,name=inbox,proto3" json:"inbox,omitempty"` - DurableName string `protobuf:"bytes,4,opt,name=durableName,proto3" json:"durableName,omitempty"` -} - -func (m *UnsubscribeRequest) Reset() { *m = UnsubscribeRequest{} } -func (m *UnsubscribeRequest) String() string { return proto.CompactTextString(m) } -func (*UnsubscribeRequest) ProtoMessage() {} - -// Protocol for a client to close a connection -type CloseRequest struct { - ClientID string `protobuf:"bytes,1,opt,name=clientID,proto3" json:"clientID,omitempty"` -} - -func (m *CloseRequest) Reset() { *m = CloseRequest{} } -func (m *CloseRequest) String() string { return proto.CompactTextString(m) } -func (*CloseRequest) ProtoMessage() {} - -// Response for CloseRequest -type CloseResponse struct { - Error string `protobuf:"bytes,1,opt,name=error,proto3" json:"error,omitempty"` -} - -func (m *CloseResponse) Reset() { *m = CloseResponse{} } -func (m *CloseResponse) String() string { return proto.CompactTextString(m) } -func (*CloseResponse) ProtoMessage() {} - -func init() { - proto.RegisterType((*PubMsg)(nil), "pb.PubMsg") - proto.RegisterType((*PubAck)(nil), "pb.PubAck") - proto.RegisterType((*MsgProto)(nil), "pb.MsgProto") - proto.RegisterType((*Ack)(nil), "pb.Ack") - proto.RegisterType((*ConnectRequest)(nil), "pb.ConnectRequest") - proto.RegisterType((*ConnectResponse)(nil), "pb.ConnectResponse") - proto.RegisterType((*SubscriptionRequest)(nil), "pb.SubscriptionRequest") - proto.RegisterType((*SubscriptionResponse)(nil), "pb.SubscriptionResponse") - proto.RegisterType((*UnsubscribeRequest)(nil), "pb.UnsubscribeRequest") - proto.RegisterType((*CloseRequest)(nil), "pb.CloseRequest") - proto.RegisterType((*CloseResponse)(nil), "pb.CloseResponse") - proto.RegisterEnum("pb.StartPosition", StartPosition_name, StartPosition_value) -} -func (m *PubMsg) Marshal() (data []byte, err error) { - size := m.Size() - data = make([]byte, size) - n, err := m.MarshalTo(data) - if err != nil { - return nil, err - } - return data[:n], nil -} - -func (m *PubMsg) MarshalTo(data []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.ClientID) > 0 { - data[i] = 0xa - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.ClientID))) - i += copy(data[i:], m.ClientID) - } - if len(m.Guid) > 0 { - data[i] = 0x12 - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Guid))) - i += copy(data[i:], m.Guid) - } - if len(m.Subject) > 0 { - data[i] = 0x1a - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Subject))) - i += copy(data[i:], m.Subject) - } - if len(m.Reply) > 0 { - data[i] = 0x22 - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Reply))) - i += copy(data[i:], m.Reply) - } - if m.Data != nil { - if len(m.Data) > 0 { - data[i] = 0x2a - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Data))) - i += copy(data[i:], m.Data) - } - } - if m.Sha256 != nil { - if len(m.Sha256) > 0 { - data[i] = 0x52 - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Sha256))) - i += copy(data[i:], m.Sha256) - } - } - return i, nil -} - -func (m *PubAck) Marshal() (data []byte, err error) { - size := m.Size() - data = make([]byte, size) - n, err := m.MarshalTo(data) - if err != nil { - return nil, err - } - return data[:n], nil -} - -func (m *PubAck) MarshalTo(data []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.Guid) > 0 { - data[i] = 0xa - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Guid))) - i += copy(data[i:], m.Guid) - } - if len(m.Error) > 0 { - data[i] = 0x12 - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Error))) - i += copy(data[i:], m.Error) - } - return i, nil -} - -func (m *MsgProto) Marshal() (data []byte, err error) { - size := m.Size() - data = make([]byte, size) - n, err := m.MarshalTo(data) - if err != nil { - return nil, err - } - return data[:n], nil -} - -func (m *MsgProto) MarshalTo(data []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if m.Sequence != 0 { - data[i] = 0x8 - i++ - i = encodeVarintProtocol(data, i, uint64(m.Sequence)) - } - if len(m.Subject) > 0 { - data[i] = 0x12 - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Subject))) - i += copy(data[i:], m.Subject) - } - if len(m.Reply) > 0 { - data[i] = 0x1a - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Reply))) - i += copy(data[i:], m.Reply) - } - if m.Data != nil { - if len(m.Data) > 0 { - data[i] = 0x22 - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Data))) - i += copy(data[i:], m.Data) - } - } - if m.Timestamp != 0 { - data[i] = 0x28 - i++ - i = encodeVarintProtocol(data, i, uint64(m.Timestamp)) - } - if m.Redelivered { - data[i] = 0x30 - i++ - if m.Redelivered { - data[i] = 1 - } else { - data[i] = 0 - } - i++ - } - if m.CRC32 != 0 { - data[i] = 0x50 - i++ - i = encodeVarintProtocol(data, i, uint64(m.CRC32)) - } - return i, nil -} - -func (m *Ack) Marshal() (data []byte, err error) { - size := m.Size() - data = make([]byte, size) - n, err := m.MarshalTo(data) - if err != nil { - return nil, err - } - return data[:n], nil -} - -func (m *Ack) MarshalTo(data []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.Subject) > 0 { - data[i] = 0xa - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Subject))) - i += copy(data[i:], m.Subject) - } - if m.Sequence != 0 { - data[i] = 0x10 - i++ - i = encodeVarintProtocol(data, i, uint64(m.Sequence)) - } - return i, nil -} - -func (m *ConnectRequest) Marshal() (data []byte, err error) { - size := m.Size() - data = make([]byte, size) - n, err := m.MarshalTo(data) - if err != nil { - return nil, err - } - return data[:n], nil -} - -func (m *ConnectRequest) MarshalTo(data []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.ClientID) > 0 { - data[i] = 0xa - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.ClientID))) - i += copy(data[i:], m.ClientID) - } - if len(m.HeartbeatInbox) > 0 { - data[i] = 0x12 - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.HeartbeatInbox))) - i += copy(data[i:], m.HeartbeatInbox) - } - return i, nil -} - -func (m *ConnectResponse) Marshal() (data []byte, err error) { - size := m.Size() - data = make([]byte, size) - n, err := m.MarshalTo(data) - if err != nil { - return nil, err - } - return data[:n], nil -} - -func (m *ConnectResponse) MarshalTo(data []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.PubPrefix) > 0 { - data[i] = 0xa - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.PubPrefix))) - i += copy(data[i:], m.PubPrefix) - } - if len(m.SubRequests) > 0 { - data[i] = 0x12 - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.SubRequests))) - i += copy(data[i:], m.SubRequests) - } - if len(m.UnsubRequests) > 0 { - data[i] = 0x1a - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.UnsubRequests))) - i += copy(data[i:], m.UnsubRequests) - } - if len(m.CloseRequests) > 0 { - data[i] = 0x22 - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.CloseRequests))) - i += copy(data[i:], m.CloseRequests) - } - if len(m.Error) > 0 { - data[i] = 0x2a - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Error))) - i += copy(data[i:], m.Error) - } - if len(m.SubCloseRequests) > 0 { - data[i] = 0x32 - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.SubCloseRequests))) - i += copy(data[i:], m.SubCloseRequests) - } - if len(m.PublicKey) > 0 { - data[i] = 0xa2 - i++ - data[i] = 0x6 - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.PublicKey))) - i += copy(data[i:], m.PublicKey) - } - return i, nil -} - -func (m *SubscriptionRequest) Marshal() (data []byte, err error) { - size := m.Size() - data = make([]byte, size) - n, err := m.MarshalTo(data) - if err != nil { - return nil, err - } - return data[:n], nil -} - -func (m *SubscriptionRequest) MarshalTo(data []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.ClientID) > 0 { - data[i] = 0xa - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.ClientID))) - i += copy(data[i:], m.ClientID) - } - if len(m.Subject) > 0 { - data[i] = 0x12 - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Subject))) - i += copy(data[i:], m.Subject) - } - if len(m.QGroup) > 0 { - data[i] = 0x1a - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.QGroup))) - i += copy(data[i:], m.QGroup) - } - if len(m.Inbox) > 0 { - data[i] = 0x22 - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Inbox))) - i += copy(data[i:], m.Inbox) - } - if m.MaxInFlight != 0 { - data[i] = 0x28 - i++ - i = encodeVarintProtocol(data, i, uint64(m.MaxInFlight)) - } - if m.AckWaitInSecs != 0 { - data[i] = 0x30 - i++ - i = encodeVarintProtocol(data, i, uint64(m.AckWaitInSecs)) - } - if len(m.DurableName) > 0 { - data[i] = 0x3a - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.DurableName))) - i += copy(data[i:], m.DurableName) - } - if m.StartPosition != 0 { - data[i] = 0x50 - i++ - i = encodeVarintProtocol(data, i, uint64(m.StartPosition)) - } - if m.StartSequence != 0 { - data[i] = 0x58 - i++ - i = encodeVarintProtocol(data, i, uint64(m.StartSequence)) - } - if m.StartTimeDelta != 0 { - data[i] = 0x60 - i++ - i = encodeVarintProtocol(data, i, uint64(m.StartTimeDelta)) - } - return i, nil -} - -func (m *SubscriptionResponse) Marshal() (data []byte, err error) { - size := m.Size() - data = make([]byte, size) - n, err := m.MarshalTo(data) - if err != nil { - return nil, err - } - return data[:n], nil -} - -func (m *SubscriptionResponse) MarshalTo(data []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.AckInbox) > 0 { - data[i] = 0x12 - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.AckInbox))) - i += copy(data[i:], m.AckInbox) - } - if len(m.Error) > 0 { - data[i] = 0x1a - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Error))) - i += copy(data[i:], m.Error) - } - return i, nil -} - -func (m *UnsubscribeRequest) Marshal() (data []byte, err error) { - size := m.Size() - data = make([]byte, size) - n, err := m.MarshalTo(data) - if err != nil { - return nil, err - } - return data[:n], nil -} - -func (m *UnsubscribeRequest) MarshalTo(data []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.ClientID) > 0 { - data[i] = 0xa - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.ClientID))) - i += copy(data[i:], m.ClientID) - } - if len(m.Subject) > 0 { - data[i] = 0x12 - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Subject))) - i += copy(data[i:], m.Subject) - } - if len(m.Inbox) > 0 { - data[i] = 0x1a - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Inbox))) - i += copy(data[i:], m.Inbox) - } - if len(m.DurableName) > 0 { - data[i] = 0x22 - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.DurableName))) - i += copy(data[i:], m.DurableName) - } - return i, nil -} - -func (m *CloseRequest) Marshal() (data []byte, err error) { - size := m.Size() - data = make([]byte, size) - n, err := m.MarshalTo(data) - if err != nil { - return nil, err - } - return data[:n], nil -} - -func (m *CloseRequest) MarshalTo(data []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.ClientID) > 0 { - data[i] = 0xa - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.ClientID))) - i += copy(data[i:], m.ClientID) - } - return i, nil -} - -func (m *CloseResponse) Marshal() (data []byte, err error) { - size := m.Size() - data = make([]byte, size) - n, err := m.MarshalTo(data) - if err != nil { - return nil, err - } - return data[:n], nil -} - -func (m *CloseResponse) MarshalTo(data []byte) (int, error) { - var i int - _ = i - var l int - _ = l - if len(m.Error) > 0 { - data[i] = 0xa - i++ - i = encodeVarintProtocol(data, i, uint64(len(m.Error))) - i += copy(data[i:], m.Error) - } - return i, nil -} - -func encodeFixed64Protocol(data []byte, offset int, v uint64) int { - data[offset] = uint8(v) - data[offset+1] = uint8(v >> 8) - data[offset+2] = uint8(v >> 16) - data[offset+3] = uint8(v >> 24) - data[offset+4] = uint8(v >> 32) - data[offset+5] = uint8(v >> 40) - data[offset+6] = uint8(v >> 48) - data[offset+7] = uint8(v >> 56) - return offset + 8 -} -func encodeFixed32Protocol(data []byte, offset int, v uint32) int { - data[offset] = uint8(v) - data[offset+1] = uint8(v >> 8) - data[offset+2] = uint8(v >> 16) - data[offset+3] = uint8(v >> 24) - return offset + 4 -} -func encodeVarintProtocol(data []byte, offset int, v uint64) int { - for v >= 1<<7 { - data[offset] = uint8(v&0x7f | 0x80) - v >>= 7 - offset++ - } - data[offset] = uint8(v) - return offset + 1 -} -func (m *PubMsg) Size() (n int) { - var l int - _ = l - l = len(m.ClientID) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.Guid) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.Subject) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.Reply) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - if m.Data != nil { - l = len(m.Data) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - } - if m.Sha256 != nil { - l = len(m.Sha256) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - } - return n -} - -func (m *PubAck) Size() (n int) { - var l int - _ = l - l = len(m.Guid) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.Error) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - return n -} - -func (m *MsgProto) Size() (n int) { - var l int - _ = l - if m.Sequence != 0 { - n += 1 + sovProtocol(uint64(m.Sequence)) - } - l = len(m.Subject) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.Reply) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - if m.Data != nil { - l = len(m.Data) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - } - if m.Timestamp != 0 { - n += 1 + sovProtocol(uint64(m.Timestamp)) - } - if m.Redelivered { - n += 2 - } - if m.CRC32 != 0 { - n += 1 + sovProtocol(uint64(m.CRC32)) - } - return n -} - -func (m *Ack) Size() (n int) { - var l int - _ = l - l = len(m.Subject) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - if m.Sequence != 0 { - n += 1 + sovProtocol(uint64(m.Sequence)) - } - return n -} - -func (m *ConnectRequest) Size() (n int) { - var l int - _ = l - l = len(m.ClientID) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.HeartbeatInbox) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - return n -} - -func (m *ConnectResponse) Size() (n int) { - var l int - _ = l - l = len(m.PubPrefix) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.SubRequests) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.UnsubRequests) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.CloseRequests) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.Error) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.SubCloseRequests) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.PublicKey) - if l > 0 { - n += 2 + l + sovProtocol(uint64(l)) - } - return n -} - -func (m *SubscriptionRequest) Size() (n int) { - var l int - _ = l - l = len(m.ClientID) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.Subject) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.QGroup) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.Inbox) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - if m.MaxInFlight != 0 { - n += 1 + sovProtocol(uint64(m.MaxInFlight)) - } - if m.AckWaitInSecs != 0 { - n += 1 + sovProtocol(uint64(m.AckWaitInSecs)) - } - l = len(m.DurableName) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - if m.StartPosition != 0 { - n += 1 + sovProtocol(uint64(m.StartPosition)) - } - if m.StartSequence != 0 { - n += 1 + sovProtocol(uint64(m.StartSequence)) - } - if m.StartTimeDelta != 0 { - n += 1 + sovProtocol(uint64(m.StartTimeDelta)) - } - return n -} - -func (m *SubscriptionResponse) Size() (n int) { - var l int - _ = l - l = len(m.AckInbox) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.Error) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - return n -} - -func (m *UnsubscribeRequest) Size() (n int) { - var l int - _ = l - l = len(m.ClientID) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.Subject) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.Inbox) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - l = len(m.DurableName) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - return n -} - -func (m *CloseRequest) Size() (n int) { - var l int - _ = l - l = len(m.ClientID) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - return n -} - -func (m *CloseResponse) Size() (n int) { - var l int - _ = l - l = len(m.Error) - if l > 0 { - n += 1 + l + sovProtocol(uint64(l)) - } - return n -} - -func sovProtocol(x uint64) (n int) { - for { - n++ - x >>= 7 - if x == 0 { - break - } - } - return n -} -func sozProtocol(x uint64) (n int) { - return sovProtocol(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *PubMsg) Unmarshal(data []byte) error { - l := len(data) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PubMsg: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PubMsg: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClientID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ClientID = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Guid", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Guid = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Subject", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Subject = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Reply", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Reply = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - byteLen |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + byteLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], data[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - iNdEx = postIndex - case 10: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Sha256", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - byteLen |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + byteLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Sha256 = append(m.Sha256[:0], data[iNdEx:postIndex]...) - if m.Sha256 == nil { - m.Sha256 = []byte{} - } - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProtocol(data[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthProtocol - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *PubAck) Unmarshal(data []byte) error { - l := len(data) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: PubAck: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: PubAck: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Guid", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Guid = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Error = string(data[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProtocol(data[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthProtocol - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *MsgProto) Unmarshal(data []byte) error { - l := len(data) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: MsgProto: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: MsgProto: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) - } - m.Sequence = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - m.Sequence |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Subject", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Subject = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Reply", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Reply = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Data", wireType) - } - var byteLen int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - byteLen |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - if byteLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + byteLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Data = append(m.Data[:0], data[iNdEx:postIndex]...) - if m.Data == nil { - m.Data = []byte{} - } - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Timestamp", wireType) - } - m.Timestamp = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - m.Timestamp |= (int64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 6: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Redelivered", wireType) - } - var v int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - v |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - m.Redelivered = bool(v != 0) - case 10: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field CRC32", wireType) - } - m.CRC32 = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - m.CRC32 |= (uint32(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipProtocol(data[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthProtocol - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *Ack) Unmarshal(data []byte) error { - l := len(data) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: Ack: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: Ack: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Subject", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Subject = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field Sequence", wireType) - } - m.Sequence = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - m.Sequence |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipProtocol(data[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthProtocol - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ConnectRequest) Unmarshal(data []byte) error { - l := len(data) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ConnectRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ConnectRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClientID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ClientID = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field HeartbeatInbox", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.HeartbeatInbox = string(data[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProtocol(data[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthProtocol - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *ConnectResponse) Unmarshal(data []byte) error { - l := len(data) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: ConnectResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: ConnectResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PubPrefix", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PubPrefix = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SubRequests", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SubRequests = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field UnsubRequests", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.UnsubRequests = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field CloseRequests", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.CloseRequests = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Error = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 6: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field SubCloseRequests", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.SubCloseRequests = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 100: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field PublicKey", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.PublicKey = string(data[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProtocol(data[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthProtocol - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *SubscriptionRequest) Unmarshal(data []byte) error { - l := len(data) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: SubscriptionRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SubscriptionRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClientID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ClientID = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Subject", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Subject = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field QGroup", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.QGroup = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Inbox", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Inbox = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 5: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field MaxInFlight", wireType) - } - m.MaxInFlight = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - m.MaxInFlight |= (int32(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 6: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field AckWaitInSecs", wireType) - } - m.AckWaitInSecs = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - m.AckWaitInSecs |= (int32(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 7: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DurableName", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DurableName = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 10: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field StartPosition", wireType) - } - m.StartPosition = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - m.StartPosition |= (StartPosition(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 11: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field StartSequence", wireType) - } - m.StartSequence = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - m.StartSequence |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - case 12: - if wireType != 0 { - return fmt.Errorf("proto: wrong wireType = %d for field StartTimeDelta", wireType) - } - m.StartTimeDelta = 0 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - m.StartTimeDelta |= (int64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - default: - iNdEx = preIndex - skippy, err := skipProtocol(data[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthProtocol - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *SubscriptionResponse) Unmarshal(data []byte) error { - l := len(data) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: SubscriptionResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: SubscriptionResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field AckInbox", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.AckInbox = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Error = string(data[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProtocol(data[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthProtocol - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *UnsubscribeRequest) Unmarshal(data []byte) error { - l := len(data) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: UnsubscribeRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: UnsubscribeRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClientID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ClientID = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 2: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Subject", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Subject = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 3: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Inbox", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Inbox = string(data[iNdEx:postIndex]) - iNdEx = postIndex - case 4: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field DurableName", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.DurableName = string(data[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProtocol(data[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthProtocol - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CloseRequest) Unmarshal(data []byte) error { - l := len(data) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CloseRequest: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CloseRequest: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ClientID", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.ClientID = string(data[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProtocol(data[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthProtocol - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func (m *CloseResponse) Unmarshal(data []byte) error { - l := len(data) - iNdEx := 0 - for iNdEx < l { - preIndex := iNdEx - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - fieldNum := int32(wire >> 3) - wireType := int(wire & 0x7) - if wireType == 4 { - return fmt.Errorf("proto: CloseResponse: wiretype end group for non-group") - } - if fieldNum <= 0 { - return fmt.Errorf("proto: CloseResponse: illegal tag %d (wire type %d)", fieldNum, wire) - } - switch fieldNum { - case 1: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field Error", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowProtocol - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - stringLen |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthProtocol - } - postIndex := iNdEx + intStringLen - if postIndex > l { - return io.ErrUnexpectedEOF - } - m.Error = string(data[iNdEx:postIndex]) - iNdEx = postIndex - default: - iNdEx = preIndex - skippy, err := skipProtocol(data[iNdEx:]) - if err != nil { - return err - } - if skippy < 0 { - return ErrInvalidLengthProtocol - } - if (iNdEx + skippy) > l { - return io.ErrUnexpectedEOF - } - iNdEx += skippy - } - } - - if iNdEx > l { - return io.ErrUnexpectedEOF - } - return nil -} -func skipProtocol(data []byte) (n int, err error) { - l := len(data) - iNdEx := 0 - for iNdEx < l { - var wire uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProtocol - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - wire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - wireType := int(wire & 0x7) - switch wireType { - case 0: - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProtocol - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - iNdEx++ - if data[iNdEx-1] < 0x80 { - break - } - } - return iNdEx, nil - case 1: - iNdEx += 8 - return iNdEx, nil - case 2: - var length int - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProtocol - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - length |= (int(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - iNdEx += length - if length < 0 { - return 0, ErrInvalidLengthProtocol - } - return iNdEx, nil - case 3: - for { - var innerWire uint64 - var start int = iNdEx - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return 0, ErrIntOverflowProtocol - } - if iNdEx >= l { - return 0, io.ErrUnexpectedEOF - } - b := data[iNdEx] - iNdEx++ - innerWire |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - break - } - } - innerWireType := int(innerWire & 0x7) - if innerWireType == 4 { - break - } - next, err := skipProtocol(data[start:]) - if err != nil { - return 0, err - } - iNdEx = start + next - } - return iNdEx, nil - case 4: - return iNdEx, nil - case 5: - iNdEx += 4 - return iNdEx, nil - default: - return 0, fmt.Errorf("proto: illegal wireType %d", wireType) - } - } - panic("unreachable") -} - -var ( - ErrInvalidLengthProtocol = fmt.Errorf("proto: negative length found during unmarshaling") - ErrIntOverflowProtocol = fmt.Errorf("proto: integer overflow") -) diff --git a/vendor/github.com/nats-io/go-nats-streaming/pb/protocol.proto b/vendor/github.com/nats-io/go-nats-streaming/pb/protocol.proto deleted file mode 100644 index a1eea67..0000000 --- a/vendor/github.com/nats-io/go-nats-streaming/pb/protocol.proto +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2016 Apcera Inc. All rights reserved. -// -// Uses https://github.com/gogo/protobuf -// compiled via `protoc -I=. -I=$GOPATH/src --gogofaster_out=. protocol.proto` - -syntax = "proto3"; -package pb; - -import "github.com/gogo/protobuf/gogoproto/gogo.proto"; - -option (gogoproto.marshaler_all) = true; -option (gogoproto.sizer_all) = true; -option (gogoproto.unmarshaler_all) = true; -option (gogoproto.goproto_getters_all) = false; - -// How messages are delivered to the STAN cluster -message PubMsg { - string clientID = 1; // ClientID - string guid = 2; // guid - string subject = 3; // subject - string reply = 4; // optional reply - bytes data = 5; // payload - - bytes sha256 = 10; // optional sha256 of data -} - -// Used to ACK to publishers -message PubAck { - string guid = 1; // guid - string error = 2; // err string, empty/omitted if no error -} - -// Msg struct. Sequence is assigned for global ordering by -// the cluster after the publisher has been acknowledged. -message MsgProto { - uint64 sequence = 1; // globally ordered sequence number for the subject's channel - string subject = 2; // subject - string reply = 3; // optional reply - bytes data = 4; // payload - int64 timestamp = 5; // received timestamp - bool redelivered = 6; // Flag specifying if the message is being redelivered - - uint32 CRC32 = 10; // optional IEEE CRC32 -} - -// Ack will deliver an ack for a delivered msg. -message Ack { - string subject = 1; // Subject - uint64 sequence = 2; // Sequence to acknowledge -} - -// Connection Request -message ConnectRequest { - string clientID = 1; // Client name/identifier. - string heartbeatInbox = 2; // Inbox for server initiated heartbeats. -} - -// Response to a client connect -message ConnectResponse { - string pubPrefix = 1; // Prefix to use when publishing to this STAN cluster - string subRequests = 2; // Subject to use for subscription requests - string unsubRequests = 3; // Subject to use for unsubscribe requests - string closeRequests = 4; // Subject for closing the stan connection - string error = 5; // err string, empty/omitted if no error - string subCloseRequests = 6; // Subject to use for subscription close requests - - string publicKey = 100; // Possibly used to sign acks, etc. -} - -// Enum for start position type. -enum StartPosition { - NewOnly = 0; - LastReceived = 1; - TimeDeltaStart = 2; - SequenceStart = 3; - First = 4; - } - -// Protocol for a client to subscribe -message SubscriptionRequest { - string clientID = 1; // ClientID - string subject = 2; // Formal subject to subscribe to, e.g. foo.bar - string qGroup = 3; // Optional queue group - string inbox = 4; // Inbox subject to deliver messages on - int32 maxInFlight = 5; // Maximum inflight messages without an ack allowed - int32 ackWaitInSecs = 6; // Timeout for receiving an ack from the client - string durableName = 7; // Optional durable name which survives client restarts - StartPosition startPosition = 10; // Start position - uint64 startSequence = 11; // Optional start sequence number - int64 startTimeDelta = 12; // Optional start time -} - -// Response for SubscriptionRequest and UnsubscribeRequests -message SubscriptionResponse { - string ackInbox = 2; // ackInbox for sending acks - string error = 3; // err string, empty/omitted if no error -} - -// Protocol for a clients to unsubscribe. Will return a SubscriptionResponse -message UnsubscribeRequest { - string clientID = 1; // ClientID - string subject = 2; // subject for the subscription - string inbox = 3; // Inbox subject to identify subscription - string durableName = 4; // Optional durable name which survives client restarts -} - -// Protocol for a client to close a connection -message CloseRequest { - string clientID = 1; // Client name provided to Connect() requests -} - -// Response for CloseRequest -message CloseResponse { - string error = 1; // err string, empty/omitted if no error -} diff --git a/vendor/github.com/nats-io/go-nats-streaming/stan.go b/vendor/github.com/nats-io/go-nats-streaming/stan.go deleted file mode 100644 index 248f5ee..0000000 --- a/vendor/github.com/nats-io/go-nats-streaming/stan.go +++ /dev/null @@ -1,476 +0,0 @@ -// Copyright 2016 Apcera Inc. All rights reserved. - -// Package stan is a Go client for the NATS Streaming messaging system (https://nats.io). -package stan - -import ( - "errors" - "fmt" - "runtime" - "sync" - "time" - - "github.com/nats-io/go-nats" - "github.com/nats-io/go-nats-streaming/pb" - "github.com/nats-io/nuid" -) - -// Version is the NATS Streaming Go Client version -const Version = "0.3.4" - -const ( - // DefaultNatsURL is the default URL the client connects to - DefaultNatsURL = "nats://localhost:4222" - // DefaultConnectWait is the default timeout used for the connect operation - DefaultConnectWait = 2 * time.Second - // DefaultDiscoverPrefix is the prefix subject used to connect to the NATS Streaming server - DefaultDiscoverPrefix = "_STAN.discover" - // DefaultACKPrefix is the prefix subject used to send ACKs to the NATS Streaming server - DefaultACKPrefix = "_STAN.acks" - // DefaultMaxPubAcksInflight is the default maximum number of published messages - // without outstanding ACKs from the server - DefaultMaxPubAcksInflight = 16384 -) - -// Conn represents a connection to the NATS Streaming subsystem. It can Publish and -// Subscribe to messages within the NATS Streaming cluster. -type Conn interface { - // Publish - Publish(subject string, data []byte) error - PublishAsync(subject string, data []byte, ah AckHandler) (string, error) - - // Subscribe - Subscribe(subject string, cb MsgHandler, opts ...SubscriptionOption) (Subscription, error) - - // QueueSubscribe - QueueSubscribe(subject, qgroup string, cb MsgHandler, opts ...SubscriptionOption) (Subscription, error) - - // Close - Close() error - - // NatsConn returns the underlying NATS conn. Use this with care. For - // example, closing the wrapped NATS conn will put the NATS Streaming Conn - // in an invalid state. - NatsConn() *nats.Conn -} - -// Errors -var ( - ErrConnectReqTimeout = errors.New("stan: connect request timeout") - ErrCloseReqTimeout = errors.New("stan: close request timeout") - ErrSubReqTimeout = errors.New("stan: subscribe request timeout") - ErrUnsubReqTimeout = errors.New("stan: unsubscribe request timeout") - ErrConnectionClosed = errors.New("stan: connection closed") - ErrTimeout = errors.New("stan: publish ack timeout") - ErrBadAck = errors.New("stan: malformed ack") - ErrBadSubscription = errors.New("stan: invalid subscription") - ErrBadConnection = errors.New("stan: invalid connection") - ErrManualAck = errors.New("stan: cannot manually ack in auto-ack mode") - ErrNilMsg = errors.New("stan: nil message") - ErrNoServerSupport = errors.New("stan: not supported by server") -) - -// AckHandler is used for Async Publishing to provide status of the ack. -// The func will be passed teh GUID and any error state. No error means the -// message was successfully received by NATS Streaming. -type AckHandler func(string, error) - -// Options can be used to a create a customized connection. -type Options struct { - NatsURL string - NatsConn *nats.Conn - ConnectTimeout time.Duration - AckTimeout time.Duration - DiscoverPrefix string - MaxPubAcksInflight int -} - -// DefaultOptions are the NATS Streaming client's default options -var DefaultOptions = Options{ - NatsURL: DefaultNatsURL, - ConnectTimeout: DefaultConnectWait, - AckTimeout: DefaultAckWait, - DiscoverPrefix: DefaultDiscoverPrefix, - MaxPubAcksInflight: DefaultMaxPubAcksInflight, -} - -// Option is a function on the options for a connection. -type Option func(*Options) error - -// NatsURL is an Option to set the URL the client should connect to. -func NatsURL(u string) Option { - return func(o *Options) error { - o.NatsURL = u - return nil - } -} - -// ConnectWait is an Option to set the timeout for establishing a connection. -func ConnectWait(t time.Duration) Option { - return func(o *Options) error { - o.ConnectTimeout = t - return nil - } -} - -// PubAckWait is an Option to set the timeout for waiting for an ACK for a -// published message. -func PubAckWait(t time.Duration) Option { - return func(o *Options) error { - o.AckTimeout = t - return nil - } -} - -// MaxPubAcksInflight is an Option to set the maximum number of published -// messages without outstanding ACKs from the server. -func MaxPubAcksInflight(max int) Option { - return func(o *Options) error { - o.MaxPubAcksInflight = max - return nil - } -} - -// NatsConn is an Option to set the underlying NATS connection to be used -// by a NATS Streaming Conn object. -func NatsConn(nc *nats.Conn) Option { - return func(o *Options) error { - o.NatsConn = nc - return nil - } -} - -// A conn represents a bare connection to a stan cluster. -type conn struct { - sync.RWMutex - clientID string - serverID string - pubPrefix string // Publish prefix set by stan, append our subject. - subRequests string // Subject to send subscription requests. - unsubRequests string // Subject to send unsubscribe requests. - subCloseRequests string // Subject to send subscription close requests. - closeRequests string // Subject to send close requests. - ackSubject string // publish acks - ackSubscription *nats.Subscription - hbSubscription *nats.Subscription - subMap map[string]*subscription - pubAckMap map[string]*ack - pubAckChan chan (struct{}) - opts Options - nc *nats.Conn - ncOwned bool // NATS Streaming created the connection, so needs to close it. -} - -// Closure for ack contexts. -type ack struct { - t *time.Timer - ah AckHandler - ch chan error -} - -// Connect will form a connection to the NATS Streaming subsystem. -func Connect(stanClusterID, clientID string, options ...Option) (Conn, error) { - // Process Options - c := conn{clientID: clientID, opts: DefaultOptions} - for _, opt := range options { - if err := opt(&c.opts); err != nil { - return nil, err - } - } - // Check if the user has provided a connection as an option - c.nc = c.opts.NatsConn - // Create a NATS connection if it doesn't exist. - if c.nc == nil { - nc, err := nats.Connect(c.opts.NatsURL) - if err != nil { - return nil, err - } - c.nc = nc - c.ncOwned = true - } else if !c.nc.IsConnected() { - // Bail if the custom NATS connection is disconnected - return nil, ErrBadConnection - } - - // Create a heartbeat inbox - hbInbox := nats.NewInbox() - var err error - if c.hbSubscription, err = c.nc.Subscribe(hbInbox, c.processHeartBeat); err != nil { - c.Close() - return nil, err - } - - // Send Request to discover the cluster - discoverSubject := c.opts.DiscoverPrefix + "." + stanClusterID - req := &pb.ConnectRequest{ClientID: clientID, HeartbeatInbox: hbInbox} - b, _ := req.Marshal() - reply, err := c.nc.Request(discoverSubject, b, c.opts.ConnectTimeout) - if err != nil { - c.Close() - if err == nats.ErrTimeout { - return nil, ErrConnectReqTimeout - } - return nil, err - } - // Process the response, grab server pubPrefix - cr := &pb.ConnectResponse{} - err = cr.Unmarshal(reply.Data) - if err != nil { - c.Close() - return nil, err - } - if cr.Error != "" { - c.Close() - return nil, errors.New(cr.Error) - } - - // Capture cluster configuration endpoints to publish and subscribe/unsubscribe. - c.pubPrefix = cr.PubPrefix - c.subRequests = cr.SubRequests - c.unsubRequests = cr.UnsubRequests - c.subCloseRequests = cr.SubCloseRequests - c.closeRequests = cr.CloseRequests - - // Setup the ACK subscription - c.ackSubject = DefaultACKPrefix + "." + nuid.Next() - if c.ackSubscription, err = c.nc.Subscribe(c.ackSubject, c.processAck); err != nil { - c.Close() - return nil, err - } - c.ackSubscription.SetPendingLimits(1024*1024, 32*1024*1024) - c.pubAckMap = make(map[string]*ack) - - // Create Subscription map - c.subMap = make(map[string]*subscription) - - c.pubAckChan = make(chan struct{}, c.opts.MaxPubAcksInflight) - - // Attach a finalizer - runtime.SetFinalizer(&c, func(sc *conn) { sc.Close() }) - - return &c, nil -} - -// Close a connection to the stan system. -func (sc *conn) Close() error { - if sc == nil { - return ErrBadConnection - } - - sc.Lock() - defer sc.Unlock() - - if sc.nc == nil { - // We are already closed. - return nil - } - - // Capture for NATS calls below. - nc := sc.nc - if sc.ncOwned { - defer nc.Close() - } - - // Signals we are closed. - sc.nc = nil - - // Now close ourselves. - if sc.ackSubscription != nil { - sc.ackSubscription.Unsubscribe() - } - - req := &pb.CloseRequest{ClientID: sc.clientID} - b, _ := req.Marshal() - reply, err := nc.Request(sc.closeRequests, b, sc.opts.ConnectTimeout) - if err != nil { - if err == nats.ErrTimeout { - return ErrCloseReqTimeout - } - return err - } - cr := &pb.CloseResponse{} - err = cr.Unmarshal(reply.Data) - if err != nil { - return err - } - if cr.Error != "" { - return errors.New(cr.Error) - } - return nil -} - -// NatsConn returns the underlying NATS conn. Use this with care. For example, -// closing the wrapped NATS conn will put the NATS Streaming Conn in an invalid -// state. -func (sc *conn) NatsConn() *nats.Conn { - return sc.nc -} - -// Process a heartbeat from the NATS Streaming cluster -func (sc *conn) processHeartBeat(m *nats.Msg) { - // No payload assumed, just reply. - sc.RLock() - nc := sc.nc - sc.RUnlock() - if nc != nil { - nc.Publish(m.Reply, nil) - } -} - -// Process an ack from the NATS Streaming cluster -func (sc *conn) processAck(m *nats.Msg) { - pa := &pb.PubAck{} - err := pa.Unmarshal(m.Data) - if err != nil { - // FIXME, make closure to have context? - fmt.Printf("Error processing unmarshal\n") - return - } - - // Remove - a := sc.removeAck(pa.Guid) - if a != nil { - // Capture error if it exists. - if pa.Error != "" { - err = errors.New(pa.Error) - } - if a.ah != nil { - // Perform the ackHandler callback - a.ah(pa.Guid, err) - } else if a.ch != nil { - // Send to channel directly - a.ch <- err - } - } -} - -// Publish will publish to the cluster and wait for an ACK. -func (sc *conn) Publish(subject string, data []byte) error { - ch := make(chan error) - _, err := sc.publishAsync(subject, data, nil, ch) - if err == nil { - err = <-ch - } - return err -} - -// PublishAsync will publish to the cluster on pubPrefix+subject and asynchronously -// process the ACK or error state. It will return the GUID for the message being sent. -func (sc *conn) PublishAsync(subject string, data []byte, ah AckHandler) (string, error) { - return sc.publishAsync(subject, data, ah, nil) -} - -func (sc *conn) publishAsync(subject string, data []byte, ah AckHandler, ch chan error) (string, error) { - a := &ack{ah: ah, ch: ch} - sc.Lock() - if sc.nc == nil { - sc.Unlock() - return "", ErrConnectionClosed - } - - subj := sc.pubPrefix + "." + subject - // This is only what we need from PubMsg in the timer below, - // so do this so that pe doesn't escape (and we same on new object) - peGUID := nuid.Next() - pe := &pb.PubMsg{ClientID: sc.clientID, Guid: peGUID, Subject: subject, Data: data} - b, _ := pe.Marshal() - - // Map ack to guid. - sc.pubAckMap[peGUID] = a - // snapshot - ackSubject := sc.ackSubject - ackTimeout := sc.opts.AckTimeout - pac := sc.pubAckChan - sc.Unlock() - - // Use the buffered channel to control the number of outstanding acks. - pac <- struct{}{} - - err := sc.nc.PublishRequest(subj, ackSubject, b) - if err != nil { - sc.removeAck(peGUID) - return "", err - } - - // Setup the timer for expiration. - sc.Lock() - a.t = time.AfterFunc(ackTimeout, func() { - sc.removeAck(peGUID) - if a.ah != nil { - ah(peGUID, ErrTimeout) - } else if a.ch != nil { - a.ch <- ErrTimeout - } - }) - sc.Unlock() - - return peGUID, nil -} - -// removeAck removes the ack from the pubAckMap and cancels any state, e.g. timers -func (sc *conn) removeAck(guid string) *ack { - var t *time.Timer - sc.Lock() - a := sc.pubAckMap[guid] - if a != nil { - t = a.t - delete(sc.pubAckMap, guid) - } - pac := sc.pubAckChan - sc.Unlock() - - // Cancel timer if needed. - if t != nil { - t.Stop() - } - - // Remove from channel to unblock PublishAsync - if a != nil && len(pac) > 0 { - <-pac - } - return a -} - -// Process an msg from the NATS Streaming cluster -func (sc *conn) processMsg(raw *nats.Msg) { - msg := &Msg{} - err := msg.Unmarshal(raw.Data) - if err != nil { - panic("Error processing unmarshal for msg") - } - // Lookup the subscription - sc.RLock() - nc := sc.nc - isClosed := nc == nil - sub := sc.subMap[raw.Subject] - sc.RUnlock() - - // Check if sub is no longer valid or connection has been closed. - if sub == nil || isClosed { - return - } - - // Store in msg for backlink - msg.Sub = sub - - sub.RLock() - cb := sub.cb - ackSubject := sub.ackInbox - isManualAck := sub.opts.ManualAcks - subsc := sub.sc // Can be nil if sub has been unsubscribed. - sub.RUnlock() - - // Perform the callback - if cb != nil && subsc != nil { - cb(msg) - } - - // Proces auto-ack - if !isManualAck && nc != nil { - ack := &pb.Ack{Subject: msg.Subject, Sequence: msg.Sequence} - b, _ := ack.Marshal() - if err := nc.Publish(ackSubject, b); err != nil { - // FIXME(dlc) - Async error handler? Retry? - } - } -} diff --git a/vendor/github.com/nats-io/go-nats-streaming/sub.go b/vendor/github.com/nats-io/go-nats-streaming/sub.go deleted file mode 100644 index b545ac7..0000000 --- a/vendor/github.com/nats-io/go-nats-streaming/sub.go +++ /dev/null @@ -1,376 +0,0 @@ -// Copyright 2016 Apcera Inc. All rights reserved. - -// Package stan is a Go client for the NATS Streaming messaging system (https://nats.io). -package stan - -import ( - "errors" - "sync" - "time" - - "github.com/nats-io/go-nats" - "github.com/nats-io/go-nats-streaming/pb" -) - -const ( - // DefaultAckWait indicates how long the server should wait for an ACK before resending a message - DefaultAckWait = 30 * time.Second - // DefaultMaxInflight indicates how many messages with outstanding ACKs the server can send - DefaultMaxInflight = 1024 -) - -// Msg is the client defined message, which includes proto, then back link to subscription. -type Msg struct { - pb.MsgProto // MsgProto: Seq, Subject, Reply[opt], Data, Timestamp, CRC32[opt] - Sub Subscription -} - -// Subscriptions and Options - -// Subscription represents a subscription within the NATS Streaming cluster. Subscriptions -// will be rate matched and follow at-least delivery semantics. -type Subscription interface { - // Unsubscribe removes interest in the subscription. - // For durables, it means that the durable interest is also removed from - // the server. Restarting a durable with the same name will not resume - // the subscription, it will be considered a new one. - Unsubscribe() error - - // Close removes this subscriber from the server, but unlike Unsubscribe(), - // the durable interest is not removed. If the client has connected to a server - // for which this feature is not available, Close() will return a ErrNoServerSupport - // error. - Close() error -} - -// A subscription represents a subscription to a stan cluster. -type subscription struct { - sync.RWMutex - sc *conn - subject string - qgroup string - inbox string - ackInbox string - inboxSub *nats.Subscription - opts SubscriptionOptions - cb MsgHandler -} - -// SubscriptionOption is a function on the options for a subscription. -type SubscriptionOption func(*SubscriptionOptions) error - -// MsgHandler is a callback function that processes messages delivered to -// asynchronous subscribers. -type MsgHandler func(msg *Msg) - -// SubscriptionOptions are used to control the Subscription's behavior. -type SubscriptionOptions struct { - // DurableName, if set will survive client restarts. - DurableName string - // Controls the number of messages the cluster will have inflight without an ACK. - MaxInflight int - // Controls the time the cluster will wait for an ACK for a given message. - AckWait time.Duration - // StartPosition enum from proto. - StartAt pb.StartPosition - // Optional start sequence number. - StartSequence uint64 - // Optional start time. - StartTime time.Time - // Option to do Manual Acks - ManualAcks bool -} - -// DefaultSubscriptionOptions are the default subscriptions' options -var DefaultSubscriptionOptions = SubscriptionOptions{ - MaxInflight: DefaultMaxInflight, - AckWait: DefaultAckWait, -} - -// MaxInflight is an Option to set the maximum number of messages the cluster will send -// without an ACK. -func MaxInflight(m int) SubscriptionOption { - return func(o *SubscriptionOptions) error { - o.MaxInflight = m - return nil - } -} - -// AckWait is an Option to set the timeout for waiting for an ACK from the cluster's -// point of view for delivered messages. -func AckWait(t time.Duration) SubscriptionOption { - return func(o *SubscriptionOptions) error { - o.AckWait = t - return nil - } -} - -// StartAt sets the desired start position for the message stream. -func StartAt(sp pb.StartPosition) SubscriptionOption { - return func(o *SubscriptionOptions) error { - o.StartAt = sp - return nil - } -} - -// StartAtSequence sets the desired start sequence position and state. -func StartAtSequence(seq uint64) SubscriptionOption { - return func(o *SubscriptionOptions) error { - o.StartAt = pb.StartPosition_SequenceStart - o.StartSequence = seq - return nil - } -} - -// StartAtTime sets the desired start time position and state. -func StartAtTime(start time.Time) SubscriptionOption { - return func(o *SubscriptionOptions) error { - o.StartAt = pb.StartPosition_TimeDeltaStart - o.StartTime = start - return nil - } -} - -// StartAtTimeDelta sets the desired start time position and state using the delta. -func StartAtTimeDelta(ago time.Duration) SubscriptionOption { - return func(o *SubscriptionOptions) error { - o.StartAt = pb.StartPosition_TimeDeltaStart - o.StartTime = time.Now().Add(-ago) - return nil - } -} - -// StartWithLastReceived is a helper function to set start position to last received. -func StartWithLastReceived() SubscriptionOption { - return func(o *SubscriptionOptions) error { - o.StartAt = pb.StartPosition_LastReceived - return nil - } -} - -// DeliverAllAvailable will deliver all messages available. -func DeliverAllAvailable() SubscriptionOption { - return func(o *SubscriptionOptions) error { - o.StartAt = pb.StartPosition_First - return nil - } -} - -// SetManualAckMode will allow clients to control their own acks to delivered messages. -func SetManualAckMode() SubscriptionOption { - return func(o *SubscriptionOptions) error { - o.ManualAcks = true - return nil - } -} - -// DurableName sets the DurableName for the subcriber. -func DurableName(name string) SubscriptionOption { - return func(o *SubscriptionOptions) error { - o.DurableName = name - return nil - } -} - -// Subscribe will perform a subscription with the given options to the NATS Streaming cluster. -func (sc *conn) Subscribe(subject string, cb MsgHandler, options ...SubscriptionOption) (Subscription, error) { - return sc.subscribe(subject, "", cb, options...) -} - -// QueueSubscribe will perform a queue subscription with the given options to the NATS Streaming cluster. -func (sc *conn) QueueSubscribe(subject, qgroup string, cb MsgHandler, options ...SubscriptionOption) (Subscription, error) { - return sc.subscribe(subject, qgroup, cb, options...) -} - -// subscribe will perform a subscription with the given options to the NATS Streaming cluster. -func (sc *conn) subscribe(subject, qgroup string, cb MsgHandler, options ...SubscriptionOption) (Subscription, error) { - sub := &subscription{subject: subject, qgroup: qgroup, inbox: nats.NewInbox(), cb: cb, sc: sc, opts: DefaultSubscriptionOptions} - for _, opt := range options { - if err := opt(&sub.opts); err != nil { - return nil, err - } - } - sc.Lock() - if sc.nc == nil { - sc.Unlock() - return nil, ErrConnectionClosed - } - - // Register subscription. - sc.subMap[sub.inbox] = sub - nc := sc.nc - sc.Unlock() - - // Hold lock throughout. - sub.Lock() - defer sub.Unlock() - - // Listen for actual messages. - nsub, err := nc.Subscribe(sub.inbox, sc.processMsg) - if err != nil { - return nil, err - } - sub.inboxSub = nsub - - // Create a subscription request - // FIXME(dlc) add others. - sr := &pb.SubscriptionRequest{ - ClientID: sc.clientID, - Subject: subject, - QGroup: qgroup, - Inbox: sub.inbox, - MaxInFlight: int32(sub.opts.MaxInflight), - AckWaitInSecs: int32(sub.opts.AckWait / time.Second), - StartPosition: sub.opts.StartAt, - DurableName: sub.opts.DurableName, - } - - // Conditionals - switch sr.StartPosition { - case pb.StartPosition_TimeDeltaStart: - sr.StartTimeDelta = time.Now().UnixNano() - sub.opts.StartTime.UnixNano() - case pb.StartPosition_SequenceStart: - sr.StartSequence = sub.opts.StartSequence - } - - b, _ := sr.Marshal() - reply, err := sc.nc.Request(sc.subRequests, b, sc.opts.ConnectTimeout) - if err != nil { - sub.inboxSub.Unsubscribe() - if err == nats.ErrTimeout { - err = ErrSubReqTimeout - } - return nil, err - } - r := &pb.SubscriptionResponse{} - if err := r.Unmarshal(reply.Data); err != nil { - sub.inboxSub.Unsubscribe() - return nil, err - } - if r.Error != "" { - sub.inboxSub.Unsubscribe() - return nil, errors.New(r.Error) - } - sub.ackInbox = r.AckInbox - - return sub, nil -} - -// closeOrUnsubscribe performs either close or unsubsribe based on -// given boolean. -func (sub *subscription) closeOrUnsubscribe(doClose bool) error { - if sub == nil { - return ErrBadSubscription - } - sub.Lock() - sc := sub.sc - if sc == nil { - // Already closed. - sub.Unlock() - return ErrBadSubscription - } - sub.sc = nil - sub.inboxSub.Unsubscribe() - sub.inboxSub = nil - sub.Unlock() - - if sc == nil { - return ErrBadSubscription - } - - sc.Lock() - if sc.nc == nil { - sc.Unlock() - return ErrConnectionClosed - } - - delete(sc.subMap, sub.inbox) - reqSubject := sc.unsubRequests - if doClose { - reqSubject = sc.subCloseRequests - if reqSubject == "" { - sc.Unlock() - return ErrNoServerSupport - } - } - - // Snapshot connection to avoid data race, since the connection may be - // closing while we try to send the request - nc := sc.nc - sc.Unlock() - - usr := &pb.UnsubscribeRequest{ - ClientID: sc.clientID, - Subject: sub.subject, - Inbox: sub.ackInbox, - } - b, _ := usr.Marshal() - reply, err := nc.Request(reqSubject, b, sc.opts.ConnectTimeout) - if err != nil { - if err == nats.ErrTimeout { - if doClose { - return ErrCloseReqTimeout - } - return ErrUnsubReqTimeout - } - return err - } - r := &pb.SubscriptionResponse{} - if err := r.Unmarshal(reply.Data); err != nil { - return err - } - if r.Error != "" { - return errors.New(r.Error) - } - - return nil -} - -// Unsubscribe implements the Subscription interface -func (sub *subscription) Unsubscribe() error { - return sub.closeOrUnsubscribe(false) -} - -// Close implements the Subscription interface -func (sub *subscription) Close() error { - return sub.closeOrUnsubscribe(true) -} - -// Ack manually acknowledges a message. -// The subscriber had to be created with SetManualAckMode() option. -func (msg *Msg) Ack() error { - if msg == nil { - return ErrNilMsg - } - // Look up subscription - sub := msg.Sub.(*subscription) - if sub == nil { - return ErrBadSubscription - } - - sub.RLock() - ackSubject := sub.ackInbox - isManualAck := sub.opts.ManualAcks - sc := sub.sc - sub.RUnlock() - - // Check for error conditions. - if sc == nil { - return ErrBadSubscription - } - // Get nc from the connection (needs locking to avoid race) - sc.RLock() - nc := sc.nc - sc.RUnlock() - if nc == nil { - return ErrBadConnection - } - if !isManualAck { - return ErrManualAck - } - - // Ack here. - ack := &pb.Ack{Subject: msg.Subject, Sequence: msg.Sequence} - b, _ := ack.Marshal() - return nc.Publish(ackSubject, b) -} diff --git a/vendor/github.com/nats-io/go-nats/LICENSE b/vendor/github.com/nats-io/go-nats/LICENSE deleted file mode 100644 index 4cfd668..0000000 --- a/vendor/github.com/nats-io/go-nats/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2012-2016 Apcera Inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/nats-io/go-nats/enc.go b/vendor/github.com/nats-io/go-nats/enc.go deleted file mode 100644 index 4653559..0000000 --- a/vendor/github.com/nats-io/go-nats/enc.go +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright 2012-2015 Apcera Inc. All rights reserved. - -package nats - -import ( - "errors" - "fmt" - "reflect" - "sync" - "time" - - // Default Encoders - . "github.com/nats-io/nats/encoders/builtin" -) - -// Encoder interface is for all register encoders -type Encoder interface { - Encode(subject string, v interface{}) ([]byte, error) - Decode(subject string, data []byte, vPtr interface{}) error -} - -var encMap map[string]Encoder -var encLock sync.Mutex - -// Indexe names into the Registered Encoders. -const ( - JSON_ENCODER = "json" - GOB_ENCODER = "gob" - DEFAULT_ENCODER = "default" -) - -func init() { - encMap = make(map[string]Encoder) - // Register json, gob and default encoder - RegisterEncoder(JSON_ENCODER, &JsonEncoder{}) - RegisterEncoder(GOB_ENCODER, &GobEncoder{}) - RegisterEncoder(DEFAULT_ENCODER, &DefaultEncoder{}) -} - -// EncodedConn are the preferred way to interface with NATS. They wrap a bare connection to -// a nats server and have an extendable encoder system that will encode and decode messages -// from raw Go types. -type EncodedConn struct { - Conn *Conn - Enc Encoder -} - -// NewEncodedConn will wrap an existing Connection and utilize the appropriate registered -// encoder. -func NewEncodedConn(c *Conn, encType string) (*EncodedConn, error) { - if c == nil { - return nil, errors.New("nats: Nil Connection") - } - if c.IsClosed() { - return nil, ErrConnectionClosed - } - ec := &EncodedConn{Conn: c, Enc: EncoderForType(encType)} - if ec.Enc == nil { - return nil, fmt.Errorf("No encoder registered for '%s'", encType) - } - return ec, nil -} - -// RegisterEncoder will register the encType with the given Encoder. Useful for customization. -func RegisterEncoder(encType string, enc Encoder) { - encLock.Lock() - defer encLock.Unlock() - encMap[encType] = enc -} - -// EncoderForType will return the registered Encoder for the encType. -func EncoderForType(encType string) Encoder { - encLock.Lock() - defer encLock.Unlock() - return encMap[encType] -} - -// Publish publishes the data argument to the given subject. The data argument -// will be encoded using the associated encoder. -func (c *EncodedConn) Publish(subject string, v interface{}) error { - b, err := c.Enc.Encode(subject, v) - if err != nil { - return err - } - return c.Conn.publish(subject, _EMPTY_, b) -} - -// PublishRequest will perform a Publish() expecting a response on the -// reply subject. Use Request() for automatically waiting for a response -// inline. -func (c *EncodedConn) PublishRequest(subject, reply string, v interface{}) error { - b, err := c.Enc.Encode(subject, v) - if err != nil { - return err - } - return c.Conn.publish(subject, reply, b) -} - -// Request will create an Inbox and perform a Request() call -// with the Inbox reply for the data v. A response will be -// decoded into the vPtrResponse. -func (c *EncodedConn) Request(subject string, v interface{}, vPtr interface{}, timeout time.Duration) error { - b, err := c.Enc.Encode(subject, v) - if err != nil { - return err - } - m, err := c.Conn.Request(subject, b, timeout) - if err != nil { - return err - } - if reflect.TypeOf(vPtr) == emptyMsgType { - mPtr := vPtr.(*Msg) - *mPtr = *m - } else { - err = c.Enc.Decode(m.Subject, m.Data, vPtr) - } - return err -} - -// Handler is a specific callback used for Subscribe. It is generalized to -// an interface{}, but we will discover its format and arguments at runtime -// and perform the correct callback, including de-marshalling JSON strings -// back into the appropriate struct based on the signature of the Handler. -// -// Handlers are expected to have one of four signatures. -// -// type person struct { -// Name string `json:"name,omitempty"` -// Age uint `json:"age,omitempty"` -// } -// -// handler := func(m *Msg) -// handler := func(p *person) -// handler := func(subject string, o *obj) -// handler := func(subject, reply string, o *obj) -// -// These forms allow a callback to request a raw Msg ptr, where the processing -// of the message from the wire is untouched. Process a JSON representation -// and demarshal it into the given struct, e.g. person. -// There are also variants where the callback wants either the subject, or the -// subject and the reply subject. -type Handler interface{} - -// Dissect the cb Handler's signature -func argInfo(cb Handler) (reflect.Type, int) { - cbType := reflect.TypeOf(cb) - if cbType.Kind() != reflect.Func { - panic("nats: Handler needs to be a func") - } - numArgs := cbType.NumIn() - if numArgs == 0 { - return nil, numArgs - } - return cbType.In(numArgs - 1), numArgs -} - -var emptyMsgType = reflect.TypeOf(&Msg{}) - -// Subscribe will create a subscription on the given subject and process incoming -// messages using the specified Handler. The Handler should be a func that matches -// a signature from the description of Handler from above. -func (c *EncodedConn) Subscribe(subject string, cb Handler) (*Subscription, error) { - return c.subscribe(subject, _EMPTY_, cb) -} - -// QueueSubscribe will create a queue subscription on the given subject and process -// incoming messages using the specified Handler. The Handler should be a func that -// matches a signature from the description of Handler from above. -func (c *EncodedConn) QueueSubscribe(subject, queue string, cb Handler) (*Subscription, error) { - return c.subscribe(subject, queue, cb) -} - -// Internal implementation that all public functions will use. -func (c *EncodedConn) subscribe(subject, queue string, cb Handler) (*Subscription, error) { - if cb == nil { - return nil, errors.New("nats: Handler required for EncodedConn Subscription") - } - argType, numArgs := argInfo(cb) - if argType == nil { - return nil, errors.New("nats: Handler requires at least one argument") - } - - cbValue := reflect.ValueOf(cb) - wantsRaw := (argType == emptyMsgType) - - natsCB := func(m *Msg) { - var oV []reflect.Value - if wantsRaw { - oV = []reflect.Value{reflect.ValueOf(m)} - } else { - var oPtr reflect.Value - if argType.Kind() != reflect.Ptr { - oPtr = reflect.New(argType) - } else { - oPtr = reflect.New(argType.Elem()) - } - if err := c.Enc.Decode(m.Subject, m.Data, oPtr.Interface()); err != nil { - if c.Conn.Opts.AsyncErrorCB != nil { - c.Conn.ach <- func() { - c.Conn.Opts.AsyncErrorCB(c.Conn, m.Sub, errors.New("nats: Got an error trying to unmarshal: "+err.Error())) - } - } - return - } - if argType.Kind() != reflect.Ptr { - oPtr = reflect.Indirect(oPtr) - } - - // Callback Arity - switch numArgs { - case 1: - oV = []reflect.Value{oPtr} - case 2: - subV := reflect.ValueOf(m.Subject) - oV = []reflect.Value{subV, oPtr} - case 3: - subV := reflect.ValueOf(m.Subject) - replyV := reflect.ValueOf(m.Reply) - oV = []reflect.Value{subV, replyV, oPtr} - } - - } - cbValue.Call(oV) - } - - return c.Conn.subscribe(subject, queue, natsCB, nil) -} - -// FlushTimeout allows a Flush operation to have an associated timeout. -func (c *EncodedConn) FlushTimeout(timeout time.Duration) (err error) { - return c.Conn.FlushTimeout(timeout) -} - -// Flush will perform a round trip to the server and return when it -// receives the internal reply. -func (c *EncodedConn) Flush() error { - return c.Conn.Flush() -} - -// Close will close the connection to the server. This call will release -// all blocking calls, such as Flush(), etc. -func (c *EncodedConn) Close() { - c.Conn.Close() -} - -// LastError reports the last error encountered via the Connection. -func (c *EncodedConn) LastError() error { - return c.Conn.err -} diff --git a/vendor/github.com/nats-io/go-nats/nats.go b/vendor/github.com/nats-io/go-nats/nats.go deleted file mode 100644 index 8524048..0000000 --- a/vendor/github.com/nats-io/go-nats/nats.go +++ /dev/null @@ -1,2630 +0,0 @@ -// Copyright 2012-2016 Apcera Inc. All rights reserved. - -// A Go client for the NATS messaging system (https://nats.io). -package nats - -import ( - "bufio" - "bytes" - "crypto/tls" - "crypto/x509" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "math/rand" - "net" - "net/url" - "regexp" - "runtime" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" - - "github.com/nats-io/nats/util" - "github.com/nats-io/nuid" -) - -// Default Constants -const ( - Version = "1.2.2" - DefaultURL = "nats://localhost:4222" - DefaultPort = 4222 - DefaultMaxReconnect = 60 - DefaultReconnectWait = 2 * time.Second - DefaultTimeout = 2 * time.Second - DefaultPingInterval = 2 * time.Minute - DefaultMaxPingOut = 2 - DefaultMaxChanLen = 8192 // 8k - DefaultReconnectBufSize = 8 * 1024 * 1024 // 8MB - RequestChanLen = 8 - LangString = "go" -) - -// STALE_CONNECTION is for detection and proper handling of stale connections. -const STALE_CONNECTION = "stale connection" - -// PERMISSIONS_ERR is for when nats server subject authorization has failed. -const PERMISSIONS_ERR = "permissions violation" - -// Errors -var ( - ErrConnectionClosed = errors.New("nats: connection closed") - ErrSecureConnRequired = errors.New("nats: secure connection required") - ErrSecureConnWanted = errors.New("nats: secure connection not available") - ErrBadSubscription = errors.New("nats: invalid subscription") - ErrTypeSubscription = errors.New("nats: invalid subscription type") - ErrBadSubject = errors.New("nats: invalid subject") - ErrSlowConsumer = errors.New("nats: slow consumer, messages dropped") - ErrTimeout = errors.New("nats: timeout") - ErrBadTimeout = errors.New("nats: timeout invalid") - ErrAuthorization = errors.New("nats: authorization violation") - ErrNoServers = errors.New("nats: no servers available for connection") - ErrJsonParse = errors.New("nats: connect message, json parse error") - ErrChanArg = errors.New("nats: argument needs to be a channel type") - ErrMaxPayload = errors.New("nats: maximum payload exceeded") - ErrMaxMessages = errors.New("nats: maximum messages delivered") - ErrSyncSubRequired = errors.New("nats: illegal call on an async subscription") - ErrMultipleTLSConfigs = errors.New("nats: multiple tls.Configs not allowed") - ErrNoInfoReceived = errors.New("nats: protocol exception, INFO not received") - ErrReconnectBufExceeded = errors.New("nats: outbound buffer limit exceeded") - ErrInvalidConnection = errors.New("nats: invalid connection") - ErrInvalidMsg = errors.New("nats: invalid message or message nil") - ErrInvalidArg = errors.New("nats: invalid argument") - ErrStaleConnection = errors.New("nats: " + STALE_CONNECTION) -) - -var DefaultOptions = Options{ - AllowReconnect: true, - MaxReconnect: DefaultMaxReconnect, - ReconnectWait: DefaultReconnectWait, - Timeout: DefaultTimeout, - PingInterval: DefaultPingInterval, - MaxPingsOut: DefaultMaxPingOut, - SubChanLen: DefaultMaxChanLen, - ReconnectBufSize: DefaultReconnectBufSize, - Dialer: &net.Dialer{ - Timeout: DefaultTimeout, - }, -} - -// Status represents the state of the connection. -type Status int - -const ( - DISCONNECTED = Status(iota) - CONNECTED - CLOSED - RECONNECTING - CONNECTING -) - -// ConnHandler is used for asynchronous events such as -// disconnected and closed connections. -type ConnHandler func(*Conn) - -// ErrHandler is used to process asynchronous errors encountered -// while processing inbound messages. -type ErrHandler func(*Conn, *Subscription, error) - -// asyncCB is used to preserve order for async callbacks. -type asyncCB func() - -// Option is a function on the options for a connection. -type Option func(*Options) error - -// Options can be used to create a customized connection. -type Options struct { - Url string - Servers []string - NoRandomize bool - Name string - Verbose bool - Pedantic bool - Secure bool - TLSConfig *tls.Config - AllowReconnect bool - MaxReconnect int - ReconnectWait time.Duration - Timeout time.Duration - PingInterval time.Duration // disabled if 0 or negative - MaxPingsOut int - ClosedCB ConnHandler - DisconnectedCB ConnHandler - ReconnectedCB ConnHandler - AsyncErrorCB ErrHandler - - // Size of the backing bufio buffer during reconnect. Once this - // has been exhausted publish operations will error. - ReconnectBufSize int - - // The size of the buffered channel used between the socket - // Go routine and the message delivery for SyncSubscriptions. - // NOTE: This does not affect AsyncSubscriptions which are - // dictated by PendingLimits() - SubChanLen int - - User string - Password string - Token string - - // Dialer allows users setting a custom Dialer - Dialer *net.Dialer -} - -const ( - // Scratch storage for assembling protocol headers - scratchSize = 512 - - // The size of the bufio reader/writer on top of the socket. - defaultBufSize = 32768 - - // The buffered size of the flush "kick" channel - flushChanSize = 1024 - - // Default server pool size - srvPoolSize = 4 - - // Channel size for the async callback handler. - asyncCBChanSize = 32 -) - -// A Conn represents a bare connection to a nats-server. -// It can send and receive []byte payloads. -type Conn struct { - // Keep all members for which we use atomic at the beginning of the - // struct and make sure they are all 64bits (or use padding if necessary). - // atomic.* functions crash on 32bit machines if operand is not aligned - // at 64bit. See https://github.com/golang/go/issues/599 - ssid int64 - - Statistics - mu sync.Mutex - Opts Options - wg sync.WaitGroup - url *url.URL - conn net.Conn - srvPool []*srv - urls map[string]struct{} // Keep track of all known URLs (used by processInfo) - bw *bufio.Writer - pending *bytes.Buffer - fch chan bool - info serverInfo - subs map[int64]*Subscription - mch chan *Msg - ach chan asyncCB - pongs []chan bool - scratch [scratchSize]byte - status Status - err error - ps *parseState - ptmr *time.Timer - pout int -} - -// A Subscription represents interest in a given subject. -type Subscription struct { - mu sync.Mutex - sid int64 - - // Subject that represents this subscription. This can be different - // than the received subject inside a Msg if this is a wildcard. - Subject string - - // Optional queue group name. If present, all subscriptions with the - // same name will form a distributed queue, and each message will - // only be processed by one member of the group. - Queue string - - delivered uint64 - max uint64 - conn *Conn - mcb MsgHandler - mch chan *Msg - closed bool - sc bool - connClosed bool - - // Type of Subscription - typ SubscriptionType - - // Async linked list - pHead *Msg - pTail *Msg - pCond *sync.Cond - - // Pending stats, async subscriptions, high-speed etc. - pMsgs int - pBytes int - pMsgsMax int - pBytesMax int - pMsgsLimit int - pBytesLimit int - dropped int -} - -// Msg is a structure used by Subscribers and PublishMsg(). -type Msg struct { - Subject string - Reply string - Data []byte - Sub *Subscription - next *Msg -} - -// Tracks various stats received and sent on this connection, -// including counts for messages and bytes. -type Statistics struct { - InMsgs uint64 - OutMsgs uint64 - InBytes uint64 - OutBytes uint64 - Reconnects uint64 -} - -// Tracks individual backend servers. -type srv struct { - url *url.URL - didConnect bool - reconnects int - lastAttempt time.Time - isImplicit bool -} - -type serverInfo struct { - Id string `json:"server_id"` - Host string `json:"host"` - Port uint `json:"port"` - Version string `json:"version"` - AuthRequired bool `json:"auth_required"` - TLSRequired bool `json:"tls_required"` - MaxPayload int64 `json:"max_payload"` - ConnectURLs []string `json:"connect_urls,omitempty"` -} - -const ( - // clientProtoZero is the original client protocol from 2009. - // http://nats.io/documentation/internals/nats-protocol/ - clientProtoZero = iota - // clientProtoInfo signals a client can receive more then the original INFO block. - // This can be used to update clients on other cluster members, etc. - clientProtoInfo -) - -type connectInfo struct { - Verbose bool `json:"verbose"` - Pedantic bool `json:"pedantic"` - User string `json:"user,omitempty"` - Pass string `json:"pass,omitempty"` - Token string `json:"auth_token,omitempty"` - TLS bool `json:"tls_required"` - Name string `json:"name"` - Lang string `json:"lang"` - Version string `json:"version"` - Protocol int `json:"protocol"` -} - -// MsgHandler is a callback function that processes messages delivered to -// asynchronous subscribers. -type MsgHandler func(msg *Msg) - -// Connect will attempt to connect to the NATS system. -// The url can contain username/password semantics. e.g. nats://derek:pass@localhost:4222 -// Comma separated arrays are also supported, e.g. urlA, urlB. -// Options start with the defaults but can be overridden. -func Connect(url string, options ...Option) (*Conn, error) { - opts := DefaultOptions - opts.Servers = processUrlString(url) - for _, opt := range options { - if err := opt(&opts); err != nil { - return nil, err - } - } - return opts.Connect() -} - -// Options that can be passed to Connect. - -// Name is an Option to set the client name. -func Name(name string) Option { - return func(o *Options) error { - o.Name = name - return nil - } -} - -// Secure is an Option to enable TLS secure connections that skip server verification by default. -// Pass a TLS Configuration for proper TLS. -func Secure(tls ...*tls.Config) Option { - return func(o *Options) error { - o.Secure = true - // Use of variadic just simplifies testing scenarios. We only take the first one. - // fixme(DLC) - Could panic if more than one. Could also do TLS option. - if len(tls) > 1 { - return ErrMultipleTLSConfigs - } - if len(tls) == 1 { - o.TLSConfig = tls[0] - } - return nil - } -} - -// RootCAs is a helper option to provide the RootCAs pool from a list of filenames. If Secure is -// not already set this will set it as well. -func RootCAs(file ...string) Option { - return func(o *Options) error { - pool := x509.NewCertPool() - for _, f := range file { - rootPEM, err := ioutil.ReadFile(f) - if err != nil || rootPEM == nil { - return fmt.Errorf("nats: error loading or parsing rootCA file: %v", err) - } - ok := pool.AppendCertsFromPEM([]byte(rootPEM)) - if !ok { - return fmt.Errorf("nats: failed to parse root certificate from %q", f) - } - } - if o.TLSConfig == nil { - o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} - } - o.TLSConfig.RootCAs = pool - o.Secure = true - return nil - } -} - -// ClientCert is a helper option to provide the client certificate from a file. If Secure is -// not already set this will set it as well -func ClientCert(certFile, keyFile string) Option { - return func(o *Options) error { - cert, err := tls.LoadX509KeyPair(certFile, keyFile) - if err != nil { - return fmt.Errorf("nats: error loading client certificate: %v", err) - } - cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0]) - if err != nil { - return fmt.Errorf("nats: error parsing client certificate: %v", err) - } - if o.TLSConfig == nil { - o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} - } - o.TLSConfig.Certificates = []tls.Certificate{cert} - o.Secure = true - return nil - } -} - -// NoReconnect is an Option to turn off reconnect behavior. -func NoReconnect() Option { - return func(o *Options) error { - o.AllowReconnect = false - return nil - } -} - -// DontRandomize is an Option to turn off randomizing the server pool. -func DontRandomize() Option { - return func(o *Options) error { - o.NoRandomize = true - return nil - } -} - -// ReconnectWait is an Option to set the wait time between reconnect attempts. -func ReconnectWait(t time.Duration) Option { - return func(o *Options) error { - o.ReconnectWait = t - return nil - } -} - -// MaxReconnects is an Option to set the maximum number of reconnect attempts. -func MaxReconnects(max int) Option { - return func(o *Options) error { - o.MaxReconnect = max - return nil - } -} - -// Timeout is an Option to set the timeout for Dial on a connection. -func Timeout(t time.Duration) Option { - return func(o *Options) error { - o.Timeout = t - return nil - } -} - -// DisconnectHandler is an Option to set the disconnected handler. -func DisconnectHandler(cb ConnHandler) Option { - return func(o *Options) error { - o.DisconnectedCB = cb - return nil - } -} - -// ReconnectHandler is an Option to set the reconnected handler. -func ReconnectHandler(cb ConnHandler) Option { - return func(o *Options) error { - o.ReconnectedCB = cb - return nil - } -} - -// ClosedHandler is an Option to set the closed handler. -func ClosedHandler(cb ConnHandler) Option { - return func(o *Options) error { - o.ClosedCB = cb - return nil - } -} - -// ErrHandler is an Option to set the async error handler. -func ErrorHandler(cb ErrHandler) Option { - return func(o *Options) error { - o.AsyncErrorCB = cb - return nil - } -} - -// UserInfo is an Option to set the username and password to -// use when not included directly in the URLs. -func UserInfo(user, password string) Option { - return func(o *Options) error { - o.User = user - o.Password = password - return nil - } -} - -// Token is an Option to set the token to use when not included -// directly in the URLs. -func Token(token string) Option { - return func(o *Options) error { - o.Token = token - return nil - } -} - -// Dialer is an Option to set the dialer which will be used when -// attempting to establish a connection. -func Dialer(dialer *net.Dialer) Option { - return func(o *Options) error { - o.Dialer = dialer - return nil - } -} - -// Handler processing - -// SetDisconnectHandler will set the disconnect event handler. -func (nc *Conn) SetDisconnectHandler(dcb ConnHandler) { - if nc == nil { - return - } - nc.mu.Lock() - defer nc.mu.Unlock() - nc.Opts.DisconnectedCB = dcb -} - -// SetReconnectHandler will set the reconnect event handler. -func (nc *Conn) SetReconnectHandler(rcb ConnHandler) { - if nc == nil { - return - } - nc.mu.Lock() - defer nc.mu.Unlock() - nc.Opts.ReconnectedCB = rcb -} - -// SetClosedHandler will set the reconnect event handler. -func (nc *Conn) SetClosedHandler(cb ConnHandler) { - if nc == nil { - return - } - nc.mu.Lock() - defer nc.mu.Unlock() - nc.Opts.ClosedCB = cb -} - -// SetErrHandler will set the async error handler. -func (nc *Conn) SetErrorHandler(cb ErrHandler) { - if nc == nil { - return - } - nc.mu.Lock() - defer nc.mu.Unlock() - nc.Opts.AsyncErrorCB = cb -} - -// Process the url string argument to Connect. Return an array of -// urls, even if only one. -func processUrlString(url string) []string { - urls := strings.Split(url, ",") - for i, s := range urls { - urls[i] = strings.TrimSpace(s) - } - return urls -} - -// Connect will attempt to connect to a NATS server with multiple options. -func (o Options) Connect() (*Conn, error) { - nc := &Conn{Opts: o} - - // Some default options processing. - if nc.Opts.MaxPingsOut == 0 { - nc.Opts.MaxPingsOut = DefaultMaxPingOut - } - // Allow old default for channel length to work correctly. - if nc.Opts.SubChanLen == 0 { - nc.Opts.SubChanLen = DefaultMaxChanLen - } - // Default ReconnectBufSize - if nc.Opts.ReconnectBufSize == 0 { - nc.Opts.ReconnectBufSize = DefaultReconnectBufSize - } - // Ensure that Timeout is not 0 - if nc.Opts.Timeout == 0 { - nc.Opts.Timeout = DefaultTimeout - } - - // Allow custom Dialer for connecting using DialTimeout by default - if nc.Opts.Dialer == nil { - nc.Opts.Dialer = &net.Dialer{ - Timeout: nc.Opts.Timeout, - } - } - - if err := nc.setupServerPool(); err != nil { - return nil, err - } - - // Create the async callback channel. - nc.ach = make(chan asyncCB, asyncCBChanSize) - - if err := nc.connect(); err != nil { - return nil, err - } - - // Spin up the async cb dispatcher on success - go nc.asyncDispatch() - - return nc, nil -} - -const ( - _CRLF_ = "\r\n" - _EMPTY_ = "" - _SPC_ = " " - _PUB_P_ = "PUB " -) - -const ( - _OK_OP_ = "+OK" - _ERR_OP_ = "-ERR" - _MSG_OP_ = "MSG" - _PING_OP_ = "PING" - _PONG_OP_ = "PONG" - _INFO_OP_ = "INFO" -) - -const ( - conProto = "CONNECT %s" + _CRLF_ - pingProto = "PING" + _CRLF_ - pongProto = "PONG" + _CRLF_ - pubProto = "PUB %s %s %d" + _CRLF_ - subProto = "SUB %s %s %d" + _CRLF_ - unsubProto = "UNSUB %d %s" + _CRLF_ - okProto = _OK_OP_ + _CRLF_ -) - -// Return the currently selected server -func (nc *Conn) currentServer() (int, *srv) { - for i, s := range nc.srvPool { - if s == nil { - continue - } - if s.url == nc.url { - return i, s - } - } - return -1, nil -} - -// Pop the current server and put onto the end of the list. Select head of list as long -// as number of reconnect attempts under MaxReconnect. -func (nc *Conn) selectNextServer() (*srv, error) { - i, s := nc.currentServer() - if i < 0 { - return nil, ErrNoServers - } - sp := nc.srvPool - num := len(sp) - copy(sp[i:num-1], sp[i+1:num]) - maxReconnect := nc.Opts.MaxReconnect - if maxReconnect < 0 || s.reconnects < maxReconnect { - nc.srvPool[num-1] = s - } else { - nc.srvPool = sp[0 : num-1] - } - if len(nc.srvPool) <= 0 { - nc.url = nil - return nil, ErrNoServers - } - nc.url = nc.srvPool[0].url - return nc.srvPool[0], nil -} - -// Will assign the correct server to the nc.Url -func (nc *Conn) pickServer() error { - nc.url = nil - if len(nc.srvPool) <= 0 { - return ErrNoServers - } - for _, s := range nc.srvPool { - if s != nil { - nc.url = s.url - return nil - } - } - return ErrNoServers -} - -const tlsScheme = "tls" - -// Create the server pool using the options given. -// We will place a Url option first, followed by any -// Server Options. We will randomize the server pool unlesss -// the NoRandomize flag is set. -func (nc *Conn) setupServerPool() error { - nc.srvPool = make([]*srv, 0, srvPoolSize) - nc.urls = make(map[string]struct{}, srvPoolSize) - - // Create srv objects from each url string in nc.Opts.Servers - // and add them to the pool - for _, urlString := range nc.Opts.Servers { - if err := nc.addURLToPool(urlString, false); err != nil { - return err - } - } - - // Randomize if allowed to - if !nc.Opts.NoRandomize { - nc.shufflePool() - } - - // Normally, if this one is set, Options.Servers should not be, - // but we always allowed that, so continue to do so. - if nc.Opts.Url != _EMPTY_ { - // Add to the end of the array - if err := nc.addURLToPool(nc.Opts.Url, false); err != nil { - return err - } - // Then swap it with first to guarantee that Options.Url is tried first. - last := len(nc.srvPool) - 1 - if last > 0 { - nc.srvPool[0], nc.srvPool[last] = nc.srvPool[last], nc.srvPool[0] - } - } else if len(nc.srvPool) <= 0 { - // Place default URL if pool is empty. - if err := nc.addURLToPool(DefaultURL, false); err != nil { - return err - } - } - - // Check for Scheme hint to move to TLS mode. - for _, srv := range nc.srvPool { - if srv.url.Scheme == tlsScheme { - // FIXME(dlc), this is for all in the pool, should be case by case. - nc.Opts.Secure = true - if nc.Opts.TLSConfig == nil { - nc.Opts.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12} - } - } - } - - return nc.pickServer() -} - -// addURLToPool adds an entry to the server pool -func (nc *Conn) addURLToPool(sURL string, implicit bool) error { - u, err := url.Parse(sURL) - if err != nil { - return err - } - s := &srv{url: u, isImplicit: implicit} - nc.srvPool = append(nc.srvPool, s) - nc.urls[u.Host] = struct{}{} - return nil -} - -// shufflePool swaps randomly elements in the server pool -func (nc *Conn) shufflePool() { - if len(nc.srvPool) <= 1 { - return - } - source := rand.NewSource(time.Now().UnixNano()) - r := rand.New(source) - for i := range nc.srvPool { - j := r.Intn(i + 1) - nc.srvPool[i], nc.srvPool[j] = nc.srvPool[j], nc.srvPool[i] - } -} - -// createConn will connect to the server and wrap the appropriate -// bufio structures. It will do the right thing when an existing -// connection is in place. -func (nc *Conn) createConn() (err error) { - if nc.Opts.Timeout < 0 { - return ErrBadTimeout - } - if _, cur := nc.currentServer(); cur == nil { - return ErrNoServers - } else { - cur.lastAttempt = time.Now() - } - - dialer := nc.Opts.Dialer - nc.conn, err = dialer.Dial("tcp", nc.url.Host) - if err != nil { - return err - } - - // No clue why, but this stalls and kills performance on Mac (Mavericks). - // https://code.google.com/p/go/issues/detail?id=6930 - //if ip, ok := nc.conn.(*net.TCPConn); ok { - // ip.SetReadBuffer(defaultBufSize) - //} - - if nc.pending != nil && nc.bw != nil { - // Move to pending buffer. - nc.bw.Flush() - } - nc.bw = bufio.NewWriterSize(nc.conn, defaultBufSize) - return nil -} - -// makeTLSConn will wrap an existing Conn using TLS -func (nc *Conn) makeTLSConn() { - // Allow the user to configure their own tls.Config structure, otherwise - // default to InsecureSkipVerify. - // TODO(dlc) - We should make the more secure version the default. - if nc.Opts.TLSConfig != nil { - tlsCopy := util.CloneTLSConfig(nc.Opts.TLSConfig) - // If its blank we will override it with the current host - if tlsCopy.ServerName == _EMPTY_ { - h, _, _ := net.SplitHostPort(nc.url.Host) - tlsCopy.ServerName = h - } - nc.conn = tls.Client(nc.conn, tlsCopy) - } else { - nc.conn = tls.Client(nc.conn, &tls.Config{InsecureSkipVerify: true}) - } - conn := nc.conn.(*tls.Conn) - conn.Handshake() - nc.bw = bufio.NewWriterSize(nc.conn, defaultBufSize) -} - -// waitForExits will wait for all socket watcher Go routines to -// be shutdown before proceeding. -func (nc *Conn) waitForExits() { - // Kick old flusher forcefully. - select { - case nc.fch <- true: - default: - } - - // Wait for any previous go routines. - nc.wg.Wait() -} - -// spinUpGoRoutines will launch the Go routines responsible for -// reading and writing to the socket. This will be launched via a -// go routine itself to release any locks that may be held. -// We also use a WaitGroup to make sure we only start them on a -// reconnect when the previous ones have exited. -func (nc *Conn) spinUpGoRoutines() { - // Make sure everything has exited. - nc.waitForExits() - - // We will wait on both. - nc.wg.Add(2) - - // Spin up the readLoop and the socket flusher. - go nc.readLoop() - go nc.flusher() - - nc.mu.Lock() - if nc.Opts.PingInterval > 0 { - if nc.ptmr == nil { - nc.ptmr = time.AfterFunc(nc.Opts.PingInterval, nc.processPingTimer) - } else { - nc.ptmr.Reset(nc.Opts.PingInterval) - } - } - nc.mu.Unlock() -} - -// Report the connected server's Url -func (nc *Conn) ConnectedUrl() string { - if nc == nil { - return _EMPTY_ - } - nc.mu.Lock() - defer nc.mu.Unlock() - if nc.status != CONNECTED { - return _EMPTY_ - } - return nc.url.String() -} - -// Report the connected server's Id -func (nc *Conn) ConnectedServerId() string { - if nc == nil { - return _EMPTY_ - } - nc.mu.Lock() - defer nc.mu.Unlock() - if nc.status != CONNECTED { - return _EMPTY_ - } - return nc.info.Id -} - -// Low level setup for structs, etc -func (nc *Conn) setup() { - nc.subs = make(map[int64]*Subscription) - nc.pongs = make([]chan bool, 0, 8) - - nc.fch = make(chan bool, flushChanSize) - - // Setup scratch outbound buffer for PUB - pub := nc.scratch[:len(_PUB_P_)] - copy(pub, _PUB_P_) -} - -// Process a connected connection and initialize properly. -func (nc *Conn) processConnectInit() error { - - // Set out deadline for the whole connect process - nc.conn.SetDeadline(time.Now().Add(nc.Opts.Timeout)) - defer nc.conn.SetDeadline(time.Time{}) - - // Set our status to connecting. - nc.status = CONNECTING - - // Process the INFO protocol received from the server - err := nc.processExpectedInfo() - if err != nil { - return err - } - - // Send the CONNECT protocol along with the initial PING protocol. - // Wait for the PONG response (or any error that we get from the server). - err = nc.sendConnect() - if err != nil { - return err - } - - // Reset the number of PING sent out - nc.pout = 0 - - go nc.spinUpGoRoutines() - - return nil -} - -// Main connect function. Will connect to the nats-server -func (nc *Conn) connect() error { - var returnedErr error - - // Create actual socket connection - // For first connect we walk all servers in the pool and try - // to connect immediately. - nc.mu.Lock() - // The pool may change inside theloop iteration due to INFO protocol. - for i := 0; i < len(nc.srvPool); i++ { - nc.url = nc.srvPool[i].url - - if err := nc.createConn(); err == nil { - // This was moved out of processConnectInit() because - // that function is now invoked from doReconnect() too. - nc.setup() - - err = nc.processConnectInit() - - if err == nil { - nc.srvPool[i].didConnect = true - nc.srvPool[i].reconnects = 0 - returnedErr = nil - break - } else { - returnedErr = err - nc.mu.Unlock() - nc.close(DISCONNECTED, false) - nc.mu.Lock() - nc.url = nil - } - } else { - // Cancel out default connection refused, will trigger the - // No servers error conditional - if matched, _ := regexp.Match(`connection refused`, []byte(err.Error())); matched { - returnedErr = nil - } - } - } - defer nc.mu.Unlock() - - if returnedErr == nil && nc.status != CONNECTED { - returnedErr = ErrNoServers - } - return returnedErr -} - -// This will check to see if the connection should be -// secure. This can be dictated from either end and should -// only be called after the INIT protocol has been received. -func (nc *Conn) checkForSecure() error { - // Check to see if we need to engage TLS - o := nc.Opts - - // Check for mismatch in setups - if o.Secure && !nc.info.TLSRequired { - return ErrSecureConnWanted - } else if nc.info.TLSRequired && !o.Secure { - return ErrSecureConnRequired - } - - // Need to rewrap with bufio - if o.Secure { - nc.makeTLSConn() - } - return nil -} - -// processExpectedInfo will look for the expected first INFO message -// sent when a connection is established. The lock should be held entering. -func (nc *Conn) processExpectedInfo() error { - - c := &control{} - - // Read the protocol - err := nc.readOp(c) - if err != nil { - return err - } - - // The nats protocol should send INFO first always. - if c.op != _INFO_OP_ { - return ErrNoInfoReceived - } - - // Parse the protocol - if err := nc.processInfo(c.args); err != nil { - return err - } - - err = nc.checkForSecure() - if err != nil { - return err - } - - return nil -} - -// Sends a protocol control message by queuing into the bufio writer -// and kicking the flush Go routine. These writes are protected. -func (nc *Conn) sendProto(proto string) { - nc.mu.Lock() - nc.bw.WriteString(proto) - nc.kickFlusher() - nc.mu.Unlock() -} - -// Generate a connect protocol message, issuing user/password if -// applicable. The lock is assumed to be held upon entering. -func (nc *Conn) connectProto() (string, error) { - o := nc.Opts - var user, pass, token string - u := nc.url.User - if u != nil { - // if no password, assume username is authToken - if _, ok := u.Password(); !ok { - token = u.Username() - } else { - user = u.Username() - pass, _ = u.Password() - } - } else { - // Take from options (pssibly all empty strings) - user = nc.Opts.User - pass = nc.Opts.Password - token = nc.Opts.Token - } - cinfo := connectInfo{o.Verbose, o.Pedantic, - user, pass, token, - o.Secure, o.Name, LangString, Version, clientProtoInfo} - b, err := json.Marshal(cinfo) - if err != nil { - return _EMPTY_, ErrJsonParse - } - return fmt.Sprintf(conProto, b), nil -} - -// normalizeErr removes the prefix -ERR, trim spaces and remove the quotes. -func normalizeErr(line string) string { - s := strings.ToLower(strings.TrimSpace(strings.TrimPrefix(line, _ERR_OP_))) - s = strings.TrimLeft(strings.TrimRight(s, "'"), "'") - return s -} - -// Send a connect protocol message to the server, issue user/password if -// applicable. Will wait for a flush to return from the server for error -// processing. -func (nc *Conn) sendConnect() error { - - // Construct the CONNECT protocol string - cProto, err := nc.connectProto() - if err != nil { - return err - } - - // Write the protocol into the buffer - _, err = nc.bw.WriteString(cProto) - if err != nil { - return err - } - - // Add to the buffer the PING protocol - _, err = nc.bw.WriteString(pingProto) - if err != nil { - return err - } - - // Flush the buffer - err = nc.bw.Flush() - if err != nil { - return err - } - - // Now read the response from the server. - br := bufio.NewReaderSize(nc.conn, defaultBufSize) - line, err := br.ReadString('\n') - if err != nil { - return err - } - - // If opts.Verbose is set, handle +OK - if nc.Opts.Verbose && line == okProto { - // Read the rest now... - line, err = br.ReadString('\n') - if err != nil { - return err - } - } - - // We expect a PONG - if line != pongProto { - // But it could be something else, like -ERR - - // Since we no longer use ReadLine(), trim the trailing "\r\n" - line = strings.TrimRight(line, "\r\n") - - // If it's a server error... - if strings.HasPrefix(line, _ERR_OP_) { - // Remove -ERR, trim spaces and quotes, and convert to lower case. - line = normalizeErr(line) - return errors.New("nats: " + line) - } - - // Notify that we got an unexpected protocol. - return errors.New(fmt.Sprintf("nats: expected '%s', got '%s'", _PONG_OP_, line)) - } - - // This is where we are truly connected. - nc.status = CONNECTED - - return nil -} - -// A control protocol line. -type control struct { - op, args string -} - -// Read a control line and process the intended op. -func (nc *Conn) readOp(c *control) error { - br := bufio.NewReaderSize(nc.conn, defaultBufSize) - line, err := br.ReadString('\n') - if err != nil { - return err - } - parseControl(line, c) - return nil -} - -// Parse a control line from the server. -func parseControl(line string, c *control) { - toks := strings.SplitN(line, _SPC_, 2) - if len(toks) == 1 { - c.op = strings.TrimSpace(toks[0]) - c.args = _EMPTY_ - } else if len(toks) == 2 { - c.op, c.args = strings.TrimSpace(toks[0]), strings.TrimSpace(toks[1]) - } else { - c.op = _EMPTY_ - } -} - -// flushReconnectPending will push the pending items that were -// gathered while we were in a RECONNECTING state to the socket. -func (nc *Conn) flushReconnectPendingItems() { - if nc.pending == nil { - return - } - if nc.pending.Len() > 0 { - nc.bw.Write(nc.pending.Bytes()) - } -} - -// Try to reconnect using the option parameters. -// This function assumes we are allowed to reconnect. -func (nc *Conn) doReconnect() { - // We want to make sure we have the other watchers shutdown properly - // here before we proceed past this point. - nc.waitForExits() - - // FIXME(dlc) - We have an issue here if we have - // outstanding flush points (pongs) and they were not - // sent out, but are still in the pipe. - - // Hold the lock manually and release where needed below, - // can't do defer here. - nc.mu.Lock() - - // Clear any queued pongs, e.g. pending flush calls. - nc.clearPendingFlushCalls() - - // Clear any errors. - nc.err = nil - - // Perform appropriate callback if needed for a disconnect. - if nc.Opts.DisconnectedCB != nil { - nc.ach <- func() { nc.Opts.DisconnectedCB(nc) } - } - - for len(nc.srvPool) > 0 { - cur, err := nc.selectNextServer() - if err != nil { - nc.err = err - break - } - - sleepTime := int64(0) - - // Sleep appropriate amount of time before the - // connection attempt if connecting to same server - // we just got disconnected from.. - if time.Since(cur.lastAttempt) < nc.Opts.ReconnectWait { - sleepTime = int64(nc.Opts.ReconnectWait - time.Since(cur.lastAttempt)) - } - - // On Windows, createConn() will take more than a second when no - // server is running at that address. So it could be that the - // time elapsed between reconnect attempts is always > than - // the set option. Release the lock to give a chance to a parallel - // nc.Close() to break the loop. - nc.mu.Unlock() - if sleepTime <= 0 { - runtime.Gosched() - } else { - time.Sleep(time.Duration(sleepTime)) - } - nc.mu.Lock() - - // Check if we have been closed first. - if nc.isClosed() { - break - } - - // Mark that we tried a reconnect - cur.reconnects++ - - // Try to create a new connection - err = nc.createConn() - - // Not yet connected, retry... - // Continue to hold the lock - if err != nil { - nc.err = nil - continue - } - - // We are reconnected - nc.Reconnects++ - - // Process connect logic - if nc.err = nc.processConnectInit(); nc.err != nil { - nc.status = RECONNECTING - continue - } - - // Clear out server stats for the server we connected to.. - cur.didConnect = true - cur.reconnects = 0 - - // Send existing subscription state - nc.resendSubscriptions() - - // Now send off and clear pending buffer - nc.flushReconnectPendingItems() - - // Flush the buffer - nc.err = nc.bw.Flush() - if nc.err != nil { - nc.status = RECONNECTING - continue - } - - // Done with the pending buffer - nc.pending = nil - - // This is where we are truly connected. - nc.status = CONNECTED - - // Queue up the reconnect callback. - if nc.Opts.ReconnectedCB != nil { - nc.ach <- func() { nc.Opts.ReconnectedCB(nc) } - } - - // Release lock here, we will return below. - nc.mu.Unlock() - - // Make sure to flush everything - nc.Flush() - - return - } - - // Call into close.. We have no servers left.. - if nc.err == nil { - nc.err = ErrNoServers - } - nc.mu.Unlock() - nc.Close() -} - -// processOpErr handles errors from reading or parsing the protocol. -// The lock should not be held entering this function. -func (nc *Conn) processOpErr(err error) { - nc.mu.Lock() - if nc.isConnecting() || nc.isClosed() || nc.isReconnecting() { - nc.mu.Unlock() - return - } - - if nc.Opts.AllowReconnect && nc.status == CONNECTED { - // Set our new status - nc.status = RECONNECTING - if nc.ptmr != nil { - nc.ptmr.Stop() - } - if nc.conn != nil { - nc.bw.Flush() - nc.conn.Close() - nc.conn = nil - } - - // Create a new pending buffer to underpin the bufio Writer while - // we are reconnecting. - nc.pending = &bytes.Buffer{} - nc.bw = bufio.NewWriterSize(nc.pending, nc.Opts.ReconnectBufSize) - - go nc.doReconnect() - nc.mu.Unlock() - return - } - - nc.status = DISCONNECTED - nc.err = err - nc.mu.Unlock() - nc.Close() -} - -// Marker to close the channel to kick out the Go routine. -func (nc *Conn) closeAsyncFunc() asyncCB { - return func() { - nc.mu.Lock() - if nc.ach != nil { - close(nc.ach) - nc.ach = nil - } - nc.mu.Unlock() - } -} - -// asyncDispatch is responsible for calling any async callbacks -func (nc *Conn) asyncDispatch() { - // snapshot since they can change from underneath of us. - nc.mu.Lock() - ach := nc.ach - nc.mu.Unlock() - - // Loop on the channel and process async callbacks. - for { - if f, ok := <-ach; !ok { - return - } else { - f() - } - } -} - -// readLoop() will sit on the socket reading and processing the -// protocol from the server. It will dispatch appropriately based -// on the op type. -func (nc *Conn) readLoop() { - // Release the wait group on exit - defer nc.wg.Done() - - // Create a parseState if needed. - nc.mu.Lock() - if nc.ps == nil { - nc.ps = &parseState{} - } - nc.mu.Unlock() - - // Stack based buffer. - b := make([]byte, defaultBufSize) - - for { - // FIXME(dlc): RWLock here? - nc.mu.Lock() - sb := nc.isClosed() || nc.isReconnecting() - if sb { - nc.ps = &parseState{} - } - conn := nc.conn - nc.mu.Unlock() - - if sb || conn == nil { - break - } - - n, err := conn.Read(b) - if err != nil { - nc.processOpErr(err) - break - } - - if err := nc.parse(b[:n]); err != nil { - nc.processOpErr(err) - break - } - } - // Clear the parseState here.. - nc.mu.Lock() - nc.ps = nil - nc.mu.Unlock() -} - -// waitForMsgs waits on the conditional shared with readLoop and processMsg. -// It is used to deliver messages to asynchronous subscribers. -func (nc *Conn) waitForMsgs(s *Subscription) { - var closed bool - var delivered, max uint64 - - for { - s.mu.Lock() - if s.pHead == nil && !s.closed { - s.pCond.Wait() - } - // Pop the msg off the list - m := s.pHead - if m != nil { - s.pHead = m.next - if s.pHead == nil { - s.pTail = nil - } - s.pMsgs-- - s.pBytes -= len(m.Data) - } - mcb := s.mcb - max = s.max - closed = s.closed - if !s.closed { - s.delivered++ - delivered = s.delivered - } - s.mu.Unlock() - - if closed { - break - } - - // Deliver the message. - if m != nil && (max <= 0 || delivered <= max) { - mcb(m) - } - // If we have hit the max for delivered msgs, remove sub. - if max > 0 && delivered >= max { - nc.mu.Lock() - nc.removeSub(s) - nc.mu.Unlock() - break - } - } -} - -// processMsg is called by parse and will place the msg on the -// appropriate channel/pending queue for processing. If the channel is full, -// or the pending queue is over the pending limits, the connection is -// considered a slow consumer. -func (nc *Conn) processMsg(data []byte) { - // Lock from here on out. - nc.mu.Lock() - - // Stats - nc.InMsgs++ - nc.InBytes += uint64(len(data)) - - sub := nc.subs[nc.ps.ma.sid] - if sub == nil { - nc.mu.Unlock() - return - } - - // Copy them into string - subj := string(nc.ps.ma.subject) - reply := string(nc.ps.ma.reply) - - // Doing message create outside of the sub's lock to reduce contention. - // It's possible that we end-up not using the message, but that's ok. - - // FIXME(dlc): Need to copy, should/can do COW? - msgPayload := make([]byte, len(data)) - copy(msgPayload, data) - - // FIXME(dlc): Should we recycle these containers? - m := &Msg{Data: msgPayload, Subject: subj, Reply: reply, Sub: sub} - - sub.mu.Lock() - - // Subscription internal stats (applicable only for non ChanSubscription's) - if sub.typ != ChanSubscription { - sub.pMsgs++ - if sub.pMsgs > sub.pMsgsMax { - sub.pMsgsMax = sub.pMsgs - } - sub.pBytes += len(m.Data) - if sub.pBytes > sub.pBytesMax { - sub.pBytesMax = sub.pBytes - } - - // Check for a Slow Consumer - if (sub.pMsgsLimit > 0 && sub.pMsgs > sub.pMsgsLimit) || - (sub.pBytesLimit > 0 && sub.pBytes > sub.pBytesLimit) { - goto slowConsumer - } - } - - // We have two modes of delivery. One is the channel, used by channel - // subscribers and syncSubscribers, the other is a linked list for async. - if sub.mch != nil { - select { - case sub.mch <- m: - default: - goto slowConsumer - } - } else { - // Push onto the async pList - if sub.pHead == nil { - sub.pHead = m - sub.pTail = m - sub.pCond.Signal() - } else { - sub.pTail.next = m - sub.pTail = m - } - } - - // Clear SlowConsumer status. - sub.sc = false - - sub.mu.Unlock() - nc.mu.Unlock() - return - -slowConsumer: - sub.dropped++ - nc.processSlowConsumer(sub) - // Undo stats from above - if sub.typ != ChanSubscription { - sub.pMsgs-- - sub.pBytes -= len(m.Data) - } - sub.mu.Unlock() - nc.mu.Unlock() - return -} - -// processSlowConsumer will set SlowConsumer state and fire the -// async error handler if registered. -func (nc *Conn) processSlowConsumer(s *Subscription) { - nc.err = ErrSlowConsumer - if nc.Opts.AsyncErrorCB != nil && !s.sc { - nc.ach <- func() { nc.Opts.AsyncErrorCB(nc, s, ErrSlowConsumer) } - } - s.sc = true -} - -// processPermissionsViolation is called when the server signals a subject -// permissions violation on either publish or subscribe. -func (nc *Conn) processPermissionsViolation(err string) { - nc.err = errors.New("nats: " + err) - if nc.Opts.AsyncErrorCB != nil { - nc.ach <- func() { nc.Opts.AsyncErrorCB(nc, nil, nc.err) } - } -} - -// flusher is a separate Go routine that will process flush requests for the write -// bufio. This allows coalescing of writes to the underlying socket. -func (nc *Conn) flusher() { - // Release the wait group - defer nc.wg.Done() - - // snapshot the bw and conn since they can change from underneath of us. - nc.mu.Lock() - bw := nc.bw - conn := nc.conn - fch := nc.fch - nc.mu.Unlock() - - if conn == nil || bw == nil { - return - } - - for { - if _, ok := <-fch; !ok { - return - } - nc.mu.Lock() - - // Check to see if we should bail out. - if !nc.isConnected() || nc.isConnecting() || bw != nc.bw || conn != nc.conn { - nc.mu.Unlock() - return - } - if bw.Buffered() > 0 { - if err := bw.Flush(); err != nil { - if nc.err == nil { - nc.err = err - } - } - } - nc.mu.Unlock() - } -} - -// processPing will send an immediate pong protocol response to the -// server. The server uses this mechanism to detect dead clients. -func (nc *Conn) processPing() { - nc.sendProto(pongProto) -} - -// processPong is used to process responses to the client's ping -// messages. We use pings for the flush mechanism as well. -func (nc *Conn) processPong() { - var ch chan bool - - nc.mu.Lock() - if len(nc.pongs) > 0 { - ch = nc.pongs[0] - nc.pongs = nc.pongs[1:] - } - nc.pout = 0 - nc.mu.Unlock() - if ch != nil { - ch <- true - } -} - -// processOK is a placeholder for processing OK messages. -func (nc *Conn) processOK() { - // do nothing -} - -// processInfo is used to parse the info messages sent -// from the server. -// This function may update the server pool. -func (nc *Conn) processInfo(info string) error { - if info == _EMPTY_ { - return nil - } - if err := json.Unmarshal([]byte(info), &nc.info); err != nil { - return err - } - updated := false - urls := nc.info.ConnectURLs - for _, curl := range urls { - if _, present := nc.urls[curl]; !present { - if err := nc.addURLToPool(fmt.Sprintf("nats://%s", curl), true); err != nil { - continue - } - updated = true - } - } - if updated && !nc.Opts.NoRandomize { - nc.shufflePool() - } - return nil -} - -// processAsyncInfo does the same than processInfo, but is called -// from the parser. Calls processInfo under connection's lock -// protection. -func (nc *Conn) processAsyncInfo(info []byte) { - nc.mu.Lock() - // Ignore errors, we will simply not update the server pool... - nc.processInfo(string(info)) - nc.mu.Unlock() -} - -// LastError reports the last error encountered via the connection. -// It can be used reliably within ClosedCB in order to find out reason -// why connection was closed for example. -func (nc *Conn) LastError() error { - if nc == nil { - return ErrInvalidConnection - } - nc.mu.Lock() - err := nc.err - nc.mu.Unlock() - return err -} - -// processErr processes any error messages from the server and -// sets the connection's lastError. -func (nc *Conn) processErr(e string) { - // Trim, remove quotes, convert to lower case. - e = normalizeErr(e) - - // FIXME(dlc) - process Slow Consumer signals special. - if e == STALE_CONNECTION { - nc.processOpErr(ErrStaleConnection) - } else if strings.HasPrefix(e, PERMISSIONS_ERR) { - nc.processPermissionsViolation(e) - } else { - nc.mu.Lock() - nc.err = errors.New("nats: " + e) - nc.mu.Unlock() - nc.Close() - } -} - -// kickFlusher will send a bool on a channel to kick the -// flush Go routine to flush data to the server. -func (nc *Conn) kickFlusher() { - if nc.bw != nil { - select { - case nc.fch <- true: - default: - } - } -} - -// Publish publishes the data argument to the given subject. The data -// argument is left untouched and needs to be correctly interpreted on -// the receiver. -func (nc *Conn) Publish(subj string, data []byte) error { - return nc.publish(subj, _EMPTY_, data) -} - -// PublishMsg publishes the Msg structure, which includes the -// Subject, an optional Reply and an optional Data field. -func (nc *Conn) PublishMsg(m *Msg) error { - if m == nil { - return ErrInvalidMsg - } - return nc.publish(m.Subject, m.Reply, m.Data) -} - -// PublishRequest will perform a Publish() excpecting a response on the -// reply subject. Use Request() for automatically waiting for a response -// inline. -func (nc *Conn) PublishRequest(subj, reply string, data []byte) error { - return nc.publish(subj, reply, data) -} - -// Used for handrolled itoa -const digits = "0123456789" - -// publish is the internal function to publish messages to a nats-server. -// Sends a protocol data message by queuing into the bufio writer -// and kicking the flush go routine. These writes should be protected. -func (nc *Conn) publish(subj, reply string, data []byte) error { - if nc == nil { - return ErrInvalidConnection - } - if subj == "" { - return ErrBadSubject - } - nc.mu.Lock() - - // Proactively reject payloads over the threshold set by server. - var msgSize int64 - msgSize = int64(len(data)) - if msgSize > nc.info.MaxPayload { - nc.mu.Unlock() - return ErrMaxPayload - } - - if nc.isClosed() { - nc.mu.Unlock() - return ErrConnectionClosed - } - - // Check if we are reconnecting, and if so check if - // we have exceeded our reconnect outbound buffer limits. - if nc.isReconnecting() { - // Flush to underlying buffer. - nc.bw.Flush() - // Check if we are over - if nc.pending.Len() >= nc.Opts.ReconnectBufSize { - nc.mu.Unlock() - return ErrReconnectBufExceeded - } - } - - msgh := nc.scratch[:len(_PUB_P_)] - msgh = append(msgh, subj...) - msgh = append(msgh, ' ') - if reply != "" { - msgh = append(msgh, reply...) - msgh = append(msgh, ' ') - } - - // We could be smarter here, but simple loop is ok, - // just avoid strconv in fast path - // FIXME(dlc) - Find a better way here. - // msgh = strconv.AppendInt(msgh, int64(len(data)), 10) - - var b [12]byte - var i = len(b) - if len(data) > 0 { - for l := len(data); l > 0; l /= 10 { - i -= 1 - b[i] = digits[l%10] - } - } else { - i -= 1 - b[i] = digits[0] - } - - msgh = append(msgh, b[i:]...) - msgh = append(msgh, _CRLF_...) - - // FIXME, do deadlines here - _, err := nc.bw.Write(msgh) - if err == nil { - _, err = nc.bw.Write(data) - } - if err == nil { - _, err = nc.bw.WriteString(_CRLF_) - } - if err != nil { - nc.mu.Unlock() - return err - } - - nc.OutMsgs++ - nc.OutBytes += uint64(len(data)) - - if len(nc.fch) == 0 { - nc.kickFlusher() - } - nc.mu.Unlock() - return nil -} - -// Request will create an Inbox and perform a Request() call -// with the Inbox reply and return the first reply received. -// This is optimized for the case of multiple responses. -func (nc *Conn) Request(subj string, data []byte, timeout time.Duration) (*Msg, error) { - inbox := NewInbox() - ch := make(chan *Msg, RequestChanLen) - - s, err := nc.subscribe(inbox, _EMPTY_, nil, ch) - if err != nil { - return nil, err - } - s.AutoUnsubscribe(1) - defer s.Unsubscribe() - - err = nc.PublishRequest(subj, inbox, data) - if err != nil { - return nil, err - } - return s.NextMsg(timeout) -} - -// InboxPrefix is the prefix for all inbox subjects. -const InboxPrefix = "_INBOX." -const inboxPrefixLen = len(InboxPrefix) - -// NewInbox will return an inbox string which can be used for directed replies from -// subscribers. These are guaranteed to be unique, but can be shared and subscribed -// to by others. -func NewInbox() string { - var b [inboxPrefixLen + 22]byte - pres := b[:inboxPrefixLen] - copy(pres, InboxPrefix) - ns := b[inboxPrefixLen:] - copy(ns, nuid.Next()) - return string(b[:]) -} - -// Subscribe will express interest in the given subject. The subject -// can have wildcards (partial:*, full:>). Messages will be delivered -// to the associated MsgHandler. If no MsgHandler is given, the -// subscription is a synchronous subscription and can be polled via -// Subscription.NextMsg(). -func (nc *Conn) Subscribe(subj string, cb MsgHandler) (*Subscription, error) { - return nc.subscribe(subj, _EMPTY_, cb, nil) -} - -// ChanSubscribe will place all messages received on the channel. -// You should not close the channel until sub.Unsubscribe() has been called. -func (nc *Conn) ChanSubscribe(subj string, ch chan *Msg) (*Subscription, error) { - return nc.subscribe(subj, _EMPTY_, nil, ch) -} - -// ChanQueueSubscribe will place all messages received on the channel. -// You should not close the channel until sub.Unsubscribe() has been called. -func (nc *Conn) ChanQueueSubscribe(subj, group string, ch chan *Msg) (*Subscription, error) { - return nc.subscribe(subj, group, nil, ch) -} - -// SubscribeSync is syntactic sugar for Subscribe(subject, nil). -func (nc *Conn) SubscribeSync(subj string) (*Subscription, error) { - if nc == nil { - return nil, ErrInvalidConnection - } - mch := make(chan *Msg, nc.Opts.SubChanLen) - s, e := nc.subscribe(subj, _EMPTY_, nil, mch) - if s != nil { - s.typ = SyncSubscription - } - return s, e -} - -// QueueSubscribe creates an asynchronous queue subscriber on the given subject. -// All subscribers with the same queue name will form the queue group and -// only one member of the group will be selected to receive any given -// message asynchronously. -func (nc *Conn) QueueSubscribe(subj, queue string, cb MsgHandler) (*Subscription, error) { - return nc.subscribe(subj, queue, cb, nil) -} - -// QueueSubscribeSync creates a synchronous queue subscriber on the given -// subject. All subscribers with the same queue name will form the queue -// group and only one member of the group will be selected to receive any -// given message synchronously. -func (nc *Conn) QueueSubscribeSync(subj, queue string) (*Subscription, error) { - mch := make(chan *Msg, nc.Opts.SubChanLen) - s, e := nc.subscribe(subj, queue, nil, mch) - if s != nil { - s.typ = SyncSubscription - } - return s, e -} - -// QueueSubscribeSyncWithChan is syntactic sugar for ChanQueueSubscribe(subject, group, ch). -func (nc *Conn) QueueSubscribeSyncWithChan(subj, queue string, ch chan *Msg) (*Subscription, error) { - return nc.subscribe(subj, queue, nil, ch) -} - -// subscribe is the internal subscribe function that indicates interest in a subject. -func (nc *Conn) subscribe(subj, queue string, cb MsgHandler, ch chan *Msg) (*Subscription, error) { - if nc == nil { - return nil, ErrInvalidConnection - } - nc.mu.Lock() - // ok here, but defer is generally expensive - defer nc.mu.Unlock() - defer nc.kickFlusher() - - // Check for some error conditions. - if nc.isClosed() { - return nil, ErrConnectionClosed - } - - if cb == nil && ch == nil { - return nil, ErrBadSubscription - } - - sub := &Subscription{Subject: subj, Queue: queue, mcb: cb, conn: nc} - // Set pending limits. - sub.pMsgsLimit = DefaultSubPendingMsgsLimit - sub.pBytesLimit = DefaultSubPendingBytesLimit - - // If we have an async callback, start up a sub specific - // Go routine to deliver the messages. - if cb != nil { - sub.typ = AsyncSubscription - sub.pCond = sync.NewCond(&sub.mu) - go nc.waitForMsgs(sub) - } else { - sub.typ = ChanSubscription - sub.mch = ch - } - - sub.sid = atomic.AddInt64(&nc.ssid, 1) - nc.subs[sub.sid] = sub - - // We will send these for all subs when we reconnect - // so that we can suppress here. - if !nc.isReconnecting() { - nc.bw.WriteString(fmt.Sprintf(subProto, subj, queue, sub.sid)) - } - return sub, nil -} - -// Lock for nc should be held here upon entry -func (nc *Conn) removeSub(s *Subscription) { - delete(nc.subs, s.sid) - s.mu.Lock() - defer s.mu.Unlock() - // Release callers on NextMsg for SyncSubscription only - if s.mch != nil && s.typ == SyncSubscription { - close(s.mch) - } - s.mch = nil - - // Mark as invalid - s.conn = nil - s.closed = true - if s.pCond != nil { - s.pCond.Broadcast() - } -} - -// SubscriptionType is the type of the Subscription. -type SubscriptionType int - -// The different types of subscription types. -const ( - AsyncSubscription = SubscriptionType(iota) - SyncSubscription - ChanSubscription - NilSubscription -) - -// Type returns the type of Subscription. -func (s *Subscription) Type() SubscriptionType { - if s == nil { - return NilSubscription - } - s.mu.Lock() - defer s.mu.Unlock() - return s.typ -} - -// IsValid returns a boolean indicating whether the subscription -// is still active. This will return false if the subscription has -// already been closed. -func (s *Subscription) IsValid() bool { - if s == nil { - return false - } - s.mu.Lock() - defer s.mu.Unlock() - return s.conn != nil -} - -// Unsubscribe will remove interest in the given subject. -func (s *Subscription) Unsubscribe() error { - if s == nil { - return ErrBadSubscription - } - s.mu.Lock() - conn := s.conn - s.mu.Unlock() - if conn == nil { - return ErrBadSubscription - } - return conn.unsubscribe(s, 0) -} - -// AutoUnsubscribe will issue an automatic Unsubscribe that is -// processed by the server when max messages have been received. -// This can be useful when sending a request to an unknown number -// of subscribers. Request() uses this functionality. -func (s *Subscription) AutoUnsubscribe(max int) error { - if s == nil { - return ErrBadSubscription - } - s.mu.Lock() - conn := s.conn - s.mu.Unlock() - if conn == nil { - return ErrBadSubscription - } - return conn.unsubscribe(s, max) -} - -// unsubscribe performs the low level unsubscribe to the server. -// Use Subscription.Unsubscribe() -func (nc *Conn) unsubscribe(sub *Subscription, max int) error { - nc.mu.Lock() - // ok here, but defer is expensive - defer nc.mu.Unlock() - defer nc.kickFlusher() - - if nc.isClosed() { - return ErrConnectionClosed - } - - s := nc.subs[sub.sid] - // Already unsubscribed - if s == nil { - return nil - } - - maxStr := _EMPTY_ - if max > 0 { - s.max = uint64(max) - maxStr = strconv.Itoa(max) - } else { - nc.removeSub(s) - } - // We will send these for all subs when we reconnect - // so that we can suppress here. - if !nc.isReconnecting() { - nc.bw.WriteString(fmt.Sprintf(unsubProto, s.sid, maxStr)) - } - return nil -} - -// NextMsg() will return the next message available to a synchronous subscriber -// or block until one is available. A timeout can be used to return when no -// message has been delivered. -func (s *Subscription) NextMsg(timeout time.Duration) (*Msg, error) { - if s == nil { - return nil, ErrBadSubscription - } - s.mu.Lock() - if s.connClosed { - s.mu.Unlock() - return nil, ErrConnectionClosed - } - if s.mch == nil { - if s.max > 0 && s.delivered >= s.max { - s.mu.Unlock() - return nil, ErrMaxMessages - } else if s.closed { - s.mu.Unlock() - return nil, ErrBadSubscription - } - } - if s.mcb != nil { - s.mu.Unlock() - return nil, ErrSyncSubRequired - } - if s.sc { - s.sc = false - s.mu.Unlock() - return nil, ErrSlowConsumer - } - - // snapshot - nc := s.conn - mch := s.mch - max := s.max - s.mu.Unlock() - - var ok bool - var msg *Msg - - t := time.NewTimer(timeout) - defer t.Stop() - - select { - case msg, ok = <-mch: - if !ok { - return nil, ErrConnectionClosed - } - // Update some stats. - s.mu.Lock() - s.delivered++ - delivered := s.delivered - if s.typ == SyncSubscription { - s.pMsgs-- - s.pBytes -= len(msg.Data) - } - s.mu.Unlock() - - if max > 0 { - if delivered > max { - return nil, ErrMaxMessages - } - // Remove subscription if we have reached max. - if delivered == max { - nc.mu.Lock() - nc.removeSub(s) - nc.mu.Unlock() - } - } - - case <-t.C: - return nil, ErrTimeout - } - - return msg, nil -} - -// Queued returns the number of queued messages in the client for this subscription. -// DEPRECATED: Use Pending() -func (s *Subscription) QueuedMsgs() (int, error) { - m, _, err := s.Pending() - return int(m), err -} - -// Pending returns the number of queued messages and queued bytes in the client for this subscription. -func (s *Subscription) Pending() (int, int, error) { - if s == nil { - return -1, -1, ErrBadSubscription - } - s.mu.Lock() - defer s.mu.Unlock() - if s.conn == nil { - return -1, -1, ErrBadSubscription - } - if s.typ == ChanSubscription { - return -1, -1, ErrTypeSubscription - } - return s.pMsgs, s.pBytes, nil -} - -// MaxPending returns the maximum number of queued messages and queued bytes seen so far. -func (s *Subscription) MaxPending() (int, int, error) { - if s == nil { - return -1, -1, ErrBadSubscription - } - s.mu.Lock() - defer s.mu.Unlock() - if s.conn == nil { - return -1, -1, ErrBadSubscription - } - if s.typ == ChanSubscription { - return -1, -1, ErrTypeSubscription - } - return s.pMsgsMax, s.pBytesMax, nil -} - -// ClearMaxPending resets the maximums seen so far. -func (s *Subscription) ClearMaxPending() error { - if s == nil { - return ErrBadSubscription - } - s.mu.Lock() - defer s.mu.Unlock() - if s.conn == nil { - return ErrBadSubscription - } - if s.typ == ChanSubscription { - return ErrTypeSubscription - } - s.pMsgsMax, s.pBytesMax = 0, 0 - return nil -} - -// Pending Limits -const ( - DefaultSubPendingMsgsLimit = 65536 - DefaultSubPendingBytesLimit = 65536 * 1024 -) - -// PendingLimits returns the current limits for this subscription. -// If no error is returned, a negative value indicates that the -// given metric is not limited. -func (s *Subscription) PendingLimits() (int, int, error) { - if s == nil { - return -1, -1, ErrBadSubscription - } - s.mu.Lock() - defer s.mu.Unlock() - if s.conn == nil { - return -1, -1, ErrBadSubscription - } - if s.typ == ChanSubscription { - return -1, -1, ErrTypeSubscription - } - return s.pMsgsLimit, s.pBytesLimit, nil -} - -// SetPendingLimits sets the limits for pending msgs and bytes for this subscription. -// Zero is not allowed. Any negative value means that the given metric is not limited. -func (s *Subscription) SetPendingLimits(msgLimit, bytesLimit int) error { - if s == nil { - return ErrBadSubscription - } - s.mu.Lock() - defer s.mu.Unlock() - if s.conn == nil { - return ErrBadSubscription - } - if s.typ == ChanSubscription { - return ErrTypeSubscription - } - if msgLimit == 0 || bytesLimit == 0 { - return ErrInvalidArg - } - s.pMsgsLimit, s.pBytesLimit = msgLimit, bytesLimit - return nil -} - -// Delivered returns the number of delivered messages for this subscription. -func (s *Subscription) Delivered() (int64, error) { - if s == nil { - return -1, ErrBadSubscription - } - s.mu.Lock() - defer s.mu.Unlock() - if s.conn == nil { - return -1, ErrBadSubscription - } - return int64(s.delivered), nil -} - -// Dropped returns the number of known dropped messages for this subscription. -// This will correspond to messages dropped by violations of PendingLimits. If -// the server declares the connection a SlowConsumer, this number may not be -// valid. -func (s *Subscription) Dropped() (int, error) { - if s == nil { - return -1, ErrBadSubscription - } - s.mu.Lock() - defer s.mu.Unlock() - if s.conn == nil { - return -1, ErrBadSubscription - } - return s.dropped, nil -} - -// FIXME: This is a hack -// removeFlushEntry is needed when we need to discard queued up responses -// for our pings as part of a flush call. This happens when we have a flush -// call outstanding and we call close. -func (nc *Conn) removeFlushEntry(ch chan bool) bool { - nc.mu.Lock() - defer nc.mu.Unlock() - if nc.pongs == nil { - return false - } - for i, c := range nc.pongs { - if c == ch { - nc.pongs[i] = nil - return true - } - } - return false -} - -// The lock must be held entering this function. -func (nc *Conn) sendPing(ch chan bool) { - nc.pongs = append(nc.pongs, ch) - nc.bw.WriteString(pingProto) - // Flush in place. - nc.bw.Flush() -} - -// This will fire periodically and send a client origin -// ping to the server. Will also check that we have received -// responses from the server. -func (nc *Conn) processPingTimer() { - nc.mu.Lock() - - if nc.status != CONNECTED { - nc.mu.Unlock() - return - } - - // Check for violation - nc.pout++ - if nc.pout > nc.Opts.MaxPingsOut { - nc.mu.Unlock() - nc.processOpErr(ErrStaleConnection) - return - } - - nc.sendPing(nil) - nc.ptmr.Reset(nc.Opts.PingInterval) - nc.mu.Unlock() -} - -// FlushTimeout allows a Flush operation to have an associated timeout. -func (nc *Conn) FlushTimeout(timeout time.Duration) (err error) { - if nc == nil { - return ErrInvalidConnection - } - if timeout <= 0 { - return ErrBadTimeout - } - - nc.mu.Lock() - if nc.isClosed() { - nc.mu.Unlock() - return ErrConnectionClosed - } - t := time.NewTimer(timeout) - defer t.Stop() - - ch := make(chan bool) // FIXME: Inefficient? - nc.sendPing(ch) - nc.mu.Unlock() - - select { - case _, ok := <-ch: - if !ok { - err = ErrConnectionClosed - } else { - close(ch) - } - case <-t.C: - err = ErrTimeout - } - - if err != nil { - nc.removeFlushEntry(ch) - } - return -} - -// Flush will perform a round trip to the server and return when it -// receives the internal reply. -func (nc *Conn) Flush() error { - return nc.FlushTimeout(60 * time.Second) -} - -// Buffered will return the number of bytes buffered to be sent to the server. -// FIXME(dlc) take into account disconnected state. -func (nc *Conn) Buffered() (int, error) { - nc.mu.Lock() - defer nc.mu.Unlock() - if nc.isClosed() || nc.bw == nil { - return -1, ErrConnectionClosed - } - return nc.bw.Buffered(), nil -} - -// resendSubscriptions will send our subscription state back to the -// server. Used in reconnects -func (nc *Conn) resendSubscriptions() { - for _, s := range nc.subs { - adjustedMax := uint64(0) - s.mu.Lock() - if s.max > 0 { - if s.delivered < s.max { - adjustedMax = s.max - s.delivered - } - - // adjustedMax could be 0 here if the number of delivered msgs - // reached the max, if so unsubscribe. - if adjustedMax == 0 { - s.mu.Unlock() - nc.bw.WriteString(fmt.Sprintf(unsubProto, s.sid, _EMPTY_)) - continue - } - } - s.mu.Unlock() - - nc.bw.WriteString(fmt.Sprintf(subProto, s.Subject, s.Queue, s.sid)) - if adjustedMax > 0 { - maxStr := strconv.Itoa(int(adjustedMax)) - nc.bw.WriteString(fmt.Sprintf(unsubProto, s.sid, maxStr)) - } - } -} - -// This will clear any pending flush calls and release pending calls. -// Lock is assumed to be held by the caller. -func (nc *Conn) clearPendingFlushCalls() { - // Clear any queued pongs, e.g. pending flush calls. - for _, ch := range nc.pongs { - if ch != nil { - close(ch) - } - } - nc.pongs = nil -} - -// Low level close call that will do correct cleanup and set -// desired status. Also controls whether user defined callbacks -// will be triggered. The lock should not be held entering this -// function. This function will handle the locking manually. -func (nc *Conn) close(status Status, doCBs bool) { - nc.mu.Lock() - if nc.isClosed() { - nc.status = status - nc.mu.Unlock() - return - } - nc.status = CLOSED - - // Kick the Go routines so they fall out. - nc.kickFlusher() - nc.mu.Unlock() - - nc.mu.Lock() - - // Clear any queued pongs, e.g. pending flush calls. - nc.clearPendingFlushCalls() - - if nc.ptmr != nil { - nc.ptmr.Stop() - } - - // Go ahead and make sure we have flushed the outbound - if nc.conn != nil { - nc.bw.Flush() - defer nc.conn.Close() - } - - // Close sync subscriber channels and release any - // pending NextMsg() calls. - for _, s := range nc.subs { - s.mu.Lock() - - // Release callers on NextMsg for SyncSubscription only - if s.mch != nil && s.typ == SyncSubscription { - close(s.mch) - } - s.mch = nil - // Mark as invalid, for signalling to deliverMsgs - s.closed = true - // Mark connection closed in subscription - s.connClosed = true - // If we have an async subscription, signals it to exit - if s.typ == AsyncSubscription && s.pCond != nil { - s.pCond.Signal() - } - - s.mu.Unlock() - } - nc.subs = nil - - // Perform appropriate callback if needed for a disconnect. - if doCBs { - if nc.Opts.DisconnectedCB != nil && nc.conn != nil { - nc.ach <- func() { nc.Opts.DisconnectedCB(nc) } - } - if nc.Opts.ClosedCB != nil { - nc.ach <- func() { nc.Opts.ClosedCB(nc) } - } - nc.ach <- nc.closeAsyncFunc() - } - nc.status = status - nc.mu.Unlock() -} - -// Close will close the connection to the server. This call will release -// all blocking calls, such as Flush() and NextMsg() -func (nc *Conn) Close() { - nc.close(CLOSED, true) -} - -// IsClosed tests if a Conn has been closed. -func (nc *Conn) IsClosed() bool { - nc.mu.Lock() - defer nc.mu.Unlock() - return nc.isClosed() -} - -// IsReconnecting tests if a Conn is reconnecting. -func (nc *Conn) IsReconnecting() bool { - nc.mu.Lock() - defer nc.mu.Unlock() - return nc.isReconnecting() -} - -// IsConnected tests if a Conn is connected. -func (nc *Conn) IsConnected() bool { - nc.mu.Lock() - defer nc.mu.Unlock() - return nc.isConnected() -} - -// caller must lock -func (nc *Conn) getServers(implicitOnly bool) []string { - poolSize := len(nc.srvPool) - var servers = make([]string, 0) - for i := 0; i < poolSize; i++ { - if implicitOnly && !nc.srvPool[i].isImplicit { - continue - } - url := nc.srvPool[i].url - servers = append(servers, fmt.Sprintf("%s://%s", url.Scheme, url.Host)) - } - return servers -} - -// Servers returns the list of known server urls, including additional -// servers discovered after a connection has been established. If -// authentication is enabled, use UserInfo or Token when connecting with -// these urls. -func (nc *Conn) Servers() []string { - nc.mu.Lock() - defer nc.mu.Unlock() - return nc.getServers(false) -} - -// DiscoveredServers returns only the server urls that have been discovered -// after a connection has been established. If authentication is enabled, -// use UserInfo or Token when connecting with these urls. -func (nc *Conn) DiscoveredServers() []string { - nc.mu.Lock() - defer nc.mu.Unlock() - return nc.getServers(true) -} - -// Status returns the current state of the connection. -func (nc *Conn) Status() Status { - nc.mu.Lock() - defer nc.mu.Unlock() - return nc.status -} - -// Test if Conn has been closed Lock is assumed held. -func (nc *Conn) isClosed() bool { - return nc.status == CLOSED -} - -// Test if Conn is in the process of connecting -func (nc *Conn) isConnecting() bool { - return nc.status == CONNECTING -} - -// Test if Conn is being reconnected. -func (nc *Conn) isReconnecting() bool { - return nc.status == RECONNECTING -} - -// Test if Conn is connected or connecting. -func (nc *Conn) isConnected() bool { - return nc.status == CONNECTED -} - -// Stats will return a race safe copy of the Statistics section for the connection. -func (nc *Conn) Stats() Statistics { - nc.mu.Lock() - defer nc.mu.Unlock() - stats := nc.Statistics - return stats -} - -// MaxPayload returns the size limit that a message payload can have. -// This is set by the server configuration and delivered to the client -// upon connect. -func (nc *Conn) MaxPayload() int64 { - nc.mu.Lock() - defer nc.mu.Unlock() - return nc.info.MaxPayload -} - -// AuthRequired will return if the connected server requires authorization. -func (nc *Conn) AuthRequired() bool { - nc.mu.Lock() - defer nc.mu.Unlock() - return nc.info.AuthRequired -} - -// TLSRequired will return if the connected server requires TLS connections. -func (nc *Conn) TLSRequired() bool { - nc.mu.Lock() - defer nc.mu.Unlock() - return nc.info.TLSRequired -} diff --git a/vendor/github.com/nats-io/go-nats/netchan.go b/vendor/github.com/nats-io/go-nats/netchan.go deleted file mode 100644 index 337674e..0000000 --- a/vendor/github.com/nats-io/go-nats/netchan.go +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright 2013-2014 Apcera Inc. All rights reserved. - -package nats - -import ( - "errors" - "reflect" -) - -// This allows the functionality for network channels by binding send and receive Go chans -// to subjects and optionally queue groups. -// Data will be encoded and decoded via the EncodedConn and its associated encoders. - -// BindSendChan binds a channel for send operations to NATS. -func (c *EncodedConn) BindSendChan(subject string, channel interface{}) error { - chVal := reflect.ValueOf(channel) - if chVal.Kind() != reflect.Chan { - return ErrChanArg - } - go chPublish(c, chVal, subject) - return nil -} - -// Publish all values that arrive on the channel until it is closed or we -// encounter an error. -func chPublish(c *EncodedConn, chVal reflect.Value, subject string) { - for { - val, ok := chVal.Recv() - if !ok { - // Channel has most likely been closed. - return - } - if e := c.Publish(subject, val.Interface()); e != nil { - // Do this under lock. - c.Conn.mu.Lock() - defer c.Conn.mu.Unlock() - - if c.Conn.Opts.AsyncErrorCB != nil { - // FIXME(dlc) - Not sure this is the right thing to do. - // FIXME(ivan) - If the connection is not yet closed, try to schedule the callback - if c.Conn.isClosed() { - go c.Conn.Opts.AsyncErrorCB(c.Conn, nil, e) - } else { - c.Conn.ach <- func() { c.Conn.Opts.AsyncErrorCB(c.Conn, nil, e) } - } - } - return - } - } -} - -// BindRecvChan binds a channel for receive operations from NATS. -func (c *EncodedConn) BindRecvChan(subject string, channel interface{}) (*Subscription, error) { - return c.bindRecvChan(subject, _EMPTY_, channel) -} - -// BindRecvQueueChan binds a channel for queue-based receive operations from NATS. -func (c *EncodedConn) BindRecvQueueChan(subject, queue string, channel interface{}) (*Subscription, error) { - return c.bindRecvChan(subject, queue, channel) -} - -// Internal function to bind receive operations for a channel. -func (c *EncodedConn) bindRecvChan(subject, queue string, channel interface{}) (*Subscription, error) { - chVal := reflect.ValueOf(channel) - if chVal.Kind() != reflect.Chan { - return nil, ErrChanArg - } - argType := chVal.Type().Elem() - - cb := func(m *Msg) { - var oPtr reflect.Value - if argType.Kind() != reflect.Ptr { - oPtr = reflect.New(argType) - } else { - oPtr = reflect.New(argType.Elem()) - } - if err := c.Enc.Decode(m.Subject, m.Data, oPtr.Interface()); err != nil { - c.Conn.err = errors.New("nats: Got an error trying to unmarshal: " + err.Error()) - if c.Conn.Opts.AsyncErrorCB != nil { - c.Conn.ach <- func() { c.Conn.Opts.AsyncErrorCB(c.Conn, m.Sub, c.Conn.err) } - } - return - } - if argType.Kind() != reflect.Ptr { - oPtr = reflect.Indirect(oPtr) - } - // This is a bit hacky, but in this instance we may be trying to send to a closed channel. - // and the user does not know when it is safe to close the channel. - defer func() { - // If we have panicked, recover and close the subscription. - if r := recover(); r != nil { - m.Sub.Unsubscribe() - } - }() - // Actually do the send to the channel. - chVal.Send(oPtr) - } - - return c.Conn.subscribe(subject, queue, cb, nil) -} diff --git a/vendor/github.com/nats-io/go-nats/parser.go b/vendor/github.com/nats-io/go-nats/parser.go deleted file mode 100644 index 0911954..0000000 --- a/vendor/github.com/nats-io/go-nats/parser.go +++ /dev/null @@ -1,470 +0,0 @@ -// Copyright 2012-2014 Apcera Inc. All rights reserved. - -package nats - -import ( - "fmt" -) - -type msgArg struct { - subject []byte - reply []byte - sid int64 - size int -} - -const MAX_CONTROL_LINE_SIZE = 1024 - -type parseState struct { - state int - as int - drop int - ma msgArg - argBuf []byte - msgBuf []byte - scratch [MAX_CONTROL_LINE_SIZE]byte -} - -const ( - OP_START = iota - OP_PLUS - OP_PLUS_O - OP_PLUS_OK - OP_MINUS - OP_MINUS_E - OP_MINUS_ER - OP_MINUS_ERR - OP_MINUS_ERR_SPC - MINUS_ERR_ARG - OP_M - OP_MS - OP_MSG - OP_MSG_SPC - MSG_ARG - MSG_PAYLOAD - MSG_END - OP_P - OP_PI - OP_PIN - OP_PING - OP_PO - OP_PON - OP_PONG - OP_I - OP_IN - OP_INF - OP_INFO - OP_INFO_SPC - INFO_ARG -) - -// parse is the fast protocol parser engine. -func (nc *Conn) parse(buf []byte) error { - var i int - var b byte - - // Move to loop instead of range syntax to allow jumping of i - for i = 0; i < len(buf); i++ { - b = buf[i] - - switch nc.ps.state { - case OP_START: - switch b { - case 'M', 'm': - nc.ps.state = OP_M - case 'P', 'p': - nc.ps.state = OP_P - case '+': - nc.ps.state = OP_PLUS - case '-': - nc.ps.state = OP_MINUS - case 'I', 'i': - nc.ps.state = OP_I - default: - goto parseErr - } - case OP_M: - switch b { - case 'S', 's': - nc.ps.state = OP_MS - default: - goto parseErr - } - case OP_MS: - switch b { - case 'G', 'g': - nc.ps.state = OP_MSG - default: - goto parseErr - } - case OP_MSG: - switch b { - case ' ', '\t': - nc.ps.state = OP_MSG_SPC - default: - goto parseErr - } - case OP_MSG_SPC: - switch b { - case ' ', '\t': - continue - default: - nc.ps.state = MSG_ARG - nc.ps.as = i - } - case MSG_ARG: - switch b { - case '\r': - nc.ps.drop = 1 - case '\n': - var arg []byte - if nc.ps.argBuf != nil { - arg = nc.ps.argBuf - } else { - arg = buf[nc.ps.as : i-nc.ps.drop] - } - if err := nc.processMsgArgs(arg); err != nil { - return err - } - nc.ps.drop, nc.ps.as, nc.ps.state = 0, i+1, MSG_PAYLOAD - - // jump ahead with the index. If this overruns - // what is left we fall out and process split - // buffer. - i = nc.ps.as + nc.ps.ma.size - 1 - default: - if nc.ps.argBuf != nil { - nc.ps.argBuf = append(nc.ps.argBuf, b) - } - } - case MSG_PAYLOAD: - if nc.ps.msgBuf != nil { - if len(nc.ps.msgBuf) >= nc.ps.ma.size { - nc.processMsg(nc.ps.msgBuf) - nc.ps.argBuf, nc.ps.msgBuf, nc.ps.state = nil, nil, MSG_END - } else { - // copy as much as we can to the buffer and skip ahead. - toCopy := nc.ps.ma.size - len(nc.ps.msgBuf) - avail := len(buf) - i - - if avail < toCopy { - toCopy = avail - } - - if toCopy > 0 { - start := len(nc.ps.msgBuf) - // This is needed for copy to work. - nc.ps.msgBuf = nc.ps.msgBuf[:start+toCopy] - copy(nc.ps.msgBuf[start:], buf[i:i+toCopy]) - // Update our index - i = (i + toCopy) - 1 - } else { - nc.ps.msgBuf = append(nc.ps.msgBuf, b) - } - } - } else if i-nc.ps.as >= nc.ps.ma.size { - nc.processMsg(buf[nc.ps.as:i]) - nc.ps.argBuf, nc.ps.msgBuf, nc.ps.state = nil, nil, MSG_END - } - case MSG_END: - switch b { - case '\n': - nc.ps.drop, nc.ps.as, nc.ps.state = 0, i+1, OP_START - default: - continue - } - case OP_PLUS: - switch b { - case 'O', 'o': - nc.ps.state = OP_PLUS_O - default: - goto parseErr - } - case OP_PLUS_O: - switch b { - case 'K', 'k': - nc.ps.state = OP_PLUS_OK - default: - goto parseErr - } - case OP_PLUS_OK: - switch b { - case '\n': - nc.processOK() - nc.ps.drop, nc.ps.state = 0, OP_START - } - case OP_MINUS: - switch b { - case 'E', 'e': - nc.ps.state = OP_MINUS_E - default: - goto parseErr - } - case OP_MINUS_E: - switch b { - case 'R', 'r': - nc.ps.state = OP_MINUS_ER - default: - goto parseErr - } - case OP_MINUS_ER: - switch b { - case 'R', 'r': - nc.ps.state = OP_MINUS_ERR - default: - goto parseErr - } - case OP_MINUS_ERR: - switch b { - case ' ', '\t': - nc.ps.state = OP_MINUS_ERR_SPC - default: - goto parseErr - } - case OP_MINUS_ERR_SPC: - switch b { - case ' ', '\t': - continue - default: - nc.ps.state = MINUS_ERR_ARG - nc.ps.as = i - } - case MINUS_ERR_ARG: - switch b { - case '\r': - nc.ps.drop = 1 - case '\n': - var arg []byte - if nc.ps.argBuf != nil { - arg = nc.ps.argBuf - nc.ps.argBuf = nil - } else { - arg = buf[nc.ps.as : i-nc.ps.drop] - } - nc.processErr(string(arg)) - nc.ps.drop, nc.ps.as, nc.ps.state = 0, i+1, OP_START - default: - if nc.ps.argBuf != nil { - nc.ps.argBuf = append(nc.ps.argBuf, b) - } - } - case OP_P: - switch b { - case 'I', 'i': - nc.ps.state = OP_PI - case 'O', 'o': - nc.ps.state = OP_PO - default: - goto parseErr - } - case OP_PO: - switch b { - case 'N', 'n': - nc.ps.state = OP_PON - default: - goto parseErr - } - case OP_PON: - switch b { - case 'G', 'g': - nc.ps.state = OP_PONG - default: - goto parseErr - } - case OP_PONG: - switch b { - case '\n': - nc.processPong() - nc.ps.drop, nc.ps.state = 0, OP_START - } - case OP_PI: - switch b { - case 'N', 'n': - nc.ps.state = OP_PIN - default: - goto parseErr - } - case OP_PIN: - switch b { - case 'G', 'g': - nc.ps.state = OP_PING - default: - goto parseErr - } - case OP_PING: - switch b { - case '\n': - nc.processPing() - nc.ps.drop, nc.ps.state = 0, OP_START - } - case OP_I: - switch b { - case 'N', 'n': - nc.ps.state = OP_IN - default: - goto parseErr - } - case OP_IN: - switch b { - case 'F', 'f': - nc.ps.state = OP_INF - default: - goto parseErr - } - case OP_INF: - switch b { - case 'O', 'o': - nc.ps.state = OP_INFO - default: - goto parseErr - } - case OP_INFO: - switch b { - case ' ', '\t': - nc.ps.state = OP_INFO_SPC - default: - goto parseErr - } - case OP_INFO_SPC: - switch b { - case ' ', '\t': - continue - default: - nc.ps.state = INFO_ARG - nc.ps.as = i - } - case INFO_ARG: - switch b { - case '\r': - nc.ps.drop = 1 - case '\n': - var arg []byte - if nc.ps.argBuf != nil { - arg = nc.ps.argBuf - nc.ps.argBuf = nil - } else { - arg = buf[nc.ps.as : i-nc.ps.drop] - } - nc.processAsyncInfo(arg) - nc.ps.drop, nc.ps.as, nc.ps.state = 0, i+1, OP_START - default: - if nc.ps.argBuf != nil { - nc.ps.argBuf = append(nc.ps.argBuf, b) - } - } - default: - goto parseErr - } - } - // Check for split buffer scenarios - if (nc.ps.state == MSG_ARG || nc.ps.state == MINUS_ERR_ARG || nc.ps.state == INFO_ARG) && nc.ps.argBuf == nil { - nc.ps.argBuf = nc.ps.scratch[:0] - nc.ps.argBuf = append(nc.ps.argBuf, buf[nc.ps.as:i-nc.ps.drop]...) - // FIXME, check max len - } - // Check for split msg - if nc.ps.state == MSG_PAYLOAD && nc.ps.msgBuf == nil { - // We need to clone the msgArg if it is still referencing the - // read buffer and we are not able to process the msg. - if nc.ps.argBuf == nil { - nc.cloneMsgArg() - } - - // If we will overflow the scratch buffer, just create a - // new buffer to hold the split message. - if nc.ps.ma.size > cap(nc.ps.scratch)-len(nc.ps.argBuf) { - lrem := len(buf[nc.ps.as:]) - - nc.ps.msgBuf = make([]byte, lrem, nc.ps.ma.size) - copy(nc.ps.msgBuf, buf[nc.ps.as:]) - } else { - nc.ps.msgBuf = nc.ps.scratch[len(nc.ps.argBuf):len(nc.ps.argBuf)] - nc.ps.msgBuf = append(nc.ps.msgBuf, (buf[nc.ps.as:])...) - } - } - - return nil - -parseErr: - return fmt.Errorf("nats: Parse Error [%d]: '%s'", nc.ps.state, buf[i:]) -} - -// cloneMsgArg is used when the split buffer scenario has the pubArg in the existing read buffer, but -// we need to hold onto it into the next read. -func (nc *Conn) cloneMsgArg() { - nc.ps.argBuf = nc.ps.scratch[:0] - nc.ps.argBuf = append(nc.ps.argBuf, nc.ps.ma.subject...) - nc.ps.argBuf = append(nc.ps.argBuf, nc.ps.ma.reply...) - nc.ps.ma.subject = nc.ps.argBuf[:len(nc.ps.ma.subject)] - if nc.ps.ma.reply != nil { - nc.ps.ma.reply = nc.ps.argBuf[len(nc.ps.ma.subject):] - } -} - -const argsLenMax = 4 - -func (nc *Conn) processMsgArgs(arg []byte) error { - // Unroll splitArgs to avoid runtime/heap issues - a := [argsLenMax][]byte{} - args := a[:0] - start := -1 - for i, b := range arg { - switch b { - case ' ', '\t', '\r', '\n': - if start >= 0 { - args = append(args, arg[start:i]) - start = -1 - } - default: - if start < 0 { - start = i - } - } - } - if start >= 0 { - args = append(args, arg[start:]) - } - - switch len(args) { - case 3: - nc.ps.ma.subject = args[0] - nc.ps.ma.sid = parseInt64(args[1]) - nc.ps.ma.reply = nil - nc.ps.ma.size = int(parseInt64(args[2])) - case 4: - nc.ps.ma.subject = args[0] - nc.ps.ma.sid = parseInt64(args[1]) - nc.ps.ma.reply = args[2] - nc.ps.ma.size = int(parseInt64(args[3])) - default: - return fmt.Errorf("nats: processMsgArgs Parse Error: '%s'", arg) - } - if nc.ps.ma.sid < 0 { - return fmt.Errorf("nats: processMsgArgs Bad or Missing Sid: '%s'", arg) - } - if nc.ps.ma.size < 0 { - return fmt.Errorf("nats: processMsgArgs Bad or Missing Size: '%s'", arg) - } - return nil -} - -// Ascii numbers 0-9 -const ( - ascii_0 = 48 - ascii_9 = 57 -) - -// parseInt64 expects decimal positive numbers. We -// return -1 to signal error -func parseInt64(d []byte) (n int64) { - if len(d) == 0 { - return -1 - } - for _, dec := range d { - if dec < ascii_0 || dec > ascii_9 { - return -1 - } - n = n*10 + (int64(dec) - ascii_0) - } - return n -} diff --git a/vendor/github.com/nats-io/nats/LICENSE b/vendor/github.com/nats-io/nats/LICENSE deleted file mode 100644 index 4cfd668..0000000 --- a/vendor/github.com/nats-io/nats/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2012-2016 Apcera Inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/nats-io/nats/encoders/builtin/default_enc.go b/vendor/github.com/nats-io/nats/encoders/builtin/default_enc.go deleted file mode 100644 index 82467ce..0000000 --- a/vendor/github.com/nats-io/nats/encoders/builtin/default_enc.go +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2012-2015 Apcera Inc. All rights reserved. - -package builtin - -import ( - "bytes" - "fmt" - "reflect" - "strconv" - "unsafe" -) - -// DefaultEncoder implementation for EncodedConn. -// This encoder will leave []byte and string untouched, but will attempt to -// turn numbers into appropriate strings that can be decoded. It will also -// propely encoded and decode bools. If will encode a struct, but if you want -// to properly handle structures you should use JsonEncoder. -type DefaultEncoder struct { - // Empty -} - -var trueB = []byte("true") -var falseB = []byte("false") -var nilB = []byte("") - -// Encode -func (je *DefaultEncoder) Encode(subject string, v interface{}) ([]byte, error) { - switch arg := v.(type) { - case string: - bytes := *(*[]byte)(unsafe.Pointer(&arg)) - return bytes, nil - case []byte: - return arg, nil - case bool: - if arg { - return trueB, nil - } else { - return falseB, nil - } - case nil: - return nilB, nil - default: - var buf bytes.Buffer - fmt.Fprintf(&buf, "%+v", arg) - return buf.Bytes(), nil - } -} - -// Decode -func (je *DefaultEncoder) Decode(subject string, data []byte, vPtr interface{}) error { - // Figure out what it's pointing to... - sData := *(*string)(unsafe.Pointer(&data)) - switch arg := vPtr.(type) { - case *string: - *arg = sData - return nil - case *[]byte: - *arg = data - return nil - case *int: - n, err := strconv.ParseInt(sData, 10, 64) - if err != nil { - return err - } - *arg = int(n) - return nil - case *int32: - n, err := strconv.ParseInt(sData, 10, 64) - if err != nil { - return err - } - *arg = int32(n) - return nil - case *int64: - n, err := strconv.ParseInt(sData, 10, 64) - if err != nil { - return err - } - *arg = int64(n) - return nil - case *float32: - n, err := strconv.ParseFloat(sData, 32) - if err != nil { - return err - } - *arg = float32(n) - return nil - case *float64: - n, err := strconv.ParseFloat(sData, 64) - if err != nil { - return err - } - *arg = float64(n) - return nil - case *bool: - b, err := strconv.ParseBool(sData) - if err != nil { - return err - } - *arg = b - return nil - default: - vt := reflect.TypeOf(arg).Elem() - return fmt.Errorf("nats: Default Encoder can't decode to type %s", vt) - } -} diff --git a/vendor/github.com/nats-io/nats/encoders/builtin/gob_enc.go b/vendor/github.com/nats-io/nats/encoders/builtin/gob_enc.go deleted file mode 100644 index 988ff42..0000000 --- a/vendor/github.com/nats-io/nats/encoders/builtin/gob_enc.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2013-2015 Apcera Inc. All rights reserved. - -package builtin - -import ( - "bytes" - "encoding/gob" -) - -// GobEncoder is a Go specific GOB Encoder implementation for EncodedConn. -// This encoder will use the builtin encoding/gob to Marshal -// and Unmarshal most types, including structs. -type GobEncoder struct { - // Empty -} - -// FIXME(dlc) - This could probably be more efficient. - -// Encode -func (ge *GobEncoder) Encode(subject string, v interface{}) ([]byte, error) { - b := new(bytes.Buffer) - enc := gob.NewEncoder(b) - if err := enc.Encode(v); err != nil { - return nil, err - } - return b.Bytes(), nil -} - -// Decode -func (ge *GobEncoder) Decode(subject string, data []byte, vPtr interface{}) (err error) { - dec := gob.NewDecoder(bytes.NewBuffer(data)) - err = dec.Decode(vPtr) - return -} diff --git a/vendor/github.com/nats-io/nats/encoders/builtin/json_enc.go b/vendor/github.com/nats-io/nats/encoders/builtin/json_enc.go deleted file mode 100644 index 3b269ef..0000000 --- a/vendor/github.com/nats-io/nats/encoders/builtin/json_enc.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2012-2015 Apcera Inc. All rights reserved. - -package builtin - -import ( - "encoding/json" - "strings" -) - -// JsonEncoder is a JSON Encoder implementation for EncodedConn. -// This encoder will use the builtin encoding/json to Marshal -// and Unmarshal most types, including structs. -type JsonEncoder struct { - // Empty -} - -// Encode -func (je *JsonEncoder) Encode(subject string, v interface{}) ([]byte, error) { - b, err := json.Marshal(v) - if err != nil { - return nil, err - } - return b, nil -} - -// Decode -func (je *JsonEncoder) Decode(subject string, data []byte, vPtr interface{}) (err error) { - switch arg := vPtr.(type) { - case *string: - // If they want a string and it is a JSON string, strip quotes - // This allows someone to send a struct but receive as a plain string - // This cast should be efficient for Go 1.3 and beyond. - str := string(data) - if strings.HasPrefix(str, `"`) && strings.HasSuffix(str, `"`) { - *arg = str[1 : len(str)-1] - } else { - *arg = str - } - case *[]byte: - *arg = data - default: - err = json.Unmarshal(data, arg) - } - return -} diff --git a/vendor/github.com/nats-io/nats/util/tls.go b/vendor/github.com/nats-io/nats/util/tls.go deleted file mode 100644 index 51da0b8..0000000 --- a/vendor/github.com/nats-io/nats/util/tls.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2016 Apcera Inc. All rights reserved. -// +build go1.7 - -package util - -import ( - "crypto/tls" -) - -// CloneTLSConfig returns a copy of c. Only the exported fields are copied. -// This is temporary, until this is provided by the language. -// https://go-review.googlesource.com/#/c/28075/ -func CloneTLSConfig(c *tls.Config) *tls.Config { - return &tls.Config{ - Rand: c.Rand, - Time: c.Time, - Certificates: c.Certificates, - NameToCertificate: c.NameToCertificate, - GetCertificate: c.GetCertificate, - RootCAs: c.RootCAs, - NextProtos: c.NextProtos, - ServerName: c.ServerName, - ClientAuth: c.ClientAuth, - ClientCAs: c.ClientCAs, - InsecureSkipVerify: c.InsecureSkipVerify, - CipherSuites: c.CipherSuites, - PreferServerCipherSuites: c.PreferServerCipherSuites, - SessionTicketsDisabled: c.SessionTicketsDisabled, - SessionTicketKey: c.SessionTicketKey, - ClientSessionCache: c.ClientSessionCache, - MinVersion: c.MinVersion, - MaxVersion: c.MaxVersion, - CurvePreferences: c.CurvePreferences, - DynamicRecordSizingDisabled: c.DynamicRecordSizingDisabled, - Renegotiation: c.Renegotiation, - } -} diff --git a/vendor/github.com/nats-io/nats/util/tls_pre17.go b/vendor/github.com/nats-io/nats/util/tls_pre17.go deleted file mode 100644 index db198ae..0000000 --- a/vendor/github.com/nats-io/nats/util/tls_pre17.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2016 Apcera Inc. All rights reserved. -// +build go1.5,!go1.7 - -package util - -import ( - "crypto/tls" -) - -// CloneTLSConfig returns a copy of c. Only the exported fields are copied. -// This is temporary, until this is provided by the language. -// https://go-review.googlesource.com/#/c/28075/ -func CloneTLSConfig(c *tls.Config) *tls.Config { - return &tls.Config{ - Rand: c.Rand, - Time: c.Time, - Certificates: c.Certificates, - NameToCertificate: c.NameToCertificate, - GetCertificate: c.GetCertificate, - RootCAs: c.RootCAs, - NextProtos: c.NextProtos, - ServerName: c.ServerName, - ClientAuth: c.ClientAuth, - ClientCAs: c.ClientCAs, - InsecureSkipVerify: c.InsecureSkipVerify, - CipherSuites: c.CipherSuites, - PreferServerCipherSuites: c.PreferServerCipherSuites, - SessionTicketsDisabled: c.SessionTicketsDisabled, - SessionTicketKey: c.SessionTicketKey, - ClientSessionCache: c.ClientSessionCache, - MinVersion: c.MinVersion, - MaxVersion: c.MaxVersion, - CurvePreferences: c.CurvePreferences, - } -} diff --git a/vendor/github.com/nats-io/nuid/LICENSE b/vendor/github.com/nats-io/nuid/LICENSE deleted file mode 100644 index cadc3a4..0000000 --- a/vendor/github.com/nats-io/nuid/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2012-2016 Apcera Inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/nats-io/nuid/nuid.go b/vendor/github.com/nats-io/nuid/nuid.go deleted file mode 100644 index 1fda377..0000000 --- a/vendor/github.com/nats-io/nuid/nuid.go +++ /dev/null @@ -1,124 +0,0 @@ -// Copyright 2016 Apcera Inc. All rights reserved. - -// A unique identifier generator that is high performance, very fast, and tries to be entropy pool friendly. -package nuid - -import ( - "crypto/rand" - "fmt" - "math" - "math/big" - "sync" - "time" - - prand "math/rand" -) - -// NUID needs to be very fast to generate and truly unique, all while being entropy pool friendly. -// We will use 12 bytes of crypto generated data (entropy draining), and 10 bytes of sequential data -// that is started at a pseudo random number and increments with a pseudo-random increment. -// Total is 22 bytes of base 62 ascii text :) - -// Version of the library -const Version = "1.0.0" - -const ( - digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - base = 62 - preLen = 12 - seqLen = 10 - maxSeq = int64(839299365868340224) // base^seqLen == 62^10 - minInc = int64(33) - maxInc = int64(333) - totalLen = preLen + seqLen -) - -type NUID struct { - pre []byte - seq int64 - inc int64 -} - -type lockedNUID struct { - sync.Mutex - *NUID -} - -// Global NUID -var globalNUID *lockedNUID - -// Seed sequential random with crypto or math/random and current time -// and generate crypto prefix. -func init() { - r, err := rand.Int(rand.Reader, big.NewInt(math.MaxInt64)) - if err != nil { - prand.Seed(time.Now().UnixNano()) - } else { - prand.Seed(r.Int64()) - } - globalNUID = &lockedNUID{NUID: New()} - globalNUID.RandomizePrefix() -} - -// New will generate a new NUID and properly initialize the prefix, sequential start, and sequential increment. -func New() *NUID { - n := &NUID{ - seq: prand.Int63n(maxSeq), - inc: minInc + prand.Int63n(maxInc-minInc), - pre: make([]byte, preLen), - } - n.RandomizePrefix() - return n -} - -// Generate the next NUID string from the global locked NUID instance. -func Next() string { - globalNUID.Lock() - nuid := globalNUID.Next() - globalNUID.Unlock() - return nuid -} - -// Generate the next NUID string. -func (n *NUID) Next() string { - // Increment and capture. - n.seq += n.inc - if n.seq >= maxSeq { - n.RandomizePrefix() - n.resetSequential() - } - seq := n.seq - - // Copy prefix - var b [totalLen]byte - bs := b[:preLen] - copy(bs, n.pre) - - // copy in the seq in base36. - for i, l := len(b), seq; i > preLen; l /= base { - i -= 1 - b[i] = digits[l%base] - } - return string(b[:]) -} - -// Resets the sequential portion of the NUID. -func (n *NUID) resetSequential() { - n.seq = prand.Int63n(maxSeq) - n.inc = minInc + prand.Int63n(maxInc-minInc) -} - -// Generate a new prefix from crypto/rand. -// This call *can* drain entropy and will be called automatically when we exhaust the sequential range. -// Will panic if it gets an error from rand.Int() -func (n *NUID) RandomizePrefix() { - var cb [preLen]byte - cbs := cb[:] - if nb, err := rand.Read(cbs); nb != preLen || err != nil { - panic(fmt.Sprintf("nuid: failed generating crypto random number: %v\n", err)) - } - - for i := 0; i < preLen; i++ { - n.pre[i] = digits[int(cbs[i])%base] - } -} diff --git a/vendor/github.com/nightlyone/lockfile/README.md b/vendor/github.com/nightlyone/lockfile/README.md new file mode 100644 index 0000000..54ee19c --- /dev/null +++ b/vendor/github.com/nightlyone/lockfile/README.md @@ -0,0 +1,52 @@ +lockfile +========= +Handle locking via pid files. + +[![Build Status Unix][1]][2] +[![Build status Windows][3]][4] + +[1]: https://secure.travis-ci.org/nightlyone/lockfile.png +[2]: https://travis-ci.org/nightlyone/lockfile +[3]: https://ci.appveyor.com/api/projects/status/7mojkmauj81uvp8u/branch/master?svg=true +[4]: https://ci.appveyor.com/project/nightlyone/lockfile/branch/master + + + +install +------- +Install [Go 1][5], either [from source][6] or [with a prepackaged binary][7]. +For Windows suport, Go 1.4 or newer is required. + +Then run + + go get github.com/nightlyone/lockfile + +[5]: http://golang.org +[6]: http://golang.org/doc/install/source +[7]: http://golang.org/doc/install + +LICENSE +------- +BSD + +documentation +------------- +[package documentation at godoc.org](http://godoc.org/github.com/nightlyone/lockfile) + +install +------------------- + go get github.com/nightlyone/lockfile + + +contributing +============ + +Contributions are welcome. Please open an issue or send me a pull request for a dedicated branch. +Make sure the git commit hooks show it works. + +git commit hooks +----------------------- +enable commit hooks via + + cd .git ; rm -rf hooks; ln -s ../git-hooks hooks ; cd .. + diff --git a/vendor/github.com/opencontainers/go-digest/LICENSE.code b/vendor/github.com/opencontainers/go-digest/LICENSE.code new file mode 100644 index 0000000..0ea3ff8 --- /dev/null +++ b/vendor/github.com/opencontainers/go-digest/LICENSE.code @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2016 Docker, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/opencontainers/go-digest/LICENSE.docs b/vendor/github.com/opencontainers/go-digest/LICENSE.docs new file mode 100644 index 0000000..e26cd4f --- /dev/null +++ b/vendor/github.com/opencontainers/go-digest/LICENSE.docs @@ -0,0 +1,425 @@ +Attribution-ShareAlike 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-ShareAlike 4.0 International Public +License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-ShareAlike 4.0 International Public License ("Public +License"). To the extent this Public License may be interpreted as a +contract, You are granted the Licensed Rights in consideration of Your +acceptance of these terms and conditions, and the Licensor grants You +such rights in consideration of benefits the Licensor receives from +making the Licensed Material available under these terms and +conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. BY-SA Compatible License means a license listed at + creativecommons.org/compatiblelicenses, approved by Creative + Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + e. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name + of a Creative Commons Public License. The License Elements of this + Public License are Attribution and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + i. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + k. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + l. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + m. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. Additional offer from the Licensor -- Adapted Material. + Every recipient of Adapted Material from You + automatically receives an offer from the Licensor to + exercise the Licensed Rights in the Adapted Material + under the conditions of the Adapter's License You apply. + + c. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + b. ShareAlike. + + In addition to the conditions in Section 3(a), if You Share + Adapted Material You produce, the following conditions also apply. + + 1. The Adapter's License You apply must be a Creative Commons + license with the same License Elements, this version or + later, or a BY-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the + Adapter's License You apply. You may satisfy this condition + in any reasonable manner based on the medium, means, and + context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms + or conditions on, or apply any Effective Technological + Measures to, Adapted Material that restrict exercise of the + rights granted under the Adapter's License You apply. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material, + + including for purposes of Section 3(b); and + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public licenses. +Notwithstanding, Creative Commons may elect to apply one of its public +licenses to material it publishes and in those instances will be +considered the "Licensor." Except for the limited purpose of indicating +that material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the public +licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/vendor/github.com/opencontainers/go-digest/README.md b/vendor/github.com/opencontainers/go-digest/README.md new file mode 100644 index 0000000..d65261e --- /dev/null +++ b/vendor/github.com/opencontainers/go-digest/README.md @@ -0,0 +1,104 @@ +# go-digest + +[![GoDoc](https://godoc.org/github.com/opencontainers/go-digest?status.svg)](https://godoc.org/github.com/opencontainers/go-digest) [![Go Report Card](https://goreportcard.com/badge/github.com/opencontainers/go-digest)](https://goreportcard.com/report/github.com/opencontainers/go-digest) [![Build Status](https://travis-ci.org/opencontainers/go-digest.svg?branch=master)](https://travis-ci.org/opencontainers/go-digest) + +Common digest package used across the container ecosystem. + +Please see the [godoc](https://godoc.org/github.com/opencontainers/go-digest) for more information. + +# What is a digest? + +A digest is just a hash. + +The most common use case for a digest is to create a content +identifier for use in [Content Addressable Storage](https://en.wikipedia.org/wiki/Content-addressable_storage) +systems: + +```go +id := digest.FromBytes([]byte("my content")) +``` + +In the example above, the id can be used to uniquely identify +the byte slice "my content". This allows two disparate applications +to agree on a verifiable identifier without having to trust one +another. + +An identifying digest can be verified, as follows: + +```go +if id != digest.FromBytes([]byte("my content")) { + return errors.New("the content has changed!") +} +``` + +A `Verifier` type can be used to handle cases where an `io.Reader` +makes more sense: + +```go +rd := getContent() +verifier := id.Verifier() +io.Copy(verifier, rd) + +if !verifier.Verified() { + return errors.New("the content has changed!") +} +``` + +Using [Merkle DAGs](https://en.wikipedia.org/wiki/Merkle_tree), this +can power a rich, safe, content distribution system. + +# Usage + +While the [godoc](https://godoc.org/github.com/opencontainers/go-digest) is +considered the best resource, a few important items need to be called +out when using this package. + +1. Make sure to import the hash implementations into your application + or the package will panic. You should have something like the + following in the main (or other entrypoint) of your application: + + ```go + import ( + _ "crypto/sha256" + _ "crypto/sha512" + ) + ``` + This may seem inconvenient but it allows you replace the hash + implementations with others, such as https://github.com/stevvooe/resumable. + +2. Even though `digest.Digest` may be assemable as a string, _always_ + verify your input with `digest.Parse` or use `Digest.Validate` + when accepting untrusted input. While there are measures to + avoid common problems, this will ensure you have valid digests + in the rest of your application. + +# Stability + +The Go API, at this stage, is considered stable, unless otherwise noted. + +As always, before using a package export, read the [godoc](https://godoc.org/github.com/opencontainers/go-digest). + +# Contributing + +This package is considered fairly complete. It has been in production +in thousands (millions?) of deployments and is fairly battle-hardened. +New additions will be met with skepticism. If you think there is a +missing feature, please file a bug clearly describing the problem and +the alternatives you tried before submitting a PR. + +# Reporting security issues + +The maintainers take security seriously. If you discover a security +issue, please bring it to their attention right away! + +Please DO NOT file a public issue, instead send your report privately +to security@docker.com. + +Security reports are greatly appreciated and we will publicly thank you +for it. We also like to send gifts—if you're into Docker schwag, make +sure to let us know. We currently do not offer a paid security bounty +program, but are not ruling it out in the future. + +# Copyright and license + +Copyright © 2016 Docker, Inc. All rights reserved, except as follows. Code is released under the [Apache 2.0 license](LICENSE.code). This `README.md` file and the [`CONTRIBUTING.md`](CONTRIBUTING.md) file are licensed under the Creative Commons Attribution 4.0 International License under the terms and conditions set forth in the file [`LICENSE.docs`](LICENSE.docs). You may obtain a duplicate copy of the same license, titled CC BY-SA 4.0, at http://creativecommons.org/licenses/by-sa/4.0/. diff --git a/vendor/github.com/opencontainers/image-spec/README.md b/vendor/github.com/opencontainers/image-spec/README.md new file mode 100644 index 0000000..e0f7816 --- /dev/null +++ b/vendor/github.com/opencontainers/image-spec/README.md @@ -0,0 +1,172 @@ +# OCI Image Format Specification +
+ + + +
+ +The OCI Image Format project creates and maintains the software shipping container image format spec (OCI Image Format). + +The specification can be found [here](spec.md). + +Additional documentation about how this group operates: + +- [Code of Conduct](https://github.com/opencontainers/tob/blob/d2f9d68c1332870e40693fe077d311e0742bc73d/code-of-conduct.md) +- [Roadmap](#roadmap) +- [Releases](RELEASES.md) +- [Project Documentation](project.md) + +The _optional_ and _base_ layers of all OCI projects are tracked in the [OCI Scope Table](https://www.opencontainers.org/governance/oci-scope-table). + +## Running an OCI Image + +The OCI Image Format partner project is the [OCI Runtime Spec project](https://github.com/opencontainers/runtime-spec). +The Runtime Specification outlines how to run a "[filesystem bundle](https://github.com/opencontainers/runtime-spec/blob/master/bundle.md)" that is unpacked on disk. +At a high-level an OCI implementation would download an OCI Image then unpack that image into an OCI Runtime filesystem bundle. +At this point the OCI Runtime Bundle would be run by an OCI Runtime. + +This entire workflow supports the UX that users have come to expect from container engines like Docker and rkt: primarily, the ability to run an image with no additional arguments: + +* docker run example.com/org/app:v1.0.0 +* rkt run example.com/org/app,version=v1.0.0 + +To support this UX the OCI Image Format contains sufficient information to launch the application on the target platform (e.g. command, arguments, environment variables, etc). + +## FAQ + +**Q: Why doesn't this project mention distribution?** + +A: Distribution, for example using HTTP as both Docker v2.2 and AppC do today, is currently out of scope on the [OCI Scope Table](https://www.opencontainers.org/governance/oci-scope-table). +There has been [some discussion on the TOB mailing list](https://groups.google.com/a/opencontainers.org/d/msg/tob/A3JnmI-D-6Y/tLuptPDHAgAJ) to make distribution an optional layer, but this topic is a work in progress. + +**Q: Why a new project?** + +A: The [first OCI spec](https://github.com/opencontainers/runtime-spec) centered around defining the run side of a container. +This is generally seen to be an orthogonal concern to the shipping container component. +As practical examples of this separation you see many organizations separating these concerns into different teams and organizations: the Docker Distribution project and the Docker containerd project; Amazon ECS and Amazon EC2 Container Registry, etc. + +**Q: Why work on this?** + +A: We are seeing many independent implementations of container image handling including build systems, registries, and image analysis tools. +As an organization we would like to encourage this growth and bring people together to ensure a technically correct and open specification continues to evolve reflecting the OCI values. + +**Q: What happens to AppC or Docker Image Formats?** + +A: Existing formats can continue to be a proving ground for technologies, as needed. +The OCI Image Format project strives to provide a dependable open specification that can be shared between different tools and be evolved for years or decades of compatibility; as the deb and rpm format have. + +## Roadmap + +The [GitHub milestones](https://github.com/opencontainers/image-spec/milestones) lay out the path to the OCI v1.0.0 release in late 2016. + +# Contributing + +Development happens on GitHub for the spec. +Issues are used for bugs and actionable items and longer discussions can happen on the [mailing list](#mailing-list). + +The specification and code is licensed under the Apache 2.0 license found in the `LICENSE` file of this repository. + +## Discuss your design + +The project welcomes submissions, but please let everyone know what you are working on. + +Before undertaking a nontrivial change to this specification, send mail to the [mailing list](#mailing-list) to discuss what you plan to do. +This gives everyone a chance to validate the design, helps prevent duplication of effort, and ensures that the idea fits. +It also guarantees that the design is sound before code is written; a GitHub pull-request is not the place for high-level discussions. + +Typos and grammatical errors can go straight to a pull-request. +When in doubt, start on the [mailing-list](#mailing-list). + +## Weekly Call + +The contributors and maintainers of all OCI projects have a weekly meeting Wednesdays at 2:00 PM (USA Pacific). +Everyone is welcome to participate via [UberConference web][UberConference] or audio-only: +1-415-968-0849 (no PIN needed). +An initial agenda will be posted to the [mailing list](#mailing-list) earlier in the week, and everyone is welcome to propose additional topics or suggest other agenda alterations there. +Minutes are posted to the [mailing list](#mailing-list) and minutes from past calls are archived to the [wiki](https://github.com/opencontainers/runtime-spec/wiki) for those who are unable to join the call. + +## Mailing List + +You can subscribe and join the mailing list on [Google Groups](https://groups.google.com/a/opencontainers.org/forum/#!forum/dev). + +## IRC + +OCI discussion happens on #opencontainers on Freenode ([logs][irc-logs]). + +## Markdown style + +To keep consistency throughout the Markdown files in the Open Container spec all files should be formatted one sentence per line. +This fixes two things: it makes diffing easier with git and it resolves fights about line wrapping length. +For example, this paragraph will span three lines in the Markdown source. + +## Git commit + +### Sign your work + +The sign-off is a simple line at the end of the explanation for the patch, which certifies that you wrote it or otherwise have the right to pass it on as an open-source patch. +The rules are pretty simple: if you can certify the below (from [developercertificate.org](http://developercertificate.org/)): + +``` +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2004, 2006 The Linux Foundation and its contributors. +660 York Street, Suite 102, +San Francisco, CA 94110 USA + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +then you just add a line to every git commit message: + + Signed-off-by: Joe Smith + +using your real name (sorry, no pseudonyms or anonymous contributions.) + +You can add the sign off when creating the git commit via `git commit -s`. + +### Commit Style + +Simple house-keeping for clean git history. +Read more on [How to Write a Git Commit Message](http://chris.beams.io/posts/git-commit/) or the Discussion section of [`git-commit(1)`](http://git-scm.com/docs/git-commit). + +1. Separate the subject from body with a blank line +2. Limit the subject line to 50 characters +3. Capitalize the subject line +4. Do not end the subject line with a period +5. Use the imperative mood in the subject line +6. Wrap the body at 72 characters +7. Use the body to explain what and why vs. how + * If there was important/useful/essential conversation or information, copy or include a reference +8. When possible, one keyword to scope the change in the subject (i.e. "README: ...", "runtime: ...") + + +[UberConference]: https://www.uberconference.com/opencontainers +[irc-logs]: http://ircbot.wl.linuxfoundation.org/eavesdrop/%23opencontainers/ diff --git a/vendor/github.com/opencontainers/runc/README.md b/vendor/github.com/opencontainers/runc/README.md new file mode 100644 index 0000000..ec9b44e --- /dev/null +++ b/vendor/github.com/opencontainers/runc/README.md @@ -0,0 +1,199 @@ +# runc + +[![Build Status](https://travis-ci.org/opencontainers/runc.svg?branch=master)](https://travis-ci.org/opencontainers/runc) +[![Go Report Card](https://goreportcard.com/badge/github.com/opencontainers/runc)](https://goreportcard.com/report/github.com/opencontainers/runc) + +## Introduction + +`runc` is a CLI tool for spawning and running containers according to the OCI specification. + +## Releases + +`runc` depends on and tracks the [runtime-spec](https://github.com/opencontainers/runtime-spec) repository. +We will try to make sure that `runc` and the OCI specification major versions stay in lockstep. +This means that `runc` 1.0.0 should implement the 1.0 version of the specification. + +You can find official releases of `runc` on the [release](https://github.com/opencontainers/runc/releases) page. + +### Security + +If you wish to report a security issue, please disclose the issue responsibly +to security@opencontainers.org. + +## Building + +`runc` currently supports the Linux platform with various architecture support. +It must be built with Go version 1.6 or higher in order for some features to function properly. + +In order to enable seccomp support you will need to install `libseccomp` on your platform. +> e.g. `libseccomp-devel` for CentOS, or `libseccomp-dev` for Ubuntu + +Otherwise, if you do not want to build `runc` with seccomp support you can add `BUILDTAGS=""` when running make. + +```bash +# create a 'github.com/opencontainers' in your GOPATH/src +cd github.com/opencontainers +git clone https://github.com/opencontainers/runc +cd runc + +make +sudo make install +``` + +`runc` will be installed to `/usr/local/sbin/runc` on your system. + +#### Build Tags + +`runc` supports optional build tags for compiling support of various features. +To add build tags to the make option the `BUILDTAGS` variable must be set. + +```bash +make BUILDTAGS='seccomp apparmor' +``` + +| Build Tag | Feature | Dependency | +|-----------|------------------------------------|-------------| +| seccomp | Syscall filtering | libseccomp | +| selinux | selinux process and mount labeling | | +| apparmor | apparmor profile support | libapparmor | +| ambient | ambient capability support | kernel 4.3 | + + +### Running the test suite + +`runc` currently supports running its test suite via Docker. +To run the suite just type `make test`. + +```bash +make test +``` + +There are additional make targets for running the tests outside of a container but this is not recommended as the tests are written with the expectation that they can write and remove anywhere. + +You can run a specific test case by setting the `TESTFLAGS` variable. + +```bash +# make test TESTFLAGS="-run=SomeTestFunction" +``` + +## Using runc + +### Creating an OCI Bundle + +In order to use runc you must have your container in the format of an OCI bundle. +If you have Docker installed you can use its `export` method to acquire a root filesystem from an existing Docker container. + +```bash +# create the top most bundle directory +mkdir /mycontainer +cd /mycontainer + +# create the rootfs directory +mkdir rootfs + +# export busybox via Docker into the rootfs directory +docker export $(docker create busybox) | tar -C rootfs -xvf - +``` + +After a root filesystem is populated you just generate a spec in the format of a `config.json` file inside your bundle. +`runc` provides a `spec` command to generate a base template spec that you are then able to edit. +To find features and documentation for fields in the spec please refer to the [specs](https://github.com/opencontainers/runtime-spec) repository. + +```bash +runc spec +``` + +### Running Containers + +Assuming you have an OCI bundle from the previous step you can execute the container in two different ways. + +The first way is to use the convenience command `run` that will handle creating, starting, and deleting the container after it exits. + +```bash +cd /mycontainer + +runc run mycontainerid +``` + +If you used the unmodified `runc spec` template this should give you a `sh` session inside the container. + +The second way to start a container is using the specs lifecycle operations. +This gives you more power over how the container is created and managed while it is running. +This will also launch the container in the background so you will have to edit the `config.json` to remove the `terminal` setting for the simple examples here. +Your process field in the `config.json` should look like this below with `"terminal": false` and `"args": ["sleep", "5"]`. + + +```json + "process": { + "terminal": false, + "user": { + "uid": 0, + "gid": 0 + }, + "args": [ + "sleep", "5" + ], + "env": [ + "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "TERM=xterm" + ], + "cwd": "/", + "capabilities": [ + "CAP_AUDIT_WRITE", + "CAP_KILL", + "CAP_NET_BIND_SERVICE" + ], + "rlimits": [ + { + "type": "RLIMIT_NOFILE", + "hard": 1024, + "soft": 1024 + } + ], + "noNewPrivileges": true + }, +``` + +Now we can go though the lifecycle operations in your shell. + + +```bash +cd /mycontainer + +runc create mycontainerid + +# view the container is created and in the "created" state +runc list + +# start the process inside the container +runc start mycontainerid + +# after 5 seconds view that the container has exited and is now in the stopped state +runc list + +# now delete the container +runc delete mycontainerid +``` + +This adds more complexity but allows higher level systems to manage runc and provides points in the containers creation to setup various settings after the container has created and/or before it is deleted. +This is commonly used to setup the container's network stack after `create` but before `start` where the user's defined process will be running. + +#### Supervisors + +`runc` can be used with process supervisors and init systems to ensure that containers are restarted when they exit. +An example systemd unit file looks something like this. + +```systemd +[Unit] +Description=Start My Container + +[Service] +Type=forking +ExecStart=/usr/local/sbin/runc run -d --pid-file /run/mycontainerid.pid mycontainerid +ExecStopPost=/usr/local/sbin/runc delete mycontainerid +WorkingDirectory=/mycontainer +PIDFile=/run/mycontainerid.pid + +[Install] +WantedBy=multi-user.target +``` diff --git a/vendor/github.com/opencontainers/runc/libcontainer/README.md b/vendor/github.com/opencontainers/runc/libcontainer/README.md new file mode 100644 index 0000000..9435cf7 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/libcontainer/README.md @@ -0,0 +1,251 @@ +Libcontainer provides a native Go implementation for creating containers +with namespaces, cgroups, capabilities, and filesystem access controls. +It allows you to manage the lifecycle of the container performing additional operations +after the container is created. + + +#### Container +A container is a self contained execution environment that shares the kernel of the +host system and which is (optionally) isolated from other containers in the system. + +#### Using libcontainer + +Because containers are spawned in a two step process you will need a binary that +will be executed as the init process for the container. In libcontainer, we use +the current binary (/proc/self/exe) to be executed as the init process, and use +arg "init", we call the first step process "bootstrap", so you always need a "init" +function as the entry of "bootstrap". + +```go +func init() { + if len(os.Args) > 1 && os.Args[1] == "init" { + runtime.GOMAXPROCS(1) + runtime.LockOSThread() + factory, _ := libcontainer.New("") + if err := factory.StartInitialization(); err != nil { + logrus.Fatal(err) + } + panic("--this line should have never been executed, congratulations--") + } +} +``` + +Then to create a container you first have to initialize an instance of a factory +that will handle the creation and initialization for a container. + +```go +factory, err := libcontainer.New("/var/lib/container", libcontainer.Cgroupfs, libcontainer.InitArgs(os.Args[0], "init")) +if err != nil { + logrus.Fatal(err) + return +} +``` + +Once you have an instance of the factory created we can create a configuration +struct describing how the container is to be created. A sample would look similar to this: + +```go +defaultMountFlags := syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV +config := &configs.Config{ + Rootfs: "/your/path/to/rootfs", + Capabilities: []string{ + "CAP_CHOWN", + "CAP_DAC_OVERRIDE", + "CAP_FSETID", + "CAP_FOWNER", + "CAP_MKNOD", + "CAP_NET_RAW", + "CAP_SETGID", + "CAP_SETUID", + "CAP_SETFCAP", + "CAP_SETPCAP", + "CAP_NET_BIND_SERVICE", + "CAP_SYS_CHROOT", + "CAP_KILL", + "CAP_AUDIT_WRITE", + }, + Namespaces: configs.Namespaces([]configs.Namespace{ + {Type: configs.NEWNS}, + {Type: configs.NEWUTS}, + {Type: configs.NEWIPC}, + {Type: configs.NEWPID}, + {Type: configs.NEWUSER}, + {Type: configs.NEWNET}, + }), + Cgroups: &configs.Cgroup{ + Name: "test-container", + Parent: "system", + Resources: &configs.Resources{ + MemorySwappiness: nil, + AllowAllDevices: nil, + AllowedDevices: configs.DefaultAllowedDevices, + }, + }, + MaskPaths: []string{ + "/proc/kcore", + "/sys/firmware", + }, + ReadonlyPaths: []string{ + "/proc/sys", "/proc/sysrq-trigger", "/proc/irq", "/proc/bus", + }, + Devices: configs.DefaultAutoCreatedDevices, + Hostname: "testing", + Mounts: []*configs.Mount{ + { + Source: "proc", + Destination: "/proc", + Device: "proc", + Flags: defaultMountFlags, + }, + { + Source: "tmpfs", + Destination: "/dev", + Device: "tmpfs", + Flags: syscall.MS_NOSUID | syscall.MS_STRICTATIME, + Data: "mode=755", + }, + { + Source: "devpts", + Destination: "/dev/pts", + Device: "devpts", + Flags: syscall.MS_NOSUID | syscall.MS_NOEXEC, + Data: "newinstance,ptmxmode=0666,mode=0620,gid=5", + }, + { + Device: "tmpfs", + Source: "shm", + Destination: "/dev/shm", + Data: "mode=1777,size=65536k", + Flags: defaultMountFlags, + }, + { + Source: "mqueue", + Destination: "/dev/mqueue", + Device: "mqueue", + Flags: defaultMountFlags, + }, + { + Source: "sysfs", + Destination: "/sys", + Device: "sysfs", + Flags: defaultMountFlags | syscall.MS_RDONLY, + }, + }, + UidMappings: []configs.IDMap{ + { + ContainerID: 0, + HostID: 1000, + Size: 65536, + }, + }, + GidMappings: []configs.IDMap{ + { + ContainerID: 0, + HostID: 1000, + Size: 65536, + }, + }, + Networks: []*configs.Network{ + { + Type: "loopback", + Address: "127.0.0.1/0", + Gateway: "localhost", + }, + }, + Rlimits: []configs.Rlimit{ + { + Type: syscall.RLIMIT_NOFILE, + Hard: uint64(1025), + Soft: uint64(1025), + }, + }, +} +``` + +Once you have the configuration populated you can create a container: + +```go +container, err := factory.Create("container-id", config) +if err != nil { + logrus.Fatal(err) + return +} +``` + +To spawn bash as the initial process inside the container and have the +processes pid returned in order to wait, signal, or kill the process: + +```go +process := &libcontainer.Process{ + Args: []string{"/bin/bash"}, + Env: []string{"PATH=/bin"}, + User: "daemon", + Stdin: os.Stdin, + Stdout: os.Stdout, + Stderr: os.Stderr, +} + +err := container.Run(process) +if err != nil { + container.Destroy() + logrus.Fatal(err) + return +} + +// wait for the process to finish. +_, err := process.Wait() +if err != nil { + logrus.Fatal(err) +} + +// destroy the container. +container.Destroy() +``` + +Additional ways to interact with a running container are: + +```go +// return all the pids for all processes running inside the container. +processes, err := container.Processes() + +// get detailed cpu, memory, io, and network statistics for the container and +// it's processes. +stats, err := container.Stats() + +// pause all processes inside the container. +container.Pause() + +// resume all paused processes. +container.Resume() + +// send signal to container's init process. +container.Signal(signal) + +// update container resource constraints. +container.Set(config) + +// get current status of the container. +status, err := container.Status() + +// get current container's state information. +state, err := container.State() +``` + + +#### Checkpoint & Restore + +libcontainer now integrates [CRIU](http://criu.org/) for checkpointing and restoring containers. +This let's you save the state of a process running inside a container to disk, and then restore +that state into a new process, on the same machine or on another machine. + +`criu` version 1.5.2 or higher is required to use checkpoint and restore. +If you don't already have `criu` installed, you can build it from source, following the +[online instructions](http://criu.org/Installation). `criu` is also installed in the docker image +generated when building libcontainer with docker. + + +## Copyright and license + +Code and documentation copyright 2014 Docker, inc. Code released under the Apache 2.0 license. +Docs released under Creative commons. + diff --git a/vendor/github.com/opencontainers/runc/libcontainer/nsenter/README.md b/vendor/github.com/opencontainers/runc/libcontainer/nsenter/README.md new file mode 100644 index 0000000..5757013 --- /dev/null +++ b/vendor/github.com/opencontainers/runc/libcontainer/nsenter/README.md @@ -0,0 +1,44 @@ +## nsenter + +The `nsenter` package registers a special init constructor that is called before +the Go runtime has a chance to boot. This provides us the ability to `setns` on +existing namespaces and avoid the issues that the Go runtime has with multiple +threads. This constructor will be called if this package is registered, +imported, in your go application. + +The `nsenter` package will `import "C"` and it uses [cgo](https://golang.org/cmd/cgo/) +package. In cgo, if the import of "C" is immediately preceded by a comment, that comment, +called the preamble, is used as a header when compiling the C parts of the package. +So every time we import package `nsenter`, the C code function `nsexec()` would be +called. And package `nsenter` is now only imported in `main_unix.go`, so every time +before we call `cmd.Start` on linux, that C code would run. + +Because `nsexec()` must be run before the Go runtime in order to use the +Linux kernel namespace, you must `import` this library into a package if +you plan to use `libcontainer` directly. Otherwise Go will not execute +the `nsexec()` constructor, which means that the re-exec will not cause +the namespaces to be joined. You can import it like this: + +```go +import _ "github.com/opencontainers/runc/libcontainer/nsenter" +``` + +`nsexec()` will first get the file descriptor number for the init pipe +from the environment variable `_LIBCONTAINER_INITPIPE` (which was opened +by the parent and kept open across the fork-exec of the `nsexec()` init +process). The init pipe is used to read bootstrap data (namespace paths, +clone flags, uid and gid mappings, and the console path) from the parent +process. `nsexec()` will then call `setns(2)` to join the namespaces +provided in the bootstrap data (if available), `clone(2)` a child process +with the provided clone flags, update the user and group ID mappings, do +some further miscellaneous setup steps, and then send the PID of the +child process to the parent of the `nsexec()` "caller". Finally, +the parent `nsexec()` will exit and the child `nsexec()` process will +return to allow the Go runtime take over. + +NOTE: We do both `setns(2)` and `clone(2)` even if we don't have any +CLONE_NEW* clone flags because we must fork a new process in order to +enter the PID namespace. + + + diff --git a/vendor/github.com/opencontainers/runtime-spec/README.md b/vendor/github.com/opencontainers/runtime-spec/README.md new file mode 100644 index 0000000..20f2908 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-spec/README.md @@ -0,0 +1,145 @@ +# Open Container Initiative Runtime Specification + +The [Open Container Initiative](http://www.opencontainers.org/) develops specifications for standards on Operating System process and application containers. + +The specification can be found [here](spec.md). + +Additional documentation about how this group operates: + +- [Code of Conduct](https://github.com/opencontainers/tob/blob/d2f9d68c1332870e40693fe077d311e0742bc73d/code-of-conduct.md) +- [Style and Conventions](style.md) +- [Roadmap](ROADMAP.md) +- [Implementations](implementations.md) +- [Releases](RELEASES.md) +- [project](project.md) +- [charter][charter] + +# Use Cases + +To provide context for users the following section gives example use cases for each part of the spec. + +#### Application Bundle Builders + +Application bundle builders can create a [bundle](bundle.md) directory that includes all of the files required for launching an application as a container. +The bundle contains an OCI [configuration file](config.md) where the builder can specify host-independent details such as [which executable to launch](config.md#process) and host-specific settings such as [mount](config.md#mounts) locations, [hook](config.md#hooks) paths, Linux [namespaces](config-linux.md#namespaces) and [cgroups](config-linux.md#control-groups). +Because the configuration includes host-specific settings, application bundle directories copied between two hosts may require configuration adjustments. + +#### Hook Developers + +[Hook](config.md#hooks) developers can extend the functionality of an OCI-compliant runtime by hooking into a container's lifecycle with an external application. +Example use cases include sophisticated network configuration, volume garbage collection, etc. + +#### Runtime Developers + +Runtime developers can build runtime implementations that run OCI-compliant bundles and container configuration, containing low-level OS and host specific details, on a particular platform. + +# Releases + +There is a loose [Road Map](./ROADMAP.md). +During the `0.x` series of OCI releases we make no backwards compatibility guarantees and intend to break the schema during this series. + +# Contributing + +Development happens on GitHub for the spec. +Issues are used for bugs and actionable items and longer discussions can happen on the [mailing list](#mailing-list). + +The specification and code is licensed under the Apache 2.0 license found in the [LICENSE](./LICENSE) file. + +## Discuss your design + +The project welcomes submissions, but please let everyone know what you are working on. + +Before undertaking a nontrivial change to this specification, send mail to the [mailing list](#mailing-list) to discuss what you plan to do. +This gives everyone a chance to validate the design, helps prevent duplication of effort, and ensures that the idea fits. +It also guarantees that the design is sound before code is written; a GitHub pull-request is not the place for high-level discussions. + +Typos and grammatical errors can go straight to a pull-request. +When in doubt, start on the [mailing-list](#mailing-list). + +## Weekly Call + +The contributors and maintainers of all OCI projects have a weekly meeting Wednesdays at 2:00 PM (USA Pacific). +Everyone is welcome to participate via [UberConference web][UberConference] or audio-only: 415-968-0849 (no PIN needed.) +An initial agenda will be posted to the [mailing list](#mailing-list) earlier in the week, and everyone is welcome to propose additional topics or suggest other agenda alterations there. +Minutes are posted to the [mailing list](#mailing-list) and minutes from past calls are archived to the [wiki](https://github.com/opencontainers/runtime-spec/wiki) for those who are unable to join the call. + +## Mailing List + +You can subscribe and join the mailing list on [Google Groups](https://groups.google.com/a/opencontainers.org/forum/#!forum/dev). + +## IRC + +OCI discussion happens on #opencontainers on Freenode ([logs][irc-logs]). + +## Git commit + +### Sign your work + +The sign-off is a simple line at the end of the explanation for the patch, which certifies that you wrote it or otherwise have the right to pass it on as an open-source patch. +The rules are pretty simple: if you can certify the below (from [developercertificate.org](http://developercertificate.org/)): + +``` +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2004, 2006 The Linux Foundation and its contributors. +660 York Street, Suite 102, +San Francisco, CA 94110 USA + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +then you just add a line to every git commit message: + + Signed-off-by: Joe Smith + +using your real name (sorry, no pseudonyms or anonymous contributions.) + +You can add the sign off when creating the git commit via `git commit -s`. + +### Commit Style + +Simple house-keeping for clean git history. +Read more on [How to Write a Git Commit Message](http://chris.beams.io/posts/git-commit/) or the Discussion section of [`git-commit(1)`](http://git-scm.com/docs/git-commit). + +1. Separate the subject from body with a blank line +2. Limit the subject line to 50 characters +3. Capitalize the subject line +4. Do not end the subject line with a period +5. Use the imperative mood in the subject line +6. Wrap the body at 72 characters +7. Use the body to explain what and why vs. how + * If there was important/useful/essential conversation or information, copy or include a reference +8. When possible, one keyword to scope the change in the subject (i.e. "README: ...", "runtime: ...") + +[UberConference]: https://www.uberconference.com/opencontainers +[irc-logs]: http://ircbot.wl.linuxfoundation.org/eavesdrop/%23opencontainers/ +[charter]: https://www.opencontainers.org/about/governance diff --git a/vendor/github.com/pkg/errors/README.md b/vendor/github.com/pkg/errors/README.md new file mode 100644 index 0000000..273db3c --- /dev/null +++ b/vendor/github.com/pkg/errors/README.md @@ -0,0 +1,52 @@ +# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) + +Package errors provides simple error handling primitives. + +`go get github.com/pkg/errors` + +The traditional error handling idiom in Go is roughly akin to +```go +if err != nil { + return err +} +``` +which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error. + +## Adding context to an error + +The errors.Wrap function returns a new error that adds context to the original error. For example +```go +_, err := ioutil.ReadAll(r) +if err != nil { + return errors.Wrap(err, "read failed") +} +``` +## Retrieving the cause of an error + +Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`. +```go +type causer interface { + Cause() error +} +``` +`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example: +```go +switch err := errors.Cause(err).(type) { +case *MyError: + // handle specifically +default: + // unknown error +} +``` + +[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors). + +## Contributing + +We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high. + +Before proposing a change, please discuss your change by raising an issue. + +## Licence + +BSD-2-Clause diff --git a/vendor/github.com/pmezard/go-difflib/README.md b/vendor/github.com/pmezard/go-difflib/README.md new file mode 100644 index 0000000..e87f307 --- /dev/null +++ b/vendor/github.com/pmezard/go-difflib/README.md @@ -0,0 +1,50 @@ +go-difflib +========== + +[![Build Status](https://travis-ci.org/pmezard/go-difflib.png?branch=master)](https://travis-ci.org/pmezard/go-difflib) +[![GoDoc](https://godoc.org/github.com/pmezard/go-difflib/difflib?status.svg)](https://godoc.org/github.com/pmezard/go-difflib/difflib) + +Go-difflib is a partial port of python 3 difflib package. Its main goal +was to make unified and context diff available in pure Go, mostly for +testing purposes. + +The following class and functions (and related tests) have be ported: + +* `SequenceMatcher` +* `unified_diff()` +* `context_diff()` + +## Installation + +```bash +$ go get github.com/pmezard/go-difflib/difflib +``` + +### Quick Start + +Diffs are configured with Unified (or ContextDiff) structures, and can +be output to an io.Writer or returned as a string. + +```Go +diff := UnifiedDiff{ + A: difflib.SplitLines("foo\nbar\n"), + B: difflib.SplitLines("foo\nbaz\n"), + FromFile: "Original", + ToFile: "Current", + Context: 3, +} +text, _ := GetUnifiedDiffString(diff) +fmt.Printf(text) +``` + +would output: + +``` +--- Original ++++ Current +@@ -1,3 +1,3 @@ + foo +-bar ++baz +``` + diff --git a/vendor/github.com/prometheus/client_golang/README.md b/vendor/github.com/prometheus/client_golang/README.md new file mode 100644 index 0000000..557eacf --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/README.md @@ -0,0 +1,45 @@ +# Prometheus Go client library + +[![Build Status](https://travis-ci.org/prometheus/client_golang.svg?branch=master)](https://travis-ci.org/prometheus/client_golang) + +This is the [Go](http://golang.org) client library for +[Prometheus](http://prometheus.io). It has two separate parts, one for +instrumenting application code, and one for creating clients that talk to the +Prometheus HTTP API. + +## Instrumenting applications + +[![code-coverage](http://gocover.io/_badge/github.com/prometheus/client_golang/prometheus)](http://gocover.io/github.com/prometheus/client_golang/prometheus) [![go-doc](https://godoc.org/github.com/prometheus/client_golang/prometheus?status.svg)](https://godoc.org/github.com/prometheus/client_golang/prometheus) + +The +[`prometheus` directory](https://github.com/prometheus/client_golang/tree/master/prometheus) +contains the instrumentation library. See the +[best practices section](http://prometheus.io/docs/practices/naming/) of the +Prometheus documentation to learn more about instrumenting applications. + +The +[`examples` directory](https://github.com/prometheus/client_golang/tree/master/examples) +contains simple examples of instrumented code. + +## Client for the Prometheus HTTP API + +[![code-coverage](http://gocover.io/_badge/github.com/prometheus/client_golang/api/prometheus)](http://gocover.io/github.com/prometheus/client_golang/api/prometheus) [![go-doc](https://godoc.org/github.com/prometheus/client_golang/api/prometheus?status.svg)](https://godoc.org/github.com/prometheus/client_golang/api/prometheus) + +The +[`api/prometheus` directory](https://github.com/prometheus/client_golang/tree/master/api/prometheus) +contains the client for the +[Prometheus HTTP API](http://prometheus.io/docs/querying/api/). It allows you +to write Go applications that query time series data from a Prometheus server. + +## Where is `model`, `extraction`, and `text`? + +The `model` packages has been moved to +[`prometheus/common/model`](https://github.com/prometheus/common/tree/master/model). + +The `extraction` and `text` packages are now contained in +[`prometheus/common/expfmt`](https://github.com/prometheus/common/tree/master/expfmt). + +## Contributing and community + +See the [contributing guidelines](CONTRIBUTING.md) and the +[Community section](http://prometheus.io/community/) of the homepage. diff --git a/vendor/github.com/prometheus/client_golang/prometheus/README.md b/vendor/github.com/prometheus/client_golang/prometheus/README.md new file mode 100644 index 0000000..44986bf --- /dev/null +++ b/vendor/github.com/prometheus/client_golang/prometheus/README.md @@ -0,0 +1 @@ +See [![go-doc](https://godoc.org/github.com/prometheus/client_golang/prometheus?status.svg)](https://godoc.org/github.com/prometheus/client_golang/prometheus). diff --git a/vendor/github.com/prometheus/client_model/README.md b/vendor/github.com/prometheus/client_model/README.md new file mode 100644 index 0000000..a710042 --- /dev/null +++ b/vendor/github.com/prometheus/client_model/README.md @@ -0,0 +1,26 @@ +# Background +Under most circumstances, manually downloading this repository should never +be required. + +# Prerequisites +# Base +* [Google Protocol Buffers](https://developers.google.com/protocol-buffers) + +## Java +* [Apache Maven](http://maven.apache.org) +* [Prometheus Maven Repository](https://github.com/prometheus/io.prometheus-maven-repository) checked out into ../io.prometheus-maven-repository + +## Go +* [Go](http://golang.org) +* [goprotobuf](https://code.google.com/p/goprotobuf) + +## Ruby +* [Ruby](https://www.ruby-lang.org) +* [bundler](https://rubygems.org/gems/bundler) + +# Building + $ make + +# Getting Started + * The Go source code is periodically indexed: [Go Protocol Buffer Model](http://godoc.org/github.com/prometheus/client_model/go). + * All of the core developers are accessible via the [Prometheus Developers Mailinglist](https://groups.google.com/forum/?fromgroups#!forum/prometheus-developers). diff --git a/vendor/github.com/prometheus/common/README.md b/vendor/github.com/prometheus/common/README.md new file mode 100644 index 0000000..98f6ce2 --- /dev/null +++ b/vendor/github.com/prometheus/common/README.md @@ -0,0 +1,12 @@ +# Common +[![Build Status](https://travis-ci.org/prometheus/common.svg)](https://travis-ci.org/prometheus/common) + +This repository contains Go libraries that are shared across Prometheus +components and libraries. + +* **config**: Common configuration structures +* **expfmt**: Decoding and encoding for the exposition format +* **log**: A logging wrapper around [logrus](https://github.com/Sirupsen/logrus) +* **model**: Shared data structures +* **route**: A routing wrapper around [httprouter](https://github.com/julienschmidt/httprouter) using `context.Context` +* **version**: Version informations and metric diff --git a/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt b/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt new file mode 100644 index 0000000..7723656 --- /dev/null +++ b/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt @@ -0,0 +1,67 @@ +PACKAGE + +package goautoneg +import "bitbucket.org/ww/goautoneg" + +HTTP Content-Type Autonegotiation. + +The functions in this package implement the behaviour specified in +http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html + +Copyright (c) 2011, Open Knowledge Foundation Ltd. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + Neither the name of the Open Knowledge Foundation Ltd. nor the + names of its contributors may be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +FUNCTIONS + +func Negotiate(header string, alternatives []string) (content_type string) +Negotiate the most appropriate content_type given the accept header +and a list of alternatives. + +func ParseAccept(header string) (accept []Accept) +Parse an Accept Header string returning a sorted list +of clauses + + +TYPES + +type Accept struct { + Type, SubType string + Q float32 + Params map[string]string +} +Structure to represent a clause in an HTTP Accept Header + + +SUBDIRECTORIES + + .hg diff --git a/vendor/github.com/prometheus/procfs/README.md b/vendor/github.com/prometheus/procfs/README.md new file mode 100644 index 0000000..6e7ee6b --- /dev/null +++ b/vendor/github.com/prometheus/procfs/README.md @@ -0,0 +1,10 @@ +# procfs + +This procfs package provides functions to retrieve system, kernel and process +metrics from the pseudo-filesystem proc. + +*WARNING*: This package is a work in progress. Its API may still break in +backwards-incompatible ways without warnings. Use it at your own risk. + +[![GoDoc](https://godoc.org/github.com/prometheus/procfs?status.png)](https://godoc.org/github.com/prometheus/procfs) +[![Build Status](https://travis-ci.org/prometheus/procfs.svg?branch=master)](https://travis-ci.org/prometheus/procfs) diff --git a/vendor/github.com/stevvooe/continuity/README.md b/vendor/github.com/stevvooe/continuity/README.md new file mode 100644 index 0000000..12d6553 --- /dev/null +++ b/vendor/github.com/stevvooe/continuity/README.md @@ -0,0 +1,16 @@ +# continuity + +A transport-agnostic, filesystem metadata manifest system + +This project is a staging area for experiments in providing transport agnostic +metadata storage. + +Please see https://github.com/opencontainers/specs/issues/11 for more details. + +## Building Proto Package + +If you change the proto file you will need to rebuild the generated Go with `go generate`. + +``` +go generate ./proto +``` diff --git a/vendor/github.com/stevvooe/go-btrfs/README.md b/vendor/github.com/stevvooe/go-btrfs/README.md new file mode 100644 index 0000000..3e3d71d --- /dev/null +++ b/vendor/github.com/stevvooe/go-btrfs/README.md @@ -0,0 +1,18 @@ +# go-btrfs +[![GoDoc](https://godoc.org/github.com/stevvooe/go-btrfs?status.svg)](https://godoc.org/github.com/stevvooe/go-btrfs) [![Build Status](https://travis-ci.org/stevvooe/go-btrfs.svg?branch=master)](https://travis-ci.org/stevvooe/go-btrfs) + +Native Go bindings for btrfs. + +# Status + +These are in the early stages. We will try to maintain stability, but please +vendor if you are relying on these directly. + +# Contribute + +This package may not cover all the use cases for btrfs. If something you need +is missing, please don't hesitate to submit a PR. + +Note that due to struct alignment issues, this isn't yet fully native. +Preferrably, this could be resolved, so contributions in this direction are +greatly appreciated. diff --git a/vendor/github.com/stretchr/testify/README.md b/vendor/github.com/stretchr/testify/README.md new file mode 100644 index 0000000..e57b181 --- /dev/null +++ b/vendor/github.com/stretchr/testify/README.md @@ -0,0 +1,332 @@ +Testify - Thou Shalt Write Tests +================================ + +[![Build Status](https://travis-ci.org/stretchr/testify.svg)](https://travis-ci.org/stretchr/testify) [![Go Report Card](https://goreportcard.com/badge/github.com/stretchr/testify)](https://goreportcard.com/report/github.com/stretchr/testify) [![GoDoc](https://godoc.org/github.com/stretchr/testify?status.svg)](https://godoc.org/github.com/stretchr/testify) + +Go code (golang) set of packages that provide many tools for testifying that your code will behave as you intend. + +Features include: + + * [Easy assertions](#assert-package) + * [Mocking](#mock-package) + * [HTTP response trapping](#http-package) + * [Testing suite interfaces and functions](#suite-package) + +Get started: + + * Install testify with [one line of code](#installation), or [update it with another](#staying-up-to-date) + * For an introduction to writing test code in Go, see http://golang.org/doc/code.html#Testing + * Check out the API Documentation http://godoc.org/github.com/stretchr/testify + * To make your testing life easier, check out our other project, [gorc](http://github.com/stretchr/gorc) + * A little about [Test-Driven Development (TDD)](http://en.wikipedia.org/wiki/Test-driven_development) + + + +[`assert`](http://godoc.org/github.com/stretchr/testify/assert "API documentation") package +------------------------------------------------------------------------------------------- + +The `assert` package provides some helpful methods that allow you to write better test code in Go. + + * Prints friendly, easy to read failure descriptions + * Allows for very readable code + * Optionally annotate each assertion with a message + +See it in action: + +```go +package yours + +import ( + "testing" + "github.com/stretchr/testify/assert" +) + +func TestSomething(t *testing.T) { + + // assert equality + assert.Equal(t, 123, 123, "they should be equal") + + // assert inequality + assert.NotEqual(t, 123, 456, "they should not be equal") + + // assert for nil (good for errors) + assert.Nil(t, object) + + // assert for not nil (good when you expect something) + if assert.NotNil(t, object) { + + // now we know that object isn't nil, we are safe to make + // further assertions without causing any errors + assert.Equal(t, "Something", object.Value) + + } + +} +``` + + * Every assert func takes the `testing.T` object as the first argument. This is how it writes the errors out through the normal `go test` capabilities. + * Every assert func returns a bool indicating whether the assertion was successful or not, this is useful for if you want to go on making further assertions under certain conditions. + +if you assert many times, use the below: + +```go +package yours + +import ( + "testing" + "github.com/stretchr/testify/assert" +) + +func TestSomething(t *testing.T) { + assert := assert.New(t) + + // assert equality + assert.Equal(123, 123, "they should be equal") + + // assert inequality + assert.NotEqual(123, 456, "they should not be equal") + + // assert for nil (good for errors) + assert.Nil(object) + + // assert for not nil (good when you expect something) + if assert.NotNil(object) { + + // now we know that object isn't nil, we are safe to make + // further assertions without causing any errors + assert.Equal("Something", object.Value) + } +} +``` + +[`require`](http://godoc.org/github.com/stretchr/testify/require "API documentation") package +--------------------------------------------------------------------------------------------- + +The `require` package provides same global functions as the `assert` package, but instead of returning a boolean result they terminate current test. + +See [t.FailNow](http://golang.org/pkg/testing/#T.FailNow) for details. + + +[`http`](http://godoc.org/github.com/stretchr/testify/http "API documentation") package +--------------------------------------------------------------------------------------- + +The `http` package contains test objects useful for testing code that relies on the `net/http` package. Check out the [(deprecated) API documentation for the `http` package](http://godoc.org/github.com/stretchr/testify/http). + +We recommend you use [httptest](http://golang.org/pkg/net/http/httptest) instead. + +[`mock`](http://godoc.org/github.com/stretchr/testify/mock "API documentation") package +---------------------------------------------------------------------------------------- + +The `mock` package provides a mechanism for easily writing mock objects that can be used in place of real objects when writing test code. + +An example test function that tests a piece of code that relies on an external object `testObj`, can setup expectations (testify) and assert that they indeed happened: + +```go +package yours + +import ( + "testing" + "github.com/stretchr/testify/mock" +) + +/* + Test objects +*/ + +// MyMockedObject is a mocked object that implements an interface +// that describes an object that the code I am testing relies on. +type MyMockedObject struct{ + mock.Mock +} + +// DoSomething is a method on MyMockedObject that implements some interface +// and just records the activity, and returns what the Mock object tells it to. +// +// In the real object, this method would do something useful, but since this +// is a mocked object - we're just going to stub it out. +// +// NOTE: This method is not being tested here, code that uses this object is. +func (m *MyMockedObject) DoSomething(number int) (bool, error) { + + args := m.Called(number) + return args.Bool(0), args.Error(1) + +} + +/* + Actual test functions +*/ + +// TestSomething is an example of how to use our test object to +// make assertions about some target code we are testing. +func TestSomething(t *testing.T) { + + // create an instance of our test object + testObj := new(MyMockedObject) + + // setup expectations + testObj.On("DoSomething", 123).Return(true, nil) + + // call the code we are testing + targetFuncThatDoesSomethingWithObj(testObj) + + // assert that the expectations were met + testObj.AssertExpectations(t) + +} +``` + +For more information on how to write mock code, check out the [API documentation for the `mock` package](http://godoc.org/github.com/stretchr/testify/mock). + +You can use the [mockery tool](http://github.com/vektra/mockery) to autogenerate the mock code against an interface as well, making using mocks much quicker. + +[`suite`](http://godoc.org/github.com/stretchr/testify/suite "API documentation") package +----------------------------------------------------------------------------------------- + +The `suite` package provides functionality that you might be used to from more common object oriented languages. With it, you can build a testing suite as a struct, build setup/teardown methods and testing methods on your struct, and run them with 'go test' as per normal. + +An example suite is shown below: + +```go +// Basic imports +import ( + "testing" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/suite" +) + +// Define the suite, and absorb the built-in basic suite +// functionality from testify - including a T() method which +// returns the current testing context +type ExampleTestSuite struct { + suite.Suite + VariableThatShouldStartAtFive int +} + +// Make sure that VariableThatShouldStartAtFive is set to five +// before each test +func (suite *ExampleTestSuite) SetupTest() { + suite.VariableThatShouldStartAtFive = 5 +} + +// All methods that begin with "Test" are run as tests within a +// suite. +func (suite *ExampleTestSuite) TestExample() { + assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) +} + +// In order for 'go test' to run this suite, we need to create +// a normal test function and pass our suite to suite.Run +func TestExampleTestSuite(t *testing.T) { + suite.Run(t, new(ExampleTestSuite)) +} +``` + +For a more complete example, using all of the functionality provided by the suite package, look at our [example testing suite](https://github.com/stretchr/testify/blob/master/suite/suite_test.go) + +For more information on writing suites, check out the [API documentation for the `suite` package](http://godoc.org/github.com/stretchr/testify/suite). + +`Suite` object has assertion methods: + +```go +// Basic imports +import ( + "testing" + "github.com/stretchr/testify/suite" +) + +// Define the suite, and absorb the built-in basic suite +// functionality from testify - including assertion methods. +type ExampleTestSuite struct { + suite.Suite + VariableThatShouldStartAtFive int +} + +// Make sure that VariableThatShouldStartAtFive is set to five +// before each test +func (suite *ExampleTestSuite) SetupTest() { + suite.VariableThatShouldStartAtFive = 5 +} + +// All methods that begin with "Test" are run as tests within a +// suite. +func (suite *ExampleTestSuite) TestExample() { + suite.Equal(suite.VariableThatShouldStartAtFive, 5) +} + +// In order for 'go test' to run this suite, we need to create +// a normal test function and pass our suite to suite.Run +func TestExampleTestSuite(t *testing.T) { + suite.Run(t, new(ExampleTestSuite)) +} +``` + +------ + +Installation +============ + +To install Testify, use `go get`: + + * Latest version: go get github.com/stretchr/testify + * Specific version: go get gopkg.in/stretchr/testify.v1 + +This will then make the following packages available to you: + + github.com/stretchr/testify/assert + github.com/stretchr/testify/mock + github.com/stretchr/testify/http + +Import the `testify/assert` package into your code using this template: + +```go +package yours + +import ( + "testing" + "github.com/stretchr/testify/assert" +) + +func TestSomething(t *testing.T) { + + assert.True(t, true, "True is true!") + +} +``` + +------ + +Staying up to date +================== + +To update Testify to the latest version, use `go get -u github.com/stretchr/testify`. + +------ + +Version History +=============== + + * 1.0 - New package versioning strategy adopted. + +------ + +Contributing +============ + +Please feel free to submit issues, fork the repository and send pull requests! + +When submitting an issue, we ask that you please include a complete test function that demonstrates the issue. Extra credit for those using Testify to write the test code that demonstrates it. + +------ + +Licence +======= +Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell + +Please consider promoting this project if you find it useful. + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/tonistiigi/fifo/readme.md b/vendor/github.com/tonistiigi/fifo/readme.md new file mode 100644 index 0000000..1c82669 --- /dev/null +++ b/vendor/github.com/tonistiigi/fifo/readme.md @@ -0,0 +1,30 @@ +### fifo + +Go package for handling fifos in a sane way. + +``` +// OpenFifo opens a fifo. Returns io.ReadWriteCloser. +// Context can be used to cancel this function until open(2) has not returned. +// Accepted flags: +// - syscall.O_CREAT - create new fifo if one doesn't exist +// - syscall.O_RDONLY - open fifo only from reader side +// - syscall.O_WRONLY - open fifo only from writer side +// - syscall.O_RDWR - open fifo from both sides, never block on syscall level +// - syscall.O_NONBLOCK - return io.ReadWriteCloser even if other side of the +// fifo isn't open. read/write will be connected after the actual fifo is +// open or after fifo is closed. +func OpenFifo(ctx context.Context, fn string, flag int, perm os.FileMode) (io.ReadWriteCloser, error) + + +// Read from a fifo to a byte array. +func (f *fifo) Read(b []byte) (int, error) + + +// Write from byte array to a fifo. +func (f *fifo) Write(b []byte) (int, error) + + +// Close the fifo. Next reads/writes will error. This method can also be used +// before open(2) has returned and fifo was never opened. +func (f *fifo) Close() error +``` \ No newline at end of file diff --git a/vendor/github.com/urfave/cli/README.md b/vendor/github.com/urfave/cli/README.md new file mode 100644 index 0000000..bb5f61e --- /dev/null +++ b/vendor/github.com/urfave/cli/README.md @@ -0,0 +1,1364 @@ +cli +=== + +[![Build Status](https://travis-ci.org/urfave/cli.svg?branch=master)](https://travis-ci.org/urfave/cli) +[![Windows Build Status](https://ci.appveyor.com/api/projects/status/rtgk5xufi932pb2v?svg=true)](https://ci.appveyor.com/project/urfave/cli) +[![GoDoc](https://godoc.org/github.com/urfave/cli?status.svg)](https://godoc.org/github.com/urfave/cli) +[![codebeat](https://codebeat.co/badges/0a8f30aa-f975-404b-b878-5fab3ae1cc5f)](https://codebeat.co/projects/github-com-urfave-cli) +[![Go Report Card](https://goreportcard.com/badge/urfave/cli)](https://goreportcard.com/report/urfave/cli) +[![top level coverage](https://gocover.io/_badge/github.com/urfave/cli?0 "top level coverage")](http://gocover.io/github.com/urfave/cli) / +[![altsrc coverage](https://gocover.io/_badge/github.com/urfave/cli/altsrc?0 "altsrc coverage")](http://gocover.io/github.com/urfave/cli/altsrc) + +**Notice:** This is the library formerly known as +`github.com/codegangsta/cli` -- Github will automatically redirect requests +to this repository, but we recommend updating your references for clarity. + +cli is a simple, fast, and fun package for building command line apps in Go. The +goal is to enable developers to write fast and distributable command line +applications in an expressive way. + + + +- [Overview](#overview) +- [Installation](#installation) + * [Supported platforms](#supported-platforms) + * [Using the `v2` branch](#using-the-v2-branch) + * [Pinning to the `v1` releases](#pinning-to-the-v1-releases) +- [Getting Started](#getting-started) +- [Examples](#examples) + * [Arguments](#arguments) + * [Flags](#flags) + + [Placeholder Values](#placeholder-values) + + [Alternate Names](#alternate-names) + + [Ordering](#ordering) + + [Values from the Environment](#values-from-the-environment) + + [Values from alternate input sources (YAML, TOML, and others)](#values-from-alternate-input-sources-yaml-toml-and-others) + * [Subcommands](#subcommands) + * [Subcommands categories](#subcommands-categories) + * [Exit code](#exit-code) + * [Bash Completion](#bash-completion) + + [Enabling](#enabling) + + [Distribution](#distribution) + + [Customization](#customization) + * [Generated Help Text](#generated-help-text) + + [Customization](#customization-1) + * [Version Flag](#version-flag) + + [Customization](#customization-2) + + [Full API Example](#full-api-example) +- [Contribution Guidelines](#contribution-guidelines) + + + +## Overview + +Command line apps are usually so tiny that there is absolutely no reason why +your code should *not* be self-documenting. Things like generating help text and +parsing command flags/options should not hinder productivity when writing a +command line app. + +**This is where cli comes into play.** cli makes command line programming fun, +organized, and expressive! + +## Installation + +Make sure you have a working Go environment. Go version 1.2+ is supported. [See +the install instructions for Go](http://golang.org/doc/install.html). + +To install cli, simply run: +``` +$ go get github.com/urfave/cli +``` + +Make sure your `PATH` includes the `$GOPATH/bin` directory so your commands can +be easily used: +``` +export PATH=$PATH:$GOPATH/bin +``` + +### Supported platforms + +cli is tested against multiple versions of Go on Linux, and against the latest +released version of Go on OS X and Windows. For full details, see +[`./.travis.yml`](./.travis.yml) and [`./appveyor.yml`](./appveyor.yml). + +### Using the `v2` branch + +**Warning**: The `v2` branch is currently unreleased and considered unstable. + +There is currently a long-lived branch named `v2` that is intended to land as +the new `master` branch once development there has settled down. The current +`master` branch (mirrored as `v1`) is being manually merged into `v2` on +an irregular human-based schedule, but generally if one wants to "upgrade" to +`v2` *now* and accept the volatility (read: "awesomeness") that comes along with +that, please use whatever version pinning of your preference, such as via +`gopkg.in`: + +``` +$ go get gopkg.in/urfave/cli.v2 +``` + +``` go +... +import ( + "gopkg.in/urfave/cli.v2" // imports as package "cli" +) +... +``` + +### Pinning to the `v1` releases + +Similarly to the section above describing use of the `v2` branch, if one wants +to avoid any unexpected compatibility pains once `v2` becomes `master`, then +pinning to `v1` is an acceptable option, e.g.: + +``` +$ go get gopkg.in/urfave/cli.v1 +``` + +``` go +... +import ( + "gopkg.in/urfave/cli.v1" // imports as package "cli" +) +... +``` + +This will pull the latest tagged `v1` release (e.g. `v1.18.1` at the time of writing). + +## Getting Started + +One of the philosophies behind cli is that an API should be playful and full of +discovery. So a cli app can be as little as one line of code in `main()`. + + +``` go +package main + +import ( + "os" + + "github.com/urfave/cli" +) + +func main() { + cli.NewApp().Run(os.Args) +} +``` + +This app will run and show help text, but is not very useful. Let's give an +action to execute and some help documentation: + + +``` go +package main + +import ( + "fmt" + "os" + + "github.com/urfave/cli" +) + +func main() { + app := cli.NewApp() + app.Name = "boom" + app.Usage = "make an explosive entrance" + app.Action = func(c *cli.Context) error { + fmt.Println("boom! I say!") + return nil + } + + app.Run(os.Args) +} +``` + +Running this already gives you a ton of functionality, plus support for things +like subcommands and flags, which are covered below. + +## Examples + +Being a programmer can be a lonely job. Thankfully by the power of automation +that is not the case! Let's create a greeter app to fend off our demons of +loneliness! + +Start by creating a directory named `greet`, and within it, add a file, +`greet.go` with the following code in it: + + +``` go +package main + +import ( + "fmt" + "os" + + "github.com/urfave/cli" +) + +func main() { + app := cli.NewApp() + app.Name = "greet" + app.Usage = "fight the loneliness!" + app.Action = func(c *cli.Context) error { + fmt.Println("Hello friend!") + return nil + } + + app.Run(os.Args) +} +``` + +Install our command to the `$GOPATH/bin` directory: + +``` +$ go install +``` + +Finally run our new command: + +``` +$ greet +Hello friend! +``` + +cli also generates neat help text: + +``` +$ greet help +NAME: + greet - fight the loneliness! + +USAGE: + greet [global options] command [command options] [arguments...] + +VERSION: + 0.0.0 + +COMMANDS: + help, h Shows a list of commands or help for one command + +GLOBAL OPTIONS + --version Shows version information +``` + +### Arguments + +You can lookup arguments by calling the `Args` function on `cli.Context`, e.g.: + + +``` go +package main + +import ( + "fmt" + "os" + + "github.com/urfave/cli" +) + +func main() { + app := cli.NewApp() + + app.Action = func(c *cli.Context) error { + fmt.Printf("Hello %q", c.Args().Get(0)) + return nil + } + + app.Run(os.Args) +} +``` + +### Flags + +Setting and querying flags is simple. + + +``` go +package main + +import ( + "fmt" + "os" + + "github.com/urfave/cli" +) + +func main() { + app := cli.NewApp() + + app.Flags = []cli.Flag { + cli.StringFlag{ + Name: "lang", + Value: "english", + Usage: "language for the greeting", + }, + } + + app.Action = func(c *cli.Context) error { + name := "Nefertiti" + if c.NArg() > 0 { + name = c.Args().Get(0) + } + if c.String("lang") == "spanish" { + fmt.Println("Hola", name) + } else { + fmt.Println("Hello", name) + } + return nil + } + + app.Run(os.Args) +} +``` + +You can also set a destination variable for a flag, to which the content will be +scanned. + + +``` go +package main + +import ( + "os" + "fmt" + + "github.com/urfave/cli" +) + +func main() { + var language string + + app := cli.NewApp() + + app.Flags = []cli.Flag { + cli.StringFlag{ + Name: "lang", + Value: "english", + Usage: "language for the greeting", + Destination: &language, + }, + } + + app.Action = func(c *cli.Context) error { + name := "someone" + if c.NArg() > 0 { + name = c.Args()[0] + } + if language == "spanish" { + fmt.Println("Hola", name) + } else { + fmt.Println("Hello", name) + } + return nil + } + + app.Run(os.Args) +} +``` + +See full list of flags at http://godoc.org/github.com/urfave/cli + +#### Placeholder Values + +Sometimes it's useful to specify a flag's value within the usage string itself. +Such placeholders are indicated with back quotes. + +For example this: + + +```go +package main + +import ( + "os" + + "github.com/urfave/cli" +) + +func main() { + app := cli.NewApp() + + app.Flags = []cli.Flag{ + cli.StringFlag{ + Name: "config, c", + Usage: "Load configuration from `FILE`", + }, + } + + app.Run(os.Args) +} +``` + +Will result in help output like: + +``` +--config FILE, -c FILE Load configuration from FILE +``` + +Note that only the first placeholder is used. Subsequent back-quoted words will +be left as-is. + +#### Alternate Names + +You can set alternate (or short) names for flags by providing a comma-delimited +list for the `Name`. e.g. + + +``` go +package main + +import ( + "os" + + "github.com/urfave/cli" +) + +func main() { + app := cli.NewApp() + + app.Flags = []cli.Flag { + cli.StringFlag{ + Name: "lang, l", + Value: "english", + Usage: "language for the greeting", + }, + } + + app.Run(os.Args) +} +``` + +That flag can then be set with `--lang spanish` or `-l spanish`. Note that +giving two different forms of the same flag in the same command invocation is an +error. + +#### Ordering + +Flags for the application and commands are shown in the order they are defined. +However, it's possible to sort them from outside this library by using `FlagsByName` +with `sort`. + +For example this: + + +``` go +package main + +import ( + "os" + "sort" + + "github.com/urfave/cli" +) + +func main() { + app := cli.NewApp() + + app.Flags = []cli.Flag { + cli.StringFlag{ + Name: "lang, l", + Value: "english", + Usage: "Language for the greeting", + }, + cli.StringFlag{ + Name: "config, c", + Usage: "Load configuration from `FILE`", + }, + } + + sort.Sort(cli.FlagsByName(app.Flags)) + + app.Run(os.Args) +} +``` + +Will result in help output like: + +``` +--config FILE, -c FILE Load configuration from FILE +--lang value, -l value Language for the greeting (default: "english") +``` + +#### Values from the Environment + +You can also have the default value set from the environment via `EnvVar`. e.g. + + +``` go +package main + +import ( + "os" + + "github.com/urfave/cli" +) + +func main() { + app := cli.NewApp() + + app.Flags = []cli.Flag { + cli.StringFlag{ + Name: "lang, l", + Value: "english", + Usage: "language for the greeting", + EnvVar: "APP_LANG", + }, + } + + app.Run(os.Args) +} +``` + +The `EnvVar` may also be given as a comma-delimited "cascade", where the first +environment variable that resolves is used as the default. + + +``` go +package main + +import ( + "os" + + "github.com/urfave/cli" +) + +func main() { + app := cli.NewApp() + + app.Flags = []cli.Flag { + cli.StringFlag{ + Name: "lang, l", + Value: "english", + Usage: "language for the greeting", + EnvVar: "LEGACY_COMPAT_LANG,APP_LANG,LANG", + }, + } + + app.Run(os.Args) +} +``` + +#### Values from alternate input sources (YAML, TOML, and others) + +There is a separate package altsrc that adds support for getting flag values +from other file input sources. + +Currently supported input source formats: +* YAML +* TOML + +In order to get values for a flag from an alternate input source the following +code would be added to wrap an existing cli.Flag like below: + +``` go + altsrc.NewIntFlag(cli.IntFlag{Name: "test"}) +``` + +Initialization must also occur for these flags. Below is an example initializing +getting data from a yaml file below. + +``` go + command.Before = altsrc.InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load")) +``` + +The code above will use the "load" string as a flag name to get the file name of +a yaml file from the cli.Context. It will then use that file name to initialize +the yaml input source for any flags that are defined on that command. As a note +the "load" flag used would also have to be defined on the command flags in order +for this code snipped to work. + +Currently only the aboved specified formats are supported but developers can +add support for other input sources by implementing the +altsrc.InputSourceContext for their given sources. + +Here is a more complete sample of a command using YAML support: + + +``` go +package notmain + +import ( + "fmt" + "os" + + "github.com/urfave/cli" + "github.com/urfave/cli/altsrc" +) + +func main() { + app := cli.NewApp() + + flags := []cli.Flag{ + altsrc.NewIntFlag(cli.IntFlag{Name: "test"}), + cli.StringFlag{Name: "load"}, + } + + app.Action = func(c *cli.Context) error { + fmt.Println("yaml ist rad") + return nil + } + + app.Before = altsrc.InitInputSourceWithContext(flags, altsrc.NewYamlSourceFromFlagFunc("load")) + app.Flags = flags + + app.Run(os.Args) +} +``` + +### Subcommands + +Subcommands can be defined for a more git-like command line app. + + +```go +package main + +import ( + "fmt" + "os" + + "github.com/urfave/cli" +) + +func main() { + app := cli.NewApp() + + app.Commands = []cli.Command{ + { + Name: "add", + Aliases: []string{"a"}, + Usage: "add a task to the list", + Action: func(c *cli.Context) error { + fmt.Println("added task: ", c.Args().First()) + return nil + }, + }, + { + Name: "complete", + Aliases: []string{"c"}, + Usage: "complete a task on the list", + Action: func(c *cli.Context) error { + fmt.Println("completed task: ", c.Args().First()) + return nil + }, + }, + { + Name: "template", + Aliases: []string{"t"}, + Usage: "options for task templates", + Subcommands: []cli.Command{ + { + Name: "add", + Usage: "add a new template", + Action: func(c *cli.Context) error { + fmt.Println("new task template: ", c.Args().First()) + return nil + }, + }, + { + Name: "remove", + Usage: "remove an existing template", + Action: func(c *cli.Context) error { + fmt.Println("removed task template: ", c.Args().First()) + return nil + }, + }, + }, + }, + } + + app.Run(os.Args) +} +``` + +### Subcommands categories + +For additional organization in apps that have many subcommands, you can +associate a category for each command to group them together in the help +output. + +E.g. + +```go +package main + +import ( + "os" + + "github.com/urfave/cli" +) + +func main() { + app := cli.NewApp() + + app.Commands = []cli.Command{ + { + Name: "noop", + }, + { + Name: "add", + Category: "template", + }, + { + Name: "remove", + Category: "template", + }, + } + + app.Run(os.Args) +} +``` + +Will include: + +``` +COMMANDS: + noop + + Template actions: + add + remove +``` + +### Exit code + +Calling `App.Run` will not automatically call `os.Exit`, which means that by +default the exit code will "fall through" to being `0`. An explicit exit code +may be set by returning a non-nil error that fulfills `cli.ExitCoder`, *or* a +`cli.MultiError` that includes an error that fulfills `cli.ExitCoder`, e.g.: + +``` go +package main + +import ( + "os" + + "github.com/urfave/cli" +) + +func main() { + app := cli.NewApp() + app.Flags = []cli.Flag{ + cli.BoolTFlag{ + Name: "ginger-crouton", + Usage: "is it in the soup?", + }, + } + app.Action = func(ctx *cli.Context) error { + if !ctx.Bool("ginger-crouton") { + return cli.NewExitError("it is not in the soup", 86) + } + return nil + } + + app.Run(os.Args) +} +``` + +### Bash Completion + +You can enable completion commands by setting the `EnableBashCompletion` +flag on the `App` object. By default, this setting will only auto-complete to +show an app's subcommands, but you can write your own completion methods for +the App or its subcommands. + + +``` go +package main + +import ( + "fmt" + "os" + + "github.com/urfave/cli" +) + +func main() { + tasks := []string{"cook", "clean", "laundry", "eat", "sleep", "code"} + + app := cli.NewApp() + app.EnableBashCompletion = true + app.Commands = []cli.Command{ + { + Name: "complete", + Aliases: []string{"c"}, + Usage: "complete a task on the list", + Action: func(c *cli.Context) error { + fmt.Println("completed task: ", c.Args().First()) + return nil + }, + BashComplete: func(c *cli.Context) { + // This will complete if no args are passed + if c.NArg() > 0 { + return + } + for _, t := range tasks { + fmt.Println(t) + } + }, + }, + } + + app.Run(os.Args) +} +``` + +#### Enabling + +Source the `autocomplete/bash_autocomplete` file in your `.bashrc` file while +setting the `PROG` variable to the name of your program: + +`PROG=myprogram source /.../cli/autocomplete/bash_autocomplete` + +#### Distribution + +Copy `autocomplete/bash_autocomplete` into `/etc/bash_completion.d/` and rename +it to the name of the program you wish to add autocomplete support for (or +automatically install it there if you are distributing a package). Don't forget +to source the file to make it active in the current shell. + +``` +sudo cp src/bash_autocomplete /etc/bash_completion.d/ +source /etc/bash_completion.d/ +``` + +Alternatively, you can just document that users should source the generic +`autocomplete/bash_autocomplete` in their bash configuration with `$PROG` set +to the name of their program (as above). + +#### Customization + +The default bash completion flag (`--generate-bash-completion`) is defined as +`cli.BashCompletionFlag`, and may be redefined if desired, e.g.: + + +``` go +package main + +import ( + "os" + + "github.com/urfave/cli" +) + +func main() { + cli.BashCompletionFlag = cli.BoolFlag{ + Name: "compgen", + Hidden: true, + } + + app := cli.NewApp() + app.EnableBashCompletion = true + app.Commands = []cli.Command{ + { + Name: "wat", + }, + } + app.Run(os.Args) +} +``` + +### Generated Help Text + +The default help flag (`-h/--help`) is defined as `cli.HelpFlag` and is checked +by the cli internals in order to print generated help text for the app, command, +or subcommand, and break execution. + +#### Customization + +All of the help text generation may be customized, and at multiple levels. The +templates are exposed as variables `AppHelpTemplate`, `CommandHelpTemplate`, and +`SubcommandHelpTemplate` which may be reassigned or augmented, and full override +is possible by assigning a compatible func to the `cli.HelpPrinter` variable, +e.g.: + + +``` go +package main + +import ( + "fmt" + "io" + "os" + + "github.com/urfave/cli" +) + +func main() { + // EXAMPLE: Append to an existing template + cli.AppHelpTemplate = fmt.Sprintf(`%s + +WEBSITE: http://awesometown.example.com + +SUPPORT: support@awesometown.example.com + +`, cli.AppHelpTemplate) + + // EXAMPLE: Override a template + cli.AppHelpTemplate = `NAME: + {{.Name}} - {{.Usage}} +USAGE: + {{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command +[command options]{{end}} {{if +.ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}} + {{if len .Authors}} +AUTHOR(S): + {{range .Authors}}{{ . }}{{end}} + {{end}}{{if .Commands}} +COMMANDS: +{{range .Commands}}{{if not .HideHelp}} {{join .Names ", "}}{{ "\t" +}}{{.Usage}}{{ "\n" }}{{end}}{{end}}{{end}}{{if .VisibleFlags}} +GLOBAL OPTIONS: + {{range .VisibleFlags}}{{.}} + {{end}}{{end}}{{if .Copyright }} +COPYRIGHT: + {{.Copyright}} + {{end}}{{if .Version}} +VERSION: + {{.Version}} + {{end}} +` + + // EXAMPLE: Replace the `HelpPrinter` func + cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) { + fmt.Println("Ha HA. I pwnd the help!!1") + } + + cli.NewApp().Run(os.Args) +} +``` + +The default flag may be customized to something other than `-h/--help` by +setting `cli.HelpFlag`, e.g.: + + +``` go +package main + +import ( + "os" + + "github.com/urfave/cli" +) + +func main() { + cli.HelpFlag = cli.BoolFlag{ + Name: "halp, haaaaalp", + Usage: "HALP", + EnvVar: "SHOW_HALP,HALPPLZ", + } + + cli.NewApp().Run(os.Args) +} +``` + +### Version Flag + +The default version flag (`-v/--version`) is defined as `cli.VersionFlag`, which +is checked by the cli internals in order to print the `App.Version` via +`cli.VersionPrinter` and break execution. + +#### Customization + +The default flag may be customized to something other than `-v/--version` by +setting `cli.VersionFlag`, e.g.: + + +``` go +package main + +import ( + "os" + + "github.com/urfave/cli" +) + +func main() { + cli.VersionFlag = cli.BoolFlag{ + Name: "print-version, V", + Usage: "print only the version", + } + + app := cli.NewApp() + app.Name = "partay" + app.Version = "19.99.0" + app.Run(os.Args) +} +``` + +Alternatively, the version printer at `cli.VersionPrinter` may be overridden, e.g.: + + +``` go +package main + +import ( + "fmt" + "os" + + "github.com/urfave/cli" +) + +var ( + Revision = "fafafaf" +) + +func main() { + cli.VersionPrinter = func(c *cli.Context) { + fmt.Printf("version=%s revision=%s\n", c.App.Version, Revision) + } + + app := cli.NewApp() + app.Name = "partay" + app.Version = "19.99.0" + app.Run(os.Args) +} +``` + +#### Full API Example + +**Notice**: This is a contrived (functioning) example meant strictly for API +demonstration purposes. Use of one's imagination is encouraged. + + +``` go +package main + +import ( + "errors" + "flag" + "fmt" + "io" + "io/ioutil" + "os" + "time" + + "github.com/urfave/cli" +) + +func init() { + cli.AppHelpTemplate += "\nCUSTOMIZED: you bet ur muffins\n" + cli.CommandHelpTemplate += "\nYMMV\n" + cli.SubcommandHelpTemplate += "\nor something\n" + + cli.HelpFlag = cli.BoolFlag{Name: "halp"} + cli.BashCompletionFlag = cli.BoolFlag{Name: "compgen", Hidden: true} + cli.VersionFlag = cli.BoolFlag{Name: "print-version, V"} + + cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) { + fmt.Fprintf(w, "best of luck to you\n") + } + cli.VersionPrinter = func(c *cli.Context) { + fmt.Fprintf(c.App.Writer, "version=%s\n", c.App.Version) + } + cli.OsExiter = func(c int) { + fmt.Fprintf(cli.ErrWriter, "refusing to exit %d\n", c) + } + cli.ErrWriter = ioutil.Discard + cli.FlagStringer = func(fl cli.Flag) string { + return fmt.Sprintf("\t\t%s", fl.GetName()) + } +} + +type hexWriter struct{} + +func (w *hexWriter) Write(p []byte) (int, error) { + for _, b := range p { + fmt.Printf("%x", b) + } + fmt.Printf("\n") + + return len(p), nil +} + +type genericType struct{ + s string +} + +func (g *genericType) Set(value string) error { + g.s = value + return nil +} + +func (g *genericType) String() string { + return g.s +} + +func main() { + app := cli.NewApp() + app.Name = "kənˈtrīv" + app.Version = "19.99.0" + app.Compiled = time.Now() + app.Authors = []cli.Author{ + cli.Author{ + Name: "Example Human", + Email: "human@example.com", + }, + } + app.Copyright = "(c) 1999 Serious Enterprise" + app.HelpName = "contrive" + app.Usage = "demonstrate available API" + app.UsageText = "contrive - demonstrating the available API" + app.ArgsUsage = "[args and such]" + app.Commands = []cli.Command{ + cli.Command{ + Name: "doo", + Aliases: []string{"do"}, + Category: "motion", + Usage: "do the doo", + UsageText: "doo - does the dooing", + Description: "no really, there is a lot of dooing to be done", + ArgsUsage: "[arrgh]", + Flags: []cli.Flag{ + cli.BoolFlag{Name: "forever, forevvarr"}, + }, + Subcommands: cli.Commands{ + cli.Command{ + Name: "wop", + Action: wopAction, + }, + }, + SkipFlagParsing: false, + HideHelp: false, + Hidden: false, + HelpName: "doo!", + BashComplete: func(c *cli.Context) { + fmt.Fprintf(c.App.Writer, "--better\n") + }, + Before: func(c *cli.Context) error { + fmt.Fprintf(c.App.Writer, "brace for impact\n") + return nil + }, + After: func(c *cli.Context) error { + fmt.Fprintf(c.App.Writer, "did we lose anyone?\n") + return nil + }, + Action: func(c *cli.Context) error { + c.Command.FullName() + c.Command.HasName("wop") + c.Command.Names() + c.Command.VisibleFlags() + fmt.Fprintf(c.App.Writer, "dodododododoodododddooooododododooo\n") + if c.Bool("forever") { + c.Command.Run(c) + } + return nil + }, + OnUsageError: func(c *cli.Context, err error, isSubcommand bool) error { + fmt.Fprintf(c.App.Writer, "for shame\n") + return err + }, + }, + } + app.Flags = []cli.Flag{ + cli.BoolFlag{Name: "fancy"}, + cli.BoolTFlag{Name: "fancier"}, + cli.DurationFlag{Name: "howlong, H", Value: time.Second * 3}, + cli.Float64Flag{Name: "howmuch"}, + cli.GenericFlag{Name: "wat", Value: &genericType{}}, + cli.Int64Flag{Name: "longdistance"}, + cli.Int64SliceFlag{Name: "intervals"}, + cli.IntFlag{Name: "distance"}, + cli.IntSliceFlag{Name: "times"}, + cli.StringFlag{Name: "dance-move, d"}, + cli.StringSliceFlag{Name: "names, N"}, + cli.UintFlag{Name: "age"}, + cli.Uint64Flag{Name: "bigage"}, + } + app.EnableBashCompletion = true + app.HideHelp = false + app.HideVersion = false + app.BashComplete = func(c *cli.Context) { + fmt.Fprintf(c.App.Writer, "lipstick\nkiss\nme\nlipstick\nringo\n") + } + app.Before = func(c *cli.Context) error { + fmt.Fprintf(c.App.Writer, "HEEEERE GOES\n") + return nil + } + app.After = func(c *cli.Context) error { + fmt.Fprintf(c.App.Writer, "Phew!\n") + return nil + } + app.CommandNotFound = func(c *cli.Context, command string) { + fmt.Fprintf(c.App.Writer, "Thar be no %q here.\n", command) + } + app.OnUsageError = func(c *cli.Context, err error, isSubcommand bool) error { + if isSubcommand { + return err + } + + fmt.Fprintf(c.App.Writer, "WRONG: %#v\n", err) + return nil + } + app.Action = func(c *cli.Context) error { + cli.DefaultAppComplete(c) + cli.HandleExitCoder(errors.New("not an exit coder, though")) + cli.ShowAppHelp(c) + cli.ShowCommandCompletions(c, "nope") + cli.ShowCommandHelp(c, "also-nope") + cli.ShowCompletions(c) + cli.ShowSubcommandHelp(c) + cli.ShowVersion(c) + + categories := c.App.Categories() + categories.AddCommand("sounds", cli.Command{ + Name: "bloop", + }) + + for _, category := range c.App.Categories() { + fmt.Fprintf(c.App.Writer, "%s\n", category.Name) + fmt.Fprintf(c.App.Writer, "%#v\n", category.Commands) + fmt.Fprintf(c.App.Writer, "%#v\n", category.VisibleCommands()) + } + + fmt.Printf("%#v\n", c.App.Command("doo")) + if c.Bool("infinite") { + c.App.Run([]string{"app", "doo", "wop"}) + } + + if c.Bool("forevar") { + c.App.RunAsSubcommand(c) + } + c.App.Setup() + fmt.Printf("%#v\n", c.App.VisibleCategories()) + fmt.Printf("%#v\n", c.App.VisibleCommands()) + fmt.Printf("%#v\n", c.App.VisibleFlags()) + + fmt.Printf("%#v\n", c.Args().First()) + if len(c.Args()) > 0 { + fmt.Printf("%#v\n", c.Args()[1]) + } + fmt.Printf("%#v\n", c.Args().Present()) + fmt.Printf("%#v\n", c.Args().Tail()) + + set := flag.NewFlagSet("contrive", 0) + nc := cli.NewContext(c.App, set, c) + + fmt.Printf("%#v\n", nc.Args()) + fmt.Printf("%#v\n", nc.Bool("nope")) + fmt.Printf("%#v\n", nc.BoolT("nerp")) + fmt.Printf("%#v\n", nc.Duration("howlong")) + fmt.Printf("%#v\n", nc.Float64("hay")) + fmt.Printf("%#v\n", nc.Generic("bloop")) + fmt.Printf("%#v\n", nc.Int64("bonk")) + fmt.Printf("%#v\n", nc.Int64Slice("burnks")) + fmt.Printf("%#v\n", nc.Int("bips")) + fmt.Printf("%#v\n", nc.IntSlice("blups")) + fmt.Printf("%#v\n", nc.String("snurt")) + fmt.Printf("%#v\n", nc.StringSlice("snurkles")) + fmt.Printf("%#v\n", nc.Uint("flub")) + fmt.Printf("%#v\n", nc.Uint64("florb")) + fmt.Printf("%#v\n", nc.GlobalBool("global-nope")) + fmt.Printf("%#v\n", nc.GlobalBoolT("global-nerp")) + fmt.Printf("%#v\n", nc.GlobalDuration("global-howlong")) + fmt.Printf("%#v\n", nc.GlobalFloat64("global-hay")) + fmt.Printf("%#v\n", nc.GlobalGeneric("global-bloop")) + fmt.Printf("%#v\n", nc.GlobalInt("global-bips")) + fmt.Printf("%#v\n", nc.GlobalIntSlice("global-blups")) + fmt.Printf("%#v\n", nc.GlobalString("global-snurt")) + fmt.Printf("%#v\n", nc.GlobalStringSlice("global-snurkles")) + + fmt.Printf("%#v\n", nc.FlagNames()) + fmt.Printf("%#v\n", nc.GlobalFlagNames()) + fmt.Printf("%#v\n", nc.GlobalIsSet("wat")) + fmt.Printf("%#v\n", nc.GlobalSet("wat", "nope")) + fmt.Printf("%#v\n", nc.NArg()) + fmt.Printf("%#v\n", nc.NumFlags()) + fmt.Printf("%#v\n", nc.Parent()) + + nc.Set("wat", "also-nope") + + ec := cli.NewExitError("ohwell", 86) + fmt.Fprintf(c.App.Writer, "%d", ec.ExitCode()) + fmt.Printf("made it!\n") + return ec + } + + if os.Getenv("HEXY") != "" { + app.Writer = &hexWriter{} + app.ErrWriter = &hexWriter{} + } + + app.Metadata = map[string]interface{}{ + "layers": "many", + "explicable": false, + "whatever-values": 19.99, + } + + app.Run(os.Args) +} + +func wopAction(c *cli.Context) error { + fmt.Fprintf(c.App.Writer, ":wave: over here, eh\n") + return nil +} +``` + +## Contribution Guidelines + +Feel free to put up a pull request to fix a bug or maybe add a feature. I will +give it a code review and make sure that it does not break backwards +compatibility. If I or any other collaborators agree that it is in line with +the vision of the project, we will work with you to get the code into +a mergeable state and merge it into the master branch. + +If you have contributed something significant to the project, we will most +likely add you as a collaborator. As a collaborator you are given the ability +to merge others pull requests. It is very important that new code does not +break existing code, so be careful about what code you do choose to merge. + +If you feel like you have contributed to the project but have not yet been +added as a collaborator, we probably forgot to add you, please open an issue. diff --git a/vendor/golang.org/x/net/README b/vendor/golang.org/x/net/README new file mode 100644 index 0000000..6b13d8e --- /dev/null +++ b/vendor/golang.org/x/net/README @@ -0,0 +1,3 @@ +This repository holds supplementary Go networking libraries. + +To submit changes to this repository, see http://golang.org/doc/contribute.html. diff --git a/vendor/golang.org/x/net/http2/README b/vendor/golang.org/x/net/http2/README new file mode 100644 index 0000000..360d5aa --- /dev/null +++ b/vendor/golang.org/x/net/http2/README @@ -0,0 +1,20 @@ +This is a work-in-progress HTTP/2 implementation for Go. + +It will eventually live in the Go standard library and won't require +any changes to your code to use. It will just be automatic. + +Status: + +* The server support is pretty good. A few things are missing + but are being worked on. +* The client work has just started but shares a lot of code + is coming along much quicker. + +Docs are at https://godoc.org/golang.org/x/net/http2 + +Demo test server at https://http2.golang.org/ + +Help & bug reports welcome! + +Contributing: https://golang.org/doc/contribute.html +Bugs: https://golang.org/issue/new?title=x/net/http2:+ diff --git a/vendor/golang.org/x/sync/README b/vendor/golang.org/x/sync/README new file mode 100644 index 0000000..59c9dcb --- /dev/null +++ b/vendor/golang.org/x/sync/README @@ -0,0 +1,2 @@ +This repository provides Go concurrency primitives in addition to the +ones provided by the language and "sync" and "sync/atomic" packages. diff --git a/vendor/golang.org/x/sys/README b/vendor/golang.org/x/sys/README new file mode 100644 index 0000000..bd422b4 --- /dev/null +++ b/vendor/golang.org/x/sys/README @@ -0,0 +1,3 @@ +This repository holds supplemental Go packages for low-level interactions with the operating system. + +To submit changes to this repository, see http://golang.org/doc/contribute.html. diff --git a/vendor/google.golang.org/grpc/README.md b/vendor/google.golang.org/grpc/README.md new file mode 100644 index 0000000..39120c2 --- /dev/null +++ b/vendor/google.golang.org/grpc/README.md @@ -0,0 +1,57 @@ +#gRPC-Go + +[![Build Status](https://travis-ci.org/grpc/grpc-go.svg)](https://travis-ci.org/grpc/grpc-go) [![GoDoc](https://godoc.org/google.golang.org/grpc?status.svg)](https://godoc.org/google.golang.org/grpc) + +The Go implementation of [gRPC](http://www.grpc.io/): A high performance, open source, general RPC framework that puts mobile and HTTP/2 first. For more information see the [gRPC Quick Start](http://www.grpc.io/docs/) guide. + +Installation +------------ + +To install this package, you need to install Go and setup your Go workspace on your computer. The simplest way to install the library is to run: + +``` +$ go get google.golang.org/grpc +``` + +Prerequisites +------------- + +This requires Go 1.5 or later. + +A note on the version used: significant performance improvements in benchmarks +of grpc-go have been seen by upgrading the go version from 1.5 to the latest +1.7.1. + +From https://golang.org/doc/install, one way to install the latest version of go is: +``` +$ GO_VERSION=1.7.1 +$ OS=linux +$ ARCH=amd64 +$ curl -O https://storage.googleapis.com/golang/go${GO_VERSION}.${OS}-${ARCH}.tar.gz +$ sudo tar -C /usr/local -xzf go$GO_VERSION.$OS-$ARCH.tar.gz +$ # Put go on the PATH, keep the usual installation dir +$ sudo ln -s /usr/local/go/bin/go /usr/bin/go +$ rm go$GO_VERSION.$OS-$ARCH.tar.gz +``` + +Constraints +----------- +The grpc package should only depend on standard Go packages and a small number of exceptions. If your contribution introduces new dependencies which are NOT in the [list](http://godoc.org/google.golang.org/grpc?imports), you need a discussion with gRPC-Go authors and consultants. + +Documentation +------------- +See [API documentation](https://godoc.org/google.golang.org/grpc) for package and API descriptions and find examples in the [examples directory](examples/). + +Status +------ +GA + +FAQ +--- + +#### Compiling error, undefined: grpc.SupportPackageIsVersion + +Please update proto package, gRPC package and rebuild the proto files: + - `go get -u github.com/golang/protobuf/{proto,protoc-gen-go}` + - `go get -u google.golang.org/grpc` + - `protoc --go_out=plugins=grpc:. *.proto`