diff --git a/api/v1/server.go b/api/v1/server.go
index 53d4d0f..67fa85c 100644
--- a/api/v1/server.go
+++ b/api/v1/server.go
@@ -217,6 +217,11 @@ func (s *server) createContainer(w http.ResponseWriter, r *http.Request) {
e := containerd.NewEvent(containerd.StartContainerEventType)
e.ID = id
e.BundlePath = c.BundlePath
+ logrus.Debug(c.Stderr, c.Stdout)
+ e.Stdio = &containerd.Stdio{
+ Stderr: c.Stderr,
+ Stdout: c.Stdout,
+ }
s.supervisor.SendEvent(e)
if err := <-e.Err; err != nil {
code := http.StatusInternalServerError
diff --git a/api/v1/types.go b/api/v1/types.go
index 2dfc8bb..ee35bc2 100644
--- a/api/v1/types.go
+++ b/api/v1/types.go
@@ -19,6 +19,8 @@ type Container struct {
ID string `json:"id,omitempty"`
BundlePath string `json:"bundlePath,omitempty"`
Processes []Process `json:"processes,omitempty"`
+ Stdout string `json:"stdout,omitempty"`
+ Stderr string `json:"stderr,omitempty"`
State *ContainerState `json:"state,omitempty"`
}
diff --git a/containerd/Godeps/Godeps.json b/containerd/Godeps/Godeps.json
deleted file mode 100644
index 771cbfb..0000000
--- a/containerd/Godeps/Godeps.json
+++ /dev/null
@@ -1,89 +0,0 @@
-{
- "ImportPath": "github.com/docker/containerd/containerd",
- "GoVersion": "go1.5",
- "Deps": [
- {
- "ImportPath": "github.com/Sirupsen/logrus",
- "Comment": "v0.7.3-2-g26709e2",
- "Rev": "26709e2714106fb8ad40b773b711ebce25b78914"
- },
- {
- "ImportPath": "github.com/codegangsta/cli",
- "Comment": "1.2.0-107-g942282e",
- "Rev": "942282e931e8286aa802a30b01fa7e16befb50f3"
- },
- {
- "ImportPath": "github.com/coreos/go-systemd/dbus",
- "Comment": "v3",
- "Rev": "be94bc700879ae8217780e9d141789a2defa302b"
- },
- {
- "ImportPath": "github.com/coreos/go-systemd/util",
- "Comment": "v3",
- "Rev": "be94bc700879ae8217780e9d141789a2defa302b"
- },
- {
- "ImportPath": "github.com/docker/containerd",
- "Rev": "1ee4428b003baadb16729459e678973618b5e5f4"
- },
- {
- "ImportPath": "github.com/docker/docker/pkg/mount",
- "Comment": "v1.4.1-7549-gcc207aa",
- "Rev": "cc207aa136fd5e01164d245de94fb900ca7212a2"
- },
- {
- "ImportPath": "github.com/docker/docker/pkg/symlink",
- "Comment": "v1.4.1-7549-gcc207aa",
- "Rev": "cc207aa136fd5e01164d245de94fb900ca7212a2"
- },
- {
- "ImportPath": "github.com/docker/docker/pkg/system",
- "Comment": "v1.4.1-7549-gcc207aa",
- "Rev": "cc207aa136fd5e01164d245de94fb900ca7212a2"
- },
- {
- "ImportPath": "github.com/docker/docker/pkg/units",
- "Comment": "v1.4.1-7549-gcc207aa",
- "Rev": "cc207aa136fd5e01164d245de94fb900ca7212a2"
- },
- {
- "ImportPath": "github.com/godbus/dbus",
- "Comment": "v2",
- "Rev": "88765d85c0fdadcd98a54e30694fa4e4f5b51133"
- },
- {
- "ImportPath": "github.com/golang/protobuf/proto",
- "Rev": "f7137ae6b19afbfd61a94b746fda3b3fe0491874"
- },
- {
- "ImportPath": "github.com/gorilla/context",
- "Rev": "215affda49addc4c8ef7e2534915df2c8c35c6cd"
- },
- {
- "ImportPath": "github.com/gorilla/mux",
- "Rev": "ad4d7a5882b961e07e2626045eb995c022ac6664"
- },
- {
- "ImportPath": "github.com/opencontainers/runc/libcontainer",
- "Comment": "v0.0.4-159-gc4e5288",
- "Rev": "c4e528889ab781cc84ba17a99f12a311016f0eed"
- },
- {
- "ImportPath": "github.com/opencontainers/specs",
- "Comment": "v0.1.1-76-g46d949e",
- "Rev": "46d949ea81080c5f60dfb72ee91468b1e9fb2998"
- },
- {
- "ImportPath": "github.com/rcrowley/go-metrics",
- "Rev": "1ce93efbc8f9c568886b2ef85ce305b2217b3de3"
- },
- {
- "ImportPath": "github.com/syndtr/gocapability/capability",
- "Rev": "2c00daeb6c3b45114c80ac44119e7b8801fdd852"
- },
- {
- "ImportPath": "github.com/vishvananda/netlink",
- "Rev": "ecf47fd5739b3d2c3daf7c89c4b9715a2605c21b"
- }
- ]
-}
diff --git a/containerd/Godeps/Readme b/containerd/Godeps/Readme
deleted file mode 100644
index 4cdaa53..0000000
--- a/containerd/Godeps/Readme
+++ /dev/null
@@ -1,5 +0,0 @@
-This directory tree is generated automatically by godep.
-
-Please do not edit.
-
-See https://github.com/tools/godep for more information.
diff --git a/containerd/Makefile b/containerd/Makefile
index 5bc14d0..6a0d4e7 100644
--- a/containerd/Makefile
+++ b/containerd/Makefile
@@ -1,6 +1,6 @@
all:
- godep go build -tags libcontainer
+ go build -tags libcontainer
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/.gitignore b/containerd/vendor/github.com/Sirupsen/logrus/.gitignore
deleted file mode 100644
index 66be63a..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-logrus
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/.travis.yml b/containerd/vendor/github.com/Sirupsen/logrus/.travis.yml
deleted file mode 100644
index 2d8c086..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/.travis.yml
+++ /dev/null
@@ -1,8 +0,0 @@
-language: go
-go:
- - 1.2
- - 1.3
- - 1.4
- - tip
-install:
- - go get -t ./...
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/CHANGELOG.md b/containerd/vendor/github.com/Sirupsen/logrus/CHANGELOG.md
deleted file mode 100644
index eb72bff..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/CHANGELOG.md
+++ /dev/null
@@ -1,7 +0,0 @@
-# 0.7.3
-
-formatter/\*: allow configuration of timestamp layout
-
-# 0.7.2
-
-formatter/text: Add configuration option for time format (#158)
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/LICENSE b/containerd/vendor/github.com/Sirupsen/logrus/LICENSE
deleted file mode 100644
index f090cb4..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 Simon Eskildsen
-
-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/containerd/vendor/github.com/Sirupsen/logrus/README.md b/containerd/vendor/github.com/Sirupsen/logrus/README.md
deleted file mode 100644
index d55f909..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/README.md
+++ /dev/null
@@ -1,349 +0,0 @@
-# Logrus [![Build Status](https://travis-ci.org/Sirupsen/logrus.svg?branch=master)](https://travis-ci.org/Sirupsen/logrus) [![godoc reference](https://godoc.org/github.com/Sirupsen/logrus?status.png)][godoc]
-
-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.Formatter = new(logrus.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.Formatter = new(logrus.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"
- "github.com/Sirupsen/logrus/hooks/airbrake"
-)
-
-func init() {
- // Log as JSON instead of the default ASCII formatter.
- log.SetFormatter(&log.JSONFormatter{})
-
- // 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("https://example.com", "xyz", "development"))
-
- // 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"
- "github.com/Sirupsen/logrus/hooks/airbrake"
- "github.com/Sirupsen/logrus/hooks/syslog"
- "log/syslog"
-)
-
-func init() {
- log.AddHook(airbrake.NewHook("https://example.com", "xyz", "development"))
-
- 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)
- }
-}
-```
-
-
-| Hook | Description |
-| ----- | ----------- |
-| [Airbrake](https://github.com/Sirupsen/logrus/blob/master/hooks/airbrake/airbrake.go) | Send errors to an exception tracking service compatible with the Airbrake API. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. |
-| [Papertrail](https://github.com/Sirupsen/logrus/blob/master/hooks/papertrail/papertrail.go) | Send errors to the Papertrail 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/Sirupsen/logrus/blob/master/hooks/bugsnag/bugsnag.go) | Send errors to the Bugsnag exception tracking 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-hooks/tree/master/graylog) | Hook for logging to [Graylog](http://graylog2.org/) |
-
-#### 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(logrus.JSONFormatter)
- } else {
- // The TextFormatter is default, you don't actually have to do this.
- log.SetFormatter(logrus.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.
-* `logrus_logstash.LogstashFormatter`. Logs fields as Logstash Events (http://logstash.net).
-
- ```go
- logrus.SetFormatter(&logrus_logstash.LogstashFormatter{Type: “application_name"})
- ```
-
-Third party logging formatters:
-
-* [`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 *JSONFormatter) 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 transormed 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.
-
-
-[godoc]: https://godoc.org/github.com/Sirupsen/logrus
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/entry.go b/containerd/vendor/github.com/Sirupsen/logrus/entry.go
deleted file mode 100644
index 17fe6f7..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/entry.go
+++ /dev/null
@@ -1,252 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "time"
-)
-
-// An entry is the final or intermediate Logrus logging entry. It contains all
-// the fields passed with WithField{,s}. It's finally logged when Debug, Info,
-// Warn, Error, Fatal or Panic is called on it. These objects can be reused and
-// passed around as much as you wish to avoid field duplication.
-type Entry struct {
- Logger *Logger
-
- // Contains all the fields set by the user.
- Data Fields
-
- // Time at which the log entry was created
- Time time.Time
-
- // Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic
- Level Level
-
- // Message passed to Debug, Info, Warn, Error, Fatal or Panic
- Message string
-}
-
-func NewEntry(logger *Logger) *Entry {
- return &Entry{
- Logger: logger,
- // Default is three fields, give a little extra room
- Data: make(Fields, 5),
- }
-}
-
-// Returns a reader for the entry, which is a proxy to the formatter.
-func (entry *Entry) Reader() (*bytes.Buffer, error) {
- serialized, err := entry.Logger.Formatter.Format(entry)
- return bytes.NewBuffer(serialized), err
-}
-
-// Returns the string representation from the reader and ultimately the
-// formatter.
-func (entry *Entry) String() (string, error) {
- reader, err := entry.Reader()
- if err != nil {
- return "", err
- }
-
- return reader.String(), err
-}
-
-// Add a single field to the Entry.
-func (entry *Entry) WithField(key string, value interface{}) *Entry {
- return entry.WithFields(Fields{key: value})
-}
-
-// Add a map of fields to the Entry.
-func (entry *Entry) WithFields(fields Fields) *Entry {
- data := Fields{}
- for k, v := range entry.Data {
- data[k] = v
- }
- for k, v := range fields {
- data[k] = v
- }
- return &Entry{Logger: entry.Logger, Data: data}
-}
-
-func (entry *Entry) log(level Level, msg string) {
- entry.Time = time.Now()
- entry.Level = level
- entry.Message = msg
-
- if err := entry.Logger.Hooks.Fire(level, entry); err != nil {
- entry.Logger.mu.Lock()
- fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
- entry.Logger.mu.Unlock()
- }
-
- reader, err := entry.Reader()
- if err != nil {
- entry.Logger.mu.Lock()
- fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
- entry.Logger.mu.Unlock()
- }
-
- entry.Logger.mu.Lock()
- defer entry.Logger.mu.Unlock()
-
- _, err = io.Copy(entry.Logger.Out, reader)
- if err != nil {
- fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
- }
-
- // To avoid Entry#log() returning a value that only would make sense for
- // panic() to use in Entry#Panic(), we avoid the allocation by checking
- // directly here.
- if level <= PanicLevel {
- panic(entry)
- }
-}
-
-func (entry *Entry) Debug(args ...interface{}) {
- if entry.Logger.Level >= DebugLevel {
- entry.log(DebugLevel, fmt.Sprint(args...))
- }
-}
-
-func (entry *Entry) Print(args ...interface{}) {
- entry.Info(args...)
-}
-
-func (entry *Entry) Info(args ...interface{}) {
- if entry.Logger.Level >= InfoLevel {
- entry.log(InfoLevel, fmt.Sprint(args...))
- }
-}
-
-func (entry *Entry) Warn(args ...interface{}) {
- if entry.Logger.Level >= WarnLevel {
- entry.log(WarnLevel, fmt.Sprint(args...))
- }
-}
-
-func (entry *Entry) Warning(args ...interface{}) {
- entry.Warn(args...)
-}
-
-func (entry *Entry) Error(args ...interface{}) {
- if entry.Logger.Level >= ErrorLevel {
- entry.log(ErrorLevel, fmt.Sprint(args...))
- }
-}
-
-func (entry *Entry) Fatal(args ...interface{}) {
- if entry.Logger.Level >= FatalLevel {
- entry.log(FatalLevel, fmt.Sprint(args...))
- }
- os.Exit(1)
-}
-
-func (entry *Entry) Panic(args ...interface{}) {
- if entry.Logger.Level >= PanicLevel {
- entry.log(PanicLevel, fmt.Sprint(args...))
- }
- panic(fmt.Sprint(args...))
-}
-
-// Entry Printf family functions
-
-func (entry *Entry) Debugf(format string, args ...interface{}) {
- if entry.Logger.Level >= DebugLevel {
- entry.Debug(fmt.Sprintf(format, args...))
- }
-}
-
-func (entry *Entry) Infof(format string, args ...interface{}) {
- if entry.Logger.Level >= InfoLevel {
- entry.Info(fmt.Sprintf(format, args...))
- }
-}
-
-func (entry *Entry) Printf(format string, args ...interface{}) {
- entry.Infof(format, args...)
-}
-
-func (entry *Entry) Warnf(format string, args ...interface{}) {
- if entry.Logger.Level >= WarnLevel {
- entry.Warn(fmt.Sprintf(format, args...))
- }
-}
-
-func (entry *Entry) Warningf(format string, args ...interface{}) {
- entry.Warnf(format, args...)
-}
-
-func (entry *Entry) Errorf(format string, args ...interface{}) {
- if entry.Logger.Level >= ErrorLevel {
- entry.Error(fmt.Sprintf(format, args...))
- }
-}
-
-func (entry *Entry) Fatalf(format string, args ...interface{}) {
- if entry.Logger.Level >= FatalLevel {
- entry.Fatal(fmt.Sprintf(format, args...))
- }
-}
-
-func (entry *Entry) Panicf(format string, args ...interface{}) {
- if entry.Logger.Level >= PanicLevel {
- entry.Panic(fmt.Sprintf(format, args...))
- }
-}
-
-// Entry Println family functions
-
-func (entry *Entry) Debugln(args ...interface{}) {
- if entry.Logger.Level >= DebugLevel {
- entry.Debug(entry.sprintlnn(args...))
- }
-}
-
-func (entry *Entry) Infoln(args ...interface{}) {
- if entry.Logger.Level >= InfoLevel {
- entry.Info(entry.sprintlnn(args...))
- }
-}
-
-func (entry *Entry) Println(args ...interface{}) {
- entry.Infoln(args...)
-}
-
-func (entry *Entry) Warnln(args ...interface{}) {
- if entry.Logger.Level >= WarnLevel {
- entry.Warn(entry.sprintlnn(args...))
- }
-}
-
-func (entry *Entry) Warningln(args ...interface{}) {
- entry.Warnln(args...)
-}
-
-func (entry *Entry) Errorln(args ...interface{}) {
- if entry.Logger.Level >= ErrorLevel {
- entry.Error(entry.sprintlnn(args...))
- }
-}
-
-func (entry *Entry) Fatalln(args ...interface{}) {
- if entry.Logger.Level >= FatalLevel {
- entry.Fatal(entry.sprintlnn(args...))
- }
-}
-
-func (entry *Entry) Panicln(args ...interface{}) {
- if entry.Logger.Level >= PanicLevel {
- entry.Panic(entry.sprintlnn(args...))
- }
-}
-
-// Sprintlnn => Sprint no newline. This is to get the behavior of how
-// fmt.Sprintln where spaces are always added between operands, regardless of
-// their type. Instead of vendoring the Sprintln implementation to spare a
-// string allocation, we do the simplest thing.
-func (entry *Entry) sprintlnn(args ...interface{}) string {
- msg := fmt.Sprintln(args...)
- return msg[:len(msg)-1]
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/examples/basic/basic.go b/containerd/vendor/github.com/Sirupsen/logrus/examples/basic/basic.go
deleted file mode 100644
index a1623ec..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/examples/basic/basic.go
+++ /dev/null
@@ -1,50 +0,0 @@
-package main
-
-import (
- "github.com/Sirupsen/logrus"
-)
-
-var log = logrus.New()
-
-func init() {
- log.Formatter = new(logrus.JSONFormatter)
- log.Formatter = new(logrus.TextFormatter) // default
- log.Level = logrus.DebugLevel
-}
-
-func main() {
- defer func() {
- err := recover()
- if err != nil {
- log.WithFields(logrus.Fields{
- "omg": true,
- "err": err,
- "number": 100,
- }).Fatal("The ice breaks!")
- }
- }()
-
- log.WithFields(logrus.Fields{
- "animal": "walrus",
- "number": 8,
- }).Debug("Started observing beach")
-
- log.WithFields(logrus.Fields{
- "animal": "walrus",
- "size": 10,
- }).Info("A group of walrus emerges from the ocean")
-
- log.WithFields(logrus.Fields{
- "omg": true,
- "number": 122,
- }).Warn("The group's number increased tremendously!")
-
- log.WithFields(logrus.Fields{
- "temperature": -4,
- }).Debug("Temperature changes")
-
- log.WithFields(logrus.Fields{
- "animal": "orca",
- "size": 9009,
- }).Panic("It's over 9000!")
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/examples/hook/hook.go b/containerd/vendor/github.com/Sirupsen/logrus/examples/hook/hook.go
deleted file mode 100644
index cb5759a..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/examples/hook/hook.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package main
-
-import (
- "github.com/Sirupsen/logrus"
- "github.com/Sirupsen/logrus/hooks/airbrake"
-)
-
-var log = logrus.New()
-
-func init() {
- log.Formatter = new(logrus.TextFormatter) // default
- log.Hooks.Add(airbrake.NewHook("https://example.com", "xyz", "development"))
-}
-
-func main() {
- log.WithFields(logrus.Fields{
- "animal": "walrus",
- "size": 10,
- }).Info("A group of walrus emerges from the ocean")
-
- log.WithFields(logrus.Fields{
- "omg": true,
- "number": 122,
- }).Warn("The group's number increased tremendously!")
-
- log.WithFields(logrus.Fields{
- "omg": true,
- "number": 100,
- }).Fatal("The ice breaks!")
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/exported.go b/containerd/vendor/github.com/Sirupsen/logrus/exported.go
deleted file mode 100644
index a67e1b8..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/exported.go
+++ /dev/null
@@ -1,188 +0,0 @@
-package logrus
-
-import (
- "io"
-)
-
-var (
- // std is the name of the standard logger in stdlib `log`
- std = New()
-)
-
-func StandardLogger() *Logger {
- return std
-}
-
-// SetOutput sets the standard logger output.
-func SetOutput(out io.Writer) {
- std.mu.Lock()
- defer std.mu.Unlock()
- std.Out = out
-}
-
-// SetFormatter sets the standard logger formatter.
-func SetFormatter(formatter Formatter) {
- std.mu.Lock()
- defer std.mu.Unlock()
- std.Formatter = formatter
-}
-
-// SetLevel sets the standard logger level.
-func SetLevel(level Level) {
- std.mu.Lock()
- defer std.mu.Unlock()
- std.Level = level
-}
-
-// GetLevel returns the standard logger level.
-func GetLevel() Level {
- std.mu.Lock()
- defer std.mu.Unlock()
- return std.Level
-}
-
-// AddHook adds a hook to the standard logger hooks.
-func AddHook(hook Hook) {
- std.mu.Lock()
- defer std.mu.Unlock()
- std.Hooks.Add(hook)
-}
-
-// WithField creates an entry from the standard logger and adds a field to
-// it. If you want multiple fields, use `WithFields`.
-//
-// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
-// or Panic on the Entry it returns.
-func WithField(key string, value interface{}) *Entry {
- return std.WithField(key, value)
-}
-
-// WithFields creates an entry from the standard logger and adds multiple
-// fields to it. This is simply a helper for `WithField`, invoking it
-// once for each field.
-//
-// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
-// or Panic on the Entry it returns.
-func WithFields(fields Fields) *Entry {
- return std.WithFields(fields)
-}
-
-// Debug logs a message at level Debug on the standard logger.
-func Debug(args ...interface{}) {
- std.Debug(args...)
-}
-
-// Print logs a message at level Info on the standard logger.
-func Print(args ...interface{}) {
- std.Print(args...)
-}
-
-// Info logs a message at level Info on the standard logger.
-func Info(args ...interface{}) {
- std.Info(args...)
-}
-
-// Warn logs a message at level Warn on the standard logger.
-func Warn(args ...interface{}) {
- std.Warn(args...)
-}
-
-// Warning logs a message at level Warn on the standard logger.
-func Warning(args ...interface{}) {
- std.Warning(args...)
-}
-
-// Error logs a message at level Error on the standard logger.
-func Error(args ...interface{}) {
- std.Error(args...)
-}
-
-// Panic logs a message at level Panic on the standard logger.
-func Panic(args ...interface{}) {
- std.Panic(args...)
-}
-
-// Fatal logs a message at level Fatal on the standard logger.
-func Fatal(args ...interface{}) {
- std.Fatal(args...)
-}
-
-// Debugf logs a message at level Debug on the standard logger.
-func Debugf(format string, args ...interface{}) {
- std.Debugf(format, args...)
-}
-
-// Printf logs a message at level Info on the standard logger.
-func Printf(format string, args ...interface{}) {
- std.Printf(format, args...)
-}
-
-// Infof logs a message at level Info on the standard logger.
-func Infof(format string, args ...interface{}) {
- std.Infof(format, args...)
-}
-
-// Warnf logs a message at level Warn on the standard logger.
-func Warnf(format string, args ...interface{}) {
- std.Warnf(format, args...)
-}
-
-// Warningf logs a message at level Warn on the standard logger.
-func Warningf(format string, args ...interface{}) {
- std.Warningf(format, args...)
-}
-
-// Errorf logs a message at level Error on the standard logger.
-func Errorf(format string, args ...interface{}) {
- std.Errorf(format, args...)
-}
-
-// Panicf logs a message at level Panic on the standard logger.
-func Panicf(format string, args ...interface{}) {
- std.Panicf(format, args...)
-}
-
-// Fatalf logs a message at level Fatal on the standard logger.
-func Fatalf(format string, args ...interface{}) {
- std.Fatalf(format, args...)
-}
-
-// Debugln logs a message at level Debug on the standard logger.
-func Debugln(args ...interface{}) {
- std.Debugln(args...)
-}
-
-// Println logs a message at level Info on the standard logger.
-func Println(args ...interface{}) {
- std.Println(args...)
-}
-
-// Infoln logs a message at level Info on the standard logger.
-func Infoln(args ...interface{}) {
- std.Infoln(args...)
-}
-
-// Warnln logs a message at level Warn on the standard logger.
-func Warnln(args ...interface{}) {
- std.Warnln(args...)
-}
-
-// Warningln logs a message at level Warn on the standard logger.
-func Warningln(args ...interface{}) {
- std.Warningln(args...)
-}
-
-// Errorln logs a message at level Error on the standard logger.
-func Errorln(args ...interface{}) {
- std.Errorln(args...)
-}
-
-// Panicln logs a message at level Panic on the standard logger.
-func Panicln(args ...interface{}) {
- std.Panicln(args...)
-}
-
-// Fatalln logs a message at level Fatal on the standard logger.
-func Fatalln(args ...interface{}) {
- std.Fatalln(args...)
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/formatter.go b/containerd/vendor/github.com/Sirupsen/logrus/formatter.go
deleted file mode 100644
index 104d689..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/formatter.go
+++ /dev/null
@@ -1,48 +0,0 @@
-package logrus
-
-import "time"
-
-const DefaultTimestampFormat = time.RFC3339
-
-// The Formatter interface is used to implement a custom Formatter. It takes an
-// `Entry`. It exposes all the fields, including the default ones:
-//
-// * `entry.Data["msg"]`. The message passed from Info, Warn, Error ..
-// * `entry.Data["time"]`. The timestamp.
-// * `entry.Data["level"]. The level the entry was logged at.
-//
-// Any additional fields added with `WithField` or `WithFields` are also in
-// `entry.Data`. Format is expected to return an array of bytes which are then
-// logged to `logger.Out`.
-type Formatter interface {
- Format(*Entry) ([]byte, error)
-}
-
-// This is to not silently overwrite `time`, `msg` and `level` fields when
-// dumping it. If this code wasn't there doing:
-//
-// logrus.WithField("level", 1).Info("hello")
-//
-// Would just silently drop the user provided level. Instead with this code
-// it'll logged as:
-//
-// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."}
-//
-// It's not exported because it's still using Data in an opinionated way. It's to
-// avoid code duplication between the two default formatters.
-func prefixFieldClashes(data Fields) {
- _, ok := data["time"]
- if ok {
- data["fields.time"] = data["time"]
- }
-
- _, ok = data["msg"]
- if ok {
- data["fields.msg"] = data["msg"]
- }
-
- _, ok = data["level"]
- if ok {
- data["fields.level"] = data["level"]
- }
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/formatters/logstash/logstash.go b/containerd/vendor/github.com/Sirupsen/logrus/formatters/logstash/logstash.go
deleted file mode 100644
index 8ea93dd..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/formatters/logstash/logstash.go
+++ /dev/null
@@ -1,56 +0,0 @@
-package logstash
-
-import (
- "encoding/json"
- "fmt"
-
- "github.com/Sirupsen/logrus"
-)
-
-// Formatter generates json in logstash format.
-// Logstash site: http://logstash.net/
-type LogstashFormatter struct {
- Type string // if not empty use for logstash type field.
-
- // TimestampFormat sets the format used for timestamps.
- TimestampFormat string
-}
-
-func (f *LogstashFormatter) Format(entry *logrus.Entry) ([]byte, error) {
- entry.Data["@version"] = 1
-
- if f.TimestampFormat == "" {
- f.TimestampFormat = logrus.DefaultTimestampFormat
- }
-
- entry.Data["@timestamp"] = entry.Time.Format(f.TimestampFormat)
-
- // set message field
- v, ok := entry.Data["message"]
- if ok {
- entry.Data["fields.message"] = v
- }
- entry.Data["message"] = entry.Message
-
- // set level field
- v, ok = entry.Data["level"]
- if ok {
- entry.Data["fields.level"] = v
- }
- entry.Data["level"] = entry.Level.String()
-
- // set type field
- if f.Type != "" {
- v, ok = entry.Data["type"]
- if ok {
- entry.Data["fields.type"] = v
- }
- entry.Data["type"] = f.Type
- }
-
- 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
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/hooks.go b/containerd/vendor/github.com/Sirupsen/logrus/hooks.go
deleted file mode 100644
index 0da2b36..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/hooks.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package logrus
-
-// A hook to be fired when logging on the logging levels returned from
-// `Levels()` on your implementation of the interface. Note that this is not
-// fired in a goroutine or a channel with workers, you should handle such
-// functionality yourself if your call is non-blocking and you don't wish for
-// the logging calls for levels returned from `Levels()` to block.
-type Hook interface {
- Levels() []Level
- Fire(*Entry) error
-}
-
-// Internal type for storing the hooks on a logger instance.
-type levelHooks map[Level][]Hook
-
-// Add a hook to an instance of logger. This is called with
-// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface.
-func (hooks levelHooks) Add(hook Hook) {
- for _, level := range hook.Levels() {
- hooks[level] = append(hooks[level], hook)
- }
-}
-
-// Fire all the hooks for the passed level. Used by `entry.log` to fire
-// appropriate hooks for a log entry.
-func (hooks levelHooks) Fire(level Level, entry *Entry) error {
- for _, hook := range hooks[level] {
- if err := hook.Fire(entry); err != nil {
- return err
- }
- }
-
- return nil
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/hooks/airbrake/airbrake.go b/containerd/vendor/github.com/Sirupsen/logrus/hooks/airbrake/airbrake.go
deleted file mode 100644
index b0502c3..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/hooks/airbrake/airbrake.go
+++ /dev/null
@@ -1,54 +0,0 @@
-package airbrake
-
-import (
- "errors"
- "fmt"
-
- "github.com/Sirupsen/logrus"
- "github.com/tobi/airbrake-go"
-)
-
-// AirbrakeHook to send exceptions to an exception-tracking service compatible
-// with the Airbrake API.
-type airbrakeHook struct {
- APIKey string
- Endpoint string
- Environment string
-}
-
-func NewHook(endpoint, apiKey, env string) *airbrakeHook {
- return &airbrakeHook{
- APIKey: apiKey,
- Endpoint: endpoint,
- Environment: env,
- }
-}
-
-func (hook *airbrakeHook) Fire(entry *logrus.Entry) error {
- airbrake.ApiKey = hook.APIKey
- airbrake.Endpoint = hook.Endpoint
- airbrake.Environment = hook.Environment
-
- var notifyErr error
- err, ok := entry.Data["error"].(error)
- if ok {
- notifyErr = err
- } else {
- notifyErr = errors.New(entry.Message)
- }
-
- airErr := airbrake.Notify(notifyErr)
- if airErr != nil {
- return fmt.Errorf("Failed to send error to Airbrake: %s", airErr)
- }
-
- return nil
-}
-
-func (hook *airbrakeHook) Levels() []logrus.Level {
- return []logrus.Level{
- logrus.ErrorLevel,
- logrus.FatalLevel,
- logrus.PanicLevel,
- }
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag.go b/containerd/vendor/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag.go
deleted file mode 100644
index d20a0f5..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag.go
+++ /dev/null
@@ -1,68 +0,0 @@
-package logrus_bugsnag
-
-import (
- "errors"
-
- "github.com/Sirupsen/logrus"
- "github.com/bugsnag/bugsnag-go"
-)
-
-type bugsnagHook struct{}
-
-// ErrBugsnagUnconfigured is returned if NewBugsnagHook is called before
-// bugsnag.Configure. Bugsnag must be configured before the hook.
-var ErrBugsnagUnconfigured = errors.New("bugsnag must be configured before installing this logrus hook")
-
-// ErrBugsnagSendFailed indicates that the hook failed to submit an error to
-// bugsnag. The error was successfully generated, but `bugsnag.Notify()`
-// failed.
-type ErrBugsnagSendFailed struct {
- err error
-}
-
-func (e ErrBugsnagSendFailed) Error() string {
- return "failed to send error to Bugsnag: " + e.err.Error()
-}
-
-// NewBugsnagHook initializes a logrus hook which sends exceptions to an
-// exception-tracking service compatible with the Bugsnag API. Before using
-// this hook, you must call bugsnag.Configure(). The returned object should be
-// registered with a log via `AddHook()`
-//
-// Entries that trigger an Error, Fatal or Panic should now include an "error"
-// field to send to Bugsnag.
-func NewBugsnagHook() (*bugsnagHook, error) {
- if bugsnag.Config.APIKey == "" {
- return nil, ErrBugsnagUnconfigured
- }
- return &bugsnagHook{}, nil
-}
-
-// Fire forwards an error to Bugsnag. Given a logrus.Entry, it extracts the
-// "error" field (or the Message if the error isn't present) and sends it off.
-func (hook *bugsnagHook) Fire(entry *logrus.Entry) error {
- var notifyErr error
- err, ok := entry.Data["error"].(error)
- if ok {
- notifyErr = err
- } else {
- notifyErr = errors.New(entry.Message)
- }
-
- bugsnagErr := bugsnag.Notify(notifyErr)
- if bugsnagErr != nil {
- return ErrBugsnagSendFailed{bugsnagErr}
- }
-
- return nil
-}
-
-// Levels enumerates the log levels on which the error should be forwarded to
-// bugsnag: everything at or above the "Error" level.
-func (hook *bugsnagHook) Levels() []logrus.Level {
- return []logrus.Level{
- logrus.ErrorLevel,
- logrus.FatalLevel,
- logrus.PanicLevel,
- }
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/hooks/papertrail/README.md b/containerd/vendor/github.com/Sirupsen/logrus/hooks/papertrail/README.md
deleted file mode 100644
index ae61e92..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/hooks/papertrail/README.md
+++ /dev/null
@@ -1,28 +0,0 @@
-# Papertrail Hook for Logrus
-
-[Papertrail](https://papertrailapp.com) provides hosted log management. Once stored in Papertrail, you can [group](http://help.papertrailapp.com/kb/how-it-works/groups/) your logs on various dimensions, [search](http://help.papertrailapp.com/kb/how-it-works/search-syntax) them, and trigger [alerts](http://help.papertrailapp.com/kb/how-it-works/alerts).
-
-In most deployments, you'll want to send logs to Papertrail via their [remote_syslog](http://help.papertrailapp.com/kb/configuration/configuring-centralized-logging-from-text-log-files-in-unix/) daemon, which requires no application-specific configuration. This hook is intended for relatively low-volume logging, likely in managed cloud hosting deployments where installing `remote_syslog` is not possible.
-
-## Usage
-
-You can find your Papertrail UDP port on your [Papertrail account page](https://papertrailapp.com/account/destinations). Substitute it below for `YOUR_PAPERTRAIL_UDP_PORT`.
-
-For `YOUR_APP_NAME`, substitute a short string that will readily identify your application or service in the logs.
-
-```go
-import (
- "log/syslog"
- "github.com/Sirupsen/logrus"
- "github.com/Sirupsen/logrus/hooks/papertrail"
-)
-
-func main() {
- log := logrus.New()
- hook, err := logrus_papertrail.NewPapertrailHook("logs.papertrailapp.com", YOUR_PAPERTRAIL_UDP_PORT, YOUR_APP_NAME)
-
- if err == nil {
- log.Hooks.Add(hook)
- }
-}
-```
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/hooks/papertrail/papertrail.go b/containerd/vendor/github.com/Sirupsen/logrus/hooks/papertrail/papertrail.go
deleted file mode 100644
index c0f10c1..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/hooks/papertrail/papertrail.go
+++ /dev/null
@@ -1,55 +0,0 @@
-package logrus_papertrail
-
-import (
- "fmt"
- "net"
- "os"
- "time"
-
- "github.com/Sirupsen/logrus"
-)
-
-const (
- format = "Jan 2 15:04:05"
-)
-
-// PapertrailHook to send logs to a logging service compatible with the Papertrail API.
-type PapertrailHook struct {
- Host string
- Port int
- AppName string
- UDPConn net.Conn
-}
-
-// NewPapertrailHook creates a hook to be added to an instance of logger.
-func NewPapertrailHook(host string, port int, appName string) (*PapertrailHook, error) {
- conn, err := net.Dial("udp", fmt.Sprintf("%s:%d", host, port))
- return &PapertrailHook{host, port, appName, conn}, err
-}
-
-// Fire is called when a log event is fired.
-func (hook *PapertrailHook) Fire(entry *logrus.Entry) error {
- date := time.Now().Format(format)
- msg, _ := entry.String()
- payload := fmt.Sprintf("<22> %s %s: %s", date, hook.AppName, msg)
-
- bytesWritten, err := hook.UDPConn.Write([]byte(payload))
- if err != nil {
- fmt.Fprintf(os.Stderr, "Unable to send log line to Papertrail via UDP. Wrote %d bytes before error: %v", bytesWritten, err)
- return err
- }
-
- return nil
-}
-
-// Levels returns the available logging levels.
-func (hook *PapertrailHook) Levels() []logrus.Level {
- return []logrus.Level{
- logrus.PanicLevel,
- logrus.FatalLevel,
- logrus.ErrorLevel,
- logrus.WarnLevel,
- logrus.InfoLevel,
- logrus.DebugLevel,
- }
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/hooks/sentry/README.md b/containerd/vendor/github.com/Sirupsen/logrus/hooks/sentry/README.md
deleted file mode 100644
index 19e58bb..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/hooks/sentry/README.md
+++ /dev/null
@@ -1,61 +0,0 @@
-# Sentry Hook for Logrus
-
-[Sentry](https://getsentry.com) provides both self-hosted and hosted
-solutions for exception tracking.
-Both client and server are
-[open source](https://github.com/getsentry/sentry).
-
-## Usage
-
-Every sentry application defined on the server gets a different
-[DSN](https://www.getsentry.com/docs/). In the example below replace
-`YOUR_DSN` with the one created for your application.
-
-```go
-import (
- "github.com/Sirupsen/logrus"
- "github.com/Sirupsen/logrus/hooks/sentry"
-)
-
-func main() {
- log := logrus.New()
- hook, err := logrus_sentry.NewSentryHook(YOUR_DSN, []logrus.Level{
- logrus.PanicLevel,
- logrus.FatalLevel,
- logrus.ErrorLevel,
- })
-
- if err == nil {
- log.Hooks.Add(hook)
- }
-}
-```
-
-## Special fields
-
-Some logrus fields have a special meaning in this hook,
-these are server_name and logger.
-When logs are sent to sentry these fields are treated differently.
-- server_name (also known as hostname) is the name of the server which
-is logging the event (hostname.example.com)
-- logger is the part of the application which is logging the event.
-In go this usually means setting it to the name of the package.
-
-## Timeout
-
-`Timeout` is the time the sentry hook will wait for a response
-from the sentry server.
-
-If this time elapses with no response from
-the server an error will be returned.
-
-If `Timeout` is set to 0 the SentryHook will not wait for a reply
-and will assume a correct delivery.
-
-The SentryHook has a default timeout of `100 milliseconds` when created
-with a call to `NewSentryHook`. This can be changed by assigning a value to the `Timeout` field:
-
-```go
-hook, _ := logrus_sentry.NewSentryHook(...)
-hook.Timeout = 20*time.Second
-```
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/hooks/sentry/sentry.go b/containerd/vendor/github.com/Sirupsen/logrus/hooks/sentry/sentry.go
deleted file mode 100644
index 379f281..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/hooks/sentry/sentry.go
+++ /dev/null
@@ -1,100 +0,0 @@
-package logrus_sentry
-
-import (
- "fmt"
- "time"
-
- "github.com/Sirupsen/logrus"
- "github.com/getsentry/raven-go"
-)
-
-var (
- severityMap = map[logrus.Level]raven.Severity{
- logrus.DebugLevel: raven.DEBUG,
- logrus.InfoLevel: raven.INFO,
- logrus.WarnLevel: raven.WARNING,
- logrus.ErrorLevel: raven.ERROR,
- logrus.FatalLevel: raven.FATAL,
- logrus.PanicLevel: raven.FATAL,
- }
-)
-
-func getAndDel(d logrus.Fields, key string) (string, bool) {
- var (
- ok bool
- v interface{}
- val string
- )
- if v, ok = d[key]; !ok {
- return "", false
- }
-
- if val, ok = v.(string); !ok {
- return "", false
- }
- delete(d, key)
- return val, true
-}
-
-// SentryHook delivers logs to a sentry server.
-type SentryHook struct {
- // Timeout sets the time to wait for a delivery error from the sentry server.
- // If this is set to zero the server will not wait for any response and will
- // consider the message correctly sent
- Timeout time.Duration
-
- client *raven.Client
- levels []logrus.Level
-}
-
-// NewSentryHook creates a hook to be added to an instance of logger
-// and initializes the raven client.
-// This method sets the timeout to 100 milliseconds.
-func NewSentryHook(DSN string, levels []logrus.Level) (*SentryHook, error) {
- client, err := raven.NewClient(DSN, nil)
- if err != nil {
- return nil, err
- }
- return &SentryHook{100 * time.Millisecond, client, levels}, nil
-}
-
-// Called when an event should be sent to sentry
-// Special fields that sentry uses to give more information to the server
-// are extracted from entry.Data (if they are found)
-// These fields are: logger and server_name
-func (hook *SentryHook) Fire(entry *logrus.Entry) error {
- packet := &raven.Packet{
- Message: entry.Message,
- Timestamp: raven.Timestamp(entry.Time),
- Level: severityMap[entry.Level],
- Platform: "go",
- }
-
- d := entry.Data
-
- if logger, ok := getAndDel(d, "logger"); ok {
- packet.Logger = logger
- }
- if serverName, ok := getAndDel(d, "server_name"); ok {
- packet.ServerName = serverName
- }
- packet.Extra = map[string]interface{}(d)
-
- _, errCh := hook.client.Capture(packet, nil)
- timeout := hook.Timeout
- if timeout != 0 {
- timeoutCh := time.After(timeout)
- select {
- case err := <-errCh:
- return err
- case <-timeoutCh:
- return fmt.Errorf("no response from sentry server in %s", timeout)
- }
- }
- return nil
-}
-
-// Levels returns the available logging levels.
-func (hook *SentryHook) Levels() []logrus.Level {
- return hook.levels
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/hooks/syslog/README.md b/containerd/vendor/github.com/Sirupsen/logrus/hooks/syslog/README.md
deleted file mode 100644
index 4dbb8e7..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/hooks/syslog/README.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# Syslog Hooks for Logrus
-
-## Usage
-
-```go
-import (
- "log/syslog"
- "github.com/Sirupsen/logrus"
- logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog"
-)
-
-func main() {
- log := logrus.New()
- hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
-
- if err == nil {
- log.Hooks.Add(hook)
- }
-}
-```
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/hooks/syslog/syslog.go b/containerd/vendor/github.com/Sirupsen/logrus/hooks/syslog/syslog.go
deleted file mode 100644
index b6fa374..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/hooks/syslog/syslog.go
+++ /dev/null
@@ -1,59 +0,0 @@
-package logrus_syslog
-
-import (
- "fmt"
- "github.com/Sirupsen/logrus"
- "log/syslog"
- "os"
-)
-
-// SyslogHook to send logs via syslog.
-type SyslogHook struct {
- Writer *syslog.Writer
- SyslogNetwork string
- SyslogRaddr string
-}
-
-// Creates a hook to be added to an instance of logger. This is called with
-// `hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_DEBUG, "")`
-// `if err == nil { log.Hooks.Add(hook) }`
-func NewSyslogHook(network, raddr string, priority syslog.Priority, tag string) (*SyslogHook, error) {
- w, err := syslog.Dial(network, raddr, priority, tag)
- return &SyslogHook{w, network, raddr}, err
-}
-
-func (hook *SyslogHook) Fire(entry *logrus.Entry) error {
- line, err := entry.String()
- if err != nil {
- fmt.Fprintf(os.Stderr, "Unable to read entry, %v", err)
- return err
- }
-
- switch entry.Level {
- case logrus.PanicLevel:
- return hook.Writer.Crit(line)
- case logrus.FatalLevel:
- return hook.Writer.Crit(line)
- case logrus.ErrorLevel:
- return hook.Writer.Err(line)
- case logrus.WarnLevel:
- return hook.Writer.Warning(line)
- case logrus.InfoLevel:
- return hook.Writer.Info(line)
- case logrus.DebugLevel:
- return hook.Writer.Debug(line)
- default:
- return nil
- }
-}
-
-func (hook *SyslogHook) Levels() []logrus.Level {
- return []logrus.Level{
- logrus.PanicLevel,
- logrus.FatalLevel,
- logrus.ErrorLevel,
- logrus.WarnLevel,
- logrus.InfoLevel,
- logrus.DebugLevel,
- }
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/json_formatter.go b/containerd/vendor/github.com/Sirupsen/logrus/json_formatter.go
deleted file mode 100644
index dcc4f1d..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/json_formatter.go
+++ /dev/null
@@ -1,40 +0,0 @@
-package logrus
-
-import (
- "encoding/json"
- "fmt"
-)
-
-type JSONFormatter struct {
- // TimestampFormat sets the format used for marshaling timestamps.
- TimestampFormat string
-}
-
-func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
- data := make(Fields, len(entry.Data)+3)
- for k, v := range entry.Data {
- switch v := v.(type) {
- case error:
- // Otherwise errors are ignored by `encoding/json`
- // https://github.com/Sirupsen/logrus/issues/137
- data[k] = v.Error()
- default:
- data[k] = v
- }
- }
- prefixFieldClashes(data)
-
- if f.TimestampFormat == "" {
- f.TimestampFormat = DefaultTimestampFormat
- }
-
- data["time"] = entry.Time.Format(f.TimestampFormat)
- data["msg"] = entry.Message
- data["level"] = entry.Level.String()
-
- serialized, err := json.Marshal(data)
- if err != nil {
- return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
- }
- return append(serialized, '\n'), nil
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/logger.go b/containerd/vendor/github.com/Sirupsen/logrus/logger.go
deleted file mode 100644
index da928a3..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/logger.go
+++ /dev/null
@@ -1,203 +0,0 @@
-package logrus
-
-import (
- "io"
- "os"
- "sync"
-)
-
-type Logger struct {
- // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
- // file, or leave it default which is `os.Stdout`. You can also set this to
- // something more adventorous, such as logging to Kafka.
- Out io.Writer
- // Hooks for the logger instance. These allow firing events based on logging
- // levels and log entries. For example, to send errors to an error tracking
- // service, log to StatsD or dump the core on fatal errors.
- Hooks levelHooks
- // All log entries pass through the formatter before logged to Out. The
- // included formatters are `TextFormatter` and `JSONFormatter` for which
- // TextFormatter is the default. In development (when a TTY is attached) it
- // logs with colors, but to a file it wouldn't. You can easily implement your
- // own that implements the `Formatter` interface, see the `README` or included
- // formatters for examples.
- Formatter Formatter
- // The logging level the logger should log at. This is typically (and defaults
- // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
- // logged. `logrus.Debug` is useful in
- Level Level
- // Used to sync writing to the log.
- mu sync.Mutex
-}
-
-// Creates a new logger. Configuration should be set by changing `Formatter`,
-// `Out` and `Hooks` directly on the default logger instance. You can also just
-// instantiate your own:
-//
-// var log = &Logger{
-// Out: os.Stderr,
-// Formatter: new(JSONFormatter),
-// Hooks: make(levelHooks),
-// Level: logrus.DebugLevel,
-// }
-//
-// It's recommended to make this a global instance called `log`.
-func New() *Logger {
- return &Logger{
- Out: os.Stdout,
- Formatter: new(TextFormatter),
- Hooks: make(levelHooks),
- Level: InfoLevel,
- }
-}
-
-// Adds a field to the log entry, note that you it doesn't log until you call
-// Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry.
-// Ff you want multiple fields, use `WithFields`.
-func (logger *Logger) WithField(key string, value interface{}) *Entry {
- return NewEntry(logger).WithField(key, value)
-}
-
-// Adds a struct of fields to the log entry. All it does is call `WithField` for
-// each `Field`.
-func (logger *Logger) WithFields(fields Fields) *Entry {
- return NewEntry(logger).WithFields(fields)
-}
-
-func (logger *Logger) Debugf(format string, args ...interface{}) {
- if logger.Level >= DebugLevel {
- NewEntry(logger).Debugf(format, args...)
- }
-}
-
-func (logger *Logger) Infof(format string, args ...interface{}) {
- if logger.Level >= InfoLevel {
- NewEntry(logger).Infof(format, args...)
- }
-}
-
-func (logger *Logger) Printf(format string, args ...interface{}) {
- NewEntry(logger).Printf(format, args...)
-}
-
-func (logger *Logger) Warnf(format string, args ...interface{}) {
- if logger.Level >= WarnLevel {
- NewEntry(logger).Warnf(format, args...)
- }
-}
-
-func (logger *Logger) Warningf(format string, args ...interface{}) {
- if logger.Level >= WarnLevel {
- NewEntry(logger).Warnf(format, args...)
- }
-}
-
-func (logger *Logger) Errorf(format string, args ...interface{}) {
- if logger.Level >= ErrorLevel {
- NewEntry(logger).Errorf(format, args...)
- }
-}
-
-func (logger *Logger) Fatalf(format string, args ...interface{}) {
- if logger.Level >= FatalLevel {
- NewEntry(logger).Fatalf(format, args...)
- }
-}
-
-func (logger *Logger) Panicf(format string, args ...interface{}) {
- if logger.Level >= PanicLevel {
- NewEntry(logger).Panicf(format, args...)
- }
-}
-
-func (logger *Logger) Debug(args ...interface{}) {
- if logger.Level >= DebugLevel {
- NewEntry(logger).Debug(args...)
- }
-}
-
-func (logger *Logger) Info(args ...interface{}) {
- if logger.Level >= InfoLevel {
- NewEntry(logger).Info(args...)
- }
-}
-
-func (logger *Logger) Print(args ...interface{}) {
- NewEntry(logger).Info(args...)
-}
-
-func (logger *Logger) Warn(args ...interface{}) {
- if logger.Level >= WarnLevel {
- NewEntry(logger).Warn(args...)
- }
-}
-
-func (logger *Logger) Warning(args ...interface{}) {
- if logger.Level >= WarnLevel {
- NewEntry(logger).Warn(args...)
- }
-}
-
-func (logger *Logger) Error(args ...interface{}) {
- if logger.Level >= ErrorLevel {
- NewEntry(logger).Error(args...)
- }
-}
-
-func (logger *Logger) Fatal(args ...interface{}) {
- if logger.Level >= FatalLevel {
- NewEntry(logger).Fatal(args...)
- }
-}
-
-func (logger *Logger) Panic(args ...interface{}) {
- if logger.Level >= PanicLevel {
- NewEntry(logger).Panic(args...)
- }
-}
-
-func (logger *Logger) Debugln(args ...interface{}) {
- if logger.Level >= DebugLevel {
- NewEntry(logger).Debugln(args...)
- }
-}
-
-func (logger *Logger) Infoln(args ...interface{}) {
- if logger.Level >= InfoLevel {
- NewEntry(logger).Infoln(args...)
- }
-}
-
-func (logger *Logger) Println(args ...interface{}) {
- NewEntry(logger).Println(args...)
-}
-
-func (logger *Logger) Warnln(args ...interface{}) {
- if logger.Level >= WarnLevel {
- NewEntry(logger).Warnln(args...)
- }
-}
-
-func (logger *Logger) Warningln(args ...interface{}) {
- if logger.Level >= WarnLevel {
- NewEntry(logger).Warnln(args...)
- }
-}
-
-func (logger *Logger) Errorln(args ...interface{}) {
- if logger.Level >= ErrorLevel {
- NewEntry(logger).Errorln(args...)
- }
-}
-
-func (logger *Logger) Fatalln(args ...interface{}) {
- if logger.Level >= FatalLevel {
- NewEntry(logger).Fatalln(args...)
- }
-}
-
-func (logger *Logger) Panicln(args ...interface{}) {
- if logger.Level >= PanicLevel {
- NewEntry(logger).Panicln(args...)
- }
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/logrus.go b/containerd/vendor/github.com/Sirupsen/logrus/logrus.go
deleted file mode 100644
index 43ee12e..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/logrus.go
+++ /dev/null
@@ -1,94 +0,0 @@
-package logrus
-
-import (
- "fmt"
- "log"
-)
-
-// Fields type, used to pass to `WithFields`.
-type Fields map[string]interface{}
-
-// Level type
-type Level uint8
-
-// Convert the Level to a string. E.g. PanicLevel becomes "panic".
-func (level Level) String() string {
- switch level {
- case DebugLevel:
- return "debug"
- case InfoLevel:
- return "info"
- case WarnLevel:
- return "warning"
- case ErrorLevel:
- return "error"
- case FatalLevel:
- return "fatal"
- case PanicLevel:
- return "panic"
- }
-
- return "unknown"
-}
-
-// ParseLevel takes a string level and returns the Logrus log level constant.
-func ParseLevel(lvl string) (Level, error) {
- switch lvl {
- case "panic":
- return PanicLevel, nil
- case "fatal":
- return FatalLevel, nil
- case "error":
- return ErrorLevel, nil
- case "warn", "warning":
- return WarnLevel, nil
- case "info":
- return InfoLevel, nil
- case "debug":
- return DebugLevel, nil
- }
-
- var l Level
- return l, fmt.Errorf("not a valid logrus Level: %q", lvl)
-}
-
-// These are the different logging levels. You can set the logging level to log
-// on your instance of logger, obtained with `logrus.New()`.
-const (
- // PanicLevel level, highest level of severity. Logs and then calls panic with the
- // message passed to Debug, Info, ...
- PanicLevel Level = iota
- // FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the
- // logging level is set to Panic.
- FatalLevel
- // ErrorLevel level. Logs. Used for errors that should definitely be noted.
- // Commonly used for hooks to send errors to an error tracking service.
- ErrorLevel
- // WarnLevel level. Non-critical entries that deserve eyes.
- WarnLevel
- // InfoLevel level. General operational entries about what's going on inside the
- // application.
- InfoLevel
- // DebugLevel level. Usually only enabled when debugging. Very verbose logging.
- DebugLevel
-)
-
-// Won't compile if StdLogger can't be realized by a log.Logger
-var _ StdLogger = &log.Logger{}
-
-// StdLogger is what your logrus-enabled library should take, that way
-// it'll accept a stdlib logger and a logrus logger. There's no standard
-// interface, this is the closest we get, unfortunately.
-type StdLogger interface {
- Print(...interface{})
- Printf(string, ...interface{})
- Println(...interface{})
-
- Fatal(...interface{})
- Fatalf(string, ...interface{})
- Fatalln(...interface{})
-
- Panic(...interface{})
- Panicf(string, ...interface{})
- Panicln(...interface{})
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/terminal_darwin.go b/containerd/vendor/github.com/Sirupsen/logrus/terminal_darwin.go
deleted file mode 100644
index 8fe02a4..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/terminal_darwin.go
+++ /dev/null
@@ -1,12 +0,0 @@
-// Based on ssh/terminal:
-// Copyright 2013 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package logrus
-
-import "syscall"
-
-const ioctlReadTermios = syscall.TIOCGETA
-
-type Termios syscall.Termios
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/terminal_freebsd.go b/containerd/vendor/github.com/Sirupsen/logrus/terminal_freebsd.go
deleted file mode 100644
index 0428ee5..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/terminal_freebsd.go
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- Go 1.2 doesn't include Termios for FreeBSD. This should be added in 1.3 and this could be merged with terminal_darwin.
-*/
-package logrus
-
-import (
- "syscall"
-)
-
-const ioctlReadTermios = syscall.TIOCGETA
-
-type Termios struct {
- Iflag uint32
- Oflag uint32
- Cflag uint32
- Lflag uint32
- Cc [20]uint8
- Ispeed uint32
- Ospeed uint32
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/terminal_linux.go b/containerd/vendor/github.com/Sirupsen/logrus/terminal_linux.go
deleted file mode 100644
index a2c0b40..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/terminal_linux.go
+++ /dev/null
@@ -1,12 +0,0 @@
-// Based on ssh/terminal:
-// Copyright 2013 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package logrus
-
-import "syscall"
-
-const ioctlReadTermios = syscall.TCGETS
-
-type Termios syscall.Termios
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go b/containerd/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go
deleted file mode 100644
index b8bebc1..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go
+++ /dev/null
@@ -1,21 +0,0 @@
-// Based on ssh/terminal:
-// Copyright 2011 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build linux darwin freebsd openbsd
-
-package logrus
-
-import (
- "syscall"
- "unsafe"
-)
-
-// IsTerminal returns true if the given file descriptor is a terminal.
-func IsTerminal() bool {
- fd := syscall.Stdout
- var termios Termios
- _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
- return err == 0
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/terminal_openbsd.go b/containerd/vendor/github.com/Sirupsen/logrus/terminal_openbsd.go
deleted file mode 100644
index af609a5..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/terminal_openbsd.go
+++ /dev/null
@@ -1,7 +0,0 @@
-package logrus
-
-import "syscall"
-
-const ioctlReadTermios = syscall.TIOCGETA
-
-type Termios syscall.Termios
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/terminal_windows.go b/containerd/vendor/github.com/Sirupsen/logrus/terminal_windows.go
deleted file mode 100644
index 2e09f6f..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/terminal_windows.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Based on ssh/terminal:
-// Copyright 2011 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build windows
-
-package logrus
-
-import (
- "syscall"
- "unsafe"
-)
-
-var kernel32 = syscall.NewLazyDLL("kernel32.dll")
-
-var (
- procGetConsoleMode = kernel32.NewProc("GetConsoleMode")
-)
-
-// IsTerminal returns true if the given file descriptor is a terminal.
-func IsTerminal() bool {
- fd := syscall.Stdout
- var st uint32
- r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0)
- return r != 0 && e == 0
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/text_formatter.go b/containerd/vendor/github.com/Sirupsen/logrus/text_formatter.go
deleted file mode 100644
index 612417f..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/text_formatter.go
+++ /dev/null
@@ -1,149 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "fmt"
- "sort"
- "strings"
- "time"
-)
-
-const (
- nocolor = 0
- red = 31
- green = 32
- yellow = 33
- blue = 34
- gray = 37
-)
-
-var (
- baseTimestamp time.Time
- isTerminal bool
-)
-
-func init() {
- baseTimestamp = time.Now()
- isTerminal = IsTerminal()
-}
-
-func miniTS() int {
- return int(time.Since(baseTimestamp) / time.Second)
-}
-
-type TextFormatter struct {
- // Set to true to bypass checking for a TTY before outputting colors.
- ForceColors bool
-
- // Force disabling colors.
- DisableColors bool
-
- // Disable timestamp logging. useful when output is redirected to logging
- // system that already adds timestamps.
- DisableTimestamp bool
-
- // Enable logging the full timestamp when a TTY is attached instead of just
- // the time passed since beginning of execution.
- FullTimestamp bool
-
- // TimestampFormat to use for display when a full timestamp is printed
- TimestampFormat string
-
- // The fields are sorted by default for a consistent output. For applications
- // that log extremely frequently and don't use the JSON formatter this may not
- // be desired.
- DisableSorting bool
-}
-
-func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
- var keys []string = make([]string, 0, len(entry.Data))
- for k := range entry.Data {
- keys = append(keys, k)
- }
-
- if !f.DisableSorting {
- sort.Strings(keys)
- }
-
- b := &bytes.Buffer{}
-
- prefixFieldClashes(entry.Data)
-
- isColored := (f.ForceColors || isTerminal) && !f.DisableColors
-
- if f.TimestampFormat == "" {
- f.TimestampFormat = DefaultTimestampFormat
- }
- if isColored {
- f.printColored(b, entry, keys)
- } else {
- if !f.DisableTimestamp {
- f.appendKeyValue(b, "time", entry.Time.Format(f.TimestampFormat))
- }
- f.appendKeyValue(b, "level", entry.Level.String())
- f.appendKeyValue(b, "msg", entry.Message)
- for _, key := range keys {
- f.appendKeyValue(b, key, entry.Data[key])
- }
- }
-
- b.WriteByte('\n')
- return b.Bytes(), nil
-}
-
-func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string) {
- var levelColor int
- switch entry.Level {
- case DebugLevel:
- levelColor = gray
- case WarnLevel:
- levelColor = yellow
- case ErrorLevel, FatalLevel, PanicLevel:
- levelColor = red
- default:
- levelColor = blue
- }
-
- levelText := strings.ToUpper(entry.Level.String())[0:4]
-
- if !f.FullTimestamp {
- fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, miniTS(), entry.Message)
- } else {
- fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(f.TimestampFormat), entry.Message)
- }
- for _, k := range keys {
- v := entry.Data[k]
- fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=%v", levelColor, k, v)
- }
-}
-
-func needsQuoting(text string) bool {
- for _, ch := range text {
- if !((ch >= 'a' && ch <= 'z') ||
- (ch >= 'A' && ch <= 'Z') ||
- (ch >= '0' && ch <= '9') ||
- ch == '-' || ch == '.') {
- return false
- }
- }
- return true
-}
-
-func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key, value interface{}) {
- switch value.(type) {
- case string:
- if needsQuoting(value.(string)) {
- fmt.Fprintf(b, "%v=%s ", key, value)
- } else {
- fmt.Fprintf(b, "%v=%q ", key, value)
- }
- case error:
- if needsQuoting(value.(error).Error()) {
- fmt.Fprintf(b, "%v=%s ", key, value)
- } else {
- fmt.Fprintf(b, "%v=%q ", key, value)
- }
- default:
- fmt.Fprintf(b, "%v=%v ", key, value)
- }
-}
diff --git a/containerd/vendor/github.com/Sirupsen/logrus/writer.go b/containerd/vendor/github.com/Sirupsen/logrus/writer.go
deleted file mode 100644
index 1e30b1c..0000000
--- a/containerd/vendor/github.com/Sirupsen/logrus/writer.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package logrus
-
-import (
- "bufio"
- "io"
- "runtime"
-)
-
-func (logger *Logger) Writer() *io.PipeWriter {
- reader, writer := io.Pipe()
-
- go logger.writerScanner(reader)
- runtime.SetFinalizer(writer, writerFinalizer)
-
- return writer
-}
-
-func (logger *Logger) writerScanner(reader *io.PipeReader) {
- scanner := bufio.NewScanner(reader)
- for scanner.Scan() {
- logger.Print(scanner.Text())
- }
- if err := scanner.Err(); err != nil {
- logger.Errorf("Error while reading from Writer: %s", err)
- }
- reader.Close()
-}
-
-func writerFinalizer(writer *io.PipeWriter) {
- writer.Close()
-}
diff --git a/containerd/vendor/github.com/codegangsta/cli/.travis.yml b/containerd/vendor/github.com/codegangsta/cli/.travis.yml
deleted file mode 100644
index baf46ab..0000000
--- a/containerd/vendor/github.com/codegangsta/cli/.travis.yml
+++ /dev/null
@@ -1,6 +0,0 @@
-language: go
-go: 1.1
-
-script:
-- go vet ./...
-- go test -v ./...
diff --git a/containerd/vendor/github.com/codegangsta/cli/LICENSE b/containerd/vendor/github.com/codegangsta/cli/LICENSE
deleted file mode 100644
index 5515ccf..0000000
--- a/containerd/vendor/github.com/codegangsta/cli/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-Copyright (C) 2013 Jeremy Saenz
-All Rights Reserved.
-
-MIT LICENSE
-
-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/containerd/vendor/github.com/codegangsta/cli/README.md b/containerd/vendor/github.com/codegangsta/cli/README.md
deleted file mode 100644
index cd980fd..0000000
--- a/containerd/vendor/github.com/codegangsta/cli/README.md
+++ /dev/null
@@ -1,306 +0,0 @@
-[![Build Status](https://travis-ci.org/codegangsta/cli.png?branch=master)](https://travis-ci.org/codegangsta/cli)
-
-# cli.go
-cli.go is 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.
-
-You can view the API docs here:
-http://godoc.org/github.com/codegangsta/cli
-
-## 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.go comes into play.** cli.go makes command line programming fun, organized, and expressive!
-
-## Installation
-Make sure you have a working Go environment (go 1.1+ is *required*). [See the install instructions](http://golang.org/doc/install.html).
-
-To install `cli.go`, simply run:
-```
-$ go get github.com/codegangsta/cli
-```
-
-Make sure your `PATH` includes to the `$GOPATH/bin` directory so your commands can be easily used:
-```
-export PATH=$PATH:$GOPATH/bin
-```
-
-## Getting Started
-One of the philosophies behind cli.go is that an API should be playful and full of discovery. So a cli.go app can be as little as one line of code in `main()`.
-
-``` go
-package main
-
-import (
- "os"
- "github.com/codegangsta/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 (
- "os"
- "github.com/codegangsta/cli"
-)
-
-func main() {
- app := cli.NewApp()
- app.Name = "boom"
- app.Usage = "make an explosive entrance"
- app.Action = func(c *cli.Context) {
- println("boom! I say!")
- }
-
- 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.
-
-## Example
-
-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 (
- "os"
- "github.com/codegangsta/cli"
-)
-
-func main() {
- app := cli.NewApp()
- app.Name = "greet"
- app.Usage = "fight the loneliness!"
- app.Action = func(c *cli.Context) {
- println("Hello friend!")
- }
-
- app.Run(os.Args)
-}
-```
-
-Install our command to the `$GOPATH/bin` directory:
-
-```
-$ go install
-```
-
-Finally run our new command:
-
-```
-$ greet
-Hello friend!
-```
-
-cli.go also generates some bitchass 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`.
-
-``` go
-...
-app.Action = func(c *cli.Context) {
- println("Hello", c.Args()[0])
-}
-...
-```
-
-### Flags
-Setting and querying flags is simple.
-``` go
-...
-app.Flags = []cli.Flag {
- cli.StringFlag{
- Name: "lang",
- Value: "english",
- Usage: "language for the greeting",
- },
-}
-app.Action = func(c *cli.Context) {
- name := "someone"
- if len(c.Args()) > 0 {
- name = c.Args()[0]
- }
- if c.String("lang") == "spanish" {
- println("Hola", name)
- } else {
- println("Hello", name)
- }
-}
-...
-```
-
-#### Alternate Names
-
-You can set alternate (or short) names for flags by providing a comma-delimited list for the `Name`. e.g.
-
-``` go
-app.Flags = []cli.Flag {
- cli.StringFlag{
- Name: "lang, l",
- Value: "english",
- Usage: "language for the greeting",
- },
-}
-```
-
-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.
-
-#### Values from the Environment
-
-You can also have the default value set from the environment via `EnvVar`. e.g.
-
-``` go
-app.Flags = []cli.Flag {
- cli.StringFlag{
- Name: "lang, l",
- Value: "english",
- Usage: "language for the greeting",
- EnvVar: "APP_LANG",
- },
-}
-```
-
-The `EnvVar` may also be given as a comma-delimited "cascade", where the first environment variable that resolves is used as the default.
-
-``` go
-app.Flags = []cli.Flag {
- cli.StringFlag{
- Name: "lang, l",
- Value: "english",
- Usage: "language for the greeting",
- EnvVar: "LEGACY_COMPAT_LANG,APP_LANG,LANG",
- },
-}
-```
-
-### Subcommands
-
-Subcommands can be defined for a more git-like command line app.
-```go
-...
-app.Commands = []cli.Command{
- {
- Name: "add",
- Aliases: []string{"a"},
- Usage: "add a task to the list",
- Action: func(c *cli.Context) {
- println("added task: ", c.Args().First())
- },
- },
- {
- Name: "complete",
- Aliases: []string{"c"},
- Usage: "complete a task on the list",
- Action: func(c *cli.Context) {
- println("completed task: ", c.Args().First())
- },
- },
- {
- Name: "template",
- Aliases: []string{"r"},
- Usage: "options for task templates",
- Subcommands: []cli.Command{
- {
- Name: "add",
- Usage: "add a new template",
- Action: func(c *cli.Context) {
- println("new task template: ", c.Args().First())
- },
- },
- {
- Name: "remove",
- Usage: "remove an existing template",
- Action: func(c *cli.Context) {
- println("removed task template: ", c.Args().First())
- },
- },
- },
- },
-}
-...
-```
-
-### 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
-...
-var 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) {
- println("completed task: ", c.Args().First())
- },
- BashComplete: func(c *cli.Context) {
- // This will complete if no args are passed
- if len(c.Args()) > 0 {
- return
- }
- for _, t := range tasks {
- fmt.Println(t)
- }
- },
- }
-}
-...
-```
-
-#### To Enable
-
-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`
-
-#### To Distribute
-
-Copy and modify `autocomplete/bash_autocomplete` to use your program name
-rather than `$PROG` and have the user copy the file into
-`/etc/bash_completion.d/` (or automatically install it there if you are
-distributing a package). Alternatively you can just document that users should
-source the generic `autocomplete/bash_autocomplete` with `$PROG` set to your
-program name in their bash configuration.
-
-## 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, I 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 have any questions feel free to link @codegangsta to the issue in question and we can review it together.
-
-If you feel like you have contributed to the project but have not yet been added as a collaborator, I probably forgot to add you. Hit @codegangsta up over email and we will get it figured out.
diff --git a/containerd/vendor/github.com/codegangsta/cli/app.go b/containerd/vendor/github.com/codegangsta/cli/app.go
deleted file mode 100644
index 891416d..0000000
--- a/containerd/vendor/github.com/codegangsta/cli/app.go
+++ /dev/null
@@ -1,298 +0,0 @@
-package cli
-
-import (
- "fmt"
- "io"
- "io/ioutil"
- "os"
- "time"
-)
-
-// App is the main structure of a cli application. It is recomended that
-// and app be created with the cli.NewApp() function
-type App struct {
- // The name of the program. Defaults to os.Args[0]
- Name string
- // Description of the program.
- Usage string
- // Version of the program
- Version string
- // List of commands to execute
- Commands []Command
- // List of flags to parse
- Flags []Flag
- // Boolean to enable bash completion commands
- EnableBashCompletion bool
- // Boolean to hide built-in help command
- HideHelp bool
- // Boolean to hide built-in version flag
- HideVersion bool
- // An action to execute when the bash-completion flag is set
- BashComplete func(context *Context)
- // An action to execute before any subcommands are run, but after the context is ready
- // If a non-nil error is returned, no subcommands are run
- Before func(context *Context) error
- // An action to execute after any subcommands are run, but after the subcommand has finished
- // It is run even if Action() panics
- After func(context *Context) error
- // The action to execute when no subcommands are specified
- Action func(context *Context)
- // Execute this function if the proper command cannot be found
- CommandNotFound func(context *Context, command string)
- // Compilation date
- Compiled time.Time
- // List of all authors who contributed
- Authors []Author
- // Name of Author (Note: Use App.Authors, this is deprecated)
- Author string
- // Email of Author (Note: Use App.Authors, this is deprecated)
- Email string
- // Writer writer to write output to
- Writer io.Writer
-}
-
-// Tries to find out when this binary was compiled.
-// Returns the current time if it fails to find it.
-func compileTime() time.Time {
- info, err := os.Stat(os.Args[0])
- if err != nil {
- return time.Now()
- }
- return info.ModTime()
-}
-
-// Creates a new cli Application with some reasonable defaults for Name, Usage, Version and Action.
-func NewApp() *App {
- return &App{
- Name: os.Args[0],
- Usage: "A new cli application",
- Version: "0.0.0",
- BashComplete: DefaultAppComplete,
- Action: helpCommand.Action,
- Compiled: compileTime(),
- Writer: os.Stdout,
- }
-}
-
-// Entry point to the cli app. Parses the arguments slice and routes to the proper flag/args combination
-func (a *App) Run(arguments []string) (err error) {
- if a.Author != "" || a.Email != "" {
- a.Authors = append(a.Authors, Author{Name: a.Author, Email: a.Email})
- }
-
- // append help to commands
- if a.Command(helpCommand.Name) == nil && !a.HideHelp {
- a.Commands = append(a.Commands, helpCommand)
- if (HelpFlag != BoolFlag{}) {
- a.appendFlag(HelpFlag)
- }
- }
-
- //append version/help flags
- if a.EnableBashCompletion {
- a.appendFlag(BashCompletionFlag)
- }
-
- if !a.HideVersion {
- a.appendFlag(VersionFlag)
- }
-
- // parse flags
- set := flagSet(a.Name, a.Flags)
- set.SetOutput(ioutil.Discard)
- err = set.Parse(arguments[1:])
- nerr := normalizeFlags(a.Flags, set)
- if nerr != nil {
- fmt.Fprintln(a.Writer, nerr)
- context := NewContext(a, set, set)
- ShowAppHelp(context)
- fmt.Fprintln(a.Writer)
- return nerr
- }
- context := NewContext(a, set, set)
-
- if err != nil {
- fmt.Fprintf(a.Writer, "Incorrect Usage.\n\n")
- ShowAppHelp(context)
- fmt.Fprintln(a.Writer)
- return err
- }
-
- if checkCompletions(context) {
- return nil
- }
-
- if checkHelp(context) {
- return nil
- }
-
- if checkVersion(context) {
- return nil
- }
-
- if a.After != nil {
- defer func() {
- // err is always nil here.
- // There is a check to see if it is non-nil
- // just few lines before.
- err = a.After(context)
- }()
- }
-
- if a.Before != nil {
- err := a.Before(context)
- if err != nil {
- return err
- }
- }
-
- args := context.Args()
- if args.Present() {
- name := args.First()
- c := a.Command(name)
- if c != nil {
- return c.Run(context)
- }
- }
-
- // Run default Action
- a.Action(context)
- return nil
-}
-
-// Another entry point to the cli app, takes care of passing arguments and error handling
-func (a *App) RunAndExitOnError() {
- if err := a.Run(os.Args); err != nil {
- fmt.Fprintln(os.Stderr, err)
- os.Exit(1)
- }
-}
-
-// Invokes the subcommand given the context, parses ctx.Args() to generate command-specific flags
-func (a *App) RunAsSubcommand(ctx *Context) (err error) {
- // append help to commands
- if len(a.Commands) > 0 {
- if a.Command(helpCommand.Name) == nil && !a.HideHelp {
- a.Commands = append(a.Commands, helpCommand)
- if (HelpFlag != BoolFlag{}) {
- a.appendFlag(HelpFlag)
- }
- }
- }
-
- // append flags
- if a.EnableBashCompletion {
- a.appendFlag(BashCompletionFlag)
- }
-
- // parse flags
- set := flagSet(a.Name, a.Flags)
- set.SetOutput(ioutil.Discard)
- err = set.Parse(ctx.Args().Tail())
- nerr := normalizeFlags(a.Flags, set)
- context := NewContext(a, set, ctx.globalSet)
-
- if nerr != nil {
- fmt.Fprintln(a.Writer, nerr)
- if len(a.Commands) > 0 {
- ShowSubcommandHelp(context)
- } else {
- ShowCommandHelp(ctx, context.Args().First())
- }
- fmt.Fprintln(a.Writer)
- return nerr
- }
-
- if err != nil {
- fmt.Fprintf(a.Writer, "Incorrect Usage.\n\n")
- ShowSubcommandHelp(context)
- return err
- }
-
- if checkCompletions(context) {
- return nil
- }
-
- if len(a.Commands) > 0 {
- if checkSubcommandHelp(context) {
- return nil
- }
- } else {
- if checkCommandHelp(ctx, context.Args().First()) {
- return nil
- }
- }
-
- if a.After != nil {
- defer func() {
- // err is always nil here.
- // There is a check to see if it is non-nil
- // just few lines before.
- err = a.After(context)
- }()
- }
-
- if a.Before != nil {
- err := a.Before(context)
- if err != nil {
- return err
- }
- }
-
- args := context.Args()
- if args.Present() {
- name := args.First()
- c := a.Command(name)
- if c != nil {
- return c.Run(context)
- }
- }
-
- // Run default Action
- a.Action(context)
-
- return nil
-}
-
-// Returns the named command on App. Returns nil if the command does not exist
-func (a *App) Command(name string) *Command {
- for _, c := range a.Commands {
- if c.HasName(name) {
- return &c
- }
- }
-
- return nil
-}
-
-func (a *App) hasFlag(flag Flag) bool {
- for _, f := range a.Flags {
- if flag == f {
- return true
- }
- }
-
- return false
-}
-
-func (a *App) appendFlag(flag Flag) {
- if !a.hasFlag(flag) {
- a.Flags = append(a.Flags, flag)
- }
-}
-
-// Author represents someone who has contributed to a cli project.
-type Author struct {
- Name string // The Authors name
- Email string // The Authors email
-}
-
-// String makes Author comply to the Stringer interface, to allow an easy print in the templating process
-func (a Author) String() string {
- e := ""
- if a.Email != "" {
- e = "<" + a.Email + "> "
- }
-
- return fmt.Sprintf("%v %v", a.Name, e)
-}
diff --git a/containerd/vendor/github.com/codegangsta/cli/autocomplete/bash_autocomplete b/containerd/vendor/github.com/codegangsta/cli/autocomplete/bash_autocomplete
deleted file mode 100644
index 9b55dd9..0000000
--- a/containerd/vendor/github.com/codegangsta/cli/autocomplete/bash_autocomplete
+++ /dev/null
@@ -1,13 +0,0 @@
-#! /bin/bash
-
-_cli_bash_autocomplete() {
- local cur prev opts base
- COMPREPLY=()
- cur="${COMP_WORDS[COMP_CWORD]}"
- prev="${COMP_WORDS[COMP_CWORD-1]}"
- opts=$( ${COMP_WORDS[@]:0:$COMP_CWORD} --generate-bash-completion )
- COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
- return 0
- }
-
- complete -F _cli_bash_autocomplete $PROG
\ No newline at end of file
diff --git a/containerd/vendor/github.com/codegangsta/cli/autocomplete/zsh_autocomplete b/containerd/vendor/github.com/codegangsta/cli/autocomplete/zsh_autocomplete
deleted file mode 100644
index 5430a18..0000000
--- a/containerd/vendor/github.com/codegangsta/cli/autocomplete/zsh_autocomplete
+++ /dev/null
@@ -1,5 +0,0 @@
-autoload -U compinit && compinit
-autoload -U bashcompinit && bashcompinit
-
-script_dir=$(dirname $0)
-source ${script_dir}/bash_autocomplete
diff --git a/containerd/vendor/github.com/codegangsta/cli/cli.go b/containerd/vendor/github.com/codegangsta/cli/cli.go
deleted file mode 100644
index b742545..0000000
--- a/containerd/vendor/github.com/codegangsta/cli/cli.go
+++ /dev/null
@@ -1,19 +0,0 @@
-// Package cli provides a minimal framework for creating and organizing command line
-// Go applications. cli is designed to be easy to understand and write, the most simple
-// cli application can be written as follows:
-// func main() {
-// cli.NewApp().Run(os.Args)
-// }
-//
-// Of course this application does not do much, so let's make this an actual application:
-// func main() {
-// app := cli.NewApp()
-// app.Name = "greet"
-// app.Usage = "say a greeting"
-// app.Action = func(c *cli.Context) {
-// println("Greetings")
-// }
-//
-// app.Run(os.Args)
-// }
-package cli
diff --git a/containerd/vendor/github.com/codegangsta/cli/command.go b/containerd/vendor/github.com/codegangsta/cli/command.go
deleted file mode 100644
index d0bbd0c..0000000
--- a/containerd/vendor/github.com/codegangsta/cli/command.go
+++ /dev/null
@@ -1,184 +0,0 @@
-package cli
-
-import (
- "fmt"
- "io/ioutil"
- "strings"
-)
-
-// Command is a subcommand for a cli.App.
-type Command struct {
- // The name of the command
- Name string
- // short name of the command. Typically one character (deprecated, use `Aliases`)
- ShortName string
- // A list of aliases for the command
- Aliases []string
- // A short description of the usage of this command
- Usage string
- // A longer explanation of how the command works
- Description string
- // The function to call when checking for bash command completions
- BashComplete func(context *Context)
- // An action to execute before any sub-subcommands are run, but after the context is ready
- // If a non-nil error is returned, no sub-subcommands are run
- Before func(context *Context) error
- // An action to execute after any subcommands are run, but after the subcommand has finished
- // It is run even if Action() panics
- After func(context *Context) error
- // The function to call when this command is invoked
- Action func(context *Context)
- // List of child commands
- Subcommands []Command
- // List of flags to parse
- Flags []Flag
- // Treat all flags as normal arguments if true
- SkipFlagParsing bool
- // Boolean to hide built-in help command
- HideHelp bool
-}
-
-// Invokes the command given the context, parses ctx.Args() to generate command-specific flags
-func (c Command) Run(ctx *Context) error {
-
- if len(c.Subcommands) > 0 || c.Before != nil || c.After != nil {
- return c.startApp(ctx)
- }
-
- if !c.HideHelp && (HelpFlag != BoolFlag{}) {
- // append help to flags
- c.Flags = append(
- c.Flags,
- HelpFlag,
- )
- }
-
- if ctx.App.EnableBashCompletion {
- c.Flags = append(c.Flags, BashCompletionFlag)
- }
-
- set := flagSet(c.Name, c.Flags)
- set.SetOutput(ioutil.Discard)
-
- firstFlagIndex := -1
- terminatorIndex := -1
- for index, arg := range ctx.Args() {
- if arg == "--" {
- terminatorIndex = index
- break
- } else if strings.HasPrefix(arg, "-") && firstFlagIndex == -1 {
- firstFlagIndex = index
- }
- }
-
- var err error
- if firstFlagIndex > -1 && !c.SkipFlagParsing {
- args := ctx.Args()
- regularArgs := make([]string, len(args[1:firstFlagIndex]))
- copy(regularArgs, args[1:firstFlagIndex])
-
- var flagArgs []string
- if terminatorIndex > -1 {
- flagArgs = args[firstFlagIndex:terminatorIndex]
- regularArgs = append(regularArgs, args[terminatorIndex:]...)
- } else {
- flagArgs = args[firstFlagIndex:]
- }
-
- err = set.Parse(append(flagArgs, regularArgs...))
- } else {
- err = set.Parse(ctx.Args().Tail())
- }
-
- if err != nil {
- fmt.Fprint(ctx.App.Writer, "Incorrect Usage.\n\n")
- ShowCommandHelp(ctx, c.Name)
- fmt.Fprintln(ctx.App.Writer)
- return err
- }
-
- nerr := normalizeFlags(c.Flags, set)
- if nerr != nil {
- fmt.Fprintln(ctx.App.Writer, nerr)
- fmt.Fprintln(ctx.App.Writer)
- ShowCommandHelp(ctx, c.Name)
- fmt.Fprintln(ctx.App.Writer)
- return nerr
- }
- context := NewContext(ctx.App, set, ctx.globalSet)
-
- if checkCommandCompletions(context, c.Name) {
- return nil
- }
-
- if checkCommandHelp(context, c.Name) {
- return nil
- }
- context.Command = c
- c.Action(context)
- return nil
-}
-
-func (c Command) Names() []string {
- names := []string{c.Name}
-
- if c.ShortName != "" {
- names = append(names, c.ShortName)
- }
-
- return append(names, c.Aliases...)
-}
-
-// Returns true if Command.Name or Command.ShortName matches given name
-func (c Command) HasName(name string) bool {
- for _, n := range c.Names() {
- if n == name {
- return true
- }
- }
- return false
-}
-
-func (c Command) startApp(ctx *Context) error {
- app := NewApp()
-
- // set the name and usage
- app.Name = fmt.Sprintf("%s %s", ctx.App.Name, c.Name)
- if c.Description != "" {
- app.Usage = c.Description
- } else {
- app.Usage = c.Usage
- }
-
- // set CommandNotFound
- app.CommandNotFound = ctx.App.CommandNotFound
-
- // set the flags and commands
- app.Commands = c.Subcommands
- app.Flags = c.Flags
- app.HideHelp = c.HideHelp
-
- app.Version = ctx.App.Version
- app.HideVersion = ctx.App.HideVersion
- app.Compiled = ctx.App.Compiled
- app.Author = ctx.App.Author
- app.Email = ctx.App.Email
- app.Writer = ctx.App.Writer
-
- // bash completion
- app.EnableBashCompletion = ctx.App.EnableBashCompletion
- if c.BashComplete != nil {
- app.BashComplete = c.BashComplete
- }
-
- // set the actions
- app.Before = c.Before
- app.After = c.After
- if c.Action != nil {
- app.Action = c.Action
- } else {
- app.Action = helpSubcommand.Action
- }
-
- return app.RunAsSubcommand(ctx)
-}
diff --git a/containerd/vendor/github.com/codegangsta/cli/context.go b/containerd/vendor/github.com/codegangsta/cli/context.go
deleted file mode 100644
index 37221bd..0000000
--- a/containerd/vendor/github.com/codegangsta/cli/context.go
+++ /dev/null
@@ -1,344 +0,0 @@
-package cli
-
-import (
- "errors"
- "flag"
- "strconv"
- "strings"
- "time"
-)
-
-// Context is a type that is passed through to
-// each Handler action in a cli application. Context
-// can be used to retrieve context-specific Args and
-// parsed command-line options.
-type Context struct {
- App *App
- Command Command
- flagSet *flag.FlagSet
- globalSet *flag.FlagSet
- setFlags map[string]bool
- globalSetFlags map[string]bool
-}
-
-// Creates a new context. For use in when invoking an App or Command action.
-func NewContext(app *App, set *flag.FlagSet, globalSet *flag.FlagSet) *Context {
- return &Context{App: app, flagSet: set, globalSet: globalSet}
-}
-
-// Looks up the value of a local int flag, returns 0 if no int flag exists
-func (c *Context) Int(name string) int {
- return lookupInt(name, c.flagSet)
-}
-
-// Looks up the value of a local time.Duration flag, returns 0 if no time.Duration flag exists
-func (c *Context) Duration(name string) time.Duration {
- return lookupDuration(name, c.flagSet)
-}
-
-// Looks up the value of a local float64 flag, returns 0 if no float64 flag exists
-func (c *Context) Float64(name string) float64 {
- return lookupFloat64(name, c.flagSet)
-}
-
-// Looks up the value of a local bool flag, returns false if no bool flag exists
-func (c *Context) Bool(name string) bool {
- return lookupBool(name, c.flagSet)
-}
-
-// Looks up the value of a local boolT flag, returns false if no bool flag exists
-func (c *Context) BoolT(name string) bool {
- return lookupBoolT(name, c.flagSet)
-}
-
-// Looks up the value of a local string flag, returns "" if no string flag exists
-func (c *Context) String(name string) string {
- return lookupString(name, c.flagSet)
-}
-
-// Looks up the value of a local string slice flag, returns nil if no string slice flag exists
-func (c *Context) StringSlice(name string) []string {
- return lookupStringSlice(name, c.flagSet)
-}
-
-// Looks up the value of a local int slice flag, returns nil if no int slice flag exists
-func (c *Context) IntSlice(name string) []int {
- return lookupIntSlice(name, c.flagSet)
-}
-
-// Looks up the value of a local generic flag, returns nil if no generic flag exists
-func (c *Context) Generic(name string) interface{} {
- return lookupGeneric(name, c.flagSet)
-}
-
-// Looks up the value of a global int flag, returns 0 if no int flag exists
-func (c *Context) GlobalInt(name string) int {
- return lookupInt(name, c.globalSet)
-}
-
-// Looks up the value of a global time.Duration flag, returns 0 if no time.Duration flag exists
-func (c *Context) GlobalDuration(name string) time.Duration {
- return lookupDuration(name, c.globalSet)
-}
-
-// Looks up the value of a global bool flag, returns false if no bool flag exists
-func (c *Context) GlobalBool(name string) bool {
- return lookupBool(name, c.globalSet)
-}
-
-// Looks up the value of a global string flag, returns "" if no string flag exists
-func (c *Context) GlobalString(name string) string {
- return lookupString(name, c.globalSet)
-}
-
-// Looks up the value of a global string slice flag, returns nil if no string slice flag exists
-func (c *Context) GlobalStringSlice(name string) []string {
- return lookupStringSlice(name, c.globalSet)
-}
-
-// Looks up the value of a global int slice flag, returns nil if no int slice flag exists
-func (c *Context) GlobalIntSlice(name string) []int {
- return lookupIntSlice(name, c.globalSet)
-}
-
-// Looks up the value of a global generic flag, returns nil if no generic flag exists
-func (c *Context) GlobalGeneric(name string) interface{} {
- return lookupGeneric(name, c.globalSet)
-}
-
-// Returns the number of flags set
-func (c *Context) NumFlags() int {
- return c.flagSet.NFlag()
-}
-
-// Determines if the flag was actually set
-func (c *Context) IsSet(name string) bool {
- if c.setFlags == nil {
- c.setFlags = make(map[string]bool)
- c.flagSet.Visit(func(f *flag.Flag) {
- c.setFlags[f.Name] = true
- })
- }
- return c.setFlags[name] == true
-}
-
-// Determines if the global flag was actually set
-func (c *Context) GlobalIsSet(name string) bool {
- if c.globalSetFlags == nil {
- c.globalSetFlags = make(map[string]bool)
- c.globalSet.Visit(func(f *flag.Flag) {
- c.globalSetFlags[f.Name] = true
- })
- }
- return c.globalSetFlags[name] == true
-}
-
-// Returns a slice of flag names used in this context.
-func (c *Context) FlagNames() (names []string) {
- for _, flag := range c.Command.Flags {
- name := strings.Split(flag.getName(), ",")[0]
- if name == "help" {
- continue
- }
- names = append(names, name)
- }
- return
-}
-
-// Returns a slice of global flag names used by the app.
-func (c *Context) GlobalFlagNames() (names []string) {
- for _, flag := range c.App.Flags {
- name := strings.Split(flag.getName(), ",")[0]
- if name == "help" || name == "version" {
- continue
- }
- names = append(names, name)
- }
- return
-}
-
-type Args []string
-
-// Returns the command line arguments associated with the context.
-func (c *Context) Args() Args {
- args := Args(c.flagSet.Args())
- return args
-}
-
-// Returns the nth argument, or else a blank string
-func (a Args) Get(n int) string {
- if len(a) > n {
- return a[n]
- }
- return ""
-}
-
-// Returns the first argument, or else a blank string
-func (a Args) First() string {
- return a.Get(0)
-}
-
-// Return the rest of the arguments (not the first one)
-// or else an empty string slice
-func (a Args) Tail() []string {
- if len(a) >= 2 {
- return []string(a)[1:]
- }
- return []string{}
-}
-
-// Checks if there are any arguments present
-func (a Args) Present() bool {
- return len(a) != 0
-}
-
-// Swaps arguments at the given indexes
-func (a Args) Swap(from, to int) error {
- if from >= len(a) || to >= len(a) {
- return errors.New("index out of range")
- }
- a[from], a[to] = a[to], a[from]
- return nil
-}
-
-func lookupInt(name string, set *flag.FlagSet) int {
- f := set.Lookup(name)
- if f != nil {
- val, err := strconv.Atoi(f.Value.String())
- if err != nil {
- return 0
- }
- return val
- }
-
- return 0
-}
-
-func lookupDuration(name string, set *flag.FlagSet) time.Duration {
- f := set.Lookup(name)
- if f != nil {
- val, err := time.ParseDuration(f.Value.String())
- if err == nil {
- return val
- }
- }
-
- return 0
-}
-
-func lookupFloat64(name string, set *flag.FlagSet) float64 {
- f := set.Lookup(name)
- if f != nil {
- val, err := strconv.ParseFloat(f.Value.String(), 64)
- if err != nil {
- return 0
- }
- return val
- }
-
- return 0
-}
-
-func lookupString(name string, set *flag.FlagSet) string {
- f := set.Lookup(name)
- if f != nil {
- return f.Value.String()
- }
-
- return ""
-}
-
-func lookupStringSlice(name string, set *flag.FlagSet) []string {
- f := set.Lookup(name)
- if f != nil {
- return (f.Value.(*StringSlice)).Value()
-
- }
-
- return nil
-}
-
-func lookupIntSlice(name string, set *flag.FlagSet) []int {
- f := set.Lookup(name)
- if f != nil {
- return (f.Value.(*IntSlice)).Value()
-
- }
-
- return nil
-}
-
-func lookupGeneric(name string, set *flag.FlagSet) interface{} {
- f := set.Lookup(name)
- if f != nil {
- return f.Value
- }
- return nil
-}
-
-func lookupBool(name string, set *flag.FlagSet) bool {
- f := set.Lookup(name)
- if f != nil {
- val, err := strconv.ParseBool(f.Value.String())
- if err != nil {
- return false
- }
- return val
- }
-
- return false
-}
-
-func lookupBoolT(name string, set *flag.FlagSet) bool {
- f := set.Lookup(name)
- if f != nil {
- val, err := strconv.ParseBool(f.Value.String())
- if err != nil {
- return true
- }
- return val
- }
-
- return false
-}
-
-func copyFlag(name string, ff *flag.Flag, set *flag.FlagSet) {
- switch ff.Value.(type) {
- case *StringSlice:
- default:
- set.Set(name, ff.Value.String())
- }
-}
-
-func normalizeFlags(flags []Flag, set *flag.FlagSet) error {
- visited := make(map[string]bool)
- set.Visit(func(f *flag.Flag) {
- visited[f.Name] = true
- })
- for _, f := range flags {
- parts := strings.Split(f.getName(), ",")
- if len(parts) == 1 {
- continue
- }
- var ff *flag.Flag
- for _, name := range parts {
- name = strings.Trim(name, " ")
- if visited[name] {
- if ff != nil {
- return errors.New("Cannot use two forms of the same flag: " + name + " " + ff.Name)
- }
- ff = set.Lookup(name)
- }
- }
- if ff == nil {
- continue
- }
- for _, name := range parts {
- name = strings.Trim(name, " ")
- if !visited[name] {
- copyFlag(name, ff, set)
- }
- }
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/codegangsta/cli/flag.go b/containerd/vendor/github.com/codegangsta/cli/flag.go
deleted file mode 100644
index 2511586..0000000
--- a/containerd/vendor/github.com/codegangsta/cli/flag.go
+++ /dev/null
@@ -1,454 +0,0 @@
-package cli
-
-import (
- "flag"
- "fmt"
- "os"
- "strconv"
- "strings"
- "time"
-)
-
-// This flag enables bash-completion for all commands and subcommands
-var BashCompletionFlag = BoolFlag{
- Name: "generate-bash-completion",
-}
-
-// This flag prints the version for the application
-var VersionFlag = BoolFlag{
- Name: "version, v",
- Usage: "print the version",
-}
-
-// This flag prints the help for all commands and subcommands
-// Set to the zero value (BoolFlag{}) to disable flag -- keeps subcommand
-// unless HideHelp is set to true)
-var HelpFlag = BoolFlag{
- Name: "help, h",
- Usage: "show help",
-}
-
-// Flag is a common interface related to parsing flags in cli.
-// For more advanced flag parsing techniques, it is recomended that
-// this interface be implemented.
-type Flag interface {
- fmt.Stringer
- // Apply Flag settings to the given flag set
- Apply(*flag.FlagSet)
- getName() string
-}
-
-func flagSet(name string, flags []Flag) *flag.FlagSet {
- set := flag.NewFlagSet(name, flag.ContinueOnError)
-
- for _, f := range flags {
- f.Apply(set)
- }
- return set
-}
-
-func eachName(longName string, fn func(string)) {
- parts := strings.Split(longName, ",")
- for _, name := range parts {
- name = strings.Trim(name, " ")
- fn(name)
- }
-}
-
-// Generic is a generic parseable type identified by a specific flag
-type Generic interface {
- Set(value string) error
- String() string
-}
-
-// GenericFlag is the flag type for types implementing Generic
-type GenericFlag struct {
- Name string
- Value Generic
- Usage string
- EnvVar string
-}
-
-// String returns the string representation of the generic flag to display the
-// help text to the user (uses the String() method of the generic flag to show
-// the value)
-func (f GenericFlag) String() string {
- return withEnvHint(f.EnvVar, fmt.Sprintf("%s%s \"%v\"\t%v", prefixFor(f.Name), f.Name, f.Value, f.Usage))
-}
-
-// Apply takes the flagset and calls Set on the generic flag with the value
-// provided by the user for parsing by the flag
-func (f GenericFlag) Apply(set *flag.FlagSet) {
- val := f.Value
- if f.EnvVar != "" {
- for _, envVar := range strings.Split(f.EnvVar, ",") {
- envVar = strings.TrimSpace(envVar)
- if envVal := os.Getenv(envVar); envVal != "" {
- val.Set(envVal)
- break
- }
- }
- }
-
- eachName(f.Name, func(name string) {
- set.Var(f.Value, name, f.Usage)
- })
-}
-
-func (f GenericFlag) getName() string {
- return f.Name
-}
-
-type StringSlice []string
-
-func (f *StringSlice) Set(value string) error {
- *f = append(*f, value)
- return nil
-}
-
-func (f *StringSlice) String() string {
- return fmt.Sprintf("%s", *f)
-}
-
-func (f *StringSlice) Value() []string {
- return *f
-}
-
-type StringSliceFlag struct {
- Name string
- Value *StringSlice
- Usage string
- EnvVar string
-}
-
-func (f StringSliceFlag) String() string {
- firstName := strings.Trim(strings.Split(f.Name, ",")[0], " ")
- pref := prefixFor(firstName)
- return withEnvHint(f.EnvVar, fmt.Sprintf("%s [%v]\t%v", prefixedNames(f.Name), pref+firstName+" option "+pref+firstName+" option", f.Usage))
-}
-
-func (f StringSliceFlag) Apply(set *flag.FlagSet) {
- if f.EnvVar != "" {
- for _, envVar := range strings.Split(f.EnvVar, ",") {
- envVar = strings.TrimSpace(envVar)
- if envVal := os.Getenv(envVar); envVal != "" {
- newVal := &StringSlice{}
- for _, s := range strings.Split(envVal, ",") {
- s = strings.TrimSpace(s)
- newVal.Set(s)
- }
- f.Value = newVal
- break
- }
- }
- }
-
- eachName(f.Name, func(name string) {
- set.Var(f.Value, name, f.Usage)
- })
-}
-
-func (f StringSliceFlag) getName() string {
- return f.Name
-}
-
-type IntSlice []int
-
-func (f *IntSlice) Set(value string) error {
-
- tmp, err := strconv.Atoi(value)
- if err != nil {
- return err
- } else {
- *f = append(*f, tmp)
- }
- return nil
-}
-
-func (f *IntSlice) String() string {
- return fmt.Sprintf("%d", *f)
-}
-
-func (f *IntSlice) Value() []int {
- return *f
-}
-
-type IntSliceFlag struct {
- Name string
- Value *IntSlice
- Usage string
- EnvVar string
-}
-
-func (f IntSliceFlag) String() string {
- firstName := strings.Trim(strings.Split(f.Name, ",")[0], " ")
- pref := prefixFor(firstName)
- return withEnvHint(f.EnvVar, fmt.Sprintf("%s [%v]\t%v", prefixedNames(f.Name), pref+firstName+" option "+pref+firstName+" option", f.Usage))
-}
-
-func (f IntSliceFlag) Apply(set *flag.FlagSet) {
- if f.EnvVar != "" {
- for _, envVar := range strings.Split(f.EnvVar, ",") {
- envVar = strings.TrimSpace(envVar)
- if envVal := os.Getenv(envVar); envVal != "" {
- newVal := &IntSlice{}
- for _, s := range strings.Split(envVal, ",") {
- s = strings.TrimSpace(s)
- err := newVal.Set(s)
- if err != nil {
- fmt.Fprintf(os.Stderr, err.Error())
- }
- }
- f.Value = newVal
- break
- }
- }
- }
-
- eachName(f.Name, func(name string) {
- set.Var(f.Value, name, f.Usage)
- })
-}
-
-func (f IntSliceFlag) getName() string {
- return f.Name
-}
-
-type BoolFlag struct {
- Name string
- Usage string
- EnvVar string
-}
-
-func (f BoolFlag) String() string {
- return withEnvHint(f.EnvVar, fmt.Sprintf("%s\t%v", prefixedNames(f.Name), f.Usage))
-}
-
-func (f BoolFlag) Apply(set *flag.FlagSet) {
- val := false
- if f.EnvVar != "" {
- for _, envVar := range strings.Split(f.EnvVar, ",") {
- envVar = strings.TrimSpace(envVar)
- if envVal := os.Getenv(envVar); envVal != "" {
- envValBool, err := strconv.ParseBool(envVal)
- if err == nil {
- val = envValBool
- }
- break
- }
- }
- }
-
- eachName(f.Name, func(name string) {
- set.Bool(name, val, f.Usage)
- })
-}
-
-func (f BoolFlag) getName() string {
- return f.Name
-}
-
-type BoolTFlag struct {
- Name string
- Usage string
- EnvVar string
-}
-
-func (f BoolTFlag) String() string {
- return withEnvHint(f.EnvVar, fmt.Sprintf("%s\t%v", prefixedNames(f.Name), f.Usage))
-}
-
-func (f BoolTFlag) Apply(set *flag.FlagSet) {
- val := true
- if f.EnvVar != "" {
- for _, envVar := range strings.Split(f.EnvVar, ",") {
- envVar = strings.TrimSpace(envVar)
- if envVal := os.Getenv(envVar); envVal != "" {
- envValBool, err := strconv.ParseBool(envVal)
- if err == nil {
- val = envValBool
- break
- }
- }
- }
- }
-
- eachName(f.Name, func(name string) {
- set.Bool(name, val, f.Usage)
- })
-}
-
-func (f BoolTFlag) getName() string {
- return f.Name
-}
-
-type StringFlag struct {
- Name string
- Value string
- Usage string
- EnvVar string
-}
-
-func (f StringFlag) String() string {
- var fmtString string
- fmtString = "%s %v\t%v"
-
- if len(f.Value) > 0 {
- fmtString = "%s \"%v\"\t%v"
- } else {
- fmtString = "%s %v\t%v"
- }
-
- return withEnvHint(f.EnvVar, fmt.Sprintf(fmtString, prefixedNames(f.Name), f.Value, f.Usage))
-}
-
-func (f StringFlag) Apply(set *flag.FlagSet) {
- if f.EnvVar != "" {
- for _, envVar := range strings.Split(f.EnvVar, ",") {
- envVar = strings.TrimSpace(envVar)
- if envVal := os.Getenv(envVar); envVal != "" {
- f.Value = envVal
- break
- }
- }
- }
-
- eachName(f.Name, func(name string) {
- set.String(name, f.Value, f.Usage)
- })
-}
-
-func (f StringFlag) getName() string {
- return f.Name
-}
-
-type IntFlag struct {
- Name string
- Value int
- Usage string
- EnvVar string
-}
-
-func (f IntFlag) String() string {
- return withEnvHint(f.EnvVar, fmt.Sprintf("%s \"%v\"\t%v", prefixedNames(f.Name), f.Value, f.Usage))
-}
-
-func (f IntFlag) Apply(set *flag.FlagSet) {
- if f.EnvVar != "" {
- for _, envVar := range strings.Split(f.EnvVar, ",") {
- envVar = strings.TrimSpace(envVar)
- if envVal := os.Getenv(envVar); envVal != "" {
- envValInt, err := strconv.ParseInt(envVal, 0, 64)
- if err == nil {
- f.Value = int(envValInt)
- break
- }
- }
- }
- }
-
- eachName(f.Name, func(name string) {
- set.Int(name, f.Value, f.Usage)
- })
-}
-
-func (f IntFlag) getName() string {
- return f.Name
-}
-
-type DurationFlag struct {
- Name string
- Value time.Duration
- Usage string
- EnvVar string
-}
-
-func (f DurationFlag) String() string {
- return withEnvHint(f.EnvVar, fmt.Sprintf("%s \"%v\"\t%v", prefixedNames(f.Name), f.Value, f.Usage))
-}
-
-func (f DurationFlag) Apply(set *flag.FlagSet) {
- if f.EnvVar != "" {
- for _, envVar := range strings.Split(f.EnvVar, ",") {
- envVar = strings.TrimSpace(envVar)
- if envVal := os.Getenv(envVar); envVal != "" {
- envValDuration, err := time.ParseDuration(envVal)
- if err == nil {
- f.Value = envValDuration
- break
- }
- }
- }
- }
-
- eachName(f.Name, func(name string) {
- set.Duration(name, f.Value, f.Usage)
- })
-}
-
-func (f DurationFlag) getName() string {
- return f.Name
-}
-
-type Float64Flag struct {
- Name string
- Value float64
- Usage string
- EnvVar string
-}
-
-func (f Float64Flag) String() string {
- return withEnvHint(f.EnvVar, fmt.Sprintf("%s \"%v\"\t%v", prefixedNames(f.Name), f.Value, f.Usage))
-}
-
-func (f Float64Flag) Apply(set *flag.FlagSet) {
- if f.EnvVar != "" {
- for _, envVar := range strings.Split(f.EnvVar, ",") {
- envVar = strings.TrimSpace(envVar)
- if envVal := os.Getenv(envVar); envVal != "" {
- envValFloat, err := strconv.ParseFloat(envVal, 10)
- if err == nil {
- f.Value = float64(envValFloat)
- }
- }
- }
- }
-
- eachName(f.Name, func(name string) {
- set.Float64(name, f.Value, f.Usage)
- })
-}
-
-func (f Float64Flag) getName() string {
- return f.Name
-}
-
-func prefixFor(name string) (prefix string) {
- if len(name) == 1 {
- prefix = "-"
- } else {
- prefix = "--"
- }
-
- return
-}
-
-func prefixedNames(fullName string) (prefixed string) {
- parts := strings.Split(fullName, ",")
- for i, name := range parts {
- name = strings.Trim(name, " ")
- prefixed += prefixFor(name) + name
- if i < len(parts)-1 {
- prefixed += ", "
- }
- }
- return
-}
-
-func withEnvHint(envVar, str string) string {
- envText := ""
- if envVar != "" {
- envText = fmt.Sprintf(" [$%s]", strings.Join(strings.Split(envVar, ","), ", $"))
- }
- return str + envText
-}
diff --git a/containerd/vendor/github.com/codegangsta/cli/help.go b/containerd/vendor/github.com/codegangsta/cli/help.go
deleted file mode 100644
index 1117945..0000000
--- a/containerd/vendor/github.com/codegangsta/cli/help.go
+++ /dev/null
@@ -1,235 +0,0 @@
-package cli
-
-import (
- "fmt"
- "io"
- "strings"
- "text/tabwriter"
- "text/template"
-)
-
-// The text template for the Default help topic.
-// cli.go uses text/template to render templates. You can
-// render custom help text by setting this variable.
-var AppHelpTemplate = `NAME:
- {{.Name}} - {{.Usage}}
-
-USAGE:
- {{.Name}} {{if .Flags}}[global options] {{end}}command{{if .Flags}} [command options]{{end}} [arguments...]
-
-VERSION:
- {{.Version}}{{if len .Authors}}
-
-AUTHOR(S):
- {{range .Authors}}{{ . }}{{end}}{{end}}
-
-COMMANDS:
- {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
- {{end}}{{if .Flags}}
-GLOBAL OPTIONS:
- {{range .Flags}}{{.}}
- {{end}}{{end}}
-`
-
-// The text template for the command help topic.
-// cli.go uses text/template to render templates. You can
-// render custom help text by setting this variable.
-var CommandHelpTemplate = `NAME:
- {{.Name}} - {{.Usage}}
-
-USAGE:
- command {{.Name}}{{if .Flags}} [command options]{{end}} [arguments...]{{if .Description}}
-
-DESCRIPTION:
- {{.Description}}{{end}}{{if .Flags}}
-
-OPTIONS:
- {{range .Flags}}{{.}}
- {{end}}{{ end }}
-`
-
-// The text template for the subcommand help topic.
-// cli.go uses text/template to render templates. You can
-// render custom help text by setting this variable.
-var SubcommandHelpTemplate = `NAME:
- {{.Name}} - {{.Usage}}
-
-USAGE:
- {{.Name}} command{{if .Flags}} [command options]{{end}} [arguments...]
-
-COMMANDS:
- {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
- {{end}}{{if .Flags}}
-OPTIONS:
- {{range .Flags}}{{.}}
- {{end}}{{end}}
-`
-
-var helpCommand = Command{
- Name: "help",
- Aliases: []string{"h"},
- Usage: "Shows a list of commands or help for one command",
- Action: func(c *Context) {
- args := c.Args()
- if args.Present() {
- ShowCommandHelp(c, args.First())
- } else {
- ShowAppHelp(c)
- }
- },
-}
-
-var helpSubcommand = Command{
- Name: "help",
- Aliases: []string{"h"},
- Usage: "Shows a list of commands or help for one command",
- Action: func(c *Context) {
- args := c.Args()
- if args.Present() {
- ShowCommandHelp(c, args.First())
- } else {
- ShowSubcommandHelp(c)
- }
- },
-}
-
-// Prints help for the App or Command
-type helpPrinter func(w io.Writer, templ string, data interface{})
-
-var HelpPrinter helpPrinter = printHelp
-
-// Prints version for the App
-var VersionPrinter = printVersion
-
-func ShowAppHelp(c *Context) {
- HelpPrinter(c.App.Writer, AppHelpTemplate, c.App)
-}
-
-// Prints the list of subcommands as the default app completion method
-func DefaultAppComplete(c *Context) {
- for _, command := range c.App.Commands {
- for _, name := range command.Names() {
- fmt.Fprintln(c.App.Writer, name)
- }
- }
-}
-
-// Prints help for the given command
-func ShowCommandHelp(ctx *Context, command string) {
- // show the subcommand help for a command with subcommands
- if command == "" {
- HelpPrinter(ctx.App.Writer, SubcommandHelpTemplate, ctx.App)
- return
- }
-
- for _, c := range ctx.App.Commands {
- if c.HasName(command) {
- HelpPrinter(ctx.App.Writer, CommandHelpTemplate, c)
- return
- }
- }
-
- if ctx.App.CommandNotFound != nil {
- ctx.App.CommandNotFound(ctx, command)
- } else {
- fmt.Fprintf(ctx.App.Writer, "No help topic for '%v'\n", command)
- }
-}
-
-// Prints help for the given subcommand
-func ShowSubcommandHelp(c *Context) {
- ShowCommandHelp(c, c.Command.Name)
-}
-
-// Prints the version number of the App
-func ShowVersion(c *Context) {
- VersionPrinter(c)
-}
-
-func printVersion(c *Context) {
- fmt.Fprintf(c.App.Writer, "%v version %v\n", c.App.Name, c.App.Version)
-}
-
-// Prints the lists of commands within a given context
-func ShowCompletions(c *Context) {
- a := c.App
- if a != nil && a.BashComplete != nil {
- a.BashComplete(c)
- }
-}
-
-// Prints the custom completions for a given command
-func ShowCommandCompletions(ctx *Context, command string) {
- c := ctx.App.Command(command)
- if c != nil && c.BashComplete != nil {
- c.BashComplete(ctx)
- }
-}
-
-func printHelp(out io.Writer, templ string, data interface{}) {
- funcMap := template.FuncMap{
- "join": strings.Join,
- }
-
- w := tabwriter.NewWriter(out, 0, 8, 1, '\t', 0)
- t := template.Must(template.New("help").Funcs(funcMap).Parse(templ))
- err := t.Execute(w, data)
- if err != nil {
- panic(err)
- }
- w.Flush()
-}
-
-func checkVersion(c *Context) bool {
- if c.GlobalBool("version") {
- ShowVersion(c)
- return true
- }
-
- return false
-}
-
-func checkHelp(c *Context) bool {
- if c.GlobalBool("h") || c.GlobalBool("help") {
- ShowAppHelp(c)
- return true
- }
-
- return false
-}
-
-func checkCommandHelp(c *Context, name string) bool {
- if c.Bool("h") || c.Bool("help") {
- ShowCommandHelp(c, name)
- return true
- }
-
- return false
-}
-
-func checkSubcommandHelp(c *Context) bool {
- if c.GlobalBool("h") || c.GlobalBool("help") {
- ShowSubcommandHelp(c)
- return true
- }
-
- return false
-}
-
-func checkCompletions(c *Context) bool {
- if (c.GlobalBool(BashCompletionFlag.Name) || c.Bool(BashCompletionFlag.Name)) && c.App.EnableBashCompletion {
- ShowCompletions(c)
- return true
- }
-
- return false
-}
-
-func checkCommandCompletions(c *Context, name string) bool {
- if c.Bool(BashCompletionFlag.Name) && c.App.EnableBashCompletion {
- ShowCommandCompletions(c, name)
- return true
- }
-
- return false
-}
diff --git a/containerd/vendor/github.com/coreos/go-systemd/dbus/dbus.go b/containerd/vendor/github.com/coreos/go-systemd/dbus/dbus.go
deleted file mode 100644
index 625a32b..0000000
--- a/containerd/vendor/github.com/coreos/go-systemd/dbus/dbus.go
+++ /dev/null
@@ -1,163 +0,0 @@
-// Copyright 2015 CoreOS, 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
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// Integration with the systemd D-Bus API. See http://www.freedesktop.org/wiki/Software/systemd/dbus/
-package dbus
-
-import (
- "fmt"
- "os"
- "strconv"
- "strings"
- "sync"
-
- "github.com/godbus/dbus"
-)
-
-const (
- alpha = `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`
- num = `0123456789`
- alphanum = alpha + num
- signalBuffer = 100
-)
-
-// needsEscape checks whether a byte in a potential dbus ObjectPath needs to be escaped
-func needsEscape(i int, b byte) bool {
- // Escape everything that is not a-z-A-Z-0-9
- // Also escape 0-9 if it's the first character
- return strings.IndexByte(alphanum, b) == -1 ||
- (i == 0 && strings.IndexByte(num, b) != -1)
-}
-
-// PathBusEscape sanitizes a constituent string of a dbus ObjectPath using the
-// rules that systemd uses for serializing special characters.
-func PathBusEscape(path string) string {
- // Special case the empty string
- if len(path) == 0 {
- return "_"
- }
- n := []byte{}
- for i := 0; i < len(path); i++ {
- c := path[i]
- if needsEscape(i, c) {
- e := fmt.Sprintf("_%x", c)
- n = append(n, []byte(e)...)
- } else {
- n = append(n, c)
- }
- }
- return string(n)
-}
-
-// Conn is a connection to systemd's dbus endpoint.
-type Conn struct {
- // sysconn/sysobj are only used to call dbus methods
- sysconn *dbus.Conn
- sysobj *dbus.Object
-
- // sigconn/sigobj are only used to receive dbus signals
- sigconn *dbus.Conn
- sigobj *dbus.Object
-
- jobListener struct {
- jobs map[dbus.ObjectPath]chan<- string
- sync.Mutex
- }
- subscriber struct {
- updateCh chan<- *SubStateUpdate
- errCh chan<- error
- sync.Mutex
- ignore map[dbus.ObjectPath]int64
- cleanIgnore int64
- }
-}
-
-// New establishes a connection to the system bus and authenticates.
-// Callers should call Close() when done with the connection.
-func New() (*Conn, error) {
- return newConnection(dbus.SystemBusPrivate)
-}
-
-// NewUserConnection establishes a connection to the session bus and
-// authenticates. This can be used to connect to systemd user instances.
-// Callers should call Close() when done with the connection.
-func NewUserConnection() (*Conn, error) {
- return newConnection(dbus.SessionBusPrivate)
-}
-
-// Close closes an established connection
-func (c *Conn) Close() {
- c.sysconn.Close()
- c.sigconn.Close()
-}
-
-func newConnection(createBus func() (*dbus.Conn, error)) (*Conn, error) {
- sysconn, err := dbusConnection(createBus)
- if err != nil {
- return nil, err
- }
-
- sigconn, err := dbusConnection(createBus)
- if err != nil {
- sysconn.Close()
- return nil, err
- }
-
- c := &Conn{
- sysconn: sysconn,
- sysobj: systemdObject(sysconn),
- sigconn: sigconn,
- sigobj: systemdObject(sigconn),
- }
-
- c.subscriber.ignore = make(map[dbus.ObjectPath]int64)
- c.jobListener.jobs = make(map[dbus.ObjectPath]chan<- string)
-
- // Setup the listeners on jobs so that we can get completions
- c.sigconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0,
- "type='signal', interface='org.freedesktop.systemd1.Manager', member='JobRemoved'")
-
- c.dispatch()
- return c, nil
-}
-
-func dbusConnection(createBus func() (*dbus.Conn, error)) (*dbus.Conn, error) {
- conn, err := createBus()
- if err != nil {
- return nil, err
- }
-
- // Only use EXTERNAL method, and hardcode the uid (not username)
- // to avoid a username lookup (which requires a dynamically linked
- // libc)
- methods := []dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))}
-
- err = conn.Auth(methods)
- if err != nil {
- conn.Close()
- return nil, err
- }
-
- err = conn.Hello()
- if err != nil {
- conn.Close()
- return nil, err
- }
-
- return conn, nil
-}
-
-func systemdObject(conn *dbus.Conn) *dbus.Object {
- return conn.Object("org.freedesktop.systemd1", dbus.ObjectPath("/org/freedesktop/systemd1"))
-}
diff --git a/containerd/vendor/github.com/coreos/go-systemd/dbus/methods.go b/containerd/vendor/github.com/coreos/go-systemd/dbus/methods.go
deleted file mode 100644
index ab614c7..0000000
--- a/containerd/vendor/github.com/coreos/go-systemd/dbus/methods.go
+++ /dev/null
@@ -1,410 +0,0 @@
-// Copyright 2015 CoreOS, 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
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package dbus
-
-import (
- "errors"
- "path"
- "strconv"
-
- "github.com/godbus/dbus"
-)
-
-func (c *Conn) jobComplete(signal *dbus.Signal) {
- var id uint32
- var job dbus.ObjectPath
- var unit string
- var result string
- dbus.Store(signal.Body, &id, &job, &unit, &result)
- c.jobListener.Lock()
- out, ok := c.jobListener.jobs[job]
- if ok {
- out <- result
- delete(c.jobListener.jobs, job)
- }
- c.jobListener.Unlock()
-}
-
-func (c *Conn) startJob(ch chan<- string, job string, args ...interface{}) (int, error) {
- if ch != nil {
- c.jobListener.Lock()
- defer c.jobListener.Unlock()
- }
-
- var p dbus.ObjectPath
- err := c.sysobj.Call(job, 0, args...).Store(&p)
- if err != nil {
- return 0, err
- }
-
- if ch != nil {
- c.jobListener.jobs[p] = ch
- }
-
- // ignore error since 0 is fine if conversion fails
- jobID, _ := strconv.Atoi(path.Base(string(p)))
-
- return jobID, nil
-}
-
-// StartUnit enqueues a start job and depending jobs, if any (unless otherwise
-// specified by the mode string).
-//
-// Takes the unit to activate, plus a mode string. The mode needs to be one of
-// replace, fail, isolate, ignore-dependencies, ignore-requirements. If
-// "replace" the call will start the unit and its dependencies, possibly
-// replacing already queued jobs that conflict with this. If "fail" the call
-// will start the unit and its dependencies, but will fail if this would change
-// an already queued job. If "isolate" the call will start the unit in question
-// and terminate all units that aren't dependencies of it. If
-// "ignore-dependencies" it will start a unit but ignore all its dependencies.
-// If "ignore-requirements" it will start a unit but only ignore the
-// requirement dependencies. It is not recommended to make use of the latter
-// two options.
-//
-// If the provided channel is non-nil, a result string will be sent to it upon
-// job completion: one of done, canceled, timeout, failed, dependency, skipped.
-// done indicates successful execution of a job. canceled indicates that a job
-// has been canceled before it finished execution. timeout indicates that the
-// job timeout was reached. failed indicates that the job failed. dependency
-// indicates that a job this job has been depending on failed and the job hence
-// has been removed too. skipped indicates that a job was skipped because it
-// didn't apply to the units current state.
-//
-// If no error occurs, the ID of the underlying systemd job will be returned. There
-// does exist the possibility for no error to be returned, but for the returned job
-// ID to be 0. In this case, the actual underlying ID is not 0 and this datapoint
-// should not be considered authoritative.
-//
-// If an error does occur, it will be returned to the user alongside a job ID of 0.
-func (c *Conn) StartUnit(name string, mode string, ch chan<- string) (int, error) {
- return c.startJob(ch, "org.freedesktop.systemd1.Manager.StartUnit", name, mode)
-}
-
-// StopUnit is similar to StartUnit but stops the specified unit rather
-// than starting it.
-func (c *Conn) StopUnit(name string, mode string, ch chan<- string) (int, error) {
- return c.startJob(ch, "org.freedesktop.systemd1.Manager.StopUnit", name, mode)
-}
-
-// ReloadUnit reloads a unit. Reloading is done only if the unit is already running and fails otherwise.
-func (c *Conn) ReloadUnit(name string, mode string, ch chan<- string) (int, error) {
- return c.startJob(ch, "org.freedesktop.systemd1.Manager.ReloadUnit", name, mode)
-}
-
-// RestartUnit restarts a service. If a service is restarted that isn't
-// running it will be started.
-func (c *Conn) RestartUnit(name string, mode string, ch chan<- string) (int, error) {
- return c.startJob(ch, "org.freedesktop.systemd1.Manager.RestartUnit", name, mode)
-}
-
-// TryRestartUnit is like RestartUnit, except that a service that isn't running
-// is not affected by the restart.
-func (c *Conn) TryRestartUnit(name string, mode string, ch chan<- string) (int, error) {
- return c.startJob(ch, "org.freedesktop.systemd1.Manager.TryRestartUnit", name, mode)
-}
-
-// ReloadOrRestart attempts a reload if the unit supports it and use a restart
-// otherwise.
-func (c *Conn) ReloadOrRestartUnit(name string, mode string, ch chan<- string) (int, error) {
- return c.startJob(ch, "org.freedesktop.systemd1.Manager.ReloadOrRestartUnit", name, mode)
-}
-
-// ReloadOrTryRestart attempts a reload if the unit supports it and use a "Try"
-// flavored restart otherwise.
-func (c *Conn) ReloadOrTryRestartUnit(name string, mode string, ch chan<- string) (int, error) {
- return c.startJob(ch, "org.freedesktop.systemd1.Manager.ReloadOrTryRestartUnit", name, mode)
-}
-
-// StartTransientUnit() may be used to create and start a transient unit, which
-// will be released as soon as it is not running or referenced anymore or the
-// system is rebooted. name is the unit name including suffix, and must be
-// unique. mode is the same as in StartUnit(), properties contains properties
-// of the unit.
-func (c *Conn) StartTransientUnit(name string, mode string, properties []Property, ch chan<- string) (int, error) {
- return c.startJob(ch, "org.freedesktop.systemd1.Manager.StartTransientUnit", name, mode, properties, make([]PropertyCollection, 0))
-}
-
-// KillUnit takes the unit name and a UNIX signal number to send. All of the unit's
-// processes are killed.
-func (c *Conn) KillUnit(name string, signal int32) {
- c.sysobj.Call("org.freedesktop.systemd1.Manager.KillUnit", 0, name, "all", signal).Store()
-}
-
-// ResetFailedUnit resets the "failed" state of a specific unit.
-func (c *Conn) ResetFailedUnit(name string) error {
- return c.sysobj.Call("org.freedesktop.systemd1.Manager.ResetFailedUnit", 0, name).Store()
-}
-
-// getProperties takes the unit name and returns all of its dbus object properties, for the given dbus interface
-func (c *Conn) getProperties(unit string, dbusInterface string) (map[string]interface{}, error) {
- var err error
- var props map[string]dbus.Variant
-
- path := unitPath(unit)
- if !path.IsValid() {
- return nil, errors.New("invalid unit name: " + unit)
- }
-
- obj := c.sysconn.Object("org.freedesktop.systemd1", path)
- err = obj.Call("org.freedesktop.DBus.Properties.GetAll", 0, dbusInterface).Store(&props)
- if err != nil {
- return nil, err
- }
-
- out := make(map[string]interface{}, len(props))
- for k, v := range props {
- out[k] = v.Value()
- }
-
- return out, nil
-}
-
-// GetUnitProperties takes the unit name and returns all of its dbus object properties.
-func (c *Conn) GetUnitProperties(unit string) (map[string]interface{}, error) {
- return c.getProperties(unit, "org.freedesktop.systemd1.Unit")
-}
-
-func (c *Conn) getProperty(unit string, dbusInterface string, propertyName string) (*Property, error) {
- var err error
- var prop dbus.Variant
-
- path := unitPath(unit)
- if !path.IsValid() {
- return nil, errors.New("invalid unit name: " + unit)
- }
-
- obj := c.sysconn.Object("org.freedesktop.systemd1", path)
- err = obj.Call("org.freedesktop.DBus.Properties.Get", 0, dbusInterface, propertyName).Store(&prop)
- if err != nil {
- return nil, err
- }
-
- return &Property{Name: propertyName, Value: prop}, nil
-}
-
-func (c *Conn) GetUnitProperty(unit string, propertyName string) (*Property, error) {
- return c.getProperty(unit, "org.freedesktop.systemd1.Unit", propertyName)
-}
-
-// GetUnitTypeProperties returns the extra properties for a unit, specific to the unit type.
-// Valid values for unitType: Service, Socket, Target, Device, Mount, Automount, Snapshot, Timer, Swap, Path, Slice, Scope
-// return "dbus.Error: Unknown interface" if the unitType is not the correct type of the unit
-func (c *Conn) GetUnitTypeProperties(unit string, unitType string) (map[string]interface{}, error) {
- return c.getProperties(unit, "org.freedesktop.systemd1."+unitType)
-}
-
-// SetUnitProperties() may be used to modify certain unit properties at runtime.
-// Not all properties may be changed at runtime, but many resource management
-// settings (primarily those in systemd.cgroup(5)) may. The changes are applied
-// instantly, and stored on disk for future boots, unless runtime is true, in which
-// case the settings only apply until the next reboot. name is the name of the unit
-// to modify. properties are the settings to set, encoded as an array of property
-// name and value pairs.
-func (c *Conn) SetUnitProperties(name string, runtime bool, properties ...Property) error {
- return c.sysobj.Call("org.freedesktop.systemd1.Manager.SetUnitProperties", 0, name, runtime, properties).Store()
-}
-
-func (c *Conn) GetUnitTypeProperty(unit string, unitType string, propertyName string) (*Property, error) {
- return c.getProperty(unit, "org.freedesktop.systemd1."+unitType, propertyName)
-}
-
-// ListUnits returns an array with all currently loaded units. Note that
-// units may be known by multiple names at the same time, and hence there might
-// be more unit names loaded than actual units behind them.
-func (c *Conn) ListUnits() ([]UnitStatus, error) {
- result := make([][]interface{}, 0)
- err := c.sysobj.Call("org.freedesktop.systemd1.Manager.ListUnits", 0).Store(&result)
- if err != nil {
- return nil, err
- }
-
- resultInterface := make([]interface{}, len(result))
- for i := range result {
- resultInterface[i] = result[i]
- }
-
- status := make([]UnitStatus, len(result))
- statusInterface := make([]interface{}, len(status))
- for i := range status {
- statusInterface[i] = &status[i]
- }
-
- err = dbus.Store(resultInterface, statusInterface...)
- if err != nil {
- return nil, err
- }
-
- return status, nil
-}
-
-type UnitStatus struct {
- Name string // The primary unit name as string
- Description string // The human readable description string
- LoadState string // The load state (i.e. whether the unit file has been loaded successfully)
- ActiveState string // The active state (i.e. whether the unit is currently started or not)
- SubState string // The sub state (a more fine-grained version of the active state that is specific to the unit type, which the active state is not)
- Followed string // A unit that is being followed in its state by this unit, if there is any, otherwise the empty string.
- Path dbus.ObjectPath // The unit object path
- JobId uint32 // If there is a job queued for the job unit the numeric job id, 0 otherwise
- JobType string // The job type as string
- JobPath dbus.ObjectPath // The job object path
-}
-
-type LinkUnitFileChange EnableUnitFileChange
-
-// LinkUnitFiles() links unit files (that are located outside of the
-// usual unit search paths) into the unit search path.
-//
-// It takes a list of absolute paths to unit files to link and two
-// booleans. The first boolean controls whether the unit shall be
-// enabled for runtime only (true, /run), or persistently (false,
-// /etc).
-// The second controls whether symlinks pointing to other units shall
-// be replaced if necessary.
-//
-// This call returns a list of the changes made. The list consists of
-// structures with three strings: the type of the change (one of symlink
-// or unlink), the file name of the symlink and the destination of the
-// symlink.
-func (c *Conn) LinkUnitFiles(files []string, runtime bool, force bool) ([]LinkUnitFileChange, error) {
- result := make([][]interface{}, 0)
- err := c.sysobj.Call("org.freedesktop.systemd1.Manager.LinkUnitFiles", 0, files, runtime, force).Store(&result)
- if err != nil {
- return nil, err
- }
-
- resultInterface := make([]interface{}, len(result))
- for i := range result {
- resultInterface[i] = result[i]
- }
-
- changes := make([]LinkUnitFileChange, len(result))
- changesInterface := make([]interface{}, len(changes))
- for i := range changes {
- changesInterface[i] = &changes[i]
- }
-
- err = dbus.Store(resultInterface, changesInterface...)
- if err != nil {
- return nil, err
- }
-
- return changes, nil
-}
-
-// EnableUnitFiles() may be used to enable one or more units in the system (by
-// creating symlinks to them in /etc or /run).
-//
-// It takes a list of unit files to enable (either just file names or full
-// absolute paths if the unit files are residing outside the usual unit
-// search paths), and two booleans: the first controls whether the unit shall
-// be enabled for runtime only (true, /run), or persistently (false, /etc).
-// The second one controls whether symlinks pointing to other units shall
-// be replaced if necessary.
-//
-// This call returns one boolean and an array with the changes made. The
-// boolean signals whether the unit files contained any enablement
-// information (i.e. an [Install]) section. The changes list consists of
-// structures with three strings: the type of the change (one of symlink
-// or unlink), the file name of the symlink and the destination of the
-// symlink.
-func (c *Conn) EnableUnitFiles(files []string, runtime bool, force bool) (bool, []EnableUnitFileChange, error) {
- var carries_install_info bool
-
- result := make([][]interface{}, 0)
- err := c.sysobj.Call("org.freedesktop.systemd1.Manager.EnableUnitFiles", 0, files, runtime, force).Store(&carries_install_info, &result)
- if err != nil {
- return false, nil, err
- }
-
- resultInterface := make([]interface{}, len(result))
- for i := range result {
- resultInterface[i] = result[i]
- }
-
- changes := make([]EnableUnitFileChange, len(result))
- changesInterface := make([]interface{}, len(changes))
- for i := range changes {
- changesInterface[i] = &changes[i]
- }
-
- err = dbus.Store(resultInterface, changesInterface...)
- if err != nil {
- return false, nil, err
- }
-
- return carries_install_info, changes, nil
-}
-
-type EnableUnitFileChange struct {
- Type string // Type of the change (one of symlink or unlink)
- Filename string // File name of the symlink
- Destination string // Destination of the symlink
-}
-
-// DisableUnitFiles() may be used to disable one or more units in the system (by
-// removing symlinks to them from /etc or /run).
-//
-// It takes a list of unit files to disable (either just file names or full
-// absolute paths if the unit files are residing outside the usual unit
-// search paths), and one boolean: whether the unit was enabled for runtime
-// only (true, /run), or persistently (false, /etc).
-//
-// This call returns an array with the changes made. The changes list
-// consists of structures with three strings: the type of the change (one of
-// symlink or unlink), the file name of the symlink and the destination of the
-// symlink.
-func (c *Conn) DisableUnitFiles(files []string, runtime bool) ([]DisableUnitFileChange, error) {
- result := make([][]interface{}, 0)
- err := c.sysobj.Call("org.freedesktop.systemd1.Manager.DisableUnitFiles", 0, files, runtime).Store(&result)
- if err != nil {
- return nil, err
- }
-
- resultInterface := make([]interface{}, len(result))
- for i := range result {
- resultInterface[i] = result[i]
- }
-
- changes := make([]DisableUnitFileChange, len(result))
- changesInterface := make([]interface{}, len(changes))
- for i := range changes {
- changesInterface[i] = &changes[i]
- }
-
- err = dbus.Store(resultInterface, changesInterface...)
- if err != nil {
- return nil, err
- }
-
- return changes, nil
-}
-
-type DisableUnitFileChange struct {
- Type string // Type of the change (one of symlink or unlink)
- Filename string // File name of the symlink
- Destination string // Destination of the symlink
-}
-
-// Reload instructs systemd to scan for and reload unit files. This is
-// equivalent to a 'systemctl daemon-reload'.
-func (c *Conn) Reload() error {
- return c.sysobj.Call("org.freedesktop.systemd1.Manager.Reload", 0).Store()
-}
-
-func unitPath(name string) dbus.ObjectPath {
- return dbus.ObjectPath("/org/freedesktop/systemd1/unit/" + PathBusEscape(name))
-}
diff --git a/containerd/vendor/github.com/coreos/go-systemd/dbus/properties.go b/containerd/vendor/github.com/coreos/go-systemd/dbus/properties.go
deleted file mode 100644
index 7520011..0000000
--- a/containerd/vendor/github.com/coreos/go-systemd/dbus/properties.go
+++ /dev/null
@@ -1,218 +0,0 @@
-// Copyright 2015 CoreOS, 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
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package dbus
-
-import (
- "github.com/godbus/dbus"
-)
-
-// From the systemd docs:
-//
-// The properties array of StartTransientUnit() may take many of the settings
-// that may also be configured in unit files. Not all parameters are currently
-// accepted though, but we plan to cover more properties with future release.
-// Currently you may set the Description, Slice and all dependency types of
-// units, as well as RemainAfterExit, ExecStart for service units,
-// TimeoutStopUSec and PIDs for scope units, and CPUAccounting, CPUShares,
-// BlockIOAccounting, BlockIOWeight, BlockIOReadBandwidth,
-// BlockIOWriteBandwidth, BlockIODeviceWeight, MemoryAccounting, MemoryLimit,
-// DevicePolicy, DeviceAllow for services/scopes/slices. These fields map
-// directly to their counterparts in unit files and as normal D-Bus object
-// properties. The exception here is the PIDs field of scope units which is
-// used for construction of the scope only and specifies the initial PIDs to
-// add to the scope object.
-
-type Property struct {
- Name string
- Value dbus.Variant
-}
-
-type PropertyCollection struct {
- Name string
- Properties []Property
-}
-
-type execStart struct {
- Path string // the binary path to execute
- Args []string // an array with all arguments to pass to the executed command, starting with argument 0
- UncleanIsFailure bool // a boolean whether it should be considered a failure if the process exits uncleanly
-}
-
-// PropExecStart sets the ExecStart service property. The first argument is a
-// slice with the binary path to execute followed by the arguments to pass to
-// the executed command. See
-// http://www.freedesktop.org/software/systemd/man/systemd.service.html#ExecStart=
-func PropExecStart(command []string, uncleanIsFailure bool) Property {
- execStarts := []execStart{
- execStart{
- Path: command[0],
- Args: command,
- UncleanIsFailure: uncleanIsFailure,
- },
- }
-
- return Property{
- Name: "ExecStart",
- Value: dbus.MakeVariant(execStarts),
- }
-}
-
-// PropRemainAfterExit sets the RemainAfterExit service property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.service.html#RemainAfterExit=
-func PropRemainAfterExit(b bool) Property {
- return Property{
- Name: "RemainAfterExit",
- Value: dbus.MakeVariant(b),
- }
-}
-
-// PropDescription sets the Description unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit#Description=
-func PropDescription(desc string) Property {
- return Property{
- Name: "Description",
- Value: dbus.MakeVariant(desc),
- }
-}
-
-func propDependency(name string, units []string) Property {
- return Property{
- Name: name,
- Value: dbus.MakeVariant(units),
- }
-}
-
-// PropRequires sets the Requires unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Requires=
-func PropRequires(units ...string) Property {
- return propDependency("Requires", units)
-}
-
-// PropRequiresOverridable sets the RequiresOverridable unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiresOverridable=
-func PropRequiresOverridable(units ...string) Property {
- return propDependency("RequiresOverridable", units)
-}
-
-// PropRequisite sets the Requisite unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Requisite=
-func PropRequisite(units ...string) Property {
- return propDependency("Requisite", units)
-}
-
-// PropRequisiteOverridable sets the RequisiteOverridable unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequisiteOverridable=
-func PropRequisiteOverridable(units ...string) Property {
- return propDependency("RequisiteOverridable", units)
-}
-
-// PropWants sets the Wants unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Wants=
-func PropWants(units ...string) Property {
- return propDependency("Wants", units)
-}
-
-// PropBindsTo sets the BindsTo unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#BindsTo=
-func PropBindsTo(units ...string) Property {
- return propDependency("BindsTo", units)
-}
-
-// PropRequiredBy sets the RequiredBy unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiredBy=
-func PropRequiredBy(units ...string) Property {
- return propDependency("RequiredBy", units)
-}
-
-// PropRequiredByOverridable sets the RequiredByOverridable unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiredByOverridable=
-func PropRequiredByOverridable(units ...string) Property {
- return propDependency("RequiredByOverridable", units)
-}
-
-// PropWantedBy sets the WantedBy unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#WantedBy=
-func PropWantedBy(units ...string) Property {
- return propDependency("WantedBy", units)
-}
-
-// PropBoundBy sets the BoundBy unit property. See
-// http://www.freedesktop.org/software/systemd/main/systemd.unit.html#BoundBy=
-func PropBoundBy(units ...string) Property {
- return propDependency("BoundBy", units)
-}
-
-// PropConflicts sets the Conflicts unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Conflicts=
-func PropConflicts(units ...string) Property {
- return propDependency("Conflicts", units)
-}
-
-// PropConflictedBy sets the ConflictedBy unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#ConflictedBy=
-func PropConflictedBy(units ...string) Property {
- return propDependency("ConflictedBy", units)
-}
-
-// PropBefore sets the Before unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Before=
-func PropBefore(units ...string) Property {
- return propDependency("Before", units)
-}
-
-// PropAfter sets the After unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#After=
-func PropAfter(units ...string) Property {
- return propDependency("After", units)
-}
-
-// PropOnFailure sets the OnFailure unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#OnFailure=
-func PropOnFailure(units ...string) Property {
- return propDependency("OnFailure", units)
-}
-
-// PropTriggers sets the Triggers unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#Triggers=
-func PropTriggers(units ...string) Property {
- return propDependency("Triggers", units)
-}
-
-// PropTriggeredBy sets the TriggeredBy unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#TriggeredBy=
-func PropTriggeredBy(units ...string) Property {
- return propDependency("TriggeredBy", units)
-}
-
-// PropPropagatesReloadTo sets the PropagatesReloadTo unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#PropagatesReloadTo=
-func PropPropagatesReloadTo(units ...string) Property {
- return propDependency("PropagatesReloadTo", units)
-}
-
-// PropRequiresMountsFor sets the RequiresMountsFor unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.unit.html#RequiresMountsFor=
-func PropRequiresMountsFor(units ...string) Property {
- return propDependency("RequiresMountsFor", units)
-}
-
-// PropSlice sets the Slice unit property. See
-// http://www.freedesktop.org/software/systemd/man/systemd.resource-control.html#Slice=
-func PropSlice(slice string) Property {
- return Property{
- Name: "Slice",
- Value: dbus.MakeVariant(slice),
- }
-}
diff --git a/containerd/vendor/github.com/coreos/go-systemd/dbus/set.go b/containerd/vendor/github.com/coreos/go-systemd/dbus/set.go
deleted file mode 100644
index f92e6fb..0000000
--- a/containerd/vendor/github.com/coreos/go-systemd/dbus/set.go
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright 2015 CoreOS, 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
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package dbus
-
-type set struct {
- data map[string]bool
-}
-
-func (s *set) Add(value string) {
- s.data[value] = true
-}
-
-func (s *set) Remove(value string) {
- delete(s.data, value)
-}
-
-func (s *set) Contains(value string) (exists bool) {
- _, exists = s.data[value]
- return
-}
-
-func (s *set) Length() int {
- return len(s.data)
-}
-
-func (s *set) Values() (values []string) {
- for val, _ := range s.data {
- values = append(values, val)
- }
- return
-}
-
-func newSet() *set {
- return &set{make(map[string]bool)}
-}
diff --git a/containerd/vendor/github.com/coreos/go-systemd/dbus/subscription.go b/containerd/vendor/github.com/coreos/go-systemd/dbus/subscription.go
deleted file mode 100644
index 9964514..0000000
--- a/containerd/vendor/github.com/coreos/go-systemd/dbus/subscription.go
+++ /dev/null
@@ -1,250 +0,0 @@
-// Copyright 2015 CoreOS, 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
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package dbus
-
-import (
- "errors"
- "time"
-
- "github.com/godbus/dbus"
-)
-
-const (
- cleanIgnoreInterval = int64(10 * time.Second)
- ignoreInterval = int64(30 * time.Millisecond)
-)
-
-// Subscribe sets up this connection to subscribe to all systemd dbus events.
-// This is required before calling SubscribeUnits. When the connection closes
-// systemd will automatically stop sending signals so there is no need to
-// explicitly call Unsubscribe().
-func (c *Conn) Subscribe() error {
- c.sigconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0,
- "type='signal',interface='org.freedesktop.systemd1.Manager',member='UnitNew'")
- c.sigconn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0,
- "type='signal',interface='org.freedesktop.DBus.Properties',member='PropertiesChanged'")
-
- err := c.sigobj.Call("org.freedesktop.systemd1.Manager.Subscribe", 0).Store()
- if err != nil {
- return err
- }
-
- return nil
-}
-
-// Unsubscribe this connection from systemd dbus events.
-func (c *Conn) Unsubscribe() error {
- err := c.sigobj.Call("org.freedesktop.systemd1.Manager.Unsubscribe", 0).Store()
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func (c *Conn) dispatch() {
- ch := make(chan *dbus.Signal, signalBuffer)
-
- c.sigconn.Signal(ch)
-
- go func() {
- for {
- signal, ok := <-ch
- if !ok {
- return
- }
-
- if signal.Name == "org.freedesktop.systemd1.Manager.JobRemoved" {
- c.jobComplete(signal)
- }
-
- if c.subscriber.updateCh == nil {
- continue
- }
-
- var unitPath dbus.ObjectPath
- switch signal.Name {
- case "org.freedesktop.systemd1.Manager.JobRemoved":
- unitName := signal.Body[2].(string)
- c.sysobj.Call("org.freedesktop.systemd1.Manager.GetUnit", 0, unitName).Store(&unitPath)
- case "org.freedesktop.systemd1.Manager.UnitNew":
- unitPath = signal.Body[1].(dbus.ObjectPath)
- case "org.freedesktop.DBus.Properties.PropertiesChanged":
- if signal.Body[0].(string) == "org.freedesktop.systemd1.Unit" {
- unitPath = signal.Path
- }
- }
-
- if unitPath == dbus.ObjectPath("") {
- continue
- }
-
- c.sendSubStateUpdate(unitPath)
- }
- }()
-}
-
-// Returns two unbuffered channels which will receive all changed units every
-// interval. Deleted units are sent as nil.
-func (c *Conn) SubscribeUnits(interval time.Duration) (<-chan map[string]*UnitStatus, <-chan error) {
- return c.SubscribeUnitsCustom(interval, 0, func(u1, u2 *UnitStatus) bool { return *u1 != *u2 }, nil)
-}
-
-// SubscribeUnitsCustom is like SubscribeUnits but lets you specify the buffer
-// size of the channels, the comparison function for detecting changes and a filter
-// function for cutting down on the noise that your channel receives.
-func (c *Conn) SubscribeUnitsCustom(interval time.Duration, buffer int, isChanged func(*UnitStatus, *UnitStatus) bool, filterUnit func(string) bool) (<-chan map[string]*UnitStatus, <-chan error) {
- old := make(map[string]*UnitStatus)
- statusChan := make(chan map[string]*UnitStatus, buffer)
- errChan := make(chan error, buffer)
-
- go func() {
- for {
- timerChan := time.After(interval)
-
- units, err := c.ListUnits()
- if err == nil {
- cur := make(map[string]*UnitStatus)
- for i := range units {
- if filterUnit != nil && filterUnit(units[i].Name) {
- continue
- }
- cur[units[i].Name] = &units[i]
- }
-
- // add all new or changed units
- changed := make(map[string]*UnitStatus)
- for n, u := range cur {
- if oldU, ok := old[n]; !ok || isChanged(oldU, u) {
- changed[n] = u
- }
- delete(old, n)
- }
-
- // add all deleted units
- for oldN := range old {
- changed[oldN] = nil
- }
-
- old = cur
-
- if len(changed) != 0 {
- statusChan <- changed
- }
- } else {
- errChan <- err
- }
-
- <-timerChan
- }
- }()
-
- return statusChan, errChan
-}
-
-type SubStateUpdate struct {
- UnitName string
- SubState string
-}
-
-// SetSubStateSubscriber writes to updateCh when any unit's substate changes.
-// Although this writes to updateCh on every state change, the reported state
-// may be more recent than the change that generated it (due to an unavoidable
-// race in the systemd dbus interface). That is, this method provides a good
-// way to keep a current view of all units' states, but is not guaranteed to
-// show every state transition they go through. Furthermore, state changes
-// will only be written to the channel with non-blocking writes. If updateCh
-// is full, it attempts to write an error to errCh; if errCh is full, the error
-// passes silently.
-func (c *Conn) SetSubStateSubscriber(updateCh chan<- *SubStateUpdate, errCh chan<- error) {
- c.subscriber.Lock()
- defer c.subscriber.Unlock()
- c.subscriber.updateCh = updateCh
- c.subscriber.errCh = errCh
-}
-
-func (c *Conn) sendSubStateUpdate(path dbus.ObjectPath) {
- c.subscriber.Lock()
- defer c.subscriber.Unlock()
-
- if c.shouldIgnore(path) {
- return
- }
-
- info, err := c.GetUnitProperties(string(path))
- if err != nil {
- select {
- case c.subscriber.errCh <- err:
- default:
- }
- }
-
- name := info["Id"].(string)
- substate := info["SubState"].(string)
-
- update := &SubStateUpdate{name, substate}
- select {
- case c.subscriber.updateCh <- update:
- default:
- select {
- case c.subscriber.errCh <- errors.New("update channel full!"):
- default:
- }
- }
-
- c.updateIgnore(path, info)
-}
-
-// The ignore functions work around a wart in the systemd dbus interface.
-// Requesting the properties of an unloaded unit will cause systemd to send a
-// pair of UnitNew/UnitRemoved signals. Because we need to get a unit's
-// properties on UnitNew (as that's the only indication of a new unit coming up
-// for the first time), we would enter an infinite loop if we did not attempt
-// to detect and ignore these spurious signals. The signal themselves are
-// indistinguishable from relevant ones, so we (somewhat hackishly) ignore an
-// unloaded unit's signals for a short time after requesting its properties.
-// This means that we will miss e.g. a transient unit being restarted
-// *immediately* upon failure and also a transient unit being started
-// immediately after requesting its status (with systemctl status, for example,
-// because this causes a UnitNew signal to be sent which then causes us to fetch
-// the properties).
-
-func (c *Conn) shouldIgnore(path dbus.ObjectPath) bool {
- t, ok := c.subscriber.ignore[path]
- return ok && t >= time.Now().UnixNano()
-}
-
-func (c *Conn) updateIgnore(path dbus.ObjectPath, info map[string]interface{}) {
- c.cleanIgnore()
-
- // unit is unloaded - it will trigger bad systemd dbus behavior
- if info["LoadState"].(string) == "not-found" {
- c.subscriber.ignore[path] = time.Now().UnixNano() + ignoreInterval
- }
-}
-
-// without this, ignore would grow unboundedly over time
-func (c *Conn) cleanIgnore() {
- now := time.Now().UnixNano()
- if c.subscriber.cleanIgnore < now {
- c.subscriber.cleanIgnore = now + cleanIgnoreInterval
-
- for p, t := range c.subscriber.ignore {
- if t < now {
- delete(c.subscriber.ignore, p)
- }
- }
- }
-}
diff --git a/containerd/vendor/github.com/coreos/go-systemd/dbus/subscription_set.go b/containerd/vendor/github.com/coreos/go-systemd/dbus/subscription_set.go
deleted file mode 100644
index 5b408d5..0000000
--- a/containerd/vendor/github.com/coreos/go-systemd/dbus/subscription_set.go
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright 2015 CoreOS, 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
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package dbus
-
-import (
- "time"
-)
-
-// SubscriptionSet returns a subscription set which is like conn.Subscribe but
-// can filter to only return events for a set of units.
-type SubscriptionSet struct {
- *set
- conn *Conn
-}
-
-func (s *SubscriptionSet) filter(unit string) bool {
- return !s.Contains(unit)
-}
-
-// Subscribe starts listening for dbus events for all of the units in the set.
-// Returns channels identical to conn.SubscribeUnits.
-func (s *SubscriptionSet) Subscribe() (<-chan map[string]*UnitStatus, <-chan error) {
- // TODO: Make fully evented by using systemd 209 with properties changed values
- return s.conn.SubscribeUnitsCustom(time.Second, 0,
- mismatchUnitStatus,
- func(unit string) bool { return s.filter(unit) },
- )
-}
-
-// NewSubscriptionSet returns a new subscription set.
-func (conn *Conn) NewSubscriptionSet() *SubscriptionSet {
- return &SubscriptionSet{newSet(), conn}
-}
-
-// mismatchUnitStatus returns true if the provided UnitStatus objects
-// are not equivalent. false is returned if the objects are equivalent.
-// Only the Name, Description and state-related fields are used in
-// the comparison.
-func mismatchUnitStatus(u1, u2 *UnitStatus) bool {
- return u1.Name != u2.Name ||
- u1.Description != u2.Description ||
- u1.LoadState != u2.LoadState ||
- u1.ActiveState != u2.ActiveState ||
- u1.SubState != u2.SubState
-}
diff --git a/containerd/vendor/github.com/coreos/go-systemd/util/util.go b/containerd/vendor/github.com/coreos/go-systemd/util/util.go
deleted file mode 100644
index 33832a1..0000000
--- a/containerd/vendor/github.com/coreos/go-systemd/util/util.go
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright 2015 CoreOS, 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
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// Package util contains utility functions related to systemd that applications
-// can use to check things like whether systemd is running.
-package util
-
-import (
- "os"
-)
-
-// IsRunningSystemd checks whether the host was booted with systemd as its init
-// system. This functions similar to systemd's `sd_booted(3)`: internally, it
-// checks whether /run/systemd/system/ exists and is a directory.
-// http://www.freedesktop.org/software/systemd/man/sd_booted.html
-func IsRunningSystemd() bool {
- fi, err := os.Lstat("/run/systemd/system")
- if err != nil {
- return false
- }
- return fi.IsDir()
-}
diff --git a/containerd/vendor/github.com/docker/containerd/.gitignore b/containerd/vendor/github.com/docker/containerd/.gitignore
deleted file mode 100644
index 280ae01..0000000
--- a/containerd/vendor/github.com/docker/containerd/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-containerd/containerd
-bin/
diff --git a/containerd/vendor/github.com/docker/containerd/README.md b/containerd/vendor/github.com/docker/containerd/README.md
deleted file mode 100644
index 0533719..0000000
--- a/containerd/vendor/github.com/docker/containerd/README.md
+++ /dev/null
@@ -1,79 +0,0 @@
-# containerd
-
-another container runtime
-
-Start a container:
-
-```bash
-curl -XPOST localhost:8888/containers/redis -d '{"bundlePath": "/containers/redis"}'
-```
-
-Add a process:
-
-```bash
-curl -s -XPUT localhost:8888/containers/redis/process -d@process.json | json_pp
-{
- "pid" : 25671,
- "user" : {
- "gid" : 0,
- "uid" : 0
- },
- "args" : [
- "sh",
- "-c",
- "sleep 10"
- ],
- "env" : [
- "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
- "TERM=xterm"
- ]
-}
-```
-
-
-Get containers:
-
-```bash
-curl -s localhost:8888/containers | json_pp
-{
- "containers" : [
- {
- "processes" : [
- {
- "args" : [
- "sh",
- "-c",
- "sleep 60"
- ],
- "user" : {
- "gid" : 0,
- "uid" : 0
- },
- "pid" : 25743,
- "env" : [
- "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
- "TERM=xterm"
- ]
- }
- ],
- "id" : "redis",
- "state" : {
- "status" : "running"
- },
- "bundlePath" : "/containers/redis"
- }
- ]
-}
-
-```
-
-Other stuff:
-
-```bash
-# pause and resume a container
-curl -XPATCH localhost:8888/containers/redis -d '{"status": "paused"}'
-curl -XPATCH localhost:8888/containers/redis -d '{"status": "running"}'
-
-# send signal to a container's specific process
-curl -XPOST localhost:8888/containers/redis/process/18306 -d '{"signal": 9}'
-```
diff --git a/containerd/vendor/github.com/docker/containerd/api/v1/server.go b/containerd/vendor/github.com/docker/containerd/api/v1/server.go
deleted file mode 100644
index 53d4d0f..0000000
--- a/containerd/vendor/github.com/docker/containerd/api/v1/server.go
+++ /dev/null
@@ -1,230 +0,0 @@
-package v1
-
-import (
- "encoding/json"
- "net/http"
- "strconv"
- "syscall"
-
- "github.com/Sirupsen/logrus"
- "github.com/docker/containerd"
- "github.com/gorilla/mux"
- "github.com/opencontainers/specs"
-)
-
-func NewServer(supervisor *containerd.Supervisor) http.Handler {
- r := mux.NewRouter()
- s := &server{
- supervisor: supervisor,
- r: r,
- }
- // TODO: add container stats
- // TODO: add container checkpoint
- // TODO: add container restore
- // TODO: set prctl child subreaper
- r.HandleFunc("/containers/{id:.*}/process/{pid:.*}", s.signalPid).Methods("POST")
- r.HandleFunc("/containers/{id:.*}/process", s.addProcess).Methods("PUT")
- r.HandleFunc("/containers/{id:.*}", s.createContainer).Methods("POST")
- r.HandleFunc("/containers/{id:.*}", s.updateContainer).Methods("PATCH")
- r.HandleFunc("/event", s.event).Methods("POST")
- r.HandleFunc("/containers", s.containers).Methods("GET")
- return s
-}
-
-type server struct {
- r *mux.Router
- supervisor *containerd.Supervisor
-}
-
-// TODO: implement correct shutdown
-func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- s.r.ServeHTTP(w, r)
-}
-
-func (s *server) updateContainer(w http.ResponseWriter, r *http.Request) {
- id := mux.Vars(r)["id"]
- var state ContainerState
- if err := json.NewDecoder(r.Body).Decode(&state); err != nil {
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
- e := containerd.NewEvent(containerd.UpdateContainerEventType)
- e.ID = id
- e.State = &containerd.State{
- Status: containerd.Status(string(state.Status)),
- }
- s.supervisor.SendEvent(e)
- if err := <-e.Err; err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
-}
-
-func (s *server) event(w http.ResponseWriter, r *http.Request) {
- var e containerd.Event
- if err := json.NewDecoder(r.Body).Decode(&e); err != nil {
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
- e.Err = make(chan error, 1)
- s.supervisor.SendEvent(&e)
- if err := <-e.Err; err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
- if e.Containers != nil && len(e.Containers) > 0 {
- if err := writeContainers(w, &e); err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
- }
-}
-
-func (s *server) addProcess(w http.ResponseWriter, r *http.Request) {
- id := mux.Vars(r)["id"]
- var process specs.Process
- if err := json.NewDecoder(r.Body).Decode(&process); err != nil {
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
- e := containerd.NewEvent(containerd.AddProcessEventType)
- e.ID = id
- e.Process = &process
- s.supervisor.SendEvent(e)
- if err := <-e.Err; err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
- p := Process{
- Pid: e.Pid,
- Terminal: process.Terminal,
- Args: process.Args,
- Env: process.Env,
- Cwd: process.Cwd,
- }
- p.User.UID = process.User.UID
- p.User.GID = process.User.GID
- p.User.AdditionalGids = process.User.AdditionalGids
- if err := json.NewEncoder(w).Encode(p); err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
-}
-
-func (s *server) signalPid(w http.ResponseWriter, r *http.Request) {
- var (
- vars = mux.Vars(r)
- id = vars["id"]
- spid = vars["pid"]
- )
- pid, err := strconv.Atoi(spid)
- if err != nil {
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
- var signal Signal
- if err := json.NewDecoder(r.Body).Decode(&signal); err != nil {
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
-
- e := containerd.NewEvent(containerd.SignalEventType)
- e.ID = id
- e.Pid = pid
- e.Signal = syscall.Signal(signal.Signal)
- s.supervisor.SendEvent(e)
- if err := <-e.Err; err != nil {
- status := http.StatusInternalServerError
- if err == containerd.ErrContainerNotFound {
- status = http.StatusNotFound
- }
- http.Error(w, err.Error(), status)
- return
- }
-}
-
-func (s *server) containers(w http.ResponseWriter, r *http.Request) {
- e := containerd.NewEvent(containerd.GetContainerEventType)
- s.supervisor.SendEvent(e)
- if err := <-e.Err; err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
- if err := writeContainers(w, e); err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
-}
-
-func writeContainers(w http.ResponseWriter, e *containerd.Event) error {
- var state State
- state.Containers = []Container{}
- for _, c := range e.Containers {
- processes, err := c.Processes()
- if err != nil {
- logrus.WithFields(logrus.Fields{
- "error": err,
- "container": c.ID(),
- }).Error("get processes for container")
- }
- var pids []Process
- for _, p := range processes {
- proc := createProcess(p)
- pids = append(pids, proc)
- }
- state.Containers = append(state.Containers, Container{
- ID: c.ID(),
- BundlePath: c.Path(),
- Processes: pids,
- State: &ContainerState{
- Status: Status(c.State().Status),
- },
- })
- }
- return json.NewEncoder(w).Encode(&state)
-}
-
-func createProcess(in containerd.Process) Process {
- pid, err := in.Pid()
- if err != nil {
- logrus.WithField("error", err).Error("get process pid")
- }
- process := in.Spec()
- p := Process{
- Pid: pid,
- Terminal: process.Terminal,
- Args: process.Args,
- Env: process.Env,
- Cwd: process.Cwd,
- }
- p.User.UID = process.User.UID
- p.User.GID = process.User.GID
- p.User.AdditionalGids = process.User.AdditionalGids
- return p
-}
-
-func (s *server) createContainer(w http.ResponseWriter, r *http.Request) {
- id := mux.Vars(r)["id"]
- var c Container
- if err := json.NewDecoder(r.Body).Decode(&c); err != nil {
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
- if c.BundlePath == "" {
- http.Error(w, "empty bundle path", http.StatusBadRequest)
- return
- }
- e := containerd.NewEvent(containerd.StartContainerEventType)
- e.ID = id
- e.BundlePath = c.BundlePath
- s.supervisor.SendEvent(e)
- if err := <-e.Err; err != nil {
- code := http.StatusInternalServerError
- if err == containerd.ErrBundleNotFound {
- code = http.StatusNotFound
- }
- http.Error(w, err.Error(), code)
- return
- }
- w.WriteHeader(http.StatusCreated)
-}
diff --git a/containerd/vendor/github.com/docker/containerd/api/v1/types.go b/containerd/vendor/github.com/docker/containerd/api/v1/types.go
deleted file mode 100644
index 2dfc8bb..0000000
--- a/containerd/vendor/github.com/docker/containerd/api/v1/types.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package v1
-
-type State struct {
- Containers []Container `json:"containers"`
-}
-
-type Status string
-
-const (
- Paused Status = "paused"
- Running Status = "running"
-)
-
-type ContainerState struct {
- Status Status `json:"status,omitempty"`
-}
-
-type Container struct {
- ID string `json:"id,omitempty"`
- BundlePath string `json:"bundlePath,omitempty"`
- Processes []Process `json:"processes,omitempty"`
- State *ContainerState `json:"state,omitempty"`
-}
-
-type User struct {
- UID uint32 `json:"uid"`
- GID uint32 `json:"gid"`
- AdditionalGids []uint32 `json:"additionalGids,omitempty"`
-}
-
-type Process struct {
- Terminal bool `json:"terminal,omitempty"`
- User User `json:"user,omitempty"`
- Args []string `json:"args,omitempty"`
- Env []string `json:"env,omitempty"`
- Cwd string `json:"cwd,omitempty"`
- Pid int `json:"pid,omitempty"`
-}
-
-type Signal struct {
- Signal int `json:"signal"`
-}
diff --git a/containerd/vendor/github.com/docker/containerd/container.go b/containerd/vendor/github.com/docker/containerd/container.go
deleted file mode 100644
index cb520e3..0000000
--- a/containerd/vendor/github.com/docker/containerd/container.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package containerd
-
-import (
- "os"
-
- "github.com/opencontainers/specs"
-)
-
-type Process interface {
- Pid() (int, error)
- Spec() specs.Process
- Signal(os.Signal) error
-}
-type Status string
-
-const (
- Paused Status = "paused"
- Running Status = "running"
-)
-
-type State struct {
- Status Status `json:"status,omitempty"`
-}
-
-type Container interface {
- ID() string
- Start() error
- Path() string
- Pid() (int, error)
- SetExited(status int)
- Delete() error
- Processes() ([]Process, error)
- RemoveProcess(pid int) error
- State() State
- Resume() error
- Pause() error
-}
diff --git a/containerd/vendor/github.com/docker/containerd/containerd/Makefile b/containerd/vendor/github.com/docker/containerd/containerd/Makefile
deleted file mode 100644
index 5bc14d0..0000000
--- a/containerd/vendor/github.com/docker/containerd/containerd/Makefile
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-all:
- godep go build -tags libcontainer
-
-
diff --git a/containerd/vendor/github.com/docker/containerd/containerd/daemon.go b/containerd/vendor/github.com/docker/containerd/containerd/daemon.go
deleted file mode 100644
index 3519b25..0000000
--- a/containerd/vendor/github.com/docker/containerd/containerd/daemon.go
+++ /dev/null
@@ -1,109 +0,0 @@
-package main
-
-import (
- "log"
- "net/http"
- "os"
- "os/signal"
- "runtime"
- "syscall"
- "time"
-
- "github.com/Sirupsen/logrus"
- "github.com/codegangsta/cli"
- "github.com/docker/containerd"
- "github.com/docker/containerd/api/v1"
- "github.com/opencontainers/runc/libcontainer/utils"
- "github.com/rcrowley/go-metrics"
-)
-
-var DaemonCommand = cli.Command{
- Name: "daemon",
- Flags: []cli.Flag{
- cli.StringFlag{
- Name: "state-dir",
- Value: "/run/containerd",
- Usage: "runtime state directory",
- },
- cli.IntFlag{
- Name: "buffer-size",
- Value: 2048,
- Usage: "set the channel buffer size for events and signals",
- },
- },
- Action: func(context *cli.Context) {
- if context.GlobalBool("debug") {
- l := log.New(os.Stdout, "[containerd] ", log.LstdFlags)
- goRoutineCounter := metrics.NewGauge()
- metrics.DefaultRegistry.Register("goroutines", goRoutineCounter)
- go func() {
- for range time.Tick(30 * time.Second) {
- goRoutineCounter.Update(int64(runtime.NumGoroutine()))
- }
- }()
- go metrics.Log(metrics.DefaultRegistry, 60*time.Second, l)
- }
- if err := daemon(context.String("state-dir"), 10, context.Int("buffer-size")); err != nil {
- logrus.Fatal(err)
- }
- },
-}
-
-func daemon(stateDir string, concurrency, bufferSize int) error {
- supervisor, err := containerd.NewSupervisor(stateDir, concurrency)
- if err != nil {
- return err
- }
- events := make(chan *containerd.Event, bufferSize)
- // start the signal handler in the background.
- go startSignalHandler(supervisor, bufferSize)
- if err := supervisor.Start(events); err != nil {
- return err
- }
- server := v1.NewServer(supervisor)
- return http.ListenAndServe("localhost:8888", server)
-}
-
-func startSignalHandler(supervisor *containerd.Supervisor, bufferSize int) {
- logrus.Debug("containerd: starting signal handler")
- signals := make(chan os.Signal, bufferSize)
- signal.Notify(signals)
- for s := range signals {
- switch s {
- case syscall.SIGTERM, syscall.SIGINT, syscall.SIGSTOP:
- supervisor.Close()
- os.Exit(0)
- case syscall.SIGCHLD:
- exits, err := reap()
- if err != nil {
- logrus.WithField("error", err).Error("containerd: reaping child processes")
- }
- for _, e := range exits {
- supervisor.SendEvent(e)
- }
- }
- }
-}
-
-func reap() (exits []*containerd.Event, err error) {
- var (
- ws syscall.WaitStatus
- rus syscall.Rusage
- )
- for {
- pid, err := syscall.Wait4(-1, &ws, syscall.WNOHANG, &rus)
- if err != nil {
- if err == syscall.ECHILD {
- return exits, nil
- }
- return exits, err
- }
- if pid <= 0 {
- return exits, nil
- }
- e := containerd.NewEvent(containerd.ExitEventType)
- e.Pid = pid
- e.Status = utils.ExitStatus(ws)
- exits = append(exits, e)
- }
-}
diff --git a/containerd/vendor/github.com/docker/containerd/containerd/journal.go b/containerd/vendor/github.com/docker/containerd/containerd/journal.go
deleted file mode 100644
index 1bbd0c8..0000000
--- a/containerd/vendor/github.com/docker/containerd/containerd/journal.go
+++ /dev/null
@@ -1,85 +0,0 @@
-package main
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "os"
- "path/filepath"
-
- "github.com/Sirupsen/logrus"
- "github.com/codegangsta/cli"
- "github.com/docker/containerd"
-)
-
-var JournalCommand = cli.Command{
- Name: "journal",
- Usage: "interact with the containerd journal",
- Subcommands: []cli.Command{
- JournalReplyCommand,
- },
-}
-
-var JournalReplyCommand = cli.Command{
- Name: "replay",
- Usage: "replay a journal to get containerd's state syncronized after a crash",
- Flags: []cli.Flag{
- cli.StringFlag{
- Name: "addr",
- Value: "localhost:8888",
- Usage: "address of the containerd daemon",
- },
- },
- Action: func(context *cli.Context) {
- if err := replay(context.Args().First(), context.String("addr")); err != nil {
- logrus.Fatal(err)
- }
- },
-}
-
-func replay(path, addr string) error {
- f, err := os.Open(path)
- if err != nil {
- return err
- }
- defer f.Close()
- dec := json.NewDecoder(f)
- var events []*containerd.Event
- type entry struct {
- Event *containerd.Event `json:"event"`
- }
- for dec.More() {
- var e entry
- if err := dec.Decode(&e); err != nil {
- if err == io.EOF {
- break
- }
- return err
- }
- events = append(events, e.Event)
- }
- c := &http.Client{}
- for _, e := range events {
- switch e.Type {
- case containerd.ExitEventType, containerd.DeleteEventType:
- // ignore these types of events
- continue
- }
- data, err := json.Marshal(e)
- if err != nil {
- return err
- }
- fmt.Printf("sending %q event\n", e.Type)
- r, err := c.Post("http://"+filepath.Join(addr, "event"), "application/json", bytes.NewBuffer(data))
- if err != nil {
- return err
- }
- if r.Body != nil {
- io.Copy(os.Stdout, r.Body)
- r.Body.Close()
- }
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/docker/containerd/containerd/main.go b/containerd/vendor/github.com/docker/containerd/containerd/main.go
deleted file mode 100644
index eae2d81..0000000
--- a/containerd/vendor/github.com/docker/containerd/containerd/main.go
+++ /dev/null
@@ -1,43 +0,0 @@
-package main
-
-import (
- "os"
-
- "github.com/Sirupsen/logrus"
- "github.com/codegangsta/cli"
-)
-
-const (
- Version = "0.0.1"
- Usage = `High performance conatiner daemon`
-)
-
-func main() {
- app := cli.NewApp()
- app.Name = "containerd"
- app.Version = Version
- app.Usage = Usage
- app.Authors = []cli.Author{
- {
- Name: "@crosbymichael",
- Email: "crosbymichael@gmail.com",
- },
- }
- app.Commands = []cli.Command{
- DaemonCommand,
- JournalCommand,
- }
- app.Flags = []cli.Flag{
- cli.BoolFlag{Name: "debug", Usage: "enable debug output in the logs"},
- // cli.StringFlag{Name: "metrics", Value: "stdout", Usage: "metrics file"},
- }
- app.Before = func(context *cli.Context) error {
- if context.GlobalBool("debug") {
- logrus.SetLevel(logrus.DebugLevel)
- }
- return nil
- }
- if err := app.Run(os.Args); err != nil {
- logrus.Fatal(err)
- }
-}
diff --git a/containerd/vendor/github.com/docker/containerd/errors.go b/containerd/vendor/github.com/docker/containerd/errors.go
deleted file mode 100644
index 65bbaf5..0000000
--- a/containerd/vendor/github.com/docker/containerd/errors.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package containerd
-
-import "errors"
-
-var (
- // External errors
- ErrEventChanNil = errors.New("containerd: event channel is nil")
- ErrBundleNotFound = errors.New("containerd: bundle not found")
- ErrContainerNotFound = errors.New("containerd: container not found")
- ErrContainerExists = errors.New("containerd: container already exists")
- ErrProcessNotFound = errors.New("containerd: processs not found for container")
- ErrUnknownContainerStatus = errors.New("containerd: unknown container status ")
-
- // Internal errors
- errShutdown = errors.New("containerd: supervisor is shutdown")
- errRootNotAbs = errors.New("containerd: rootfs path is not an absolute path")
- errNoContainerForPid = errors.New("containerd: pid not registered for any container")
- errInvalidContainerType = errors.New("containerd: invalid container type for runtime")
- errNotChildProcess = errors.New("containerd: not a child process for container")
-)
diff --git a/containerd/vendor/github.com/docker/containerd/event.go b/containerd/vendor/github.com/docker/containerd/event.go
deleted file mode 100644
index f4735dd..0000000
--- a/containerd/vendor/github.com/docker/containerd/event.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package containerd
-
-import (
- "os"
- "time"
-
- "github.com/opencontainers/specs"
-)
-
-type EventType string
-
-const (
- ExitEventType EventType = "exit"
- StartContainerEventType EventType = "startContainer"
- DeleteEventType EventType = "deleteContainerEvent"
- GetContainerEventType EventType = "getContainer"
- SignalEventType EventType = "signal"
- AddProcessEventType EventType = "addProcess"
- UpdateContainerEventType EventType = "updateContainer"
-)
-
-func NewEvent(t EventType) *Event {
- return &Event{
- Type: t,
- Timestamp: time.Now(),
- Err: make(chan error, 1),
- }
-}
-
-type Event struct {
- Type EventType `json:"type"`
- Timestamp time.Time `json:"timestamp"`
- ID string `json:"id,omitempty"`
- BundlePath string `json:"bundlePath,omitempty"`
- Pid int `json:"pid,omitempty"`
- Status int `json:"status,omitempty"`
- Signal os.Signal `json:"signal,omitempty"`
- Process *specs.Process `json:"process,omitempty"`
- State *State `json:"state,omitempty"`
- Containers []Container `json:"-"`
- Err chan error `json:"-"`
-}
diff --git a/containerd/vendor/github.com/docker/containerd/journal.go b/containerd/vendor/github.com/docker/containerd/journal.go
deleted file mode 100644
index 5889f0f..0000000
--- a/containerd/vendor/github.com/docker/containerd/journal.go
+++ /dev/null
@@ -1,41 +0,0 @@
-package containerd
-
-import (
- "encoding/json"
- "os"
- "path/filepath"
-)
-
-type entry struct {
- Event *Event `json:"event"`
-}
-
-func newJournal(path string) (*journal, error) {
- if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
- return nil, err
- }
- f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0755)
- if err != nil {
- return nil, err
- }
- return &journal{
- f: f,
- enc: json.NewEncoder(f),
- }, nil
-}
-
-type journal struct {
- f *os.File
- enc *json.Encoder
-}
-
-func (j *journal) write(e *Event) error {
- et := &entry{
- Event: e,
- }
- return j.enc.Encode(et)
-}
-
-func (j *journal) Close() error {
- return j.f.Close()
-}
diff --git a/containerd/vendor/github.com/docker/containerd/runtime.go b/containerd/vendor/github.com/docker/containerd/runtime.go
deleted file mode 100644
index 72daf9a..0000000
--- a/containerd/vendor/github.com/docker/containerd/runtime.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package containerd
-
-import "github.com/opencontainers/specs"
-
-// runtime handles containers, containers handle their own actions.
-type Runtime interface {
- Create(id, bundlePath string) (Container, error)
- StartProcess(Container, specs.Process) (Process, error)
-}
diff --git a/containerd/vendor/github.com/docker/containerd/runtime_linux.go b/containerd/vendor/github.com/docker/containerd/runtime_linux.go
deleted file mode 100644
index c840280..0000000
--- a/containerd/vendor/github.com/docker/containerd/runtime_linux.go
+++ /dev/null
@@ -1,755 +0,0 @@
-// +build libcontainer
-
-package containerd
-
-import (
- "encoding/json"
- "fmt"
- "os"
- "path/filepath"
- "runtime"
- "strconv"
- "strings"
- "syscall"
-
- "github.com/opencontainers/runc/libcontainer"
- "github.com/opencontainers/runc/libcontainer/configs"
- _ "github.com/opencontainers/runc/libcontainer/nsenter"
- "github.com/opencontainers/runc/libcontainer/seccomp"
- "github.com/opencontainers/specs"
-)
-
-const (
- RLIMIT_CPU = iota // CPU time in sec
- RLIMIT_FSIZE // Maximum filesize
- RLIMIT_DATA // max data size
- RLIMIT_STACK // max stack size
- RLIMIT_CORE // max core file size
- RLIMIT_RSS // max resident set size
- RLIMIT_NPROC // max number of processes
- RLIMIT_NOFILE // max number of open files
- RLIMIT_MEMLOCK // max locked-in-memory address space
- RLIMIT_AS // address space limit
- RLIMIT_LOCKS // maximum file locks held
- RLIMIT_SIGPENDING // max number of pending signals
- RLIMIT_MSGQUEUE // maximum bytes in POSIX mqueues
- RLIMIT_NICE // max nice prio allowed to raise to
- RLIMIT_RTPRIO // maximum realtime priority
- RLIMIT_RTTIME // timeout for RT tasks in us
-)
-
-var rlimitMap = map[string]int{
- "RLIMIT_CPU": RLIMIT_CPU,
- "RLIMIT_FSIZE": RLIMIT_FSIZE,
- "RLIMIT_DATA": RLIMIT_DATA,
- "RLIMIT_STACK": RLIMIT_STACK,
- "RLIMIT_CORE": RLIMIT_CORE,
- "RLIMIT_RSS": RLIMIT_RSS,
- "RLIMIT_NPROC": RLIMIT_NPROC,
- "RLIMIT_NOFILE": RLIMIT_NOFILE,
- "RLIMIT_MEMLOCK": RLIMIT_MEMLOCK,
- "RLIMIT_AS": RLIMIT_AS,
- "RLIMIT_LOCKS": RLIMIT_LOCKS,
- "RLIMIT_SGPENDING": RLIMIT_SIGPENDING,
- "RLIMIT_MSGQUEUE": RLIMIT_MSGQUEUE,
- "RLIMIT_NICE": RLIMIT_NICE,
- "RLIMIT_RTPRIO": RLIMIT_RTPRIO,
- "RLIMIT_RTTIME": RLIMIT_RTTIME,
-}
-
-func strToRlimit(key string) (int, error) {
- rl, ok := rlimitMap[key]
- if !ok {
- return 0, fmt.Errorf("Wrong rlimit value: %s", key)
- }
- return rl, nil
-}
-
-const wildcard = -1
-
-var allowedDevices = []*configs.Device{
- // allow mknod for any device
- {
- Type: 'c',
- Major: wildcard,
- Minor: wildcard,
- Permissions: "m",
- },
- {
- Type: 'b',
- Major: wildcard,
- Minor: wildcard,
- Permissions: "m",
- },
- {
- Path: "/dev/console",
- Type: 'c',
- Major: 5,
- Minor: 1,
- Permissions: "rwm",
- },
- {
- Path: "/dev/tty0",
- Type: 'c',
- Major: 4,
- Minor: 0,
- Permissions: "rwm",
- },
- {
- Path: "/dev/tty1",
- Type: 'c',
- Major: 4,
- Minor: 1,
- Permissions: "rwm",
- },
- // /dev/pts/ - pts namespaces are "coming soon"
- {
- Path: "",
- Type: 'c',
- Major: 136,
- Minor: wildcard,
- Permissions: "rwm",
- },
- {
- Path: "",
- Type: 'c',
- Major: 5,
- Minor: 2,
- Permissions: "rwm",
- },
- // tuntap
- {
- Path: "",
- Type: 'c',
- Major: 10,
- Minor: 200,
- Permissions: "rwm",
- },
-}
-
-var namespaceMapping = map[specs.NamespaceType]configs.NamespaceType{
- specs.PIDNamespace: configs.NEWPID,
- specs.NetworkNamespace: configs.NEWNET,
- specs.MountNamespace: configs.NEWNS,
- specs.UserNamespace: configs.NEWUSER,
- specs.IPCNamespace: configs.NEWIPC,
- specs.UTSNamespace: configs.NEWUTS,
-}
-
-var mountPropagationMapping = map[string]int{
- "rprivate": syscall.MS_PRIVATE | syscall.MS_REC,
- "private": syscall.MS_PRIVATE,
- "rslave": syscall.MS_SLAVE | syscall.MS_REC,
- "slave": syscall.MS_SLAVE,
- "rshared": syscall.MS_SHARED | syscall.MS_REC,
- "shared": syscall.MS_SHARED,
- "": syscall.MS_PRIVATE | syscall.MS_REC,
-}
-
-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 {
- fmt.Fprint(os.Stderr, err)
- os.Exit(1)
- }
- panic("--this line should have never been executed, congratulations--")
- }
-}
-
-type libcontainerProcess struct {
- process *libcontainer.Process
- spec specs.Process
-}
-
-// change interface to support an error
-func (p *libcontainerProcess) Pid() (int, error) {
- pid, err := p.process.Pid()
- if err != nil {
- return -1, err
- }
- return pid, nil
-}
-
-func (p *libcontainerProcess) Spec() specs.Process {
- return p.spec
-}
-
-func (p *libcontainerProcess) Signal(s os.Signal) error {
- return p.process.Signal(s)
-}
-
-type libcontainerContainer struct {
- c libcontainer.Container
- initProcess *libcontainerProcess
- additionalProcesses map[int]*libcontainerProcess
- exitStatus int
- exited bool
- path string
-}
-
-func (c *libcontainerContainer) Resume() error {
- return c.c.Resume()
-}
-
-func (c *libcontainerContainer) Pause() error {
- return c.c.Pause()
-}
-
-func (c *libcontainerContainer) State() State {
- s := State{}
- // TODO: what to do with error
- state, err := c.c.Status()
- if err != nil {
- return s
- }
- switch state {
- case libcontainer.Paused, libcontainer.Pausing:
- s.Status = Paused
- default:
- s.Status = Running
- }
- return s
-}
-
-func (c *libcontainerContainer) ID() string {
- return c.c.ID()
-}
-
-func (c *libcontainerContainer) Path() string {
- return c.path
-}
-
-func (c *libcontainerContainer) Pid() (int, error) {
- return c.initProcess.Pid()
-}
-
-func (c *libcontainerContainer) Start() error {
- return c.c.Start(c.initProcess.process)
-}
-
-func (c *libcontainerContainer) SetExited(status int) {
- c.exitStatus = status
- // meh
- c.exited = true
-}
-
-func (c *libcontainerContainer) Delete() error {
- return c.c.Destroy()
-}
-
-func (c *libcontainerContainer) Processes() ([]Process, error) {
- procs := []Process{
- c.initProcess,
- }
- for _, p := range c.additionalProcesses {
- procs = append(procs, p)
- }
- return procs, nil
-}
-
-func (c *libcontainerContainer) RemoveProcess(pid int) error {
- if _, ok := c.additionalProcesses[pid]; !ok {
- return errNotChildProcess
- }
- delete(c.additionalProcesses, pid)
- return nil
-}
-
-func NewRuntime(stateDir string) (Runtime, error) {
- f, err := libcontainer.New(stateDir, libcontainer.Cgroupfs, func(l *libcontainer.LinuxFactory) error {
- //l.CriuPath = context.GlobalString("criu")
- return nil
- })
- if err != nil {
- return nil, err
- }
- return &libcontainerRuntime{
- factory: f,
- }, nil
-}
-
-type libcontainerRuntime struct {
- factory libcontainer.Factory
-}
-
-func (r *libcontainerRuntime) Create(id, bundlePath string) (Container, error) {
- spec, rspec, err := r.loadSpec(
- filepath.Join(bundlePath, "config.json"),
- filepath.Join(bundlePath, "runtime.json"),
- )
- if err != nil {
- return nil, err
- }
- config, err := r.createLibcontainerConfig(id, bundlePath, spec, rspec)
- if err != nil {
- return nil, err
- }
- container, err := r.factory.Create(id, config)
- if err != nil {
- return nil, err
- }
- process := r.newProcess(spec.Process)
- c := &libcontainerContainer{
- c: container,
- additionalProcesses: make(map[int]*libcontainerProcess),
- initProcess: &libcontainerProcess{
- process: process,
- spec: spec.Process,
- },
- path: bundlePath,
- }
- return c, nil
-}
-
-func (r *libcontainerRuntime) StartProcess(ci Container, p specs.Process) (Process, error) {
- c, ok := ci.(*libcontainerContainer)
- if !ok {
- return nil, errInvalidContainerType
- }
- process := r.newProcess(p)
- if err := c.c.Start(process); err != nil {
- return nil, err
- }
- lp := &libcontainerProcess{
- process: process,
- spec: p,
- }
- pid, err := process.Pid()
- if err != nil {
- return nil, err
- }
- c.additionalProcesses[pid] = lp
- return lp, nil
-}
-
-// newProcess returns a new libcontainer Process with the arguments from the
-// spec and stdio from the current process.
-func (r *libcontainerRuntime) newProcess(p specs.Process) *libcontainer.Process {
- return &libcontainer.Process{
- Args: p.Args,
- Env: p.Env,
- // TODO: fix libcontainer's API to better support uid/gid in a typesafe way.
- User: fmt.Sprintf("%d:%d", p.User.UID, p.User.GID),
- Cwd: p.Cwd,
- }
-}
-
-// loadSpec loads the specification from the provided path.
-// If the path is empty then the default path will be "config.json"
-func (r *libcontainerRuntime) loadSpec(cPath, rPath string) (spec *specs.LinuxSpec, rspec *specs.LinuxRuntimeSpec, err error) {
- cf, err := os.Open(cPath)
- if err != nil {
- if os.IsNotExist(err) {
- return nil, nil, fmt.Errorf("JSON specification file at %s not found", cPath)
- }
- return spec, rspec, err
- }
- defer cf.Close()
-
- rf, err := os.Open(rPath)
- if err != nil {
- if os.IsNotExist(err) {
- return nil, nil, fmt.Errorf("JSON runtime config file at %s not found", rPath)
- }
- return spec, rspec, err
- }
- defer rf.Close()
-
- if err = json.NewDecoder(cf).Decode(&spec); err != nil {
- return spec, rspec, err
- }
- if err = json.NewDecoder(rf).Decode(&rspec); err != nil {
- return spec, rspec, err
- }
- return spec, rspec, r.checkSpecVersion(spec)
-}
-
-// checkSpecVersion makes sure that the spec version matches runc's while we are in the initial
-// development period. It is better to hard fail than have missing fields or options in the spec.
-func (r *libcontainerRuntime) checkSpecVersion(s *specs.LinuxSpec) error {
- if s.Version != specs.Version {
- return fmt.Errorf("spec version is not compatible with implemented version %q: spec %q", specs.Version, s.Version)
- }
- return nil
-}
-
-func (r *libcontainerRuntime) createLibcontainerConfig(cgroupName, bundlePath string, spec *specs.LinuxSpec, rspec *specs.LinuxRuntimeSpec) (*configs.Config, error) {
- rootfsPath := spec.Root.Path
- if !filepath.IsAbs(rootfsPath) {
- rootfsPath = filepath.Join(bundlePath, rootfsPath)
- }
- config := &configs.Config{
- Rootfs: rootfsPath,
- Capabilities: spec.Linux.Capabilities,
- Readonlyfs: spec.Root.Readonly,
- Hostname: spec.Hostname,
- }
- for _, ns := range rspec.Linux.Namespaces {
- t, exists := namespaceMapping[ns.Type]
- if !exists {
- return nil, fmt.Errorf("namespace %q does not exist", ns)
- }
- config.Namespaces.Add(t, ns.Path)
- }
- if config.Namespaces.Contains(configs.NEWNET) {
- config.Networks = []*configs.Network{
- {
- Type: "loopback",
- },
- }
- }
- for _, mp := range spec.Mounts {
- m, ok := rspec.Mounts[mp.Name]
- if !ok {
- return nil, fmt.Errorf("Mount with Name %q not found in runtime config", mp.Name)
- }
- config.Mounts = append(config.Mounts, r.createLibcontainerMount(bundlePath, mp.Path, m))
- }
- if err := r.createDevices(rspec, config); err != nil {
- return nil, err
- }
- if err := r.setupUserNamespace(rspec, config); err != nil {
- return nil, err
- }
- for _, rlimit := range rspec.Linux.Rlimits {
- rl, err := r.createLibContainerRlimit(rlimit)
- if err != nil {
- return nil, err
- }
- config.Rlimits = append(config.Rlimits, rl)
- }
- c, err := r.createCgroupConfig(cgroupName, rspec, config.Devices)
- if err != nil {
- return nil, err
- }
- config.Cgroups = c
- if config.Readonlyfs {
- r.setReadonly(config)
- config.MaskPaths = []string{
- "/proc/kcore",
- }
- config.ReadonlyPaths = []string{
- "/proc/sys", "/proc/sysrq-trigger", "/proc/irq", "/proc/bus",
- }
- }
- seccomp, err := r.setupSeccomp(&rspec.Linux.Seccomp)
- if err != nil {
- return nil, err
- }
- config.Seccomp = seccomp
- config.Sysctl = rspec.Linux.Sysctl
- config.ProcessLabel = rspec.Linux.SelinuxProcessLabel
- config.AppArmorProfile = rspec.Linux.ApparmorProfile
- for _, g := range spec.Process.User.AdditionalGids {
- config.AdditionalGroups = append(config.AdditionalGroups, strconv.FormatUint(uint64(g), 10))
- }
- r.createHooks(rspec, config)
- config.Version = specs.Version
- return config, nil
-}
-
-func (r *libcontainerRuntime) createLibcontainerMount(cwd, dest string, m specs.Mount) *configs.Mount {
- flags, pgflags, data := parseMountOptions(m.Options)
- source := m.Source
- if m.Type == "bind" {
- if !filepath.IsAbs(source) {
- source = filepath.Join(cwd, m.Source)
- }
- }
- return &configs.Mount{
- Device: m.Type,
- Source: source,
- Destination: dest,
- Data: data,
- Flags: flags,
- PropagationFlags: pgflags,
- }
-}
-
-func (rt *libcontainerRuntime) createCgroupConfig(name string, spec *specs.LinuxRuntimeSpec, devices []*configs.Device) (*configs.Cgroup, error) {
- c := &configs.Cgroup{
- Name: name,
- Parent: "/containerd",
- AllowedDevices: append(devices, allowedDevices...),
- }
- r := spec.Linux.Resources
- c.Memory = int64(r.Memory.Limit)
- c.MemoryReservation = int64(r.Memory.Reservation)
- c.MemorySwap = int64(r.Memory.Swap)
- c.KernelMemory = int64(r.Memory.Kernel)
- c.MemorySwappiness = int64(r.Memory.Swappiness)
- c.CpuShares = int64(r.CPU.Shares)
- c.CpuQuota = int64(r.CPU.Quota)
- c.CpuPeriod = int64(r.CPU.Period)
- c.CpuRtRuntime = int64(r.CPU.RealtimeRuntime)
- c.CpuRtPeriod = int64(r.CPU.RealtimePeriod)
- c.CpusetCpus = r.CPU.Cpus
- c.CpusetMems = r.CPU.Mems
- c.BlkioWeight = r.BlockIO.Weight
- c.BlkioLeafWeight = r.BlockIO.LeafWeight
- for _, wd := range r.BlockIO.WeightDevice {
- weightDevice := configs.NewWeightDevice(wd.Major, wd.Minor, wd.Weight, wd.LeafWeight)
- c.BlkioWeightDevice = append(c.BlkioWeightDevice, weightDevice)
- }
- for _, td := range r.BlockIO.ThrottleReadBpsDevice {
- throttleDevice := configs.NewThrottleDevice(td.Major, td.Minor, td.Rate)
- c.BlkioThrottleReadBpsDevice = append(c.BlkioThrottleReadBpsDevice, throttleDevice)
- }
- for _, td := range r.BlockIO.ThrottleWriteBpsDevice {
- throttleDevice := configs.NewThrottleDevice(td.Major, td.Minor, td.Rate)
- c.BlkioThrottleWriteBpsDevice = append(c.BlkioThrottleWriteBpsDevice, throttleDevice)
- }
- for _, td := range r.BlockIO.ThrottleReadIOPSDevice {
- throttleDevice := configs.NewThrottleDevice(td.Major, td.Minor, td.Rate)
- c.BlkioThrottleReadIOPSDevice = append(c.BlkioThrottleReadIOPSDevice, throttleDevice)
- }
- for _, td := range r.BlockIO.ThrottleWriteIOPSDevice {
- throttleDevice := configs.NewThrottleDevice(td.Major, td.Minor, td.Rate)
- c.BlkioThrottleWriteIOPSDevice = append(c.BlkioThrottleWriteIOPSDevice, throttleDevice)
- }
- for _, l := range r.HugepageLimits {
- c.HugetlbLimit = append(c.HugetlbLimit, &configs.HugepageLimit{
- Pagesize: l.Pagesize,
- Limit: l.Limit,
- })
- }
- c.OomKillDisable = r.DisableOOMKiller
- c.NetClsClassid = r.Network.ClassID
- for _, m := range r.Network.Priorities {
- c.NetPrioIfpriomap = append(c.NetPrioIfpriomap, &configs.IfPrioMap{
- Interface: m.Name,
- Priority: int64(m.Priority),
- })
- }
- return c, nil
-}
-
-func (r *libcontainerRuntime) createDevices(spec *specs.LinuxRuntimeSpec, config *configs.Config) error {
- for _, d := range spec.Linux.Devices {
- device := &configs.Device{
- Type: d.Type,
- Path: d.Path,
- Major: d.Major,
- Minor: d.Minor,
- Permissions: d.Permissions,
- FileMode: d.FileMode,
- Uid: d.UID,
- Gid: d.GID,
- }
- config.Devices = append(config.Devices, device)
- }
- return nil
-}
-
-func (r *libcontainerRuntime) setReadonly(config *configs.Config) {
- for _, m := range config.Mounts {
- if m.Device == "sysfs" {
- m.Flags |= syscall.MS_RDONLY
- }
- }
-}
-
-func (r *libcontainerRuntime) setupUserNamespace(spec *specs.LinuxRuntimeSpec, config *configs.Config) error {
- if len(spec.Linux.UIDMappings) == 0 {
- return nil
- }
- config.Namespaces.Add(configs.NEWUSER, "")
- create := func(m specs.IDMapping) configs.IDMap {
- return configs.IDMap{
- HostID: int(m.HostID),
- ContainerID: int(m.ContainerID),
- Size: int(m.Size),
- }
- }
- for _, m := range spec.Linux.UIDMappings {
- config.UidMappings = append(config.UidMappings, create(m))
- }
- for _, m := range spec.Linux.GIDMappings {
- config.GidMappings = append(config.GidMappings, create(m))
- }
- rootUID, err := config.HostUID()
- if err != nil {
- return err
- }
- rootGID, err := config.HostGID()
- if err != nil {
- return err
- }
- for _, node := range config.Devices {
- node.Uid = uint32(rootUID)
- node.Gid = uint32(rootGID)
- }
- return nil
-}
-
-func (r *libcontainerRuntime) createLibContainerRlimit(rlimit specs.Rlimit) (configs.Rlimit, error) {
- rl, err := strToRlimit(rlimit.Type)
- if err != nil {
- return configs.Rlimit{}, err
- }
- return configs.Rlimit{
- Type: rl,
- Hard: uint64(rlimit.Hard),
- Soft: uint64(rlimit.Soft),
- }, nil
-}
-
-// parseMountOptions parses the string and returns the flags, propagation
-// flags and any mount data that it contains.
-func parseMountOptions(options []string) (int, []int, string) {
- var (
- flag int
- pgflag []int
- data []string
- )
- flags := map[string]struct {
- clear bool
- flag int
- }{
- "async": {true, syscall.MS_SYNCHRONOUS},
- "atime": {true, syscall.MS_NOATIME},
- "bind": {false, syscall.MS_BIND},
- "defaults": {false, 0},
- "dev": {true, syscall.MS_NODEV},
- "diratime": {true, syscall.MS_NODIRATIME},
- "dirsync": {false, syscall.MS_DIRSYNC},
- "exec": {true, syscall.MS_NOEXEC},
- "mand": {false, syscall.MS_MANDLOCK},
- "noatime": {false, syscall.MS_NOATIME},
- "nodev": {false, syscall.MS_NODEV},
- "nodiratime": {false, syscall.MS_NODIRATIME},
- "noexec": {false, syscall.MS_NOEXEC},
- "nomand": {true, syscall.MS_MANDLOCK},
- "norelatime": {true, syscall.MS_RELATIME},
- "nostrictatime": {true, syscall.MS_STRICTATIME},
- "nosuid": {false, syscall.MS_NOSUID},
- "rbind": {false, syscall.MS_BIND | syscall.MS_REC},
- "relatime": {false, syscall.MS_RELATIME},
- "remount": {false, syscall.MS_REMOUNT},
- "ro": {false, syscall.MS_RDONLY},
- "rw": {true, syscall.MS_RDONLY},
- "strictatime": {false, syscall.MS_STRICTATIME},
- "suid": {true, syscall.MS_NOSUID},
- "sync": {false, syscall.MS_SYNCHRONOUS},
- }
- propagationFlags := map[string]struct {
- clear bool
- flag int
- }{
- "private": {false, syscall.MS_PRIVATE},
- "shared": {false, syscall.MS_SHARED},
- "slave": {false, syscall.MS_SLAVE},
- "unbindable": {false, syscall.MS_UNBINDABLE},
- "rprivate": {false, syscall.MS_PRIVATE | syscall.MS_REC},
- "rshared": {false, syscall.MS_SHARED | syscall.MS_REC},
- "rslave": {false, syscall.MS_SLAVE | syscall.MS_REC},
- "runbindable": {false, syscall.MS_UNBINDABLE | syscall.MS_REC},
- }
- for _, o := range options {
- // If the option does not exist in the flags table or the flag
- // is not supported on the platform,
- // then it is a data value for a specific fs type
- if f, exists := flags[o]; exists && f.flag != 0 {
- if f.clear {
- flag &= ^f.flag
- } else {
- flag |= f.flag
- }
- } else if f, exists := propagationFlags[o]; exists && f.flag != 0 {
- pgflag = append(pgflag, f.flag)
- } else {
- data = append(data, o)
- }
- }
- return flag, pgflag, strings.Join(data, ",")
-}
-
-func (r *libcontainerRuntime) setupSeccomp(config *specs.Seccomp) (*configs.Seccomp, error) {
- if config == nil {
- return nil, nil
- }
-
- // No default action specified, no syscalls listed, assume seccomp disabled
- if config.DefaultAction == "" && len(config.Syscalls) == 0 {
- return nil, nil
- }
-
- newConfig := new(configs.Seccomp)
- newConfig.Syscalls = []*configs.Syscall{}
-
- if len(config.Architectures) > 0 {
- newConfig.Architectures = []string{}
- for _, arch := range config.Architectures {
- newArch, err := seccomp.ConvertStringToArch(string(arch))
- if err != nil {
- return nil, err
- }
- newConfig.Architectures = append(newConfig.Architectures, newArch)
- }
- }
-
- // Convert default action from string representation
- newDefaultAction, err := seccomp.ConvertStringToAction(string(config.DefaultAction))
- if err != nil {
- return nil, err
- }
- newConfig.DefaultAction = newDefaultAction
-
- // Loop through all syscall blocks and convert them to libcontainer format
- for _, call := range config.Syscalls {
- newAction, err := seccomp.ConvertStringToAction(string(call.Action))
- if err != nil {
- return nil, err
- }
-
- newCall := configs.Syscall{
- Name: call.Name,
- Action: newAction,
- Args: []*configs.Arg{},
- }
-
- // Loop through all the arguments of the syscall and convert them
- for _, arg := range call.Args {
- newOp, err := seccomp.ConvertStringToOperator(string(arg.Op))
- if err != nil {
- return nil, err
- }
-
- newArg := configs.Arg{
- Index: arg.Index,
- Value: arg.Value,
- ValueTwo: arg.ValueTwo,
- Op: newOp,
- }
-
- newCall.Args = append(newCall.Args, &newArg)
- }
-
- newConfig.Syscalls = append(newConfig.Syscalls, &newCall)
- }
-
- return newConfig, nil
-}
-
-func (r *libcontainerRuntime) createHooks(rspec *specs.LinuxRuntimeSpec, config *configs.Config) {
- config.Hooks = &configs.Hooks{}
- for _, h := range rspec.Hooks.Prestart {
- cmd := configs.Command{
- Path: h.Path,
- Args: h.Args,
- Env: h.Env,
- }
- config.Hooks.Prestart = append(config.Hooks.Prestart, configs.NewCommandHook(cmd))
- }
- for _, h := range rspec.Hooks.Poststop {
- cmd := configs.Command{
- Path: h.Path,
- Args: h.Args,
- Env: h.Env,
- }
- config.Hooks.Poststop = append(config.Hooks.Poststop, configs.NewCommandHook(cmd))
- }
-}
diff --git a/containerd/vendor/github.com/docker/containerd/supervisor.go b/containerd/vendor/github.com/docker/containerd/supervisor.go
deleted file mode 100644
index 35594ca..0000000
--- a/containerd/vendor/github.com/docker/containerd/supervisor.go
+++ /dev/null
@@ -1,234 +0,0 @@
-package containerd
-
-import (
- "os"
- "path/filepath"
- "sync"
-
- "github.com/Sirupsen/logrus"
- "github.com/opencontainers/runc/libcontainer"
-)
-
-// NewSupervisor returns an initialized Process supervisor.
-func NewSupervisor(stateDir string, concurrency int) (*Supervisor, error) {
- if err := os.MkdirAll(stateDir, 0755); err != nil {
- return nil, err
- }
- // register counters
- runtime, err := NewRuntime(stateDir)
- if err != nil {
- return nil, err
- }
- j, err := newJournal(filepath.Join(stateDir, "journal.json"))
- if err != nil {
- return nil, err
- }
- s := &Supervisor{
- stateDir: stateDir,
- containers: make(map[string]Container),
- processes: make(map[int]Container),
- runtime: runtime,
- tasks: make(chan *startTask, concurrency*100),
- journal: j,
- }
- for i := 0; i < concurrency; i++ {
- s.workerGroup.Add(1)
- go s.startContainerWorker(s.tasks)
- }
- return s, nil
-}
-
-type Supervisor struct {
- // stateDir is the directory on the system to store container runtime state information.
- stateDir string
-
- containers map[string]Container
-
- processes map[int]Container
-
- runtime Runtime
-
- journal *journal
-
- events chan *Event
- tasks chan *startTask
- workerGroup sync.WaitGroup
-}
-
-// need proper close logic for jobs and stuff so that sending to the channels dont panic
-// but can complete jobs
-func (s *Supervisor) Close() error {
- return s.journal.Close()
-}
-
-// Start is a non-blocking call that runs the supervisor for monitoring contianer processes and
-// executing new containers.
-//
-// This event loop is the only thing that is allowed to modify state of containers and processes.
-func (s *Supervisor) Start(events chan *Event) error {
- if events == nil {
- return ErrEventChanNil
- }
- s.events = events
- go func() {
- for e := range events {
- if err := s.journal.write(e); err != nil {
- logrus.WithField("error", err).Error("write journal entry")
- }
- switch e.Type {
- case ExitEventType:
- logrus.WithFields(logrus.Fields{"pid": e.Pid, "status": e.Status}).
- Debug("containerd: process exited")
- // is it the child process of a container
- if container, ok := s.processes[e.Pid]; ok {
- if err := container.RemoveProcess(e.Pid); err != nil {
- logrus.WithField("error", err).Error("containerd: find container for pid")
- }
- delete(s.processes, e.Pid)
- close(e.Err)
- continue
- }
- // is it the main container's process
- container, err := s.getContainerForPid(e.Pid)
- if err != nil {
- if err != errNoContainerForPid {
- logrus.WithField("error", err).Error("containerd: find container for pid")
- }
- continue
- }
- container.SetExited(e.Status)
- ne := NewEvent(DeleteEventType)
- ne.ID = container.ID()
- s.SendEvent(ne)
- case StartContainerEventType:
- container, err := s.runtime.Create(e.ID, e.BundlePath)
- if err != nil {
- e.Err <- err
- continue
- }
- s.containers[e.ID] = container
- s.tasks <- &startTask{
- err: e.Err,
- container: container,
- }
- continue
- case DeleteEventType:
- if container, ok := s.containers[e.ID]; ok {
- if err := s.deleteContainer(container); err != nil {
- logrus.WithField("error", err).Error("containerd: deleting container")
- }
- }
- case GetContainerEventType:
- for _, c := range s.containers {
- e.Containers = append(e.Containers, c)
- }
- case SignalEventType:
- container, ok := s.containers[e.ID]
- if !ok {
- e.Err <- ErrContainerNotFound
- continue
- }
- processes, err := container.Processes()
- if err != nil {
- e.Err <- err
- continue
- }
- for _, p := range processes {
- if pid, err := p.Pid(); err == nil && pid == e.Pid {
- e.Err <- p.Signal(e.Signal)
- continue
- }
- }
- e.Err <- ErrProcessNotFound
- continue
- case AddProcessEventType:
- container, ok := s.containers[e.ID]
- if !ok {
- e.Err <- ErrContainerNotFound
- continue
- }
- p, err := s.runtime.StartProcess(container, *e.Process)
- if err != nil {
- e.Err <- err
- continue
- }
- if e.Pid, err = p.Pid(); err != nil {
- e.Err <- err
- continue
- }
- s.processes[e.Pid] = container
- case UpdateContainerEventType:
- container, ok := s.containers[e.ID]
- if !ok {
- e.Err <- ErrContainerNotFound
- continue
- }
- if e.State.Status != "" {
- switch e.State.Status {
- case Running:
- if err := container.Resume(); err != nil {
- e.Err <- ErrUnknownContainerStatus
- continue
- }
- case Paused:
- if err := container.Pause(); err != nil {
- e.Err <- ErrUnknownContainerStatus
- continue
- }
- default:
- e.Err <- ErrUnknownContainerStatus
- continue
- }
- }
- }
- close(e.Err)
- }
- }()
- return nil
-}
-
-func (s *Supervisor) deleteContainer(container Container) error {
- delete(s.containers, container.ID())
- return container.Delete()
-}
-
-func (s *Supervisor) getContainerForPid(pid int) (Container, error) {
- for _, container := range s.containers {
- cpid, err := container.Pid()
- if err != nil {
- if lerr, ok := err.(libcontainer.Error); ok {
- if lerr.Code() == libcontainer.ProcessNotExecuted {
- continue
- }
- }
- logrus.WithField("error", err).Error("containerd: get container pid")
- }
- if pid == cpid {
- return container, nil
- }
- }
- return nil, errNoContainerForPid
-}
-
-func (s *Supervisor) SendEvent(evt *Event) {
- s.events <- evt
-}
-
-type startTask struct {
- container Container
- err chan error
-}
-
-func (s *Supervisor) startContainerWorker(tasks chan *startTask) {
- defer s.workerGroup.Done()
- for t := range tasks {
- if err := t.container.Start(); err != nil {
- e := NewEvent(StartContainerEventType)
- e.ID = t.container.ID()
- s.SendEvent(e)
- t.err <- err
- continue
- }
- t.err <- nil
- }
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/mount/flags.go b/containerd/vendor/github.com/docker/docker/pkg/mount/flags.go
deleted file mode 100644
index 17dbd7a..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/mount/flags.go
+++ /dev/null
@@ -1,69 +0,0 @@
-package mount
-
-import (
- "strings"
-)
-
-// Parse fstab type mount options into mount() flags
-// and device specific data
-func parseOptions(options string) (int, string) {
- var (
- flag int
- data []string
- )
-
- flags := map[string]struct {
- clear bool
- flag int
- }{
- "defaults": {false, 0},
- "ro": {false, RDONLY},
- "rw": {true, RDONLY},
- "suid": {true, NOSUID},
- "nosuid": {false, NOSUID},
- "dev": {true, NODEV},
- "nodev": {false, NODEV},
- "exec": {true, NOEXEC},
- "noexec": {false, NOEXEC},
- "sync": {false, SYNCHRONOUS},
- "async": {true, SYNCHRONOUS},
- "dirsync": {false, DIRSYNC},
- "remount": {false, REMOUNT},
- "mand": {false, MANDLOCK},
- "nomand": {true, MANDLOCK},
- "atime": {true, NOATIME},
- "noatime": {false, NOATIME},
- "diratime": {true, NODIRATIME},
- "nodiratime": {false, NODIRATIME},
- "bind": {false, BIND},
- "rbind": {false, RBIND},
- "unbindable": {false, UNBINDABLE},
- "runbindable": {false, RUNBINDABLE},
- "private": {false, PRIVATE},
- "rprivate": {false, RPRIVATE},
- "shared": {false, SHARED},
- "rshared": {false, RSHARED},
- "slave": {false, SLAVE},
- "rslave": {false, RSLAVE},
- "relatime": {false, RELATIME},
- "norelatime": {true, RELATIME},
- "strictatime": {false, STRICTATIME},
- "nostrictatime": {true, STRICTATIME},
- }
-
- for _, o := range strings.Split(options, ",") {
- // If the option does not exist in the flags table or the flag
- // is not supported on the platform,
- // then it is a data value for a specific fs type
- if f, exists := flags[o]; exists && f.flag != 0 {
- if f.clear {
- flag &= ^f.flag
- } else {
- flag |= f.flag
- }
- } else {
- data = append(data, o)
- }
- }
- return flag, strings.Join(data, ",")
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/mount/flags_freebsd.go b/containerd/vendor/github.com/docker/docker/pkg/mount/flags_freebsd.go
deleted file mode 100644
index f166cb2..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/mount/flags_freebsd.go
+++ /dev/null
@@ -1,48 +0,0 @@
-// +build freebsd,cgo
-
-package mount
-
-/*
-#include
-*/
-import "C"
-
-const (
- // RDONLY will mount the filesystem as read-only.
- RDONLY = C.MNT_RDONLY
-
- // NOSUID will not allow set-user-identifier or set-group-identifier bits to
- // take effect.
- NOSUID = C.MNT_NOSUID
-
- // NOEXEC will not allow execution of any binaries on the mounted file system.
- NOEXEC = C.MNT_NOEXEC
-
- // SYNCHRONOUS will allow any I/O to the file system to be done synchronously.
- SYNCHRONOUS = C.MNT_SYNCHRONOUS
-
- // NOATIME will not update the file access time when reading from a file.
- NOATIME = C.MNT_NOATIME
-)
-
-// These flags are unsupported.
-const (
- BIND = 0
- DIRSYNC = 0
- MANDLOCK = 0
- NODEV = 0
- NODIRATIME = 0
- UNBINDABLE = 0
- RUNBINDABLE = 0
- PRIVATE = 0
- RPRIVATE = 0
- SHARED = 0
- RSHARED = 0
- SLAVE = 0
- RSLAVE = 0
- RBIND = 0
- RELATIVE = 0
- RELATIME = 0
- REMOUNT = 0
- STRICTATIME = 0
-)
diff --git a/containerd/vendor/github.com/docker/docker/pkg/mount/flags_linux.go b/containerd/vendor/github.com/docker/docker/pkg/mount/flags_linux.go
deleted file mode 100644
index 2f9f5c5..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/mount/flags_linux.go
+++ /dev/null
@@ -1,85 +0,0 @@
-package mount
-
-import (
- "syscall"
-)
-
-const (
- // RDONLY will mount the file system read-only.
- RDONLY = syscall.MS_RDONLY
-
- // NOSUID will not allow set-user-identifier or set-group-identifier bits to
- // take effect.
- NOSUID = syscall.MS_NOSUID
-
- // NODEV will not interpret character or block special devices on the file
- // system.
- NODEV = syscall.MS_NODEV
-
- // NOEXEC will not allow execution of any binaries on the mounted file system.
- NOEXEC = syscall.MS_NOEXEC
-
- // SYNCHRONOUS will allow I/O to the file system to be done synchronously.
- SYNCHRONOUS = syscall.MS_SYNCHRONOUS
-
- // DIRSYNC will force all directory updates within the file system to be done
- // synchronously. This affects the following system calls: creat, link,
- // unlink, symlink, mkdir, rmdir, mknod and rename.
- DIRSYNC = syscall.MS_DIRSYNC
-
- // REMOUNT will attempt to remount an already-mounted file system. This is
- // commonly used to change the mount flags for a file system, especially to
- // make a readonly file system writeable. It does not change device or mount
- // point.
- REMOUNT = syscall.MS_REMOUNT
-
- // MANDLOCK will force mandatory locks on a filesystem.
- MANDLOCK = syscall.MS_MANDLOCK
-
- // NOATIME will not update the file access time when reading from a file.
- NOATIME = syscall.MS_NOATIME
-
- // NODIRATIME will not update the directory access time.
- NODIRATIME = syscall.MS_NODIRATIME
-
- // BIND remounts a subtree somewhere else.
- BIND = syscall.MS_BIND
-
- // RBIND remounts a subtree and all possible submounts somewhere else.
- RBIND = syscall.MS_BIND | syscall.MS_REC
-
- // UNBINDABLE creates a mount which cannot be cloned through a bind operation.
- UNBINDABLE = syscall.MS_UNBINDABLE
-
- // RUNBINDABLE marks the entire mount tree as UNBINDABLE.
- RUNBINDABLE = syscall.MS_UNBINDABLE | syscall.MS_REC
-
- // PRIVATE creates a mount which carries no propagation abilities.
- PRIVATE = syscall.MS_PRIVATE
-
- // RPRIVATE marks the entire mount tree as PRIVATE.
- RPRIVATE = syscall.MS_PRIVATE | syscall.MS_REC
-
- // SLAVE creates a mount which receives propagation from its master, but not
- // vice versa.
- SLAVE = syscall.MS_SLAVE
-
- // RSLAVE marks the entire mount tree as SLAVE.
- RSLAVE = syscall.MS_SLAVE | syscall.MS_REC
-
- // SHARED creates a mount which provides the ability to create mirrors of
- // that mount such that mounts and unmounts within any of the mirrors
- // propagate to the other mirrors.
- SHARED = syscall.MS_SHARED
-
- // RSHARED marks the entire mount tree as SHARED.
- RSHARED = syscall.MS_SHARED | syscall.MS_REC
-
- // RELATIME updates inode access times relative to modify or change time.
- RELATIME = syscall.MS_RELATIME
-
- // STRICTATIME allows to explicitly request full atime updates. This makes
- // it possible for the kernel to default to relatime or noatime but still
- // allow userspace to override it.
- STRICTATIME = syscall.MS_STRICTATIME
-)
diff --git a/containerd/vendor/github.com/docker/docker/pkg/mount/flags_unsupported.go b/containerd/vendor/github.com/docker/docker/pkg/mount/flags_unsupported.go
deleted file mode 100644
index a90d3d1..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/mount/flags_unsupported.go
+++ /dev/null
@@ -1,30 +0,0 @@
-// +build !linux,!freebsd freebsd,!cgo
-
-package mount
-
-// These flags are unsupported.
-const (
- BIND = 0
- DIRSYNC = 0
- MANDLOCK = 0
- NOATIME = 0
- NODEV = 0
- NODIRATIME = 0
- NOEXEC = 0
- NOSUID = 0
- UNBINDABLE = 0
- RUNBINDABLE = 0
- PRIVATE = 0
- RPRIVATE = 0
- SHARED = 0
- RSHARED = 0
- SLAVE = 0
- RSLAVE = 0
- RBIND = 0
- RELATIME = 0
- RELATIVE = 0
- REMOUNT = 0
- STRICTATIME = 0
- SYNCHRONOUS = 0
- RDONLY = 0
-)
diff --git a/containerd/vendor/github.com/docker/docker/pkg/mount/mount.go b/containerd/vendor/github.com/docker/docker/pkg/mount/mount.go
deleted file mode 100644
index ed7216e..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/mount/mount.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package mount
-
-import (
- "time"
-)
-
-// GetMounts retrieves a list of mounts for the current running process.
-func GetMounts() ([]*Info, error) {
- return parseMountTable()
-}
-
-// Mounted looks at /proc/self/mountinfo to determine of the specified
-// mountpoint has been mounted
-func Mounted(mountpoint string) (bool, error) {
- entries, err := parseMountTable()
- if err != nil {
- return false, err
- }
-
- // Search the table for the mountpoint
- for _, e := range entries {
- if e.Mountpoint == mountpoint {
- return true, nil
- }
- }
- return false, nil
-}
-
-// Mount will mount filesystem according to the specified configuration, on the
-// condition that the target path is *not* already mounted. Options must be
-// specified like the mount or fstab unix commands: "opt1=val1,opt2=val2". See
-// flags.go for supported option flags.
-func Mount(device, target, mType, options string) error {
- flag, _ := parseOptions(options)
- if flag&REMOUNT != REMOUNT {
- if mounted, err := Mounted(target); err != nil || mounted {
- return err
- }
- }
- return ForceMount(device, target, mType, options)
-}
-
-// ForceMount will mount a filesystem according to the specified configuration,
-// *regardless* if the target path is not already mounted. Options must be
-// specified like the mount or fstab unix commands: "opt1=val1,opt2=val2". See
-// flags.go for supported option flags.
-func ForceMount(device, target, mType, options string) error {
- flag, data := parseOptions(options)
- if err := mount(device, target, mType, uintptr(flag), data); err != nil {
- return err
- }
- return nil
-}
-
-// Unmount will unmount the target filesystem, so long as it is mounted.
-func Unmount(target string) error {
- if mounted, err := Mounted(target); err != nil || !mounted {
- return err
- }
- return ForceUnmount(target)
-}
-
-// ForceUnmount will force an unmount of the target filesystem, regardless if
-// it is mounted or not.
-func ForceUnmount(target string) (err error) {
- // Simple retry logic for unmount
- for i := 0; i < 10; i++ {
- if err = unmount(target, 0); err == nil {
- return nil
- }
- time.Sleep(100 * time.Millisecond)
- }
- return
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/mount/mounter_freebsd.go b/containerd/vendor/github.com/docker/docker/pkg/mount/mounter_freebsd.go
deleted file mode 100644
index bb870e6..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/mount/mounter_freebsd.go
+++ /dev/null
@@ -1,59 +0,0 @@
-package mount
-
-/*
-#include
-#include
-#include
-#include
-#include
-#include
-*/
-import "C"
-
-import (
- "fmt"
- "strings"
- "syscall"
- "unsafe"
-)
-
-func allocateIOVecs(options []string) []C.struct_iovec {
- out := make([]C.struct_iovec, len(options))
- for i, option := range options {
- out[i].iov_base = unsafe.Pointer(C.CString(option))
- out[i].iov_len = C.size_t(len(option) + 1)
- }
- return out
-}
-
-func mount(device, target, mType string, flag uintptr, data string) error {
- isNullFS := false
-
- xs := strings.Split(data, ",")
- for _, x := range xs {
- if x == "bind" {
- isNullFS = true
- }
- }
-
- options := []string{"fspath", target}
- if isNullFS {
- options = append(options, "fstype", "nullfs", "target", device)
- } else {
- options = append(options, "fstype", mType, "from", device)
- }
- rawOptions := allocateIOVecs(options)
- for _, rawOption := range rawOptions {
- defer C.free(rawOption.iov_base)
- }
-
- if errno := C.nmount(&rawOptions[0], C.uint(len(options)), C.int(flag)); errno != 0 {
- reason := C.GoString(C.strerror(*C.__error()))
- return fmt.Errorf("Failed to call nmount: %s", reason)
- }
- return nil
-}
-
-func unmount(target string, flag int) error {
- return syscall.Unmount(target, flag)
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/mount/mounter_linux.go b/containerd/vendor/github.com/docker/docker/pkg/mount/mounter_linux.go
deleted file mode 100644
index dd4280c..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/mount/mounter_linux.go
+++ /dev/null
@@ -1,21 +0,0 @@
-package mount
-
-import (
- "syscall"
-)
-
-func mount(device, target, mType string, flag uintptr, data string) error {
- if err := syscall.Mount(device, target, mType, flag, data); err != nil {
- return err
- }
-
- // If we have a bind mount or remount, remount...
- if flag&syscall.MS_BIND == syscall.MS_BIND && flag&syscall.MS_RDONLY == syscall.MS_RDONLY {
- return syscall.Mount(device, target, mType, flag|syscall.MS_REMOUNT, data)
- }
- return nil
-}
-
-func unmount(target string, flag int) error {
- return syscall.Unmount(target, flag)
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/mount/mounter_unsupported.go b/containerd/vendor/github.com/docker/docker/pkg/mount/mounter_unsupported.go
deleted file mode 100644
index eb93365..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/mount/mounter_unsupported.go
+++ /dev/null
@@ -1,11 +0,0 @@
-// +build !linux,!freebsd freebsd,!cgo
-
-package mount
-
-func mount(device, target, mType string, flag uintptr, data string) error {
- panic("Not implemented")
-}
-
-func unmount(target string, flag int) error {
- panic("Not implemented")
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/mount/mountinfo.go b/containerd/vendor/github.com/docker/docker/pkg/mount/mountinfo.go
deleted file mode 100644
index e3fc353..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/mount/mountinfo.go
+++ /dev/null
@@ -1,40 +0,0 @@
-package mount
-
-// Info reveals information about a particular mounted filesystem. This
-// struct is populated from the content in the /proc//mountinfo file.
-type Info struct {
- // ID is a unique identifier of the mount (may be reused after umount).
- ID int
-
- // Parent indicates the ID of the mount parent (or of self for the top of the
- // mount tree).
- Parent int
-
- // Major indicates one half of the device ID which identifies the device class.
- Major int
-
- // Minor indicates one half of the device ID which identifies a specific
- // instance of device.
- Minor int
-
- // Root of the mount within the filesystem.
- Root string
-
- // Mountpoint indicates the mount point relative to the process's root.
- Mountpoint string
-
- // Opts represents mount-specific options.
- Opts string
-
- // Optional represents optional fields.
- Optional string
-
- // Fstype indicates the type of filesystem, such as EXT3.
- Fstype string
-
- // Source indicates filesystem specific information or "none".
- Source string
-
- // VfsOpts represents per super block options.
- VfsOpts string
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/mount/mountinfo_freebsd.go b/containerd/vendor/github.com/docker/docker/pkg/mount/mountinfo_freebsd.go
deleted file mode 100644
index 4f32edc..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/mount/mountinfo_freebsd.go
+++ /dev/null
@@ -1,41 +0,0 @@
-package mount
-
-/*
-#include
-#include
-#include
-*/
-import "C"
-
-import (
- "fmt"
- "reflect"
- "unsafe"
-)
-
-// Parse /proc/self/mountinfo because comparing Dev and ino does not work from
-// bind mounts.
-func parseMountTable() ([]*Info, error) {
- var rawEntries *C.struct_statfs
-
- count := int(C.getmntinfo(&rawEntries, C.MNT_WAIT))
- if count == 0 {
- return nil, fmt.Errorf("Failed to call getmntinfo")
- }
-
- var entries []C.struct_statfs
- header := (*reflect.SliceHeader)(unsafe.Pointer(&entries))
- header.Cap = count
- header.Len = count
- header.Data = uintptr(unsafe.Pointer(rawEntries))
-
- var out []*Info
- for _, entry := range entries {
- var mountinfo Info
- mountinfo.Mountpoint = C.GoString(&entry.f_mntonname[0])
- mountinfo.Source = C.GoString(&entry.f_mntfromname[0])
- mountinfo.Fstype = C.GoString(&entry.f_fstypename[0])
- out = append(out, &mountinfo)
- }
- return out, nil
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/mount/mountinfo_linux.go b/containerd/vendor/github.com/docker/docker/pkg/mount/mountinfo_linux.go
deleted file mode 100644
index be69fee..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/mount/mountinfo_linux.go
+++ /dev/null
@@ -1,95 +0,0 @@
-// +build linux
-
-package mount
-
-import (
- "bufio"
- "fmt"
- "io"
- "os"
- "strings"
-)
-
-const (
- /* 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue
- (1)(2)(3) (4) (5) (6) (7) (8) (9) (10) (11)
-
- (1) mount ID: unique identifier of the mount (may be reused after umount)
- (2) parent ID: ID of parent (or of self for the top of the mount tree)
- (3) major:minor: value of st_dev for files on filesystem
- (4) root: root of the mount within the filesystem
- (5) mount point: mount point relative to the process's root
- (6) mount options: per mount options
- (7) optional fields: zero or more fields of the form "tag[:value]"
- (8) separator: marks the end of the optional fields
- (9) filesystem type: name of filesystem of the form "type[.subtype]"
- (10) mount source: filesystem specific information or "none"
- (11) super options: per super block options*/
- mountinfoFormat = "%d %d %d:%d %s %s %s %s"
-)
-
-// Parse /proc/self/mountinfo because comparing Dev and ino does not work from
-// bind mounts
-func parseMountTable() ([]*Info, error) {
- f, err := os.Open("/proc/self/mountinfo")
- if err != nil {
- return nil, err
- }
- defer f.Close()
-
- return parseInfoFile(f)
-}
-
-func parseInfoFile(r io.Reader) ([]*Info, error) {
- var (
- s = bufio.NewScanner(r)
- out = []*Info{}
- )
-
- for s.Scan() {
- if err := s.Err(); err != nil {
- return nil, err
- }
-
- var (
- p = &Info{}
- text = s.Text()
- optionalFields string
- )
-
- if _, err := fmt.Sscanf(text, mountinfoFormat,
- &p.ID, &p.Parent, &p.Major, &p.Minor,
- &p.Root, &p.Mountpoint, &p.Opts, &optionalFields); err != nil {
- return nil, fmt.Errorf("Scanning '%s' failed: %s", text, err)
- }
- // Safe as mountinfo encodes mountpoints with spaces as \040.
- index := strings.Index(text, " - ")
- postSeparatorFields := strings.Fields(text[index+3:])
- if len(postSeparatorFields) < 3 {
- return nil, fmt.Errorf("Error found less than 3 fields post '-' in %q", text)
- }
-
- if optionalFields != "-" {
- p.Optional = optionalFields
- }
-
- p.Fstype = postSeparatorFields[0]
- p.Source = postSeparatorFields[1]
- p.VfsOpts = strings.Join(postSeparatorFields[2:], " ")
- out = append(out, p)
- }
- return out, nil
-}
-
-// PidMountInfo collects the mounts for a specific process ID. If the process
-// ID is unknown, it is better to use `GetMounts` which will inspect
-// "/proc/self/mountinfo" instead.
-func PidMountInfo(pid int) ([]*Info, error) {
- f, err := os.Open(fmt.Sprintf("/proc/%d/mountinfo", pid))
- if err != nil {
- return nil, err
- }
- defer f.Close()
-
- return parseInfoFile(f)
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/mount/mountinfo_unsupported.go b/containerd/vendor/github.com/docker/docker/pkg/mount/mountinfo_unsupported.go
deleted file mode 100644
index 8245f01..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/mount/mountinfo_unsupported.go
+++ /dev/null
@@ -1,12 +0,0 @@
-// +build !linux,!freebsd freebsd,!cgo
-
-package mount
-
-import (
- "fmt"
- "runtime"
-)
-
-func parseMountTable() ([]*Info, error) {
- return nil, fmt.Errorf("mount.parseMountTable is not implemented on %s/%s", runtime.GOOS, runtime.GOARCH)
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/mount/sharedsubtree_linux.go b/containerd/vendor/github.com/docker/docker/pkg/mount/sharedsubtree_linux.go
deleted file mode 100644
index 47303bb..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/mount/sharedsubtree_linux.go
+++ /dev/null
@@ -1,70 +0,0 @@
-// +build linux
-
-package mount
-
-// MakeShared ensures a mounted filesystem has the SHARED mount option enabled.
-// See the supported options in flags.go for further reference.
-func MakeShared(mountPoint string) error {
- return ensureMountedAs(mountPoint, "shared")
-}
-
-// MakeRShared ensures a mounted filesystem has the RSHARED mount option enabled.
-// See the supported options in flags.go for further reference.
-func MakeRShared(mountPoint string) error {
- return ensureMountedAs(mountPoint, "rshared")
-}
-
-// MakePrivate ensures a mounted filesystem has the PRIVATE mount option enabled.
-// See the supported options in flags.go for further reference.
-func MakePrivate(mountPoint string) error {
- return ensureMountedAs(mountPoint, "private")
-}
-
-// MakeRPrivate ensures a mounted filesystem has the RPRIVATE mount option
-// enabled. See the supported options in flags.go for further reference.
-func MakeRPrivate(mountPoint string) error {
- return ensureMountedAs(mountPoint, "rprivate")
-}
-
-// MakeSlave ensures a mounted filesystem has the SLAVE mount option enabled.
-// See the supported options in flags.go for further reference.
-func MakeSlave(mountPoint string) error {
- return ensureMountedAs(mountPoint, "slave")
-}
-
-// MakeRSlave ensures a mounted filesystem has the RSLAVE mount option enabled.
-// See the supported options in flags.go for further reference.
-func MakeRSlave(mountPoint string) error {
- return ensureMountedAs(mountPoint, "rslave")
-}
-
-// MakeUnbindable ensures a mounted filesystem has the UNBINDABLE mount option
-// enabled. See the supported options in flags.go for further reference.
-func MakeUnbindable(mountPoint string) error {
- return ensureMountedAs(mountPoint, "unbindable")
-}
-
-// MakeRUnbindable ensures a mounted filesystem has the RUNBINDABLE mount
-// option enabled. See the supported options in flags.go for further reference.
-func MakeRUnbindable(mountPoint string) error {
- return ensureMountedAs(mountPoint, "runbindable")
-}
-
-func ensureMountedAs(mountPoint, options string) error {
- mounted, err := Mounted(mountPoint)
- if err != nil {
- return err
- }
-
- if !mounted {
- if err := Mount(mountPoint, mountPoint, "none", "bind,rw"); err != nil {
- return err
- }
- }
- mounted, err = Mounted(mountPoint)
- if err != nil {
- return err
- }
-
- return ForceMount("", mountPoint, "none", options)
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/symlink/LICENSE.APACHE b/containerd/vendor/github.com/docker/docker/pkg/symlink/LICENSE.APACHE
deleted file mode 100644
index 9e4bd4d..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/symlink/LICENSE.APACHE
+++ /dev/null
@@ -1,191 +0,0 @@
-
- Apache License
- Version 2.0, January 2004
- http://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 2014-2015 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
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
diff --git a/containerd/vendor/github.com/docker/docker/pkg/symlink/LICENSE.BSD b/containerd/vendor/github.com/docker/docker/pkg/symlink/LICENSE.BSD
deleted file mode 100644
index ac74d8f..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/symlink/LICENSE.BSD
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2014-2015 The Docker & Go Authors. 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 Google Inc. 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
-OWNER 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.
diff --git a/containerd/vendor/github.com/docker/docker/pkg/symlink/README.md b/containerd/vendor/github.com/docker/docker/pkg/symlink/README.md
deleted file mode 100644
index 8dba54f..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/symlink/README.md
+++ /dev/null
@@ -1,6 +0,0 @@
-Package symlink implements EvalSymlinksInScope which is an extension of filepath.EvalSymlinks,
-as well as a Windows long-path aware version of filepath.EvalSymlinks
-from the [Go standard library](https://golang.org/pkg/path/filepath).
-
-The code from filepath.EvalSymlinks has been adapted in fs.go.
-Please read the LICENSE.BSD file that governs fs.go and LICENSE.APACHE for fs_test.go.
diff --git a/containerd/vendor/github.com/docker/docker/pkg/symlink/fs.go b/containerd/vendor/github.com/docker/docker/pkg/symlink/fs.go
deleted file mode 100644
index dcf707f..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/symlink/fs.go
+++ /dev/null
@@ -1,143 +0,0 @@
-// Copyright 2012 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE.BSD file.
-
-// This code is a modified version of path/filepath/symlink.go from the Go standard library.
-
-package symlink
-
-import (
- "bytes"
- "errors"
- "os"
- "path/filepath"
- "strings"
-
- "github.com/docker/docker/pkg/system"
-)
-
-// FollowSymlinkInScope is a wrapper around evalSymlinksInScope that returns an
-// absolute path. This function handles paths in a platform-agnostic manner.
-func FollowSymlinkInScope(path, root string) (string, error) {
- path, err := filepath.Abs(filepath.FromSlash(path))
- if err != nil {
- return "", err
- }
- root, err = filepath.Abs(filepath.FromSlash(root))
- if err != nil {
- return "", err
- }
- return evalSymlinksInScope(path, root)
-}
-
-// evalSymlinksInScope will evaluate symlinks in `path` within a scope `root` and return
-// a result guaranteed to be contained within the scope `root`, at the time of the call.
-// Symlinks in `root` are not evaluated and left as-is.
-// Errors encountered while attempting to evaluate symlinks in path will be returned.
-// Non-existing paths are valid and do not constitute an error.
-// `path` has to contain `root` as a prefix, or else an error will be returned.
-// Trying to break out from `root` does not constitute an error.
-//
-// Example:
-// If /foo/bar -> /outside,
-// FollowSymlinkInScope("/foo/bar", "/foo") == "/foo/outside" instead of "/oustide"
-//
-// IMPORTANT: it is the caller's responsibility to call evalSymlinksInScope *after* relevant symlinks
-// are created and not to create subsequently, additional symlinks that could potentially make a
-// previously-safe path, unsafe. Example: if /foo/bar does not exist, evalSymlinksInScope("/foo/bar", "/foo")
-// would return "/foo/bar". If one makes /foo/bar a symlink to /baz subsequently, then "/foo/bar" should
-// no longer be considered safely contained in "/foo".
-func evalSymlinksInScope(path, root string) (string, error) {
- root = filepath.Clean(root)
- if path == root {
- return path, nil
- }
- if !strings.HasPrefix(path, root) {
- return "", errors.New("evalSymlinksInScope: " + path + " is not in " + root)
- }
- const maxIter = 255
- originalPath := path
- // given root of "/a" and path of "/a/b/../../c" we want path to be "/b/../../c"
- path = path[len(root):]
- if root == string(filepath.Separator) {
- path = string(filepath.Separator) + path
- }
- if !strings.HasPrefix(path, string(filepath.Separator)) {
- return "", errors.New("evalSymlinksInScope: " + path + " is not in " + root)
- }
- path = filepath.Clean(path)
- // consume path by taking each frontmost path element,
- // expanding it if it's a symlink, and appending it to b
- var b bytes.Buffer
- // b here will always be considered to be the "current absolute path inside
- // root" when we append paths to it, we also append a slash and use
- // filepath.Clean after the loop to trim the trailing slash
- for n := 0; path != ""; n++ {
- if n > maxIter {
- return "", errors.New("evalSymlinksInScope: too many links in " + originalPath)
- }
-
- // find next path component, p
- i := strings.IndexRune(path, filepath.Separator)
- var p string
- if i == -1 {
- p, path = path, ""
- } else {
- p, path = path[:i], path[i+1:]
- }
-
- if p == "" {
- continue
- }
-
- // this takes a b.String() like "b/../" and a p like "c" and turns it
- // into "/b/../c" which then gets filepath.Cleaned into "/c" and then
- // root gets prepended and we Clean again (to remove any trailing slash
- // if the first Clean gave us just "/")
- cleanP := filepath.Clean(string(filepath.Separator) + b.String() + p)
- if cleanP == string(filepath.Separator) {
- // never Lstat "/" itself
- b.Reset()
- continue
- }
- fullP := filepath.Clean(root + cleanP)
-
- fi, err := os.Lstat(fullP)
- if os.IsNotExist(err) {
- // if p does not exist, accept it
- b.WriteString(p)
- b.WriteRune(filepath.Separator)
- continue
- }
- if err != nil {
- return "", err
- }
- if fi.Mode()&os.ModeSymlink == 0 {
- b.WriteString(p + string(filepath.Separator))
- continue
- }
-
- // it's a symlink, put it at the front of path
- dest, err := os.Readlink(fullP)
- if err != nil {
- return "", err
- }
- if system.IsAbs(dest) {
- b.Reset()
- }
- path = dest + string(filepath.Separator) + path
- }
-
- // see note above on "fullP := ..." for why this is double-cleaned and
- // what's happening here
- return filepath.Clean(root + filepath.Clean(string(filepath.Separator)+b.String())), nil
-}
-
-// EvalSymlinks returns the path name after the evaluation of any symbolic
-// links.
-// If path is relative the result will be relative to the current directory,
-// unless one of the components is an absolute symbolic link.
-// This version has been updated to support long paths prepended with `\\?\`.
-func EvalSymlinks(path string) (string, error) {
- return evalSymlinks(path)
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/symlink/fs_unix.go b/containerd/vendor/github.com/docker/docker/pkg/symlink/fs_unix.go
deleted file mode 100644
index 818004f..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/symlink/fs_unix.go
+++ /dev/null
@@ -1,11 +0,0 @@
-// +build !windows
-
-package symlink
-
-import (
- "path/filepath"
-)
-
-func evalSymlinks(path string) (string, error) {
- return filepath.EvalSymlinks(path)
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/symlink/fs_windows.go b/containerd/vendor/github.com/docker/docker/pkg/symlink/fs_windows.go
deleted file mode 100644
index 29bd456..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/symlink/fs_windows.go
+++ /dev/null
@@ -1,156 +0,0 @@
-package symlink
-
-import (
- "bytes"
- "errors"
- "os"
- "path/filepath"
- "strings"
- "syscall"
-
- "github.com/docker/docker/pkg/longpath"
-)
-
-func toShort(path string) (string, error) {
- p, err := syscall.UTF16FromString(path)
- if err != nil {
- return "", err
- }
- b := p // GetShortPathName says we can reuse buffer
- n, err := syscall.GetShortPathName(&p[0], &b[0], uint32(len(b)))
- if err != nil {
- return "", err
- }
- if n > uint32(len(b)) {
- b = make([]uint16, n)
- n, err = syscall.GetShortPathName(&p[0], &b[0], uint32(len(b)))
- if err != nil {
- return "", err
- }
- }
- return syscall.UTF16ToString(b), nil
-}
-
-func toLong(path string) (string, error) {
- p, err := syscall.UTF16FromString(path)
- if err != nil {
- return "", err
- }
- b := p // GetLongPathName says we can reuse buffer
- n, err := syscall.GetLongPathName(&p[0], &b[0], uint32(len(b)))
- if err != nil {
- return "", err
- }
- if n > uint32(len(b)) {
- b = make([]uint16, n)
- n, err = syscall.GetLongPathName(&p[0], &b[0], uint32(len(b)))
- if err != nil {
- return "", err
- }
- }
- b = b[:n]
- return syscall.UTF16ToString(b), nil
-}
-
-func evalSymlinks(path string) (string, error) {
- path, err := walkSymlinks(path)
- if err != nil {
- return "", err
- }
-
- p, err := toShort(path)
- if err != nil {
- return "", err
- }
- p, err = toLong(p)
- if err != nil {
- return "", err
- }
- // syscall.GetLongPathName does not change the case of the drive letter,
- // but the result of EvalSymlinks must be unique, so we have
- // EvalSymlinks(`c:\a`) == EvalSymlinks(`C:\a`).
- // Make drive letter upper case.
- if len(p) >= 2 && p[1] == ':' && 'a' <= p[0] && p[0] <= 'z' {
- p = string(p[0]+'A'-'a') + p[1:]
- } else if len(p) >= 6 && p[5] == ':' && 'a' <= p[4] && p[4] <= 'z' {
- p = p[:3] + string(p[4]+'A'-'a') + p[5:]
- }
- return filepath.Clean(p), nil
-}
-
-const utf8RuneSelf = 0x80
-
-func walkSymlinks(path string) (string, error) {
- const maxIter = 255
- originalPath := path
- // consume path by taking each frontmost path element,
- // expanding it if it's a symlink, and appending it to b
- var b bytes.Buffer
- for n := 0; path != ""; n++ {
- if n > maxIter {
- return "", errors.New("EvalSymlinks: too many links in " + originalPath)
- }
-
- // A path beginnging with `\\?\` represents the root, so automatically
- // skip that part and begin processing the next segment.
- if strings.HasPrefix(path, longpath.Prefix) {
- b.WriteString(longpath.Prefix)
- path = path[4:]
- continue
- }
-
- // find next path component, p
- var i = -1
- for j, c := range path {
- if c < utf8RuneSelf && os.IsPathSeparator(uint8(c)) {
- i = j
- break
- }
- }
- var p string
- if i == -1 {
- p, path = path, ""
- } else {
- p, path = path[:i], path[i+1:]
- }
-
- if p == "" {
- if b.Len() == 0 {
- // must be absolute path
- b.WriteRune(filepath.Separator)
- }
- continue
- }
-
- // If this is the first segment after the long path prefix, accept the
- // current segment as a volume root or UNC share and move on to the next.
- if b.String() == longpath.Prefix {
- b.WriteString(p)
- b.WriteRune(filepath.Separator)
- continue
- }
-
- fi, err := os.Lstat(b.String() + p)
- if err != nil {
- return "", err
- }
- if fi.Mode()&os.ModeSymlink == 0 {
- b.WriteString(p)
- if path != "" || (b.Len() == 2 && len(p) == 2 && p[1] == ':') {
- b.WriteRune(filepath.Separator)
- }
- continue
- }
-
- // it's a symlink, put it at the front of path
- dest, err := os.Readlink(b.String() + p)
- if err != nil {
- return "", err
- }
- if filepath.IsAbs(dest) || os.IsPathSeparator(dest[0]) {
- b.Reset()
- }
- path = dest + string(filepath.Separator) + path
- }
- return filepath.Clean(b.String()), nil
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/chtimes.go b/containerd/vendor/github.com/docker/docker/pkg/system/chtimes.go
deleted file mode 100644
index 31ed9ff..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/chtimes.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package system
-
-import (
- "os"
- "time"
-)
-
-// Chtimes changes the access time and modified time of a file at the given path
-func Chtimes(name string, atime time.Time, mtime time.Time) error {
- unixMinTime := time.Unix(0, 0)
- // The max Unix time is 33 bits set
- unixMaxTime := unixMinTime.Add((1<<33 - 1) * time.Second)
-
- // If the modified time is prior to the Unix Epoch, or after the
- // end of Unix Time, os.Chtimes has undefined behavior
- // default to Unix Epoch in this case, just in case
-
- if atime.Before(unixMinTime) || atime.After(unixMaxTime) {
- atime = unixMinTime
- }
-
- if mtime.Before(unixMinTime) || mtime.After(unixMaxTime) {
- mtime = unixMinTime
- }
-
- if err := os.Chtimes(name, atime, mtime); err != nil {
- return err
- }
-
- return nil
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/errors.go b/containerd/vendor/github.com/docker/docker/pkg/system/errors.go
deleted file mode 100644
index 2883189..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/errors.go
+++ /dev/null
@@ -1,10 +0,0 @@
-package system
-
-import (
- "errors"
-)
-
-var (
- // ErrNotSupportedPlatform means the platform is not supported.
- ErrNotSupportedPlatform = errors.New("platform and architecture is not supported")
-)
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/events_windows.go b/containerd/vendor/github.com/docker/docker/pkg/system/events_windows.go
deleted file mode 100644
index 04e2de7..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/events_windows.go
+++ /dev/null
@@ -1,83 +0,0 @@
-package system
-
-// This file implements syscalls for Win32 events which are not implemented
-// in golang.
-
-import (
- "syscall"
- "unsafe"
-)
-
-var (
- procCreateEvent = modkernel32.NewProc("CreateEventW")
- procOpenEvent = modkernel32.NewProc("OpenEventW")
- procSetEvent = modkernel32.NewProc("SetEvent")
- procResetEvent = modkernel32.NewProc("ResetEvent")
- procPulseEvent = modkernel32.NewProc("PulseEvent")
-)
-
-// CreateEvent implements win32 CreateEventW func in golang. It will create an event object.
-func CreateEvent(eventAttributes *syscall.SecurityAttributes, manualReset bool, initialState bool, name string) (handle syscall.Handle, err error) {
- namep, _ := syscall.UTF16PtrFromString(name)
- var _p1 uint32
- if manualReset {
- _p1 = 1
- }
- var _p2 uint32
- if initialState {
- _p2 = 1
- }
- r0, _, e1 := procCreateEvent.Call(uintptr(unsafe.Pointer(eventAttributes)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(namep)))
- use(unsafe.Pointer(namep))
- handle = syscall.Handle(r0)
- if handle == syscall.InvalidHandle {
- err = e1
- }
- return
-}
-
-// OpenEvent implements win32 OpenEventW func in golang. It opens an event object.
-func OpenEvent(desiredAccess uint32, inheritHandle bool, name string) (handle syscall.Handle, err error) {
- namep, _ := syscall.UTF16PtrFromString(name)
- var _p1 uint32
- if inheritHandle {
- _p1 = 1
- }
- r0, _, e1 := procOpenEvent.Call(uintptr(desiredAccess), uintptr(_p1), uintptr(unsafe.Pointer(namep)))
- use(unsafe.Pointer(namep))
- handle = syscall.Handle(r0)
- if handle == syscall.InvalidHandle {
- err = e1
- }
- return
-}
-
-// SetEvent implements win32 SetEvent func in golang.
-func SetEvent(handle syscall.Handle) (err error) {
- return setResetPulse(handle, procSetEvent)
-}
-
-// ResetEvent implements win32 ResetEvent func in golang.
-func ResetEvent(handle syscall.Handle) (err error) {
- return setResetPulse(handle, procResetEvent)
-}
-
-// PulseEvent implements win32 PulseEvent func in golang.
-func PulseEvent(handle syscall.Handle) (err error) {
- return setResetPulse(handle, procPulseEvent)
-}
-
-func setResetPulse(handle syscall.Handle, proc *syscall.LazyProc) (err error) {
- r0, _, _ := proc.Call(uintptr(handle))
- if r0 != 0 {
- err = syscall.Errno(r0)
- }
- return
-}
-
-var temp unsafe.Pointer
-
-// use ensures a variable is kept alive without the GC freeing while still needed
-func use(p unsafe.Pointer) {
- temp = p
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/filesys.go b/containerd/vendor/github.com/docker/docker/pkg/system/filesys.go
deleted file mode 100644
index c14feb8..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/filesys.go
+++ /dev/null
@@ -1,19 +0,0 @@
-// +build !windows
-
-package system
-
-import (
- "os"
- "path/filepath"
-)
-
-// MkdirAll creates a directory named path along with any necessary parents,
-// with permission specified by attribute perm for all dir created.
-func MkdirAll(path string, perm os.FileMode) error {
- return os.MkdirAll(path, perm)
-}
-
-// IsAbs is a platform-specific wrapper for filepath.IsAbs.
-func IsAbs(path string) bool {
- return filepath.IsAbs(path)
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/filesys_windows.go b/containerd/vendor/github.com/docker/docker/pkg/system/filesys_windows.go
deleted file mode 100644
index 16823d5..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/filesys_windows.go
+++ /dev/null
@@ -1,82 +0,0 @@
-// +build windows
-
-package system
-
-import (
- "os"
- "path/filepath"
- "regexp"
- "strings"
- "syscall"
-)
-
-// MkdirAll implementation that is volume path aware for Windows.
-func MkdirAll(path string, perm os.FileMode) error {
- if re := regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}$`); re.MatchString(path) {
- return nil
- }
-
- // The rest of this method is copied from os.MkdirAll and should be kept
- // as-is to ensure compatibility.
-
- // Fast path: if we can tell whether path is a directory or file, stop with success or error.
- dir, err := os.Stat(path)
- if err == nil {
- if dir.IsDir() {
- return nil
- }
- return &os.PathError{
- Op: "mkdir",
- Path: path,
- Err: syscall.ENOTDIR,
- }
- }
-
- // Slow path: make sure parent exists and then call Mkdir for path.
- i := len(path)
- for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator.
- i--
- }
-
- j := i
- for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element.
- j--
- }
-
- if j > 1 {
- // Create parent
- err = MkdirAll(path[0:j-1], perm)
- if err != nil {
- return err
- }
- }
-
- // Parent now exists; invoke Mkdir and use its result.
- err = os.Mkdir(path, perm)
- if err != nil {
- // Handle arguments like "foo/." by
- // double-checking that directory doesn't exist.
- dir, err1 := os.Lstat(path)
- if err1 == nil && dir.IsDir() {
- return nil
- }
- return err
- }
- return nil
-}
-
-// IsAbs is a platform-specific wrapper for filepath.IsAbs. On Windows,
-// golang filepath.IsAbs does not consider a path \windows\system32 as absolute
-// as it doesn't start with a drive-letter/colon combination. However, in
-// docker we need to verify things such as WORKDIR /windows/system32 in
-// a Dockerfile (which gets translated to \windows\system32 when being processed
-// by the daemon. This SHOULD be treated as absolute from a docker processing
-// perspective.
-func IsAbs(path string) bool {
- if !filepath.IsAbs(path) {
- if !strings.HasPrefix(path, string(os.PathSeparator)) {
- return false
- }
- }
- return true
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/lstat.go b/containerd/vendor/github.com/docker/docker/pkg/system/lstat.go
deleted file mode 100644
index bd23c4d..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/lstat.go
+++ /dev/null
@@ -1,19 +0,0 @@
-// +build !windows
-
-package system
-
-import (
- "syscall"
-)
-
-// Lstat takes a path to a file and returns
-// a system.StatT type pertaining to that file.
-//
-// Throws an error if the file does not exist
-func Lstat(path string) (*StatT, error) {
- s := &syscall.Stat_t{}
- if err := syscall.Lstat(path, s); err != nil {
- return nil, err
- }
- return fromStatT(s)
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/lstat_windows.go b/containerd/vendor/github.com/docker/docker/pkg/system/lstat_windows.go
deleted file mode 100644
index 49e87eb..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/lstat_windows.go
+++ /dev/null
@@ -1,25 +0,0 @@
-// +build windows
-
-package system
-
-import (
- "os"
-)
-
-// Lstat calls os.Lstat to get a fileinfo interface back.
-// This is then copied into our own locally defined structure.
-// Note the Linux version uses fromStatT to do the copy back,
-// but that not strictly necessary when already in an OS specific module.
-func Lstat(path string) (*StatT, error) {
- fi, err := os.Lstat(path)
- if err != nil {
- return nil, err
- }
-
- return &StatT{
- name: fi.Name(),
- size: fi.Size(),
- mode: fi.Mode(),
- modTime: fi.ModTime(),
- isDir: fi.IsDir()}, nil
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/meminfo.go b/containerd/vendor/github.com/docker/docker/pkg/system/meminfo.go
deleted file mode 100644
index 3b6e947..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/meminfo.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package system
-
-// MemInfo contains memory statistics of the host system.
-type MemInfo struct {
- // Total usable RAM (i.e. physical RAM minus a few reserved bits and the
- // kernel binary code).
- MemTotal int64
-
- // Amount of free memory.
- MemFree int64
-
- // Total amount of swap space available.
- SwapTotal int64
-
- // Amount of swap space that is currently unused.
- SwapFree int64
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/meminfo_linux.go b/containerd/vendor/github.com/docker/docker/pkg/system/meminfo_linux.go
deleted file mode 100644
index a07bb17..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/meminfo_linux.go
+++ /dev/null
@@ -1,66 +0,0 @@
-package system
-
-import (
- "bufio"
- "io"
- "os"
- "strconv"
- "strings"
-
- "github.com/docker/docker/pkg/units"
-)
-
-// ReadMemInfo retrieves memory statistics of the host system and returns a
-// MemInfo type.
-func ReadMemInfo() (*MemInfo, error) {
- file, err := os.Open("/proc/meminfo")
- if err != nil {
- return nil, err
- }
- defer file.Close()
- return parseMemInfo(file)
-}
-
-// parseMemInfo parses the /proc/meminfo file into
-// a MemInfo object given a io.Reader to the file.
-//
-// Throws error if there are problems reading from the file
-func parseMemInfo(reader io.Reader) (*MemInfo, error) {
- meminfo := &MemInfo{}
- scanner := bufio.NewScanner(reader)
- for scanner.Scan() {
- // Expected format: ["MemTotal:", "1234", "kB"]
- parts := strings.Fields(scanner.Text())
-
- // Sanity checks: Skip malformed entries.
- if len(parts) < 3 || parts[2] != "kB" {
- continue
- }
-
- // Convert to bytes.
- size, err := strconv.Atoi(parts[1])
- if err != nil {
- continue
- }
- bytes := int64(size) * units.KiB
-
- switch parts[0] {
- case "MemTotal:":
- meminfo.MemTotal = bytes
- case "MemFree:":
- meminfo.MemFree = bytes
- case "SwapTotal:":
- meminfo.SwapTotal = bytes
- case "SwapFree:":
- meminfo.SwapFree = bytes
- }
-
- }
-
- // Handle errors that may have occurred during the reading of the file.
- if err := scanner.Err(); err != nil {
- return nil, err
- }
-
- return meminfo, nil
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go b/containerd/vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go
deleted file mode 100644
index 82ddd30..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go
+++ /dev/null
@@ -1,8 +0,0 @@
-// +build !linux,!windows
-
-package system
-
-// ReadMemInfo is not supported on platforms other than linux and windows.
-func ReadMemInfo() (*MemInfo, error) {
- return nil, ErrNotSupportedPlatform
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/meminfo_windows.go b/containerd/vendor/github.com/docker/docker/pkg/system/meminfo_windows.go
deleted file mode 100644
index d466425..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/meminfo_windows.go
+++ /dev/null
@@ -1,44 +0,0 @@
-package system
-
-import (
- "syscall"
- "unsafe"
-)
-
-var (
- modkernel32 = syscall.NewLazyDLL("kernel32.dll")
-
- procGlobalMemoryStatusEx = modkernel32.NewProc("GlobalMemoryStatusEx")
-)
-
-// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366589(v=vs.85).aspx
-// https://msdn.microsoft.com/en-us/library/windows/desktop/aa366770(v=vs.85).aspx
-type memorystatusex struct {
- dwLength uint32
- dwMemoryLoad uint32
- ullTotalPhys uint64
- ullAvailPhys uint64
- ullTotalPageFile uint64
- ullAvailPageFile uint64
- ullTotalVirtual uint64
- ullAvailVirtual uint64
- ullAvailExtendedVirtual uint64
-}
-
-// ReadMemInfo retrieves memory statistics of the host system and returns a
-// MemInfo type.
-func ReadMemInfo() (*MemInfo, error) {
- msi := &memorystatusex{
- dwLength: 64,
- }
- r1, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(msi)))
- if r1 == 0 {
- return &MemInfo{}, nil
- }
- return &MemInfo{
- MemTotal: int64(msi.ullTotalPhys),
- MemFree: int64(msi.ullAvailPhys),
- SwapTotal: int64(msi.ullTotalPageFile),
- SwapFree: int64(msi.ullAvailPageFile),
- }, nil
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/mknod.go b/containerd/vendor/github.com/docker/docker/pkg/system/mknod.go
deleted file mode 100644
index 7395818..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/mknod.go
+++ /dev/null
@@ -1,22 +0,0 @@
-// +build !windows
-
-package system
-
-import (
- "syscall"
-)
-
-// Mknod creates a filesystem node (file, device special file or named pipe) named path
-// with attributes specified by mode and dev.
-func Mknod(path string, mode uint32, dev int) error {
- return syscall.Mknod(path, mode, dev)
-}
-
-// Mkdev is used to build the value of linux devices (in /dev/) which specifies major
-// and minor number of the newly created device special file.
-// Linux device nodes are a bit weird due to backwards compat with 16 bit device nodes.
-// They are, from low to high: the lower 8 bits of the minor, then 12 bits of the major,
-// then the top 12 bits of the minor.
-func Mkdev(major int64, minor int64) uint32 {
- return uint32(((minor & 0xfff00) << 12) | ((major & 0xfff) << 8) | (minor & 0xff))
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/mknod_windows.go b/containerd/vendor/github.com/docker/docker/pkg/system/mknod_windows.go
deleted file mode 100644
index 2e863c0..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/mknod_windows.go
+++ /dev/null
@@ -1,13 +0,0 @@
-// +build windows
-
-package system
-
-// Mknod is not implemented on Windows.
-func Mknod(path string, mode uint32, dev int) error {
- return ErrNotSupportedPlatform
-}
-
-// Mkdev is not implemented on Windows.
-func Mkdev(major int64, minor int64) uint32 {
- panic("Mkdev not implemented on Windows.")
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/stat.go b/containerd/vendor/github.com/docker/docker/pkg/system/stat.go
deleted file mode 100644
index 087034c..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/stat.go
+++ /dev/null
@@ -1,53 +0,0 @@
-// +build !windows
-
-package system
-
-import (
- "syscall"
-)
-
-// StatT type contains status of a file. It contains metadata
-// like permission, owner, group, size, etc about a file.
-type StatT struct {
- mode uint32
- uid uint32
- gid uint32
- rdev uint64
- size int64
- mtim syscall.Timespec
-}
-
-// Mode returns file's permission mode.
-func (s StatT) Mode() uint32 {
- return s.mode
-}
-
-// UID returns file's user id of owner.
-func (s StatT) UID() uint32 {
- return s.uid
-}
-
-// GID returns file's group id of owner.
-func (s StatT) GID() uint32 {
- return s.gid
-}
-
-// Rdev returns file's device ID (if it's special file).
-func (s StatT) Rdev() uint64 {
- return s.rdev
-}
-
-// Size returns file's size.
-func (s StatT) Size() int64 {
- return s.size
-}
-
-// Mtim returns file's last modification time.
-func (s StatT) Mtim() syscall.Timespec {
- return s.mtim
-}
-
-// GetLastModification returns file's last modification time.
-func (s StatT) GetLastModification() syscall.Timespec {
- return s.Mtim()
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/stat_freebsd.go b/containerd/vendor/github.com/docker/docker/pkg/system/stat_freebsd.go
deleted file mode 100644
index d0fb6f1..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/stat_freebsd.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package system
-
-import (
- "syscall"
-)
-
-// fromStatT converts a syscall.Stat_t type to a system.Stat_t type
-func fromStatT(s *syscall.Stat_t) (*StatT, error) {
- return &StatT{size: s.Size,
- mode: uint32(s.Mode),
- uid: s.Uid,
- gid: s.Gid,
- rdev: uint64(s.Rdev),
- mtim: s.Mtimespec}, nil
-}
-
-// Stat takes a path to a file and returns
-// a system.Stat_t type pertaining to that file.
-//
-// Throws an error if the file does not exist
-func Stat(path string) (*StatT, error) {
- s := &syscall.Stat_t{}
- if err := syscall.Stat(path, s); err != nil {
- return nil, err
- }
- return fromStatT(s)
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/stat_linux.go b/containerd/vendor/github.com/docker/docker/pkg/system/stat_linux.go
deleted file mode 100644
index 8b1eded..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/stat_linux.go
+++ /dev/null
@@ -1,33 +0,0 @@
-package system
-
-import (
- "syscall"
-)
-
-// fromStatT converts a syscall.Stat_t type to a system.Stat_t type
-func fromStatT(s *syscall.Stat_t) (*StatT, error) {
- return &StatT{size: s.Size,
- mode: s.Mode,
- uid: s.Uid,
- gid: s.Gid,
- rdev: s.Rdev,
- mtim: s.Mtim}, nil
-}
-
-// FromStatT exists only on linux, and loads a system.StatT from a
-// syscal.Stat_t.
-func FromStatT(s *syscall.Stat_t) (*StatT, error) {
- return fromStatT(s)
-}
-
-// Stat takes a path to a file and returns
-// a system.StatT type pertaining to that file.
-//
-// Throws an error if the file does not exist
-func Stat(path string) (*StatT, error) {
- s := &syscall.Stat_t{}
- if err := syscall.Stat(path, s); err != nil {
- return nil, err
- }
- return fromStatT(s)
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/stat_unsupported.go b/containerd/vendor/github.com/docker/docker/pkg/system/stat_unsupported.go
deleted file mode 100644
index 381ea82..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/stat_unsupported.go
+++ /dev/null
@@ -1,17 +0,0 @@
-// +build !linux,!windows,!freebsd
-
-package system
-
-import (
- "syscall"
-)
-
-// fromStatT creates a system.StatT type from a syscall.Stat_t type
-func fromStatT(s *syscall.Stat_t) (*StatT, error) {
- return &StatT{size: s.Size,
- mode: uint32(s.Mode),
- uid: s.Uid,
- gid: s.Gid,
- rdev: uint64(s.Rdev),
- mtim: s.Mtimespec}, nil
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/stat_windows.go b/containerd/vendor/github.com/docker/docker/pkg/system/stat_windows.go
deleted file mode 100644
index 39490c6..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/stat_windows.go
+++ /dev/null
@@ -1,43 +0,0 @@
-// +build windows
-
-package system
-
-import (
- "os"
- "time"
-)
-
-// StatT type contains status of a file. It contains metadata
-// like name, permission, size, etc about a file.
-type StatT struct {
- name string
- size int64
- mode os.FileMode
- modTime time.Time
- isDir bool
-}
-
-// Name returns file's name.
-func (s StatT) Name() string {
- return s.name
-}
-
-// Size returns file's size.
-func (s StatT) Size() int64 {
- return s.size
-}
-
-// Mode returns file's permission mode.
-func (s StatT) Mode() os.FileMode {
- return s.mode
-}
-
-// ModTime returns file's last modification time.
-func (s StatT) ModTime() time.Time {
- return s.modTime
-}
-
-// IsDir returns whether file is actually a directory.
-func (s StatT) IsDir() bool {
- return s.isDir
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/syscall_unix.go b/containerd/vendor/github.com/docker/docker/pkg/system/syscall_unix.go
deleted file mode 100644
index f1497c5..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/syscall_unix.go
+++ /dev/null
@@ -1,11 +0,0 @@
-// +build linux freebsd
-
-package system
-
-import "syscall"
-
-// Unmount is a platform-specific helper function to call
-// the unmount syscall.
-func Unmount(dest string) error {
- return syscall.Unmount(dest, 0)
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/syscall_windows.go b/containerd/vendor/github.com/docker/docker/pkg/system/syscall_windows.go
deleted file mode 100644
index b3b94cb..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/syscall_windows.go
+++ /dev/null
@@ -1,7 +0,0 @@
-package system
-
-// Unmount is a platform-specific helper function to call
-// the unmount syscall. Not supported on Windows
-func Unmount(dest string) error {
- return nil
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/umask.go b/containerd/vendor/github.com/docker/docker/pkg/system/umask.go
deleted file mode 100644
index c670fcd..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/umask.go
+++ /dev/null
@@ -1,13 +0,0 @@
-// +build !windows
-
-package system
-
-import (
- "syscall"
-)
-
-// Umask sets current process's file mode creation mask to newmask
-// and return oldmask.
-func Umask(newmask int) (oldmask int, err error) {
- return syscall.Umask(newmask), nil
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/umask_windows.go b/containerd/vendor/github.com/docker/docker/pkg/system/umask_windows.go
deleted file mode 100644
index 13f1de1..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/umask_windows.go
+++ /dev/null
@@ -1,9 +0,0 @@
-// +build windows
-
-package system
-
-// Umask is not supported on the windows platform.
-func Umask(newmask int) (oldmask int, err error) {
- // should not be called on cli code path
- return 0, ErrNotSupportedPlatform
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/utimes_darwin.go b/containerd/vendor/github.com/docker/docker/pkg/system/utimes_darwin.go
deleted file mode 100644
index 0a16197..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/utimes_darwin.go
+++ /dev/null
@@ -1,8 +0,0 @@
-package system
-
-import "syscall"
-
-// LUtimesNano is not supported by darwin platform.
-func LUtimesNano(path string, ts []syscall.Timespec) error {
- return ErrNotSupportedPlatform
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/utimes_freebsd.go b/containerd/vendor/github.com/docker/docker/pkg/system/utimes_freebsd.go
deleted file mode 100644
index e2eac3b..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/utimes_freebsd.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package system
-
-import (
- "syscall"
- "unsafe"
-)
-
-// LUtimesNano is used to change access and modification time of the specified path.
-// It's used for symbol link file because syscall.UtimesNano doesn't support a NOFOLLOW flag atm.
-func LUtimesNano(path string, ts []syscall.Timespec) error {
- var _path *byte
- _path, err := syscall.BytePtrFromString(path)
- if err != nil {
- return err
- }
-
- if _, _, err := syscall.Syscall(syscall.SYS_LUTIMES, uintptr(unsafe.Pointer(_path)), uintptr(unsafe.Pointer(&ts[0])), 0); err != 0 && err != syscall.ENOSYS {
- return err
- }
-
- return nil
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/utimes_linux.go b/containerd/vendor/github.com/docker/docker/pkg/system/utimes_linux.go
deleted file mode 100644
index 007bfa8..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/utimes_linux.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package system
-
-import (
- "syscall"
- "unsafe"
-)
-
-// LUtimesNano is used to change access and modification time of the speficied path.
-// It's used for symbol link file because syscall.UtimesNano doesn't support a NOFOLLOW flag atm.
-func LUtimesNano(path string, ts []syscall.Timespec) error {
- // These are not currently available in syscall
- atFdCwd := -100
- atSymLinkNoFollow := 0x100
-
- var _path *byte
- _path, err := syscall.BytePtrFromString(path)
- if err != nil {
- return err
- }
-
- if _, _, err := syscall.Syscall6(syscall.SYS_UTIMENSAT, uintptr(atFdCwd), uintptr(unsafe.Pointer(_path)), uintptr(unsafe.Pointer(&ts[0])), uintptr(atSymLinkNoFollow), 0, 0); err != 0 && err != syscall.ENOSYS {
- return err
- }
-
- return nil
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/utimes_unsupported.go b/containerd/vendor/github.com/docker/docker/pkg/system/utimes_unsupported.go
deleted file mode 100644
index 50c3a04..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/utimes_unsupported.go
+++ /dev/null
@@ -1,10 +0,0 @@
-// +build !linux,!freebsd,!darwin
-
-package system
-
-import "syscall"
-
-// LUtimesNano is not supported on platforms other than linux, freebsd and darwin.
-func LUtimesNano(path string, ts []syscall.Timespec) error {
- return ErrNotSupportedPlatform
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/xattrs_linux.go b/containerd/vendor/github.com/docker/docker/pkg/system/xattrs_linux.go
deleted file mode 100644
index d2e2c05..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/xattrs_linux.go
+++ /dev/null
@@ -1,63 +0,0 @@
-package system
-
-import (
- "syscall"
- "unsafe"
-)
-
-// Lgetxattr retrieves the value of the extended attribute identified by attr
-// and associated with the given path in the file system.
-// It will returns a nil slice and nil error if the xattr is not set.
-func Lgetxattr(path string, attr string) ([]byte, error) {
- pathBytes, err := syscall.BytePtrFromString(path)
- if err != nil {
- return nil, err
- }
- attrBytes, err := syscall.BytePtrFromString(attr)
- if err != nil {
- return nil, err
- }
-
- dest := make([]byte, 128)
- destBytes := unsafe.Pointer(&dest[0])
- sz, _, errno := syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0)
- if errno == syscall.ENODATA {
- return nil, nil
- }
- if errno == syscall.ERANGE {
- dest = make([]byte, sz)
- destBytes := unsafe.Pointer(&dest[0])
- sz, _, errno = syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0)
- }
- if errno != 0 {
- return nil, errno
- }
-
- return dest[:sz], nil
-}
-
-var _zero uintptr
-
-// Lsetxattr sets the value of the extended attribute identified by attr
-// and associated with the given path in the file system.
-func Lsetxattr(path string, attr string, data []byte, flags int) error {
- pathBytes, err := syscall.BytePtrFromString(path)
- if err != nil {
- return err
- }
- attrBytes, err := syscall.BytePtrFromString(attr)
- if err != nil {
- return err
- }
- var dataBytes unsafe.Pointer
- if len(data) > 0 {
- dataBytes = unsafe.Pointer(&data[0])
- } else {
- dataBytes = unsafe.Pointer(&_zero)
- }
- _, _, errno := syscall.Syscall6(syscall.SYS_LSETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(dataBytes), uintptr(len(data)), uintptr(flags), 0)
- if errno != 0 {
- return errno
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/system/xattrs_unsupported.go b/containerd/vendor/github.com/docker/docker/pkg/system/xattrs_unsupported.go
deleted file mode 100644
index 0114f22..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/system/xattrs_unsupported.go
+++ /dev/null
@@ -1,13 +0,0 @@
-// +build !linux
-
-package system
-
-// Lgetxattr is not supported on platforms other than linux.
-func Lgetxattr(path string, attr string) ([]byte, error) {
- return nil, ErrNotSupportedPlatform
-}
-
-// Lsetxattr is not supported on platforms other than linux.
-func Lsetxattr(path string, attr string, data []byte, flags int) error {
- return ErrNotSupportedPlatform
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/units/duration.go b/containerd/vendor/github.com/docker/docker/pkg/units/duration.go
deleted file mode 100644
index c219a8a..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/units/duration.go
+++ /dev/null
@@ -1,33 +0,0 @@
-// Package units provides helper function to parse and print size and time units
-// in human-readable format.
-package units
-
-import (
- "fmt"
- "time"
-)
-
-// HumanDuration returns a human-readable approximation of a duration
-// (eg. "About a minute", "4 hours ago", etc.).
-func HumanDuration(d time.Duration) string {
- if seconds := int(d.Seconds()); seconds < 1 {
- return "Less than a second"
- } else if seconds < 60 {
- return fmt.Sprintf("%d seconds", seconds)
- } else if minutes := int(d.Minutes()); minutes == 1 {
- return "About a minute"
- } else if minutes < 60 {
- return fmt.Sprintf("%d minutes", minutes)
- } else if hours := int(d.Hours()); hours == 1 {
- return "About an hour"
- } else if hours < 48 {
- return fmt.Sprintf("%d hours", hours)
- } else if hours < 24*7*2 {
- return fmt.Sprintf("%d days", hours/24)
- } else if hours < 24*30*3 {
- return fmt.Sprintf("%d weeks", hours/24/7)
- } else if hours < 24*365*2 {
- return fmt.Sprintf("%d months", hours/24/30)
- }
- return fmt.Sprintf("%d years", int(d.Hours())/24/365)
-}
diff --git a/containerd/vendor/github.com/docker/docker/pkg/units/size.go b/containerd/vendor/github.com/docker/docker/pkg/units/size.go
deleted file mode 100644
index 3b59daf..0000000
--- a/containerd/vendor/github.com/docker/docker/pkg/units/size.go
+++ /dev/null
@@ -1,95 +0,0 @@
-package units
-
-import (
- "fmt"
- "regexp"
- "strconv"
- "strings"
-)
-
-// See: http://en.wikipedia.org/wiki/Binary_prefix
-const (
- // Decimal
-
- KB = 1000
- MB = 1000 * KB
- GB = 1000 * MB
- TB = 1000 * GB
- PB = 1000 * TB
-
- // Binary
-
- KiB = 1024
- MiB = 1024 * KiB
- GiB = 1024 * MiB
- TiB = 1024 * GiB
- PiB = 1024 * TiB
-)
-
-type unitMap map[string]int64
-
-var (
- decimalMap = unitMap{"k": KB, "m": MB, "g": GB, "t": TB, "p": PB}
- binaryMap = unitMap{"k": KiB, "m": MiB, "g": GiB, "t": TiB, "p": PiB}
- sizeRegex = regexp.MustCompile(`^(\d+)([kKmMgGtTpP])?[bB]?$`)
-)
-
-var decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
-var binaryAbbrs = []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"}
-
-// CustomSize returns a human-readable approximation of a size
-// using custom format.
-func CustomSize(format string, size float64, base float64, _map []string) string {
- i := 0
- for size >= base {
- size = size / base
- i++
- }
- return fmt.Sprintf(format, size, _map[i])
-}
-
-// HumanSize returns a human-readable approximation of a size
-// capped at 4 valid numbers (eg. "2.746 MB", "796 KB").
-func HumanSize(size float64) string {
- return CustomSize("%.4g %s", size, 1000.0, decimapAbbrs)
-}
-
-// BytesSize returns a human-readable size in bytes, kibibytes,
-// mebibytes, gibibytes, or tebibytes (eg. "44kiB", "17MiB").
-func BytesSize(size float64) string {
- return CustomSize("%.4g %s", size, 1024.0, binaryAbbrs)
-}
-
-// FromHumanSize returns an integer from a human-readable specification of a
-// size using SI standard (eg. "44kB", "17MB").
-func FromHumanSize(size string) (int64, error) {
- return parseSize(size, decimalMap)
-}
-
-// RAMInBytes parses a human-readable string representing an amount of RAM
-// in bytes, kibibytes, mebibytes, gibibytes, or tebibytes and
-// returns the number of bytes, or -1 if the string is unparseable.
-// Units are case-insensitive, and the 'b' suffix is optional.
-func RAMInBytes(size string) (int64, error) {
- return parseSize(size, binaryMap)
-}
-
-// Parses the human-readable size string into the amount it represents.
-func parseSize(sizeStr string, uMap unitMap) (int64, error) {
- matches := sizeRegex.FindStringSubmatch(sizeStr)
- if len(matches) != 3 {
- return -1, fmt.Errorf("invalid size: '%s'", sizeStr)
- }
-
- size, err := strconv.ParseInt(matches[1], 10, 0)
- if err != nil {
- return -1, err
- }
-
- unitPrefix := strings.ToLower(matches[2])
- if mul, ok := uMap[unitPrefix]; ok {
- size *= mul
- }
-
- return size, nil
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/CONTRIBUTING.md b/containerd/vendor/github.com/godbus/dbus/CONTRIBUTING.md
deleted file mode 100644
index c88f9b2..0000000
--- a/containerd/vendor/github.com/godbus/dbus/CONTRIBUTING.md
+++ /dev/null
@@ -1,50 +0,0 @@
-# How to Contribute
-
-## Getting Started
-
-- Fork the repository on GitHub
-- Read the [README](README.markdown) for build and test instructions
-- Play with the project, submit bugs, submit patches!
-
-## Contribution Flow
-
-This is a rough outline of what a contributor's workflow looks like:
-
-- Create a topic branch from where you want to base your work (usually master).
-- Make commits of logical units.
-- Make sure your commit messages are in the proper format (see below).
-- Push your changes to a topic branch in your fork of the repository.
-- Make sure the tests pass, and add any new tests as appropriate.
-- Submit a pull request to the original repository.
-
-Thanks for your contributions!
-
-### Format of the Commit Message
-
-We follow a rough convention for commit messages that is designed to answer two
-questions: what changed and why. The subject line should feature the what and
-the body of the commit should describe the why.
-
-```
-scripts: add the test-cluster command
-
-this uses tmux to setup a test cluster that you can easily kill and
-start for debugging.
-
-Fixes #38
-```
-
-The format can be described more formally as follows:
-
-```
-:
-
-
-
-
-```
-
-The first line is the subject and should be no longer than 70 characters, the
-second line is always blank, and other lines should be wrapped at 80 characters.
-This allows the message to be easier to read on GitHub as well as in various
-git tools.
diff --git a/containerd/vendor/github.com/godbus/dbus/LICENSE b/containerd/vendor/github.com/godbus/dbus/LICENSE
deleted file mode 100644
index 06b252b..0000000
--- a/containerd/vendor/github.com/godbus/dbus/LICENSE
+++ /dev/null
@@ -1,25 +0,0 @@
-Copyright (c) 2013, Georg Reinke ()
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions
-are met:
-
-1. Redistributions of source code must retain the above copyright notice,
-this list of conditions and the following disclaimer.
-
-2. 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.
-
-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.
diff --git a/containerd/vendor/github.com/godbus/dbus/MAINTAINERS b/containerd/vendor/github.com/godbus/dbus/MAINTAINERS
deleted file mode 100644
index e8968ec..0000000
--- a/containerd/vendor/github.com/godbus/dbus/MAINTAINERS
+++ /dev/null
@@ -1,2 +0,0 @@
-Brandon Philips (@philips)
-Brian Waldon (@bcwaldon)
diff --git a/containerd/vendor/github.com/godbus/dbus/README.markdown b/containerd/vendor/github.com/godbus/dbus/README.markdown
deleted file mode 100644
index 3ab2116..0000000
--- a/containerd/vendor/github.com/godbus/dbus/README.markdown
+++ /dev/null
@@ -1,38 +0,0 @@
-dbus
-----
-
-dbus is a simple library that implements native Go client bindings for the
-D-Bus message bus system.
-
-### Features
-
-* Complete native implementation of the D-Bus message protocol
-* Go-like API (channels for signals / asynchronous method calls, Goroutine-safe connections)
-* Subpackages that help with the introspection / property interfaces
-
-### Installation
-
-This packages requires Go 1.1. If you installed it and set up your GOPATH, just run:
-
-```
-go get github.com/godbus/dbus
-```
-
-If you want to use the subpackages, you can install them the same way.
-
-### Usage
-
-The complete package documentation and some simple examples are available at
-[godoc.org](http://godoc.org/github.com/godbus/dbus). Also, the
-[_examples](https://github.com/godbus/dbus/tree/master/_examples) directory
-gives a short overview over the basic usage.
-
-Please note that the API is considered unstable for now and may change without
-further notice.
-
-### License
-
-go.dbus is available under the Simplified BSD License; see LICENSE for the full
-text.
-
-Nearly all of the credit for this library goes to github.com/guelfey/go.dbus.
diff --git a/containerd/vendor/github.com/godbus/dbus/auth.go b/containerd/vendor/github.com/godbus/dbus/auth.go
deleted file mode 100644
index 98017b6..0000000
--- a/containerd/vendor/github.com/godbus/dbus/auth.go
+++ /dev/null
@@ -1,253 +0,0 @@
-package dbus
-
-import (
- "bufio"
- "bytes"
- "errors"
- "io"
- "os"
- "strconv"
-)
-
-// AuthStatus represents the Status of an authentication mechanism.
-type AuthStatus byte
-
-const (
- // AuthOk signals that authentication is finished; the next command
- // from the server should be an OK.
- AuthOk AuthStatus = iota
-
- // AuthContinue signals that additional data is needed; the next command
- // from the server should be a DATA.
- AuthContinue
-
- // AuthError signals an error; the server sent invalid data or some
- // other unexpected thing happened and the current authentication
- // process should be aborted.
- AuthError
-)
-
-type authState byte
-
-const (
- waitingForData authState = iota
- waitingForOk
- waitingForReject
-)
-
-// Auth defines the behaviour of an authentication mechanism.
-type Auth interface {
- // Return the name of the mechnism, the argument to the first AUTH command
- // and the next status.
- FirstData() (name, resp []byte, status AuthStatus)
-
- // Process the given DATA command, and return the argument to the DATA
- // command and the next status. If len(resp) == 0, no DATA command is sent.
- HandleData(data []byte) (resp []byte, status AuthStatus)
-}
-
-// Auth authenticates the connection, trying the given list of authentication
-// mechanisms (in that order). If nil is passed, the EXTERNAL and
-// DBUS_COOKIE_SHA1 mechanisms are tried for the current user. For private
-// connections, this method must be called before sending any messages to the
-// bus. Auth must not be called on shared connections.
-func (conn *Conn) Auth(methods []Auth) error {
- if methods == nil {
- uid := strconv.Itoa(os.Getuid())
- methods = []Auth{AuthExternal(uid), AuthCookieSha1(uid, getHomeDir())}
- }
- in := bufio.NewReader(conn.transport)
- err := conn.transport.SendNullByte()
- if err != nil {
- return err
- }
- err = authWriteLine(conn.transport, []byte("AUTH"))
- if err != nil {
- return err
- }
- s, err := authReadLine(in)
- if err != nil {
- return err
- }
- if len(s) < 2 || !bytes.Equal(s[0], []byte("REJECTED")) {
- return errors.New("dbus: authentication protocol error")
- }
- s = s[1:]
- for _, v := range s {
- for _, m := range methods {
- if name, data, status := m.FirstData(); bytes.Equal(v, name) {
- var ok bool
- err = authWriteLine(conn.transport, []byte("AUTH"), []byte(v), data)
- if err != nil {
- return err
- }
- switch status {
- case AuthOk:
- err, ok = conn.tryAuth(m, waitingForOk, in)
- case AuthContinue:
- err, ok = conn.tryAuth(m, waitingForData, in)
- default:
- panic("dbus: invalid authentication status")
- }
- if err != nil {
- return err
- }
- if ok {
- if conn.transport.SupportsUnixFDs() {
- err = authWriteLine(conn, []byte("NEGOTIATE_UNIX_FD"))
- if err != nil {
- return err
- }
- line, err := authReadLine(in)
- if err != nil {
- return err
- }
- switch {
- case bytes.Equal(line[0], []byte("AGREE_UNIX_FD")):
- conn.EnableUnixFDs()
- conn.unixFD = true
- case bytes.Equal(line[0], []byte("ERROR")):
- default:
- return errors.New("dbus: authentication protocol error")
- }
- }
- err = authWriteLine(conn.transport, []byte("BEGIN"))
- if err != nil {
- return err
- }
- go conn.inWorker()
- go conn.outWorker()
- return nil
- }
- }
- }
- }
- return errors.New("dbus: authentication failed")
-}
-
-// tryAuth tries to authenticate with m as the mechanism, using state as the
-// initial authState and in for reading input. It returns (nil, true) on
-// success, (nil, false) on a REJECTED and (someErr, false) if some other
-// error occured.
-func (conn *Conn) tryAuth(m Auth, state authState, in *bufio.Reader) (error, bool) {
- for {
- s, err := authReadLine(in)
- if err != nil {
- return err, false
- }
- switch {
- case state == waitingForData && string(s[0]) == "DATA":
- if len(s) != 2 {
- err = authWriteLine(conn.transport, []byte("ERROR"))
- if err != nil {
- return err, false
- }
- continue
- }
- data, status := m.HandleData(s[1])
- switch status {
- case AuthOk, AuthContinue:
- if len(data) != 0 {
- err = authWriteLine(conn.transport, []byte("DATA"), data)
- if err != nil {
- return err, false
- }
- }
- if status == AuthOk {
- state = waitingForOk
- }
- case AuthError:
- err = authWriteLine(conn.transport, []byte("ERROR"))
- if err != nil {
- return err, false
- }
- }
- case state == waitingForData && string(s[0]) == "REJECTED":
- return nil, false
- case state == waitingForData && string(s[0]) == "ERROR":
- err = authWriteLine(conn.transport, []byte("CANCEL"))
- if err != nil {
- return err, false
- }
- state = waitingForReject
- case state == waitingForData && string(s[0]) == "OK":
- if len(s) != 2 {
- err = authWriteLine(conn.transport, []byte("CANCEL"))
- if err != nil {
- return err, false
- }
- state = waitingForReject
- }
- conn.uuid = string(s[1])
- return nil, true
- case state == waitingForData:
- err = authWriteLine(conn.transport, []byte("ERROR"))
- if err != nil {
- return err, false
- }
- case state == waitingForOk && string(s[0]) == "OK":
- if len(s) != 2 {
- err = authWriteLine(conn.transport, []byte("CANCEL"))
- if err != nil {
- return err, false
- }
- state = waitingForReject
- }
- conn.uuid = string(s[1])
- return nil, true
- case state == waitingForOk && string(s[0]) == "REJECTED":
- return nil, false
- case state == waitingForOk && (string(s[0]) == "DATA" ||
- string(s[0]) == "ERROR"):
-
- err = authWriteLine(conn.transport, []byte("CANCEL"))
- if err != nil {
- return err, false
- }
- state = waitingForReject
- case state == waitingForOk:
- err = authWriteLine(conn.transport, []byte("ERROR"))
- if err != nil {
- return err, false
- }
- case state == waitingForReject && string(s[0]) == "REJECTED":
- return nil, false
- case state == waitingForReject:
- return errors.New("dbus: authentication protocol error"), false
- default:
- panic("dbus: invalid auth state")
- }
- }
-}
-
-// authReadLine reads a line and separates it into its fields.
-func authReadLine(in *bufio.Reader) ([][]byte, error) {
- data, err := in.ReadBytes('\n')
- if err != nil {
- return nil, err
- }
- data = bytes.TrimSuffix(data, []byte("\r\n"))
- return bytes.Split(data, []byte{' '}), nil
-}
-
-// authWriteLine writes the given line in the authentication protocol format
-// (elements of data separated by a " " and terminated by "\r\n").
-func authWriteLine(out io.Writer, data ...[]byte) error {
- buf := make([]byte, 0)
- for i, v := range data {
- buf = append(buf, v...)
- if i != len(data)-1 {
- buf = append(buf, ' ')
- }
- }
- buf = append(buf, '\r')
- buf = append(buf, '\n')
- n, err := out.Write(buf)
- if err != nil {
- return err
- }
- if n != len(buf) {
- return io.ErrUnexpectedEOF
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/auth_external.go b/containerd/vendor/github.com/godbus/dbus/auth_external.go
deleted file mode 100644
index 7e376d3..0000000
--- a/containerd/vendor/github.com/godbus/dbus/auth_external.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package dbus
-
-import (
- "encoding/hex"
-)
-
-// AuthExternal returns an Auth that authenticates as the given user with the
-// EXTERNAL mechanism.
-func AuthExternal(user string) Auth {
- return authExternal{user}
-}
-
-// AuthExternal implements the EXTERNAL authentication mechanism.
-type authExternal struct {
- user string
-}
-
-func (a authExternal) FirstData() ([]byte, []byte, AuthStatus) {
- b := make([]byte, 2*len(a.user))
- hex.Encode(b, []byte(a.user))
- return []byte("EXTERNAL"), b, AuthOk
-}
-
-func (a authExternal) HandleData(b []byte) ([]byte, AuthStatus) {
- return nil, AuthError
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/auth_sha1.go b/containerd/vendor/github.com/godbus/dbus/auth_sha1.go
deleted file mode 100644
index df15b46..0000000
--- a/containerd/vendor/github.com/godbus/dbus/auth_sha1.go
+++ /dev/null
@@ -1,102 +0,0 @@
-package dbus
-
-import (
- "bufio"
- "bytes"
- "crypto/rand"
- "crypto/sha1"
- "encoding/hex"
- "os"
-)
-
-// AuthCookieSha1 returns an Auth that authenticates as the given user with the
-// DBUS_COOKIE_SHA1 mechanism. The home parameter should specify the home
-// directory of the user.
-func AuthCookieSha1(user, home string) Auth {
- return authCookieSha1{user, home}
-}
-
-type authCookieSha1 struct {
- user, home string
-}
-
-func (a authCookieSha1) FirstData() ([]byte, []byte, AuthStatus) {
- b := make([]byte, 2*len(a.user))
- hex.Encode(b, []byte(a.user))
- return []byte("DBUS_COOKIE_SHA1"), b, AuthContinue
-}
-
-func (a authCookieSha1) HandleData(data []byte) ([]byte, AuthStatus) {
- challenge := make([]byte, len(data)/2)
- _, err := hex.Decode(challenge, data)
- if err != nil {
- return nil, AuthError
- }
- b := bytes.Split(challenge, []byte{' '})
- if len(b) != 3 {
- return nil, AuthError
- }
- context := b[0]
- id := b[1]
- svchallenge := b[2]
- cookie := a.getCookie(context, id)
- if cookie == nil {
- return nil, AuthError
- }
- clchallenge := a.generateChallenge()
- if clchallenge == nil {
- return nil, AuthError
- }
- hash := sha1.New()
- hash.Write(bytes.Join([][]byte{svchallenge, clchallenge, cookie}, []byte{':'}))
- hexhash := make([]byte, 2*hash.Size())
- hex.Encode(hexhash, hash.Sum(nil))
- data = append(clchallenge, ' ')
- data = append(data, hexhash...)
- resp := make([]byte, 2*len(data))
- hex.Encode(resp, data)
- return resp, AuthOk
-}
-
-// getCookie searches for the cookie identified by id in context and returns
-// the cookie content or nil. (Since HandleData can't return a specific error,
-// but only whether an error occured, this function also doesn't bother to
-// return an error.)
-func (a authCookieSha1) getCookie(context, id []byte) []byte {
- file, err := os.Open(a.home + "/.dbus-keyrings/" + string(context))
- if err != nil {
- return nil
- }
- defer file.Close()
- rd := bufio.NewReader(file)
- for {
- line, err := rd.ReadBytes('\n')
- if err != nil {
- return nil
- }
- line = line[:len(line)-1]
- b := bytes.Split(line, []byte{' '})
- if len(b) != 3 {
- return nil
- }
- if bytes.Equal(b[0], id) {
- return b[2]
- }
- }
-}
-
-// generateChallenge returns a random, hex-encoded challenge, or nil on error
-// (see above).
-func (a authCookieSha1) generateChallenge() []byte {
- b := make([]byte, 16)
- n, err := rand.Read(b)
- if err != nil {
- return nil
- }
- if n != 16 {
- return nil
- }
- enc := make([]byte, 32)
- hex.Encode(enc, b)
- return enc
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/call.go b/containerd/vendor/github.com/godbus/dbus/call.go
deleted file mode 100644
index 1d2fbc7..0000000
--- a/containerd/vendor/github.com/godbus/dbus/call.go
+++ /dev/null
@@ -1,147 +0,0 @@
-package dbus
-
-import (
- "errors"
- "strings"
-)
-
-// Call represents a pending or completed method call.
-type Call struct {
- Destination string
- Path ObjectPath
- Method string
- Args []interface{}
-
- // Strobes when the call is complete.
- Done chan *Call
-
- // After completion, the error status. If this is non-nil, it may be an
- // error message from the peer (with Error as its type) or some other error.
- Err error
-
- // Holds the response once the call is done.
- Body []interface{}
-}
-
-var errSignature = errors.New("dbus: mismatched signature")
-
-// Store stores the body of the reply into the provided pointers. It returns
-// an error if the signatures of the body and retvalues don't match, or if
-// the error status is not nil.
-func (c *Call) Store(retvalues ...interface{}) error {
- if c.Err != nil {
- return c.Err
- }
-
- return Store(c.Body, retvalues...)
-}
-
-// Object represents a remote object on which methods can be invoked.
-type Object struct {
- conn *Conn
- dest string
- path ObjectPath
-}
-
-// Call calls a method with (*Object).Go and waits for its reply.
-func (o *Object) Call(method string, flags Flags, args ...interface{}) *Call {
- return <-o.Go(method, flags, make(chan *Call, 1), args...).Done
-}
-
-// GetProperty calls org.freedesktop.DBus.Properties.GetProperty on the given
-// object. The property name must be given in interface.member notation.
-func (o *Object) GetProperty(p string) (Variant, error) {
- idx := strings.LastIndex(p, ".")
- if idx == -1 || idx+1 == len(p) {
- return Variant{}, errors.New("dbus: invalid property " + p)
- }
-
- iface := p[:idx]
- prop := p[idx+1:]
-
- result := Variant{}
- err := o.Call("org.freedesktop.DBus.Properties.Get", 0, iface, prop).Store(&result)
-
- if err != nil {
- return Variant{}, err
- }
-
- return result, nil
-}
-
-// Go calls a method with the given arguments asynchronously. It returns a
-// Call structure representing this method call. The passed channel will
-// return the same value once the call is done. If ch is nil, a new channel
-// will be allocated. Otherwise, ch has to be buffered or Go will panic.
-//
-// If the flags include FlagNoReplyExpected, ch is ignored and a Call structure
-// is returned of which only the Err member is valid.
-//
-// If the method parameter contains a dot ('.'), the part before the last dot
-// specifies the interface on which the method is called.
-func (o *Object) Go(method string, flags Flags, ch chan *Call, args ...interface{}) *Call {
- iface := ""
- i := strings.LastIndex(method, ".")
- if i != -1 {
- iface = method[:i]
- }
- method = method[i+1:]
- msg := new(Message)
- msg.Type = TypeMethodCall
- msg.serial = o.conn.getSerial()
- msg.Flags = flags & (FlagNoAutoStart | FlagNoReplyExpected)
- msg.Headers = make(map[HeaderField]Variant)
- msg.Headers[FieldPath] = MakeVariant(o.path)
- msg.Headers[FieldDestination] = MakeVariant(o.dest)
- msg.Headers[FieldMember] = MakeVariant(method)
- if iface != "" {
- msg.Headers[FieldInterface] = MakeVariant(iface)
- }
- msg.Body = args
- if len(args) > 0 {
- msg.Headers[FieldSignature] = MakeVariant(SignatureOf(args...))
- }
- if msg.Flags&FlagNoReplyExpected == 0 {
- if ch == nil {
- ch = make(chan *Call, 10)
- } else if cap(ch) == 0 {
- panic("dbus: unbuffered channel passed to (*Object).Go")
- }
- call := &Call{
- Destination: o.dest,
- Path: o.path,
- Method: method,
- Args: args,
- Done: ch,
- }
- o.conn.callsLck.Lock()
- o.conn.calls[msg.serial] = call
- o.conn.callsLck.Unlock()
- o.conn.outLck.RLock()
- if o.conn.closed {
- call.Err = ErrClosed
- call.Done <- call
- } else {
- o.conn.out <- msg
- }
- o.conn.outLck.RUnlock()
- return call
- }
- o.conn.outLck.RLock()
- defer o.conn.outLck.RUnlock()
- if o.conn.closed {
- return &Call{Err: ErrClosed}
- }
- o.conn.out <- msg
- return &Call{Err: nil}
-}
-
-// Destination returns the destination that calls on o are sent to.
-func (o *Object) Destination() string {
- return o.dest
-}
-
-// Path returns the path that calls on o are sent to.
-func (o *Object) Path() ObjectPath {
- return o.path
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/conn.go b/containerd/vendor/github.com/godbus/dbus/conn.go
deleted file mode 100644
index 18027a0..0000000
--- a/containerd/vendor/github.com/godbus/dbus/conn.go
+++ /dev/null
@@ -1,609 +0,0 @@
-package dbus
-
-import (
- "errors"
- "io"
- "os"
- "reflect"
- "strings"
- "sync"
-)
-
-const defaultSystemBusAddress = "unix:path=/var/run/dbus/system_bus_socket"
-
-var (
- systemBus *Conn
- systemBusLck sync.Mutex
- sessionBus *Conn
- sessionBusLck sync.Mutex
-)
-
-// ErrClosed is the error returned by calls on a closed connection.
-var ErrClosed = errors.New("dbus: connection closed by user")
-
-// Conn represents a connection to a message bus (usually, the system or
-// session bus).
-//
-// Connections are either shared or private. Shared connections
-// are shared between calls to the functions that return them. As a result,
-// the methods Close, Auth and Hello must not be called on them.
-//
-// Multiple goroutines may invoke methods on a connection simultaneously.
-type Conn struct {
- transport
-
- busObj *Object
- unixFD bool
- uuid string
-
- names []string
- namesLck sync.RWMutex
-
- serialLck sync.Mutex
- nextSerial uint32
- serialUsed map[uint32]bool
-
- calls map[uint32]*Call
- callsLck sync.RWMutex
-
- handlers map[ObjectPath]map[string]interface{}
- handlersLck sync.RWMutex
-
- out chan *Message
- closed bool
- outLck sync.RWMutex
-
- signals []chan<- *Signal
- signalsLck sync.Mutex
-
- eavesdropped chan<- *Message
- eavesdroppedLck sync.Mutex
-}
-
-// SessionBus returns a shared connection to the session bus, connecting to it
-// if not already done.
-func SessionBus() (conn *Conn, err error) {
- sessionBusLck.Lock()
- defer sessionBusLck.Unlock()
- if sessionBus != nil {
- return sessionBus, nil
- }
- defer func() {
- if conn != nil {
- sessionBus = conn
- }
- }()
- conn, err = SessionBusPrivate()
- if err != nil {
- return
- }
- if err = conn.Auth(nil); err != nil {
- conn.Close()
- conn = nil
- return
- }
- if err = conn.Hello(); err != nil {
- conn.Close()
- conn = nil
- }
- return
-}
-
-// SessionBusPrivate returns a new private connection to the session bus.
-func SessionBusPrivate() (*Conn, error) {
- address := os.Getenv("DBUS_SESSION_BUS_ADDRESS")
- if address != "" && address != "autolaunch:" {
- return Dial(address)
- }
-
- return sessionBusPlatform()
-}
-
-// SystemBus returns a shared connection to the system bus, connecting to it if
-// not already done.
-func SystemBus() (conn *Conn, err error) {
- systemBusLck.Lock()
- defer systemBusLck.Unlock()
- if systemBus != nil {
- return systemBus, nil
- }
- defer func() {
- if conn != nil {
- systemBus = conn
- }
- }()
- conn, err = SystemBusPrivate()
- if err != nil {
- return
- }
- if err = conn.Auth(nil); err != nil {
- conn.Close()
- conn = nil
- return
- }
- if err = conn.Hello(); err != nil {
- conn.Close()
- conn = nil
- }
- return
-}
-
-// SystemBusPrivate returns a new private connection to the system bus.
-func SystemBusPrivate() (*Conn, error) {
- address := os.Getenv("DBUS_SYSTEM_BUS_ADDRESS")
- if address != "" {
- return Dial(address)
- }
- return Dial(defaultSystemBusAddress)
-}
-
-// Dial establishes a new private connection to the message bus specified by address.
-func Dial(address string) (*Conn, error) {
- tr, err := getTransport(address)
- if err != nil {
- return nil, err
- }
- return newConn(tr)
-}
-
-// NewConn creates a new private *Conn from an already established connection.
-func NewConn(conn io.ReadWriteCloser) (*Conn, error) {
- return newConn(genericTransport{conn})
-}
-
-// newConn creates a new *Conn from a transport.
-func newConn(tr transport) (*Conn, error) {
- conn := new(Conn)
- conn.transport = tr
- conn.calls = make(map[uint32]*Call)
- conn.out = make(chan *Message, 10)
- conn.handlers = make(map[ObjectPath]map[string]interface{})
- conn.nextSerial = 1
- conn.serialUsed = map[uint32]bool{0: true}
- conn.busObj = conn.Object("org.freedesktop.DBus", "/org/freedesktop/DBus")
- return conn, nil
-}
-
-// BusObject returns the object owned by the bus daemon which handles
-// administrative requests.
-func (conn *Conn) BusObject() *Object {
- return conn.busObj
-}
-
-// Close closes the connection. Any blocked operations will return with errors
-// and the channels passed to Eavesdrop and Signal are closed. This method must
-// not be called on shared connections.
-func (conn *Conn) Close() error {
- conn.outLck.Lock()
- if conn.closed {
- // inWorker calls Close on read error, the read error may
- // be caused by another caller calling Close to shutdown the
- // dbus connection, a double-close scenario we prevent here.
- conn.outLck.Unlock()
- return nil
- }
- close(conn.out)
- conn.closed = true
- conn.outLck.Unlock()
- conn.signalsLck.Lock()
- for _, ch := range conn.signals {
- close(ch)
- }
- conn.signalsLck.Unlock()
- conn.eavesdroppedLck.Lock()
- if conn.eavesdropped != nil {
- close(conn.eavesdropped)
- }
- conn.eavesdroppedLck.Unlock()
- return conn.transport.Close()
-}
-
-// Eavesdrop causes conn to send all incoming messages to the given channel
-// without further processing. Method replies, errors and signals will not be
-// sent to the appropiate channels and method calls will not be handled. If nil
-// is passed, the normal behaviour is restored.
-//
-// The caller has to make sure that ch is sufficiently buffered;
-// if a message arrives when a write to ch is not possible, the message is
-// discarded.
-func (conn *Conn) Eavesdrop(ch chan<- *Message) {
- conn.eavesdroppedLck.Lock()
- conn.eavesdropped = ch
- conn.eavesdroppedLck.Unlock()
-}
-
-// getSerial returns an unused serial.
-func (conn *Conn) getSerial() uint32 {
- conn.serialLck.Lock()
- defer conn.serialLck.Unlock()
- n := conn.nextSerial
- for conn.serialUsed[n] {
- n++
- }
- conn.serialUsed[n] = true
- conn.nextSerial = n + 1
- return n
-}
-
-// Hello sends the initial org.freedesktop.DBus.Hello call. This method must be
-// called after authentication, but before sending any other messages to the
-// bus. Hello must not be called for shared connections.
-func (conn *Conn) Hello() error {
- var s string
- err := conn.busObj.Call("org.freedesktop.DBus.Hello", 0).Store(&s)
- if err != nil {
- return err
- }
- conn.namesLck.Lock()
- conn.names = make([]string, 1)
- conn.names[0] = s
- conn.namesLck.Unlock()
- return nil
-}
-
-// inWorker runs in an own goroutine, reading incoming messages from the
-// transport and dispatching them appropiately.
-func (conn *Conn) inWorker() {
- for {
- msg, err := conn.ReadMessage()
- if err == nil {
- conn.eavesdroppedLck.Lock()
- if conn.eavesdropped != nil {
- select {
- case conn.eavesdropped <- msg:
- default:
- }
- conn.eavesdroppedLck.Unlock()
- continue
- }
- conn.eavesdroppedLck.Unlock()
- dest, _ := msg.Headers[FieldDestination].value.(string)
- found := false
- if dest == "" {
- found = true
- } else {
- conn.namesLck.RLock()
- if len(conn.names) == 0 {
- found = true
- }
- for _, v := range conn.names {
- if dest == v {
- found = true
- break
- }
- }
- conn.namesLck.RUnlock()
- }
- if !found {
- // Eavesdropped a message, but no channel for it is registered.
- // Ignore it.
- continue
- }
- switch msg.Type {
- case TypeMethodReply, TypeError:
- serial := msg.Headers[FieldReplySerial].value.(uint32)
- conn.callsLck.Lock()
- if c, ok := conn.calls[serial]; ok {
- if msg.Type == TypeError {
- name, _ := msg.Headers[FieldErrorName].value.(string)
- c.Err = Error{name, msg.Body}
- } else {
- c.Body = msg.Body
- }
- c.Done <- c
- conn.serialLck.Lock()
- delete(conn.serialUsed, serial)
- conn.serialLck.Unlock()
- delete(conn.calls, serial)
- }
- conn.callsLck.Unlock()
- case TypeSignal:
- iface := msg.Headers[FieldInterface].value.(string)
- member := msg.Headers[FieldMember].value.(string)
- // as per http://dbus.freedesktop.org/doc/dbus-specification.html ,
- // sender is optional for signals.
- sender, _ := msg.Headers[FieldSender].value.(string)
- if iface == "org.freedesktop.DBus" && member == "NameLost" &&
- sender == "org.freedesktop.DBus" {
-
- name, _ := msg.Body[0].(string)
- conn.namesLck.Lock()
- for i, v := range conn.names {
- if v == name {
- copy(conn.names[i:], conn.names[i+1:])
- conn.names = conn.names[:len(conn.names)-1]
- }
- }
- conn.namesLck.Unlock()
- }
- signal := &Signal{
- Sender: sender,
- Path: msg.Headers[FieldPath].value.(ObjectPath),
- Name: iface + "." + member,
- Body: msg.Body,
- }
- conn.signalsLck.Lock()
- for _, ch := range conn.signals {
- ch <- signal
- }
- conn.signalsLck.Unlock()
- case TypeMethodCall:
- go conn.handleCall(msg)
- }
- } else if _, ok := err.(InvalidMessageError); !ok {
- // Some read error occured (usually EOF); we can't really do
- // anything but to shut down all stuff and returns errors to all
- // pending replies.
- conn.Close()
- conn.callsLck.RLock()
- for _, v := range conn.calls {
- v.Err = err
- v.Done <- v
- }
- conn.callsLck.RUnlock()
- return
- }
- // invalid messages are ignored
- }
-}
-
-// Names returns the list of all names that are currently owned by this
-// connection. The slice is always at least one element long, the first element
-// being the unique name of the connection.
-func (conn *Conn) Names() []string {
- conn.namesLck.RLock()
- // copy the slice so it can't be modified
- s := make([]string, len(conn.names))
- copy(s, conn.names)
- conn.namesLck.RUnlock()
- return s
-}
-
-// Object returns the object identified by the given destination name and path.
-func (conn *Conn) Object(dest string, path ObjectPath) *Object {
- return &Object{conn, dest, path}
-}
-
-// outWorker runs in an own goroutine, encoding and sending messages that are
-// sent to conn.out.
-func (conn *Conn) outWorker() {
- for msg := range conn.out {
- err := conn.SendMessage(msg)
- conn.callsLck.RLock()
- if err != nil {
- if c := conn.calls[msg.serial]; c != nil {
- c.Err = err
- c.Done <- c
- }
- conn.serialLck.Lock()
- delete(conn.serialUsed, msg.serial)
- conn.serialLck.Unlock()
- } else if msg.Type != TypeMethodCall {
- conn.serialLck.Lock()
- delete(conn.serialUsed, msg.serial)
- conn.serialLck.Unlock()
- }
- conn.callsLck.RUnlock()
- }
-}
-
-// Send sends the given message to the message bus. You usually don't need to
-// use this; use the higher-level equivalents (Call / Go, Emit and Export)
-// instead. If msg is a method call and NoReplyExpected is not set, a non-nil
-// call is returned and the same value is sent to ch (which must be buffered)
-// once the call is complete. Otherwise, ch is ignored and a Call structure is
-// returned of which only the Err member is valid.
-func (conn *Conn) Send(msg *Message, ch chan *Call) *Call {
- var call *Call
-
- msg.serial = conn.getSerial()
- if msg.Type == TypeMethodCall && msg.Flags&FlagNoReplyExpected == 0 {
- if ch == nil {
- ch = make(chan *Call, 5)
- } else if cap(ch) == 0 {
- panic("dbus: unbuffered channel passed to (*Conn).Send")
- }
- call = new(Call)
- call.Destination, _ = msg.Headers[FieldDestination].value.(string)
- call.Path, _ = msg.Headers[FieldPath].value.(ObjectPath)
- iface, _ := msg.Headers[FieldInterface].value.(string)
- member, _ := msg.Headers[FieldMember].value.(string)
- call.Method = iface + "." + member
- call.Args = msg.Body
- call.Done = ch
- conn.callsLck.Lock()
- conn.calls[msg.serial] = call
- conn.callsLck.Unlock()
- conn.outLck.RLock()
- if conn.closed {
- call.Err = ErrClosed
- call.Done <- call
- } else {
- conn.out <- msg
- }
- conn.outLck.RUnlock()
- } else {
- conn.outLck.RLock()
- if conn.closed {
- call = &Call{Err: ErrClosed}
- } else {
- conn.out <- msg
- call = &Call{Err: nil}
- }
- conn.outLck.RUnlock()
- }
- return call
-}
-
-// sendError creates an error message corresponding to the parameters and sends
-// it to conn.out.
-func (conn *Conn) sendError(e Error, dest string, serial uint32) {
- msg := new(Message)
- msg.Type = TypeError
- msg.serial = conn.getSerial()
- msg.Headers = make(map[HeaderField]Variant)
- if dest != "" {
- msg.Headers[FieldDestination] = MakeVariant(dest)
- }
- msg.Headers[FieldErrorName] = MakeVariant(e.Name)
- msg.Headers[FieldReplySerial] = MakeVariant(serial)
- msg.Body = e.Body
- if len(e.Body) > 0 {
- msg.Headers[FieldSignature] = MakeVariant(SignatureOf(e.Body...))
- }
- conn.outLck.RLock()
- if !conn.closed {
- conn.out <- msg
- }
- conn.outLck.RUnlock()
-}
-
-// sendReply creates a method reply message corresponding to the parameters and
-// sends it to conn.out.
-func (conn *Conn) sendReply(dest string, serial uint32, values ...interface{}) {
- msg := new(Message)
- msg.Type = TypeMethodReply
- msg.serial = conn.getSerial()
- msg.Headers = make(map[HeaderField]Variant)
- if dest != "" {
- msg.Headers[FieldDestination] = MakeVariant(dest)
- }
- msg.Headers[FieldReplySerial] = MakeVariant(serial)
- msg.Body = values
- if len(values) > 0 {
- msg.Headers[FieldSignature] = MakeVariant(SignatureOf(values...))
- }
- conn.outLck.RLock()
- if !conn.closed {
- conn.out <- msg
- }
- conn.outLck.RUnlock()
-}
-
-// Signal registers the given channel to be passed all received signal messages.
-// The caller has to make sure that ch is sufficiently buffered; if a message
-// arrives when a write to c is not possible, it is discarded.
-//
-// Multiple of these channels can be registered at the same time. Passing a
-// channel that already is registered will remove it from the list of the
-// registered channels.
-//
-// These channels are "overwritten" by Eavesdrop; i.e., if there currently is a
-// channel for eavesdropped messages, this channel receives all signals, and
-// none of the channels passed to Signal will receive any signals.
-func (conn *Conn) Signal(ch chan<- *Signal) {
- conn.signalsLck.Lock()
- conn.signals = append(conn.signals, ch)
- conn.signalsLck.Unlock()
-}
-
-// SupportsUnixFDs returns whether the underlying transport supports passing of
-// unix file descriptors. If this is false, method calls containing unix file
-// descriptors will return an error and emitted signals containing them will
-// not be sent.
-func (conn *Conn) SupportsUnixFDs() bool {
- return conn.unixFD
-}
-
-// Error represents a D-Bus message of type Error.
-type Error struct {
- Name string
- Body []interface{}
-}
-
-func NewError(name string, body []interface{}) *Error {
- return &Error{name, body}
-}
-
-func (e Error) Error() string {
- if len(e.Body) >= 1 {
- s, ok := e.Body[0].(string)
- if ok {
- return s
- }
- }
- return e.Name
-}
-
-// Signal represents a D-Bus message of type Signal. The name member is given in
-// "interface.member" notation, e.g. org.freedesktop.D-Bus.NameLost.
-type Signal struct {
- Sender string
- Path ObjectPath
- Name string
- Body []interface{}
-}
-
-// transport is a D-Bus transport.
-type transport interface {
- // Read and Write raw data (for example, for the authentication protocol).
- io.ReadWriteCloser
-
- // Send the initial null byte used for the EXTERNAL mechanism.
- SendNullByte() error
-
- // Returns whether this transport supports passing Unix FDs.
- SupportsUnixFDs() bool
-
- // Signal the transport that Unix FD passing is enabled for this connection.
- EnableUnixFDs()
-
- // Read / send a message, handling things like Unix FDs.
- ReadMessage() (*Message, error)
- SendMessage(*Message) error
-}
-
-var (
- transports map[string]func(string) (transport, error) = make(map[string]func(string) (transport, error))
-)
-
-func getTransport(address string) (transport, error) {
- var err error
- var t transport
-
- addresses := strings.Split(address, ";")
- for _, v := range addresses {
- i := strings.IndexRune(v, ':')
- if i == -1 {
- err = errors.New("dbus: invalid bus address (no transport)")
- continue
- }
- f := transports[v[:i]]
- if f == nil {
- err = errors.New("dbus: invalid bus address (invalid or unsupported transport)")
- }
- t, err = f(v[i+1:])
- if err == nil {
- return t, nil
- }
- }
- return nil, err
-}
-
-// dereferenceAll returns a slice that, assuming that vs is a slice of pointers
-// of arbitrary types, containes the values that are obtained from dereferencing
-// all elements in vs.
-func dereferenceAll(vs []interface{}) []interface{} {
- for i := range vs {
- v := reflect.ValueOf(vs[i])
- v = v.Elem()
- vs[i] = v.Interface()
- }
- return vs
-}
-
-// getKey gets a key from a the list of keys. Returns "" on error / not found...
-func getKey(s, key string) string {
- i := strings.Index(s, key)
- if i == -1 {
- return ""
- }
- if i+len(key)+1 >= len(s) || s[i+len(key)] != '=' {
- return ""
- }
- j := strings.Index(s, ",")
- if j == -1 {
- j = len(s)
- }
- return s[i+len(key)+1 : j]
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/conn_darwin.go b/containerd/vendor/github.com/godbus/dbus/conn_darwin.go
deleted file mode 100644
index b67bb1b..0000000
--- a/containerd/vendor/github.com/godbus/dbus/conn_darwin.go
+++ /dev/null
@@ -1,21 +0,0 @@
-package dbus
-
-import (
- "errors"
- "os/exec"
-)
-
-func sessionBusPlatform() (*Conn, error) {
- cmd := exec.Command("launchctl", "getenv", "DBUS_LAUNCHD_SESSION_BUS_SOCKET")
- b, err := cmd.CombinedOutput()
-
- if err != nil {
- return nil, err
- }
-
- if len(b) == 0 {
- return nil, errors.New("dbus: couldn't determine address of session bus")
- }
-
- return Dial("unix:path=" + string(b[:len(b)-1]))
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/conn_other.go b/containerd/vendor/github.com/godbus/dbus/conn_other.go
deleted file mode 100644
index f74b875..0000000
--- a/containerd/vendor/github.com/godbus/dbus/conn_other.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// +build !darwin
-
-package dbus
-
-import (
- "bytes"
- "errors"
- "os/exec"
-)
-
-func sessionBusPlatform() (*Conn, error) {
- cmd := exec.Command("dbus-launch")
- b, err := cmd.CombinedOutput()
-
- if err != nil {
- return nil, err
- }
-
- i := bytes.IndexByte(b, '=')
- j := bytes.IndexByte(b, '\n')
-
- if i == -1 || j == -1 {
- return nil, errors.New("dbus: couldn't determine address of session bus")
- }
-
- return Dial(string(b[i+1 : j]))
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/dbus.go b/containerd/vendor/github.com/godbus/dbus/dbus.go
deleted file mode 100644
index 2ce6873..0000000
--- a/containerd/vendor/github.com/godbus/dbus/dbus.go
+++ /dev/null
@@ -1,258 +0,0 @@
-package dbus
-
-import (
- "errors"
- "reflect"
- "strings"
-)
-
-var (
- byteType = reflect.TypeOf(byte(0))
- boolType = reflect.TypeOf(false)
- uint8Type = reflect.TypeOf(uint8(0))
- int16Type = reflect.TypeOf(int16(0))
- uint16Type = reflect.TypeOf(uint16(0))
- int32Type = reflect.TypeOf(int32(0))
- uint32Type = reflect.TypeOf(uint32(0))
- int64Type = reflect.TypeOf(int64(0))
- uint64Type = reflect.TypeOf(uint64(0))
- float64Type = reflect.TypeOf(float64(0))
- stringType = reflect.TypeOf("")
- signatureType = reflect.TypeOf(Signature{""})
- objectPathType = reflect.TypeOf(ObjectPath(""))
- variantType = reflect.TypeOf(Variant{Signature{""}, nil})
- interfacesType = reflect.TypeOf([]interface{}{})
- unixFDType = reflect.TypeOf(UnixFD(0))
- unixFDIndexType = reflect.TypeOf(UnixFDIndex(0))
-)
-
-// An InvalidTypeError signals that a value which cannot be represented in the
-// D-Bus wire format was passed to a function.
-type InvalidTypeError struct {
- Type reflect.Type
-}
-
-func (e InvalidTypeError) Error() string {
- return "dbus: invalid type " + e.Type.String()
-}
-
-// Store copies the values contained in src to dest, which must be a slice of
-// pointers. It converts slices of interfaces from src to corresponding structs
-// in dest. An error is returned if the lengths of src and dest or the types of
-// their elements don't match.
-func Store(src []interface{}, dest ...interface{}) error {
- if len(src) != len(dest) {
- return errors.New("dbus.Store: length mismatch")
- }
-
- for i := range src {
- if err := store(src[i], dest[i]); err != nil {
- return err
- }
- }
- return nil
-}
-
-func store(src, dest interface{}) error {
- if reflect.TypeOf(dest).Elem() == reflect.TypeOf(src) {
- reflect.ValueOf(dest).Elem().Set(reflect.ValueOf(src))
- return nil
- } else if hasStruct(dest) {
- rv := reflect.ValueOf(dest).Elem()
- switch rv.Kind() {
- case reflect.Struct:
- vs, ok := src.([]interface{})
- if !ok {
- return errors.New("dbus.Store: type mismatch")
- }
- t := rv.Type()
- ndest := make([]interface{}, 0, rv.NumField())
- for i := 0; i < rv.NumField(); i++ {
- field := t.Field(i)
- if field.PkgPath == "" && field.Tag.Get("dbus") != "-" {
- ndest = append(ndest, rv.Field(i).Addr().Interface())
- }
- }
- if len(vs) != len(ndest) {
- return errors.New("dbus.Store: type mismatch")
- }
- err := Store(vs, ndest...)
- if err != nil {
- return errors.New("dbus.Store: type mismatch")
- }
- case reflect.Slice:
- sv := reflect.ValueOf(src)
- if sv.Kind() != reflect.Slice {
- return errors.New("dbus.Store: type mismatch")
- }
- rv.Set(reflect.MakeSlice(rv.Type(), sv.Len(), sv.Len()))
- for i := 0; i < sv.Len(); i++ {
- if err := store(sv.Index(i).Interface(), rv.Index(i).Addr().Interface()); err != nil {
- return err
- }
- }
- case reflect.Map:
- sv := reflect.ValueOf(src)
- if sv.Kind() != reflect.Map {
- return errors.New("dbus.Store: type mismatch")
- }
- keys := sv.MapKeys()
- rv.Set(reflect.MakeMap(sv.Type()))
- for _, key := range keys {
- v := reflect.New(sv.Type().Elem())
- if err := store(v, sv.MapIndex(key).Interface()); err != nil {
- return err
- }
- rv.SetMapIndex(key, v.Elem())
- }
- default:
- return errors.New("dbus.Store: type mismatch")
- }
- return nil
- } else {
- return errors.New("dbus.Store: type mismatch")
- }
-}
-
-func hasStruct(v interface{}) bool {
- t := reflect.TypeOf(v)
- for {
- switch t.Kind() {
- case reflect.Struct:
- return true
- case reflect.Slice, reflect.Ptr, reflect.Map:
- t = t.Elem()
- default:
- return false
- }
- }
-}
-
-// An ObjectPath is an object path as defined by the D-Bus spec.
-type ObjectPath string
-
-// IsValid returns whether the object path is valid.
-func (o ObjectPath) IsValid() bool {
- s := string(o)
- if len(s) == 0 {
- return false
- }
- if s[0] != '/' {
- return false
- }
- if s[len(s)-1] == '/' && len(s) != 1 {
- return false
- }
- // probably not used, but technically possible
- if s == "/" {
- return true
- }
- split := strings.Split(s[1:], "/")
- for _, v := range split {
- if len(v) == 0 {
- return false
- }
- for _, c := range v {
- if !isMemberChar(c) {
- return false
- }
- }
- }
- return true
-}
-
-// A UnixFD is a Unix file descriptor sent over the wire. See the package-level
-// documentation for more information about Unix file descriptor passsing.
-type UnixFD int32
-
-// A UnixFDIndex is the representation of a Unix file descriptor in a message.
-type UnixFDIndex uint32
-
-// alignment returns the alignment of values of type t.
-func alignment(t reflect.Type) int {
- switch t {
- case variantType:
- return 1
- case objectPathType:
- return 4
- case signatureType:
- return 1
- case interfacesType: // sometimes used for structs
- return 8
- }
- switch t.Kind() {
- case reflect.Uint8:
- return 1
- case reflect.Uint16, reflect.Int16:
- return 2
- case reflect.Uint32, reflect.Int32, reflect.String, reflect.Array, reflect.Slice, reflect.Map:
- return 4
- case reflect.Uint64, reflect.Int64, reflect.Float64, reflect.Struct:
- return 8
- case reflect.Ptr:
- return alignment(t.Elem())
- }
- return 1
-}
-
-// isKeyType returns whether t is a valid type for a D-Bus dict.
-func isKeyType(t reflect.Type) bool {
- switch t.Kind() {
- case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
- reflect.Int16, reflect.Int32, reflect.Int64, reflect.Float64,
- reflect.String:
-
- return true
- }
- return false
-}
-
-// isValidInterface returns whether s is a valid name for an interface.
-func isValidInterface(s string) bool {
- if len(s) == 0 || len(s) > 255 || s[0] == '.' {
- return false
- }
- elem := strings.Split(s, ".")
- if len(elem) < 2 {
- return false
- }
- for _, v := range elem {
- if len(v) == 0 {
- return false
- }
- if v[0] >= '0' && v[0] <= '9' {
- return false
- }
- for _, c := range v {
- if !isMemberChar(c) {
- return false
- }
- }
- }
- return true
-}
-
-// isValidMember returns whether s is a valid name for a member.
-func isValidMember(s string) bool {
- if len(s) == 0 || len(s) > 255 {
- return false
- }
- i := strings.Index(s, ".")
- if i != -1 {
- return false
- }
- if s[0] >= '0' && s[0] <= '9' {
- return false
- }
- for _, c := range s {
- if !isMemberChar(c) {
- return false
- }
- }
- return true
-}
-
-func isMemberChar(c rune) bool {
- return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') ||
- (c >= 'a' && c <= 'z') || c == '_'
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/decoder.go b/containerd/vendor/github.com/godbus/dbus/decoder.go
deleted file mode 100644
index ef50dca..0000000
--- a/containerd/vendor/github.com/godbus/dbus/decoder.go
+++ /dev/null
@@ -1,228 +0,0 @@
-package dbus
-
-import (
- "encoding/binary"
- "io"
- "reflect"
-)
-
-type decoder struct {
- in io.Reader
- order binary.ByteOrder
- pos int
-}
-
-// newDecoder returns a new decoder that reads values from in. The input is
-// expected to be in the given byte order.
-func newDecoder(in io.Reader, order binary.ByteOrder) *decoder {
- dec := new(decoder)
- dec.in = in
- dec.order = order
- return dec
-}
-
-// align aligns the input to the given boundary and panics on error.
-func (dec *decoder) align(n int) {
- if dec.pos%n != 0 {
- newpos := (dec.pos + n - 1) & ^(n - 1)
- empty := make([]byte, newpos-dec.pos)
- if _, err := io.ReadFull(dec.in, empty); err != nil {
- panic(err)
- }
- dec.pos = newpos
- }
-}
-
-// Calls binary.Read(dec.in, dec.order, v) and panics on read errors.
-func (dec *decoder) binread(v interface{}) {
- if err := binary.Read(dec.in, dec.order, v); err != nil {
- panic(err)
- }
-}
-
-func (dec *decoder) Decode(sig Signature) (vs []interface{}, err error) {
- defer func() {
- var ok bool
- v := recover()
- if err, ok = v.(error); ok {
- if err == io.EOF || err == io.ErrUnexpectedEOF {
- err = FormatError("unexpected EOF")
- }
- }
- }()
- vs = make([]interface{}, 0)
- s := sig.str
- for s != "" {
- err, rem := validSingle(s, 0)
- if err != nil {
- return nil, err
- }
- v := dec.decode(s[:len(s)-len(rem)], 0)
- vs = append(vs, v)
- s = rem
- }
- return vs, nil
-}
-
-func (dec *decoder) decode(s string, depth int) interface{} {
- dec.align(alignment(typeFor(s)))
- switch s[0] {
- case 'y':
- var b [1]byte
- if _, err := dec.in.Read(b[:]); err != nil {
- panic(err)
- }
- dec.pos++
- return b[0]
- case 'b':
- i := dec.decode("u", depth).(uint32)
- switch {
- case i == 0:
- return false
- case i == 1:
- return true
- default:
- panic(FormatError("invalid value for boolean"))
- }
- case 'n':
- var i int16
- dec.binread(&i)
- dec.pos += 2
- return i
- case 'i':
- var i int32
- dec.binread(&i)
- dec.pos += 4
- return i
- case 'x':
- var i int64
- dec.binread(&i)
- dec.pos += 8
- return i
- case 'q':
- var i uint16
- dec.binread(&i)
- dec.pos += 2
- return i
- case 'u':
- var i uint32
- dec.binread(&i)
- dec.pos += 4
- return i
- case 't':
- var i uint64
- dec.binread(&i)
- dec.pos += 8
- return i
- case 'd':
- var f float64
- dec.binread(&f)
- dec.pos += 8
- return f
- case 's':
- length := dec.decode("u", depth).(uint32)
- b := make([]byte, int(length)+1)
- if _, err := io.ReadFull(dec.in, b); err != nil {
- panic(err)
- }
- dec.pos += int(length) + 1
- return string(b[:len(b)-1])
- case 'o':
- return ObjectPath(dec.decode("s", depth).(string))
- case 'g':
- length := dec.decode("y", depth).(byte)
- b := make([]byte, int(length)+1)
- if _, err := io.ReadFull(dec.in, b); err != nil {
- panic(err)
- }
- dec.pos += int(length) + 1
- sig, err := ParseSignature(string(b[:len(b)-1]))
- if err != nil {
- panic(err)
- }
- return sig
- case 'v':
- if depth >= 64 {
- panic(FormatError("input exceeds container depth limit"))
- }
- var variant Variant
- sig := dec.decode("g", depth).(Signature)
- if len(sig.str) == 0 {
- panic(FormatError("variant signature is empty"))
- }
- err, rem := validSingle(sig.str, 0)
- if err != nil {
- panic(err)
- }
- if rem != "" {
- panic(FormatError("variant signature has multiple types"))
- }
- variant.sig = sig
- variant.value = dec.decode(sig.str, depth+1)
- return variant
- case 'h':
- return UnixFDIndex(dec.decode("u", depth).(uint32))
- case 'a':
- if len(s) > 1 && s[1] == '{' {
- ksig := s[2:3]
- vsig := s[3 : len(s)-1]
- v := reflect.MakeMap(reflect.MapOf(typeFor(ksig), typeFor(vsig)))
- if depth >= 63 {
- panic(FormatError("input exceeds container depth limit"))
- }
- length := dec.decode("u", depth).(uint32)
- // Even for empty maps, the correct padding must be included
- dec.align(8)
- spos := dec.pos
- for dec.pos < spos+int(length) {
- dec.align(8)
- if !isKeyType(v.Type().Key()) {
- panic(InvalidTypeError{v.Type()})
- }
- kv := dec.decode(ksig, depth+2)
- vv := dec.decode(vsig, depth+2)
- v.SetMapIndex(reflect.ValueOf(kv), reflect.ValueOf(vv))
- }
- return v.Interface()
- }
- if depth >= 64 {
- panic(FormatError("input exceeds container depth limit"))
- }
- length := dec.decode("u", depth).(uint32)
- v := reflect.MakeSlice(reflect.SliceOf(typeFor(s[1:])), 0, int(length))
- // Even for empty arrays, the correct padding must be included
- dec.align(alignment(typeFor(s[1:])))
- spos := dec.pos
- for dec.pos < spos+int(length) {
- ev := dec.decode(s[1:], depth+1)
- v = reflect.Append(v, reflect.ValueOf(ev))
- }
- return v.Interface()
- case '(':
- if depth >= 64 {
- panic(FormatError("input exceeds container depth limit"))
- }
- dec.align(8)
- v := make([]interface{}, 0)
- s = s[1 : len(s)-1]
- for s != "" {
- err, rem := validSingle(s, 0)
- if err != nil {
- panic(err)
- }
- ev := dec.decode(s[:len(s)-len(rem)], depth+1)
- v = append(v, ev)
- s = rem
- }
- return v
- default:
- panic(SignatureError{Sig: s})
- }
-}
-
-// A FormatError is an error in the wire format.
-type FormatError string
-
-func (e FormatError) Error() string {
- return "dbus: wire format error: " + string(e)
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/doc.go b/containerd/vendor/github.com/godbus/dbus/doc.go
deleted file mode 100644
index deff554..0000000
--- a/containerd/vendor/github.com/godbus/dbus/doc.go
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
-Package dbus implements bindings to the D-Bus message bus system.
-
-To use the message bus API, you first need to connect to a bus (usually the
-session or system bus). The acquired connection then can be used to call methods
-on remote objects and emit or receive signals. Using the Export method, you can
-arrange D-Bus methods calls to be directly translated to method calls on a Go
-value.
-
-Conversion Rules
-
-For outgoing messages, Go types are automatically converted to the
-corresponding D-Bus types. The following types are directly encoded as their
-respective D-Bus equivalents:
-
- Go type | D-Bus type
- ------------+-----------
- byte | BYTE
- bool | BOOLEAN
- int16 | INT16
- uint16 | UINT16
- int32 | INT32
- uint32 | UINT32
- int64 | INT64
- uint64 | UINT64
- float64 | DOUBLE
- string | STRING
- ObjectPath | OBJECT_PATH
- Signature | SIGNATURE
- Variant | VARIANT
- UnixFDIndex | UNIX_FD
-
-Slices and arrays encode as ARRAYs of their element type.
-
-Maps encode as DICTs, provided that their key type can be used as a key for
-a DICT.
-
-Structs other than Variant and Signature encode as a STRUCT containing their
-exported fields. Fields whose tags contain `dbus:"-"` and unexported fields will
-be skipped.
-
-Pointers encode as the value they're pointed to.
-
-Trying to encode any other type or a slice, map or struct containing an
-unsupported type will result in an InvalidTypeError.
-
-For incoming messages, the inverse of these rules are used, with the exception
-of STRUCTs. Incoming STRUCTS are represented as a slice of empty interfaces
-containing the struct fields in the correct order. The Store function can be
-used to convert such values to Go structs.
-
-Unix FD passing
-
-Handling Unix file descriptors deserves special mention. To use them, you should
-first check that they are supported on a connection by calling SupportsUnixFDs.
-If it returns true, all method of Connection will translate messages containing
-UnixFD's to messages that are accompanied by the given file descriptors with the
-UnixFD values being substituted by the correct indices. Similarily, the indices
-of incoming messages are automatically resolved. It shouldn't be necessary to use
-UnixFDIndex.
-
-*/
-package dbus
diff --git a/containerd/vendor/github.com/godbus/dbus/encoder.go b/containerd/vendor/github.com/godbus/dbus/encoder.go
deleted file mode 100644
index f9d2f05..0000000
--- a/containerd/vendor/github.com/godbus/dbus/encoder.go
+++ /dev/null
@@ -1,179 +0,0 @@
-package dbus
-
-import (
- "bytes"
- "encoding/binary"
- "io"
- "reflect"
-)
-
-// An encoder encodes values to the D-Bus wire format.
-type encoder struct {
- out io.Writer
- order binary.ByteOrder
- pos int
-}
-
-// NewEncoder returns a new encoder that writes to out in the given byte order.
-func newEncoder(out io.Writer, order binary.ByteOrder) *encoder {
- enc := new(encoder)
- enc.out = out
- enc.order = order
- return enc
-}
-
-// Aligns the next output to be on a multiple of n. Panics on write errors.
-func (enc *encoder) align(n int) {
- if enc.pos%n != 0 {
- newpos := (enc.pos + n - 1) & ^(n - 1)
- empty := make([]byte, newpos-enc.pos)
- if _, err := enc.out.Write(empty); err != nil {
- panic(err)
- }
- enc.pos = newpos
- }
-}
-
-// Calls binary.Write(enc.out, enc.order, v) and panics on write errors.
-func (enc *encoder) binwrite(v interface{}) {
- if err := binary.Write(enc.out, enc.order, v); err != nil {
- panic(err)
- }
-}
-
-// Encode encodes the given values to the underyling reader. All written values
-// are aligned properly as required by the D-Bus spec.
-func (enc *encoder) Encode(vs ...interface{}) (err error) {
- defer func() {
- err, _ = recover().(error)
- }()
- for _, v := range vs {
- enc.encode(reflect.ValueOf(v), 0)
- }
- return nil
-}
-
-// encode encodes the given value to the writer and panics on error. depth holds
-// the depth of the container nesting.
-func (enc *encoder) encode(v reflect.Value, depth int) {
- enc.align(alignment(v.Type()))
- switch v.Kind() {
- case reflect.Uint8:
- var b [1]byte
- b[0] = byte(v.Uint())
- if _, err := enc.out.Write(b[:]); err != nil {
- panic(err)
- }
- enc.pos++
- case reflect.Bool:
- if v.Bool() {
- enc.encode(reflect.ValueOf(uint32(1)), depth)
- } else {
- enc.encode(reflect.ValueOf(uint32(0)), depth)
- }
- case reflect.Int16:
- enc.binwrite(int16(v.Int()))
- enc.pos += 2
- case reflect.Uint16:
- enc.binwrite(uint16(v.Uint()))
- enc.pos += 2
- case reflect.Int32:
- enc.binwrite(int32(v.Int()))
- enc.pos += 4
- case reflect.Uint32:
- enc.binwrite(uint32(v.Uint()))
- enc.pos += 4
- case reflect.Int64:
- enc.binwrite(v.Int())
- enc.pos += 8
- case reflect.Uint64:
- enc.binwrite(v.Uint())
- enc.pos += 8
- case reflect.Float64:
- enc.binwrite(v.Float())
- enc.pos += 8
- case reflect.String:
- enc.encode(reflect.ValueOf(uint32(len(v.String()))), depth)
- b := make([]byte, v.Len()+1)
- copy(b, v.String())
- b[len(b)-1] = 0
- n, err := enc.out.Write(b)
- if err != nil {
- panic(err)
- }
- enc.pos += n
- case reflect.Ptr:
- enc.encode(v.Elem(), depth)
- case reflect.Slice, reflect.Array:
- if depth >= 64 {
- panic(FormatError("input exceeds container depth limit"))
- }
- var buf bytes.Buffer
- bufenc := newEncoder(&buf, enc.order)
-
- for i := 0; i < v.Len(); i++ {
- bufenc.encode(v.Index(i), depth+1)
- }
- enc.encode(reflect.ValueOf(uint32(buf.Len())), depth)
- length := buf.Len()
- enc.align(alignment(v.Type().Elem()))
- if _, err := buf.WriteTo(enc.out); err != nil {
- panic(err)
- }
- enc.pos += length
- case reflect.Struct:
- if depth >= 64 && v.Type() != signatureType {
- panic(FormatError("input exceeds container depth limit"))
- }
- switch t := v.Type(); t {
- case signatureType:
- str := v.Field(0)
- enc.encode(reflect.ValueOf(byte(str.Len())), depth+1)
- b := make([]byte, str.Len()+1)
- copy(b, str.String())
- b[len(b)-1] = 0
- n, err := enc.out.Write(b)
- if err != nil {
- panic(err)
- }
- enc.pos += n
- case variantType:
- variant := v.Interface().(Variant)
- enc.encode(reflect.ValueOf(variant.sig), depth+1)
- enc.encode(reflect.ValueOf(variant.value), depth+1)
- default:
- for i := 0; i < v.Type().NumField(); i++ {
- field := t.Field(i)
- if field.PkgPath == "" && field.Tag.Get("dbus") != "-" {
- enc.encode(v.Field(i), depth+1)
- }
- }
- }
- case reflect.Map:
- // Maps are arrays of structures, so they actually increase the depth by
- // 2.
- if depth >= 63 {
- panic(FormatError("input exceeds container depth limit"))
- }
- if !isKeyType(v.Type().Key()) {
- panic(InvalidTypeError{v.Type()})
- }
- keys := v.MapKeys()
- var buf bytes.Buffer
- bufenc := newEncoder(&buf, enc.order)
- for _, k := range keys {
- bufenc.align(8)
- bufenc.encode(k, depth+2)
- bufenc.encode(v.MapIndex(k), depth+2)
- }
- enc.encode(reflect.ValueOf(uint32(buf.Len())), depth)
- length := buf.Len()
- enc.align(8)
- if _, err := buf.WriteTo(enc.out); err != nil {
- panic(err)
- }
- enc.pos += length
- default:
- panic(InvalidTypeError{v.Type()})
- }
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/export.go b/containerd/vendor/github.com/godbus/dbus/export.go
deleted file mode 100644
index 1dd1591..0000000
--- a/containerd/vendor/github.com/godbus/dbus/export.go
+++ /dev/null
@@ -1,302 +0,0 @@
-package dbus
-
-import (
- "errors"
- "reflect"
- "strings"
- "unicode"
-)
-
-var (
- errmsgInvalidArg = Error{
- "org.freedesktop.DBus.Error.InvalidArgs",
- []interface{}{"Invalid type / number of args"},
- }
- errmsgNoObject = Error{
- "org.freedesktop.DBus.Error.NoSuchObject",
- []interface{}{"No such object"},
- }
- errmsgUnknownMethod = Error{
- "org.freedesktop.DBus.Error.UnknownMethod",
- []interface{}{"Unknown / invalid method"},
- }
-)
-
-// Sender is a type which can be used in exported methods to receive the message
-// sender.
-type Sender string
-
-func exportedMethod(v interface{}, name string) reflect.Value {
- if v == nil {
- return reflect.Value{}
- }
- m := reflect.ValueOf(v).MethodByName(name)
- if !m.IsValid() {
- return reflect.Value{}
- }
- t := m.Type()
- if t.NumOut() == 0 ||
- t.Out(t.NumOut()-1) != reflect.TypeOf(&errmsgInvalidArg) {
-
- return reflect.Value{}
- }
- return m
-}
-
-// handleCall handles the given method call (i.e. looks if it's one of the
-// pre-implemented ones and searches for a corresponding handler if not).
-func (conn *Conn) handleCall(msg *Message) {
- name := msg.Headers[FieldMember].value.(string)
- path := msg.Headers[FieldPath].value.(ObjectPath)
- ifaceName, hasIface := msg.Headers[FieldInterface].value.(string)
- sender, hasSender := msg.Headers[FieldSender].value.(string)
- serial := msg.serial
- if ifaceName == "org.freedesktop.DBus.Peer" {
- switch name {
- case "Ping":
- conn.sendReply(sender, serial)
- case "GetMachineId":
- conn.sendReply(sender, serial, conn.uuid)
- default:
- conn.sendError(errmsgUnknownMethod, sender, serial)
- }
- return
- }
- if len(name) == 0 || unicode.IsLower([]rune(name)[0]) {
- conn.sendError(errmsgUnknownMethod, sender, serial)
- }
- var m reflect.Value
- if hasIface {
- conn.handlersLck.RLock()
- obj, ok := conn.handlers[path]
- if !ok {
- conn.sendError(errmsgNoObject, sender, serial)
- conn.handlersLck.RUnlock()
- return
- }
- iface := obj[ifaceName]
- conn.handlersLck.RUnlock()
- m = exportedMethod(iface, name)
- } else {
- conn.handlersLck.RLock()
- if _, ok := conn.handlers[path]; !ok {
- conn.sendError(errmsgNoObject, sender, serial)
- conn.handlersLck.RUnlock()
- return
- }
- for _, v := range conn.handlers[path] {
- m = exportedMethod(v, name)
- if m.IsValid() {
- break
- }
- }
- conn.handlersLck.RUnlock()
- }
- if !m.IsValid() {
- conn.sendError(errmsgUnknownMethod, sender, serial)
- return
- }
- t := m.Type()
- vs := msg.Body
- pointers := make([]interface{}, t.NumIn())
- decode := make([]interface{}, 0, len(vs))
- for i := 0; i < t.NumIn(); i++ {
- tp := t.In(i)
- val := reflect.New(tp)
- pointers[i] = val.Interface()
- if tp == reflect.TypeOf((*Sender)(nil)).Elem() {
- val.Elem().SetString(sender)
- } else {
- decode = append(decode, pointers[i])
- }
- }
- if len(decode) != len(vs) {
- conn.sendError(errmsgInvalidArg, sender, serial)
- return
- }
- if err := Store(vs, decode...); err != nil {
- conn.sendError(errmsgInvalidArg, sender, serial)
- return
- }
- params := make([]reflect.Value, len(pointers))
- for i := 0; i < len(pointers); i++ {
- params[i] = reflect.ValueOf(pointers[i]).Elem()
- }
- ret := m.Call(params)
- if em := ret[t.NumOut()-1].Interface().(*Error); em != nil {
- conn.sendError(*em, sender, serial)
- return
- }
- if msg.Flags&FlagNoReplyExpected == 0 {
- reply := new(Message)
- reply.Type = TypeMethodReply
- reply.serial = conn.getSerial()
- reply.Headers = make(map[HeaderField]Variant)
- if hasSender {
- reply.Headers[FieldDestination] = msg.Headers[FieldSender]
- }
- reply.Headers[FieldReplySerial] = MakeVariant(msg.serial)
- reply.Body = make([]interface{}, len(ret)-1)
- for i := 0; i < len(ret)-1; i++ {
- reply.Body[i] = ret[i].Interface()
- }
- if len(ret) != 1 {
- reply.Headers[FieldSignature] = MakeVariant(SignatureOf(reply.Body...))
- }
- conn.outLck.RLock()
- if !conn.closed {
- conn.out <- reply
- }
- conn.outLck.RUnlock()
- }
-}
-
-// Emit emits the given signal on the message bus. The name parameter must be
-// formatted as "interface.member", e.g., "org.freedesktop.DBus.NameLost".
-func (conn *Conn) Emit(path ObjectPath, name string, values ...interface{}) error {
- if !path.IsValid() {
- return errors.New("dbus: invalid object path")
- }
- i := strings.LastIndex(name, ".")
- if i == -1 {
- return errors.New("dbus: invalid method name")
- }
- iface := name[:i]
- member := name[i+1:]
- if !isValidMember(member) {
- return errors.New("dbus: invalid method name")
- }
- if !isValidInterface(iface) {
- return errors.New("dbus: invalid interface name")
- }
- msg := new(Message)
- msg.Type = TypeSignal
- msg.serial = conn.getSerial()
- msg.Headers = make(map[HeaderField]Variant)
- msg.Headers[FieldInterface] = MakeVariant(iface)
- msg.Headers[FieldMember] = MakeVariant(member)
- msg.Headers[FieldPath] = MakeVariant(path)
- msg.Body = values
- if len(values) > 0 {
- msg.Headers[FieldSignature] = MakeVariant(SignatureOf(values...))
- }
- conn.outLck.RLock()
- defer conn.outLck.RUnlock()
- if conn.closed {
- return ErrClosed
- }
- conn.out <- msg
- return nil
-}
-
-// Export registers the given value to be exported as an object on the
-// message bus.
-//
-// If a method call on the given path and interface is received, an exported
-// method with the same name is called with v as the receiver if the
-// parameters match and the last return value is of type *Error. If this
-// *Error is not nil, it is sent back to the caller as an error.
-// Otherwise, a method reply is sent with the other return values as its body.
-//
-// Any parameters with the special type Sender are set to the sender of the
-// dbus message when the method is called. Parameters of this type do not
-// contribute to the dbus signature of the method (i.e. the method is exposed
-// as if the parameters of type Sender were not there).
-//
-// Every method call is executed in a new goroutine, so the method may be called
-// in multiple goroutines at once.
-//
-// Method calls on the interface org.freedesktop.DBus.Peer will be automatically
-// handled for every object.
-//
-// Passing nil as the first parameter will cause conn to cease handling calls on
-// the given combination of path and interface.
-//
-// Export returns an error if path is not a valid path name.
-func (conn *Conn) Export(v interface{}, path ObjectPath, iface string) error {
- if !path.IsValid() {
- return errors.New("dbus: invalid path name")
- }
- conn.handlersLck.Lock()
- if v == nil {
- if _, ok := conn.handlers[path]; ok {
- delete(conn.handlers[path], iface)
- if len(conn.handlers[path]) == 0 {
- delete(conn.handlers, path)
- }
- }
- return nil
- }
- if _, ok := conn.handlers[path]; !ok {
- conn.handlers[path] = make(map[string]interface{})
- }
- conn.handlers[path][iface] = v
- conn.handlersLck.Unlock()
- return nil
-}
-
-// ReleaseName calls org.freedesktop.DBus.ReleaseName. You should use only this
-// method to release a name (see below).
-func (conn *Conn) ReleaseName(name string) (ReleaseNameReply, error) {
- var r uint32
- err := conn.busObj.Call("org.freedesktop.DBus.ReleaseName", 0, name).Store(&r)
- if err != nil {
- return 0, err
- }
- if r == uint32(ReleaseNameReplyReleased) {
- conn.namesLck.Lock()
- for i, v := range conn.names {
- if v == name {
- copy(conn.names[i:], conn.names[i+1:])
- conn.names = conn.names[:len(conn.names)-1]
- }
- }
- conn.namesLck.Unlock()
- }
- return ReleaseNameReply(r), nil
-}
-
-// RequestName calls org.freedesktop.DBus.RequestName. You should use only this
-// method to request a name because package dbus needs to keep track of all
-// names that the connection has.
-func (conn *Conn) RequestName(name string, flags RequestNameFlags) (RequestNameReply, error) {
- var r uint32
- err := conn.busObj.Call("org.freedesktop.DBus.RequestName", 0, name, flags).Store(&r)
- if err != nil {
- return 0, err
- }
- if r == uint32(RequestNameReplyPrimaryOwner) {
- conn.namesLck.Lock()
- conn.names = append(conn.names, name)
- conn.namesLck.Unlock()
- }
- return RequestNameReply(r), nil
-}
-
-// ReleaseNameReply is the reply to a ReleaseName call.
-type ReleaseNameReply uint32
-
-const (
- ReleaseNameReplyReleased ReleaseNameReply = 1 + iota
- ReleaseNameReplyNonExistent
- ReleaseNameReplyNotOwner
-)
-
-// RequestNameFlags represents the possible flags for a RequestName call.
-type RequestNameFlags uint32
-
-const (
- NameFlagAllowReplacement RequestNameFlags = 1 << iota
- NameFlagReplaceExisting
- NameFlagDoNotQueue
-)
-
-// RequestNameReply is the reply to a RequestName call.
-type RequestNameReply uint32
-
-const (
- RequestNameReplyPrimaryOwner RequestNameReply = 1 + iota
- RequestNameReplyInQueue
- RequestNameReplyExists
- RequestNameReplyAlreadyOwner
-)
diff --git a/containerd/vendor/github.com/godbus/dbus/homedir.go b/containerd/vendor/github.com/godbus/dbus/homedir.go
deleted file mode 100644
index 0b745f9..0000000
--- a/containerd/vendor/github.com/godbus/dbus/homedir.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package dbus
-
-import (
- "os"
- "sync"
-)
-
-var (
- homeDir string
- homeDirLock sync.Mutex
-)
-
-func getHomeDir() string {
- homeDirLock.Lock()
- defer homeDirLock.Unlock()
-
- if homeDir != "" {
- return homeDir
- }
-
- homeDir = os.Getenv("HOME")
- if homeDir != "" {
- return homeDir
- }
-
- homeDir = lookupHomeDir()
- return homeDir
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/homedir_dynamic.go b/containerd/vendor/github.com/godbus/dbus/homedir_dynamic.go
deleted file mode 100644
index 2732081..0000000
--- a/containerd/vendor/github.com/godbus/dbus/homedir_dynamic.go
+++ /dev/null
@@ -1,15 +0,0 @@
-// +build !static_build
-
-package dbus
-
-import (
- "os/user"
-)
-
-func lookupHomeDir() string {
- u, err := user.Current()
- if err != nil {
- return "/"
- }
- return u.HomeDir
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/homedir_static.go b/containerd/vendor/github.com/godbus/dbus/homedir_static.go
deleted file mode 100644
index b9d9cb5..0000000
--- a/containerd/vendor/github.com/godbus/dbus/homedir_static.go
+++ /dev/null
@@ -1,45 +0,0 @@
-// +build static_build
-
-package dbus
-
-import (
- "bufio"
- "os"
- "strconv"
- "strings"
-)
-
-func lookupHomeDir() string {
- myUid := os.Getuid()
-
- f, err := os.Open("/etc/passwd")
- if err != nil {
- return "/"
- }
- defer f.Close()
-
- s := bufio.NewScanner(f)
-
- for s.Scan() {
- if err := s.Err(); err != nil {
- break
- }
-
- line := strings.TrimSpace(s.Text())
- if line == "" {
- continue
- }
-
- parts := strings.Split(line, ":")
-
- if len(parts) >= 6 {
- uid, err := strconv.Atoi(parts[2])
- if err == nil && uid == myUid {
- return parts[5]
- }
- }
- }
-
- // Default to / if we can't get a better value
- return "/"
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/introspect/call.go b/containerd/vendor/github.com/godbus/dbus/introspect/call.go
deleted file mode 100644
index 4aca2ea..0000000
--- a/containerd/vendor/github.com/godbus/dbus/introspect/call.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package introspect
-
-import (
- "encoding/xml"
- "github.com/godbus/dbus"
- "strings"
-)
-
-// Call calls org.freedesktop.Introspectable.Introspect on a remote object
-// and returns the introspection data.
-func Call(o *dbus.Object) (*Node, error) {
- var xmldata string
- var node Node
-
- err := o.Call("org.freedesktop.DBus.Introspectable.Introspect", 0).Store(&xmldata)
- if err != nil {
- return nil, err
- }
- err = xml.NewDecoder(strings.NewReader(xmldata)).Decode(&node)
- if err != nil {
- return nil, err
- }
- if node.Name == "" {
- node.Name = string(o.Path())
- }
- return &node, nil
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/introspect/introspect.go b/containerd/vendor/github.com/godbus/dbus/introspect/introspect.go
deleted file mode 100644
index b06c3f1..0000000
--- a/containerd/vendor/github.com/godbus/dbus/introspect/introspect.go
+++ /dev/null
@@ -1,86 +0,0 @@
-// Package introspect provides some utilities for dealing with the DBus
-// introspection format.
-package introspect
-
-import "encoding/xml"
-
-// The introspection data for the org.freedesktop.DBus.Introspectable interface.
-var IntrospectData = Interface{
- Name: "org.freedesktop.DBus.Introspectable",
- Methods: []Method{
- {
- Name: "Introspect",
- Args: []Arg{
- {"out", "s", "out"},
- },
- },
- },
-}
-
-// XML document type declaration of the introspection format version 1.0
-const IntrospectDeclarationString = `
-
-`
-
-// The introspection data for the org.freedesktop.DBus.Introspectable interface,
-// as a string.
-const IntrospectDataString = `
-
-
-
-
-
-`
-
-// Node is the root element of an introspection.
-type Node struct {
- XMLName xml.Name `xml:"node"`
- Name string `xml:"name,attr,omitempty"`
- Interfaces []Interface `xml:"interface"`
- Children []Node `xml:"node,omitempty"`
-}
-
-// Interface describes a DBus interface that is available on the message bus.
-type Interface struct {
- Name string `xml:"name,attr"`
- Methods []Method `xml:"method"`
- Signals []Signal `xml:"signal"`
- Properties []Property `xml:"property"`
- Annotations []Annotation `xml:"annotation"`
-}
-
-// Method describes a Method on an Interface as retured by an introspection.
-type Method struct {
- Name string `xml:"name,attr"`
- Args []Arg `xml:"arg"`
- Annotations []Annotation `xml:"annotation"`
-}
-
-// Signal describes a Signal emitted on an Interface.
-type Signal struct {
- Name string `xml:"name,attr"`
- Args []Arg `xml:"arg"`
- Annotations []Annotation `xml:"annotation"`
-}
-
-// Property describes a property of an Interface.
-type Property struct {
- Name string `xml:"name,attr"`
- Type string `xml:"type,attr"`
- Access string `xml:"access,attr"`
- Annotations []Annotation `xml:"annotation"`
-}
-
-// Arg represents an argument of a method or a signal.
-type Arg struct {
- Name string `xml:"name,attr,omitempty"`
- Type string `xml:"type,attr"`
- Direction string `xml:"direction,attr,omitempty"`
-}
-
-// Annotation is an annotation in the introspection format.
-type Annotation struct {
- Name string `xml:"name,attr"`
- Value string `xml:"value,attr"`
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/introspect/introspectable.go b/containerd/vendor/github.com/godbus/dbus/introspect/introspectable.go
deleted file mode 100644
index 38982e7..0000000
--- a/containerd/vendor/github.com/godbus/dbus/introspect/introspectable.go
+++ /dev/null
@@ -1,75 +0,0 @@
-package introspect
-
-import (
- "encoding/xml"
- "github.com/godbus/dbus"
- "reflect"
- "strings"
-)
-
-// Introspectable implements org.freedesktop.Introspectable.
-//
-// You can create it by converting the XML-formatted introspection data from a
-// string to an Introspectable or call NewIntrospectable with a Node. Then,
-// export it as org.freedesktop.Introspectable on you object.
-type Introspectable string
-
-// NewIntrospectable returns an Introspectable that returns the introspection
-// data that corresponds to the given Node. If n.Interfaces doesn't contain the
-// data for org.freedesktop.DBus.Introspectable, it is added automatically.
-func NewIntrospectable(n *Node) Introspectable {
- found := false
- for _, v := range n.Interfaces {
- if v.Name == "org.freedesktop.DBus.Introspectable" {
- found = true
- break
- }
- }
- if !found {
- n.Interfaces = append(n.Interfaces, IntrospectData)
- }
- b, err := xml.Marshal(n)
- if err != nil {
- panic(err)
- }
- return Introspectable(strings.TrimSpace(IntrospectDeclarationString) + string(b))
-}
-
-// Introspect implements org.freedesktop.Introspectable.Introspect.
-func (i Introspectable) Introspect() (string, *dbus.Error) {
- return string(i), nil
-}
-
-// Methods returns the description of the methods of v. This can be used to
-// create a Node which can be passed to NewIntrospectable.
-func Methods(v interface{}) []Method {
- t := reflect.TypeOf(v)
- ms := make([]Method, 0, t.NumMethod())
- for i := 0; i < t.NumMethod(); i++ {
- if t.Method(i).PkgPath != "" {
- continue
- }
- mt := t.Method(i).Type
- if mt.NumOut() == 0 ||
- mt.Out(mt.NumOut()-1) != reflect.TypeOf(&dbus.Error{}) {
-
- continue
- }
- var m Method
- m.Name = t.Method(i).Name
- m.Args = make([]Arg, 0, mt.NumIn()+mt.NumOut()-2)
- for j := 1; j < mt.NumIn(); j++ {
- if mt.In(j) != reflect.TypeOf((*dbus.Sender)(nil)).Elem() {
- arg := Arg{"", dbus.SignatureOfType(mt.In(j)).String(), "in"}
- m.Args = append(m.Args, arg)
- }
- }
- for j := 0; j < mt.NumOut()-1; j++ {
- arg := Arg{"", dbus.SignatureOfType(mt.Out(j)).String(), "out"}
- m.Args = append(m.Args, arg)
- }
- m.Annotations = make([]Annotation, 0)
- ms = append(ms, m)
- }
- return ms
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/message.go b/containerd/vendor/github.com/godbus/dbus/message.go
deleted file mode 100644
index 075d6e3..0000000
--- a/containerd/vendor/github.com/godbus/dbus/message.go
+++ /dev/null
@@ -1,346 +0,0 @@
-package dbus
-
-import (
- "bytes"
- "encoding/binary"
- "errors"
- "io"
- "reflect"
- "strconv"
-)
-
-const protoVersion byte = 1
-
-// Flags represents the possible flags of a D-Bus message.
-type Flags byte
-
-const (
- // FlagNoReplyExpected signals that the message is not expected to generate
- // a reply. If this flag is set on outgoing messages, any possible reply
- // will be discarded.
- FlagNoReplyExpected Flags = 1 << iota
- // FlagNoAutoStart signals that the message bus should not automatically
- // start an application when handling this message.
- FlagNoAutoStart
-)
-
-// Type represents the possible types of a D-Bus message.
-type Type byte
-
-const (
- TypeMethodCall Type = 1 + iota
- TypeMethodReply
- TypeError
- TypeSignal
- typeMax
-)
-
-func (t Type) String() string {
- switch t {
- case TypeMethodCall:
- return "method call"
- case TypeMethodReply:
- return "reply"
- case TypeError:
- return "error"
- case TypeSignal:
- return "signal"
- }
- return "invalid"
-}
-
-// HeaderField represents the possible byte codes for the headers
-// of a D-Bus message.
-type HeaderField byte
-
-const (
- FieldPath HeaderField = 1 + iota
- FieldInterface
- FieldMember
- FieldErrorName
- FieldReplySerial
- FieldDestination
- FieldSender
- FieldSignature
- FieldUnixFDs
- fieldMax
-)
-
-// An InvalidMessageError describes the reason why a D-Bus message is regarded as
-// invalid.
-type InvalidMessageError string
-
-func (e InvalidMessageError) Error() string {
- return "dbus: invalid message: " + string(e)
-}
-
-// fieldType are the types of the various header fields.
-var fieldTypes = [fieldMax]reflect.Type{
- FieldPath: objectPathType,
- FieldInterface: stringType,
- FieldMember: stringType,
- FieldErrorName: stringType,
- FieldReplySerial: uint32Type,
- FieldDestination: stringType,
- FieldSender: stringType,
- FieldSignature: signatureType,
- FieldUnixFDs: uint32Type,
-}
-
-// requiredFields lists the header fields that are required by the different
-// message types.
-var requiredFields = [typeMax][]HeaderField{
- TypeMethodCall: {FieldPath, FieldMember},
- TypeMethodReply: {FieldReplySerial},
- TypeError: {FieldErrorName, FieldReplySerial},
- TypeSignal: {FieldPath, FieldInterface, FieldMember},
-}
-
-// Message represents a single D-Bus message.
-type Message struct {
- Type
- Flags
- Headers map[HeaderField]Variant
- Body []interface{}
-
- serial uint32
-}
-
-type header struct {
- Field byte
- Variant
-}
-
-// DecodeMessage tries to decode a single message in the D-Bus wire format
-// from the given reader. The byte order is figured out from the first byte.
-// The possibly returned error can be an error of the underlying reader, an
-// InvalidMessageError or a FormatError.
-func DecodeMessage(rd io.Reader) (msg *Message, err error) {
- var order binary.ByteOrder
- var hlength, length uint32
- var typ, flags, proto byte
- var headers []header
-
- b := make([]byte, 1)
- _, err = rd.Read(b)
- if err != nil {
- return
- }
- switch b[0] {
- case 'l':
- order = binary.LittleEndian
- case 'B':
- order = binary.BigEndian
- default:
- return nil, InvalidMessageError("invalid byte order")
- }
-
- dec := newDecoder(rd, order)
- dec.pos = 1
-
- msg = new(Message)
- vs, err := dec.Decode(Signature{"yyyuu"})
- if err != nil {
- return nil, err
- }
- if err = Store(vs, &typ, &flags, &proto, &length, &msg.serial); err != nil {
- return nil, err
- }
- msg.Type = Type(typ)
- msg.Flags = Flags(flags)
-
- // get the header length separately because we need it later
- b = make([]byte, 4)
- _, err = io.ReadFull(rd, b)
- if err != nil {
- return nil, err
- }
- binary.Read(bytes.NewBuffer(b), order, &hlength)
- if hlength+length+16 > 1<<27 {
- return nil, InvalidMessageError("message is too long")
- }
- dec = newDecoder(io.MultiReader(bytes.NewBuffer(b), rd), order)
- dec.pos = 12
- vs, err = dec.Decode(Signature{"a(yv)"})
- if err != nil {
- return nil, err
- }
- if err = Store(vs, &headers); err != nil {
- return nil, err
- }
-
- msg.Headers = make(map[HeaderField]Variant)
- for _, v := range headers {
- msg.Headers[HeaderField(v.Field)] = v.Variant
- }
-
- dec.align(8)
- body := make([]byte, int(length))
- if length != 0 {
- _, err := io.ReadFull(rd, body)
- if err != nil {
- return nil, err
- }
- }
-
- if err = msg.IsValid(); err != nil {
- return nil, err
- }
- sig, _ := msg.Headers[FieldSignature].value.(Signature)
- if sig.str != "" {
- buf := bytes.NewBuffer(body)
- dec = newDecoder(buf, order)
- vs, err := dec.Decode(sig)
- if err != nil {
- return nil, err
- }
- msg.Body = vs
- }
-
- return
-}
-
-// EncodeTo encodes and sends a message to the given writer. The byte order must
-// be either binary.LittleEndian or binary.BigEndian. If the message is not
-// valid or an error occurs when writing, an error is returned.
-func (msg *Message) EncodeTo(out io.Writer, order binary.ByteOrder) error {
- if err := msg.IsValid(); err != nil {
- return err
- }
- var vs [7]interface{}
- switch order {
- case binary.LittleEndian:
- vs[0] = byte('l')
- case binary.BigEndian:
- vs[0] = byte('B')
- default:
- return errors.New("dbus: invalid byte order")
- }
- body := new(bytes.Buffer)
- enc := newEncoder(body, order)
- if len(msg.Body) != 0 {
- enc.Encode(msg.Body...)
- }
- vs[1] = msg.Type
- vs[2] = msg.Flags
- vs[3] = protoVersion
- vs[4] = uint32(len(body.Bytes()))
- vs[5] = msg.serial
- headers := make([]header, 0, len(msg.Headers))
- for k, v := range msg.Headers {
- headers = append(headers, header{byte(k), v})
- }
- vs[6] = headers
- var buf bytes.Buffer
- enc = newEncoder(&buf, order)
- enc.Encode(vs[:]...)
- enc.align(8)
- body.WriteTo(&buf)
- if buf.Len() > 1<<27 {
- return InvalidMessageError("message is too long")
- }
- if _, err := buf.WriteTo(out); err != nil {
- return err
- }
- return nil
-}
-
-// IsValid checks whether msg is a valid message and returns an
-// InvalidMessageError if it is not.
-func (msg *Message) IsValid() error {
- if msg.Flags & ^(FlagNoAutoStart|FlagNoReplyExpected) != 0 {
- return InvalidMessageError("invalid flags")
- }
- if msg.Type == 0 || msg.Type >= typeMax {
- return InvalidMessageError("invalid message type")
- }
- for k, v := range msg.Headers {
- if k == 0 || k >= fieldMax {
- return InvalidMessageError("invalid header")
- }
- if reflect.TypeOf(v.value) != fieldTypes[k] {
- return InvalidMessageError("invalid type of header field")
- }
- }
- for _, v := range requiredFields[msg.Type] {
- if _, ok := msg.Headers[v]; !ok {
- return InvalidMessageError("missing required header")
- }
- }
- if path, ok := msg.Headers[FieldPath]; ok {
- if !path.value.(ObjectPath).IsValid() {
- return InvalidMessageError("invalid path name")
- }
- }
- if iface, ok := msg.Headers[FieldInterface]; ok {
- if !isValidInterface(iface.value.(string)) {
- return InvalidMessageError("invalid interface name")
- }
- }
- if member, ok := msg.Headers[FieldMember]; ok {
- if !isValidMember(member.value.(string)) {
- return InvalidMessageError("invalid member name")
- }
- }
- if errname, ok := msg.Headers[FieldErrorName]; ok {
- if !isValidInterface(errname.value.(string)) {
- return InvalidMessageError("invalid error name")
- }
- }
- if len(msg.Body) != 0 {
- if _, ok := msg.Headers[FieldSignature]; !ok {
- return InvalidMessageError("missing signature")
- }
- }
- return nil
-}
-
-// Serial returns the message's serial number. The returned value is only valid
-// for messages received by eavesdropping.
-func (msg *Message) Serial() uint32 {
- return msg.serial
-}
-
-// String returns a string representation of a message similar to the format of
-// dbus-monitor.
-func (msg *Message) String() string {
- if err := msg.IsValid(); err != nil {
- return ""
- }
- s := msg.Type.String()
- if v, ok := msg.Headers[FieldSender]; ok {
- s += " from " + v.value.(string)
- }
- if v, ok := msg.Headers[FieldDestination]; ok {
- s += " to " + v.value.(string)
- }
- s += " serial " + strconv.FormatUint(uint64(msg.serial), 10)
- if v, ok := msg.Headers[FieldReplySerial]; ok {
- s += " reply_serial " + strconv.FormatUint(uint64(v.value.(uint32)), 10)
- }
- if v, ok := msg.Headers[FieldUnixFDs]; ok {
- s += " unixfds " + strconv.FormatUint(uint64(v.value.(uint32)), 10)
- }
- if v, ok := msg.Headers[FieldPath]; ok {
- s += " path " + string(v.value.(ObjectPath))
- }
- if v, ok := msg.Headers[FieldInterface]; ok {
- s += " interface " + v.value.(string)
- }
- if v, ok := msg.Headers[FieldErrorName]; ok {
- s += " error " + v.value.(string)
- }
- if v, ok := msg.Headers[FieldMember]; ok {
- s += " member " + v.value.(string)
- }
- if len(msg.Body) != 0 {
- s += "\n"
- }
- for i, v := range msg.Body {
- s += " " + MakeVariant(v).String()
- if i != len(msg.Body)-1 {
- s += "\n"
- }
- }
- return s
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/prop/prop.go b/containerd/vendor/github.com/godbus/dbus/prop/prop.go
deleted file mode 100644
index 834a1fa..0000000
--- a/containerd/vendor/github.com/godbus/dbus/prop/prop.go
+++ /dev/null
@@ -1,264 +0,0 @@
-// Package prop provides the Properties struct which can be used to implement
-// org.freedesktop.DBus.Properties.
-package prop
-
-import (
- "github.com/godbus/dbus"
- "github.com/godbus/dbus/introspect"
- "sync"
-)
-
-// EmitType controls how org.freedesktop.DBus.Properties.PropertiesChanged is
-// emitted for a property. If it is EmitTrue, the signal is emitted. If it is
-// EmitInvalidates, the signal is also emitted, but the new value of the property
-// is not disclosed.
-type EmitType byte
-
-const (
- EmitFalse EmitType = iota
- EmitTrue
- EmitInvalidates
-)
-
-// ErrIfaceNotFound is the error returned to peers who try to access properties
-// on interfaces that aren't found.
-var ErrIfaceNotFound = dbus.NewError("org.freedesktop.DBus.Properties.Error.InterfaceNotFound", nil)
-
-// ErrPropNotFound is the error returned to peers trying to access properties
-// that aren't found.
-var ErrPropNotFound = dbus.NewError("org.freedesktop.DBus.Properties.Error.PropertyNotFound", nil)
-
-// ErrReadOnly is the error returned to peers trying to set a read-only
-// property.
-var ErrReadOnly = dbus.NewError("org.freedesktop.DBus.Properties.Error.ReadOnly", nil)
-
-// ErrInvalidArg is returned to peers if the type of the property that is being
-// changed and the argument don't match.
-var ErrInvalidArg = dbus.NewError("org.freedesktop.DBus.Properties.Error.InvalidArg", nil)
-
-// The introspection data for the org.freedesktop.DBus.Properties interface.
-var IntrospectData = introspect.Interface{
- Name: "org.freedesktop.DBus.Properties",
- Methods: []introspect.Method{
- {
- Name: "Get",
- Args: []introspect.Arg{
- {"interface", "s", "in"},
- {"property", "s", "in"},
- {"value", "v", "out"},
- },
- },
- {
- Name: "GetAll",
- Args: []introspect.Arg{
- {"interface", "s", "in"},
- {"props", "a{sv}", "out"},
- },
- },
- {
- Name: "Set",
- Args: []introspect.Arg{
- {"interface", "s", "in"},
- {"property", "s", "in"},
- {"value", "v", "in"},
- },
- },
- },
- Signals: []introspect.Signal{
- {
- Name: "PropertiesChanged",
- Args: []introspect.Arg{
- {"interface", "s", "out"},
- {"changed_properties", "a{sv}", "out"},
- {"invalidates_properties", "as", "out"},
- },
- },
- },
-}
-
-// The introspection data for the org.freedesktop.DBus.Properties interface, as
-// a string.
-const IntrospectDataString = `
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-`
-
-// Prop represents a single property. It is used for creating a Properties
-// value.
-type Prop struct {
- // Initial value. Must be a DBus-representable type.
- Value interface{}
-
- // If true, the value can be modified by calls to Set.
- Writable bool
-
- // Controls how org.freedesktop.DBus.Properties.PropertiesChanged is
- // emitted if this property changes.
- Emit EmitType
-
- // If not nil, anytime this property is changed by Set, this function is
- // called with an appropiate Change as its argument. If the returned error
- // is not nil, it is sent back to the caller of Set and the property is not
- // changed.
- Callback func(*Change) *dbus.Error
-}
-
-// Change represents a change of a property by a call to Set.
-type Change struct {
- Props *Properties
- Iface string
- Name string
- Value interface{}
-}
-
-// Properties is a set of values that can be made available to the message bus
-// using the org.freedesktop.DBus.Properties interface. It is safe for
-// concurrent use by multiple goroutines.
-type Properties struct {
- m map[string]map[string]*Prop
- mut sync.RWMutex
- conn *dbus.Conn
- path dbus.ObjectPath
-}
-
-// New returns a new Properties structure that manages the given properties.
-// The key for the first-level map of props is the name of the interface; the
-// second-level key is the name of the property. The returned structure will be
-// exported as org.freedesktop.DBus.Properties on path.
-func New(conn *dbus.Conn, path dbus.ObjectPath, props map[string]map[string]*Prop) *Properties {
- p := &Properties{m: props, conn: conn, path: path}
- conn.Export(p, path, "org.freedesktop.DBus.Properties")
- return p
-}
-
-// Get implements org.freedesktop.DBus.Properties.Get.
-func (p *Properties) Get(iface, property string) (dbus.Variant, *dbus.Error) {
- p.mut.RLock()
- defer p.mut.RUnlock()
- m, ok := p.m[iface]
- if !ok {
- return dbus.Variant{}, ErrIfaceNotFound
- }
- prop, ok := m[property]
- if !ok {
- return dbus.Variant{}, ErrPropNotFound
- }
- return dbus.MakeVariant(prop.Value), nil
-}
-
-// GetAll implements org.freedesktop.DBus.Properties.GetAll.
-func (p *Properties) GetAll(iface string) (map[string]dbus.Variant, *dbus.Error) {
- p.mut.RLock()
- defer p.mut.RUnlock()
- m, ok := p.m[iface]
- if !ok {
- return nil, ErrIfaceNotFound
- }
- rm := make(map[string]dbus.Variant, len(m))
- for k, v := range m {
- rm[k] = dbus.MakeVariant(v.Value)
- }
- return rm, nil
-}
-
-// GetMust returns the value of the given property and panics if either the
-// interface or the property name are invalid.
-func (p *Properties) GetMust(iface, property string) interface{} {
- p.mut.RLock()
- defer p.mut.RUnlock()
- return p.m[iface][property].Value
-}
-
-// Introspection returns the introspection data that represents the properties
-// of iface.
-func (p *Properties) Introspection(iface string) []introspect.Property {
- p.mut.RLock()
- defer p.mut.RUnlock()
- m := p.m[iface]
- s := make([]introspect.Property, 0, len(m))
- for k, v := range m {
- p := introspect.Property{Name: k, Type: dbus.SignatureOf(v.Value).String()}
- if v.Writable {
- p.Access = "readwrite"
- } else {
- p.Access = "read"
- }
- s = append(s, p)
- }
- return s
-}
-
-// set sets the given property and emits PropertyChanged if appropiate. p.mut
-// must already be locked.
-func (p *Properties) set(iface, property string, v interface{}) {
- prop := p.m[iface][property]
- prop.Value = v
- switch prop.Emit {
- case EmitFalse:
- // do nothing
- case EmitInvalidates:
- p.conn.Emit(p.path, "org.freedesktop.DBus.Properties.PropertiesChanged",
- iface, map[string]dbus.Variant{}, []string{property})
- case EmitTrue:
- p.conn.Emit(p.path, "org.freedesktop.DBus.Properties.PropertiesChanged",
- iface, map[string]dbus.Variant{property: dbus.MakeVariant(v)},
- []string{})
- default:
- panic("invalid value for EmitType")
- }
-}
-
-// Set implements org.freedesktop.Properties.Set.
-func (p *Properties) Set(iface, property string, newv dbus.Variant) *dbus.Error {
- p.mut.Lock()
- defer p.mut.Unlock()
- m, ok := p.m[iface]
- if !ok {
- return ErrIfaceNotFound
- }
- prop, ok := m[property]
- if !ok {
- return ErrPropNotFound
- }
- if !prop.Writable {
- return ErrReadOnly
- }
- if newv.Signature() != dbus.SignatureOf(prop.Value) {
- return ErrInvalidArg
- }
- if prop.Callback != nil {
- err := prop.Callback(&Change{p, iface, property, newv.Value()})
- if err != nil {
- return err
- }
- }
- p.set(iface, property, newv.Value())
- return nil
-}
-
-// SetMust sets the value of the given property and panics if the interface or
-// the property name are invalid.
-func (p *Properties) SetMust(iface, property string, v interface{}) {
- p.mut.Lock()
- p.set(iface, property, v)
- p.mut.Unlock()
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/sig.go b/containerd/vendor/github.com/godbus/dbus/sig.go
deleted file mode 100644
index f45b53c..0000000
--- a/containerd/vendor/github.com/godbus/dbus/sig.go
+++ /dev/null
@@ -1,257 +0,0 @@
-package dbus
-
-import (
- "fmt"
- "reflect"
- "strings"
-)
-
-var sigToType = map[byte]reflect.Type{
- 'y': byteType,
- 'b': boolType,
- 'n': int16Type,
- 'q': uint16Type,
- 'i': int32Type,
- 'u': uint32Type,
- 'x': int64Type,
- 't': uint64Type,
- 'd': float64Type,
- 's': stringType,
- 'g': signatureType,
- 'o': objectPathType,
- 'v': variantType,
- 'h': unixFDIndexType,
-}
-
-// Signature represents a correct type signature as specified by the D-Bus
-// specification. The zero value represents the empty signature, "".
-type Signature struct {
- str string
-}
-
-// SignatureOf returns the concatenation of all the signatures of the given
-// values. It panics if one of them is not representable in D-Bus.
-func SignatureOf(vs ...interface{}) Signature {
- var s string
- for _, v := range vs {
- s += getSignature(reflect.TypeOf(v))
- }
- return Signature{s}
-}
-
-// SignatureOfType returns the signature of the given type. It panics if the
-// type is not representable in D-Bus.
-func SignatureOfType(t reflect.Type) Signature {
- return Signature{getSignature(t)}
-}
-
-// getSignature returns the signature of the given type and panics on unknown types.
-func getSignature(t reflect.Type) string {
- // handle simple types first
- switch t.Kind() {
- case reflect.Uint8:
- return "y"
- case reflect.Bool:
- return "b"
- case reflect.Int16:
- return "n"
- case reflect.Uint16:
- return "q"
- case reflect.Int32:
- if t == unixFDType {
- return "h"
- }
- return "i"
- case reflect.Uint32:
- if t == unixFDIndexType {
- return "h"
- }
- return "u"
- case reflect.Int64:
- return "x"
- case reflect.Uint64:
- return "t"
- case reflect.Float64:
- return "d"
- case reflect.Ptr:
- return getSignature(t.Elem())
- case reflect.String:
- if t == objectPathType {
- return "o"
- }
- return "s"
- case reflect.Struct:
- if t == variantType {
- return "v"
- } else if t == signatureType {
- return "g"
- }
- var s string
- for i := 0; i < t.NumField(); i++ {
- field := t.Field(i)
- if field.PkgPath == "" && field.Tag.Get("dbus") != "-" {
- s += getSignature(t.Field(i).Type)
- }
- }
- return "(" + s + ")"
- case reflect.Array, reflect.Slice:
- return "a" + getSignature(t.Elem())
- case reflect.Map:
- if !isKeyType(t.Key()) {
- panic(InvalidTypeError{t})
- }
- return "a{" + getSignature(t.Key()) + getSignature(t.Elem()) + "}"
- }
- panic(InvalidTypeError{t})
-}
-
-// ParseSignature returns the signature represented by this string, or a
-// SignatureError if the string is not a valid signature.
-func ParseSignature(s string) (sig Signature, err error) {
- if len(s) == 0 {
- return
- }
- if len(s) > 255 {
- return Signature{""}, SignatureError{s, "too long"}
- }
- sig.str = s
- for err == nil && len(s) != 0 {
- err, s = validSingle(s, 0)
- }
- if err != nil {
- sig = Signature{""}
- }
-
- return
-}
-
-// ParseSignatureMust behaves like ParseSignature, except that it panics if s
-// is not valid.
-func ParseSignatureMust(s string) Signature {
- sig, err := ParseSignature(s)
- if err != nil {
- panic(err)
- }
- return sig
-}
-
-// Empty retruns whether the signature is the empty signature.
-func (s Signature) Empty() bool {
- return s.str == ""
-}
-
-// Single returns whether the signature represents a single, complete type.
-func (s Signature) Single() bool {
- err, r := validSingle(s.str, 0)
- return err != nil && r == ""
-}
-
-// String returns the signature's string representation.
-func (s Signature) String() string {
- return s.str
-}
-
-// A SignatureError indicates that a signature passed to a function or received
-// on a connection is not a valid signature.
-type SignatureError struct {
- Sig string
- Reason string
-}
-
-func (e SignatureError) Error() string {
- return fmt.Sprintf("dbus: invalid signature: %q (%s)", e.Sig, e.Reason)
-}
-
-// Try to read a single type from this string. If it was successfull, err is nil
-// and rem is the remaining unparsed part. Otherwise, err is a non-nil
-// SignatureError and rem is "". depth is the current recursion depth which may
-// not be greater than 64 and should be given as 0 on the first call.
-func validSingle(s string, depth int) (err error, rem string) {
- if s == "" {
- return SignatureError{Sig: s, Reason: "empty signature"}, ""
- }
- if depth > 64 {
- return SignatureError{Sig: s, Reason: "container nesting too deep"}, ""
- }
- switch s[0] {
- case 'y', 'b', 'n', 'q', 'i', 'u', 'x', 't', 'd', 's', 'g', 'o', 'v', 'h':
- return nil, s[1:]
- case 'a':
- if len(s) > 1 && s[1] == '{' {
- i := findMatching(s[1:], '{', '}')
- if i == -1 {
- return SignatureError{Sig: s, Reason: "unmatched '{'"}, ""
- }
- i++
- rem = s[i+1:]
- s = s[2:i]
- if err, _ = validSingle(s[:1], depth+1); err != nil {
- return err, ""
- }
- err, nr := validSingle(s[1:], depth+1)
- if err != nil {
- return err, ""
- }
- if nr != "" {
- return SignatureError{Sig: s, Reason: "too many types in dict"}, ""
- }
- return nil, rem
- }
- return validSingle(s[1:], depth+1)
- case '(':
- i := findMatching(s, '(', ')')
- if i == -1 {
- return SignatureError{Sig: s, Reason: "unmatched ')'"}, ""
- }
- rem = s[i+1:]
- s = s[1:i]
- for err == nil && s != "" {
- err, s = validSingle(s, depth+1)
- }
- if err != nil {
- rem = ""
- }
- return
- }
- return SignatureError{Sig: s, Reason: "invalid type character"}, ""
-}
-
-func findMatching(s string, left, right rune) int {
- n := 0
- for i, v := range s {
- if v == left {
- n++
- } else if v == right {
- n--
- }
- if n == 0 {
- return i
- }
- }
- return -1
-}
-
-// typeFor returns the type of the given signature. It ignores any left over
-// characters and panics if s doesn't start with a valid type signature.
-func typeFor(s string) (t reflect.Type) {
- err, _ := validSingle(s, 0)
- if err != nil {
- panic(err)
- }
-
- if t, ok := sigToType[s[0]]; ok {
- return t
- }
- switch s[0] {
- case 'a':
- if s[1] == '{' {
- i := strings.LastIndex(s, "}")
- t = reflect.MapOf(sigToType[s[2]], typeFor(s[3:i]))
- } else {
- t = reflect.SliceOf(typeFor(s[1:]))
- }
- case '(':
- t = interfacesType
- }
- return
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/transport_darwin.go b/containerd/vendor/github.com/godbus/dbus/transport_darwin.go
deleted file mode 100644
index 1bba0d6..0000000
--- a/containerd/vendor/github.com/godbus/dbus/transport_darwin.go
+++ /dev/null
@@ -1,6 +0,0 @@
-package dbus
-
-func (t *unixTransport) SendNullByte() error {
- _, err := t.Write([]byte{0})
- return err
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/transport_generic.go b/containerd/vendor/github.com/godbus/dbus/transport_generic.go
deleted file mode 100644
index 46f8f49..0000000
--- a/containerd/vendor/github.com/godbus/dbus/transport_generic.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package dbus
-
-import (
- "encoding/binary"
- "errors"
- "io"
-)
-
-type genericTransport struct {
- io.ReadWriteCloser
-}
-
-func (t genericTransport) SendNullByte() error {
- _, err := t.Write([]byte{0})
- return err
-}
-
-func (t genericTransport) SupportsUnixFDs() bool {
- return false
-}
-
-func (t genericTransport) EnableUnixFDs() {}
-
-func (t genericTransport) ReadMessage() (*Message, error) {
- return DecodeMessage(t)
-}
-
-func (t genericTransport) SendMessage(msg *Message) error {
- for _, v := range msg.Body {
- if _, ok := v.(UnixFD); ok {
- return errors.New("dbus: unix fd passing not enabled")
- }
- }
- return msg.EncodeTo(t, binary.LittleEndian)
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/transport_unix.go b/containerd/vendor/github.com/godbus/dbus/transport_unix.go
deleted file mode 100644
index 3fafeab..0000000
--- a/containerd/vendor/github.com/godbus/dbus/transport_unix.go
+++ /dev/null
@@ -1,196 +0,0 @@
-//+build !windows
-
-package dbus
-
-import (
- "bytes"
- "encoding/binary"
- "errors"
- "io"
- "net"
- "syscall"
-)
-
-type oobReader struct {
- conn *net.UnixConn
- oob []byte
- buf [4096]byte
-}
-
-func (o *oobReader) Read(b []byte) (n int, err error) {
- n, oobn, flags, _, err := o.conn.ReadMsgUnix(b, o.buf[:])
- if err != nil {
- return n, err
- }
- if flags&syscall.MSG_CTRUNC != 0 {
- return n, errors.New("dbus: control data truncated (too many fds received)")
- }
- o.oob = append(o.oob, o.buf[:oobn]...)
- return n, nil
-}
-
-type unixTransport struct {
- *net.UnixConn
- hasUnixFDs bool
-}
-
-func newUnixTransport(keys string) (transport, error) {
- var err error
-
- t := new(unixTransport)
- abstract := getKey(keys, "abstract")
- path := getKey(keys, "path")
- switch {
- case abstract == "" && path == "":
- return nil, errors.New("dbus: invalid address (neither path nor abstract set)")
- case abstract != "" && path == "":
- t.UnixConn, err = net.DialUnix("unix", nil, &net.UnixAddr{Name: "@" + abstract, Net: "unix"})
- if err != nil {
- return nil, err
- }
- return t, nil
- case abstract == "" && path != "":
- t.UnixConn, err = net.DialUnix("unix", nil, &net.UnixAddr{Name: path, Net: "unix"})
- if err != nil {
- return nil, err
- }
- return t, nil
- default:
- return nil, errors.New("dbus: invalid address (both path and abstract set)")
- }
-}
-
-func init() {
- transports["unix"] = newUnixTransport
-}
-
-func (t *unixTransport) EnableUnixFDs() {
- t.hasUnixFDs = true
-}
-
-func (t *unixTransport) ReadMessage() (*Message, error) {
- var (
- blen, hlen uint32
- csheader [16]byte
- headers []header
- order binary.ByteOrder
- unixfds uint32
- )
- // To be sure that all bytes of out-of-band data are read, we use a special
- // reader that uses ReadUnix on the underlying connection instead of Read
- // and gathers the out-of-band data in a buffer.
- rd := &oobReader{conn: t.UnixConn}
- // read the first 16 bytes (the part of the header that has a constant size),
- // from which we can figure out the length of the rest of the message
- if _, err := io.ReadFull(rd, csheader[:]); err != nil {
- return nil, err
- }
- switch csheader[0] {
- case 'l':
- order = binary.LittleEndian
- case 'B':
- order = binary.BigEndian
- default:
- return nil, InvalidMessageError("invalid byte order")
- }
- // csheader[4:8] -> length of message body, csheader[12:16] -> length of
- // header fields (without alignment)
- binary.Read(bytes.NewBuffer(csheader[4:8]), order, &blen)
- binary.Read(bytes.NewBuffer(csheader[12:]), order, &hlen)
- if hlen%8 != 0 {
- hlen += 8 - (hlen % 8)
- }
-
- // decode headers and look for unix fds
- headerdata := make([]byte, hlen+4)
- copy(headerdata, csheader[12:])
- if _, err := io.ReadFull(t, headerdata[4:]); err != nil {
- return nil, err
- }
- dec := newDecoder(bytes.NewBuffer(headerdata), order)
- dec.pos = 12
- vs, err := dec.Decode(Signature{"a(yv)"})
- if err != nil {
- return nil, err
- }
- Store(vs, &headers)
- for _, v := range headers {
- if v.Field == byte(FieldUnixFDs) {
- unixfds, _ = v.Variant.value.(uint32)
- }
- }
- all := make([]byte, 16+hlen+blen)
- copy(all, csheader[:])
- copy(all[16:], headerdata[4:])
- if _, err := io.ReadFull(rd, all[16+hlen:]); err != nil {
- return nil, err
- }
- if unixfds != 0 {
- if !t.hasUnixFDs {
- return nil, errors.New("dbus: got unix fds on unsupported transport")
- }
- // read the fds from the OOB data
- scms, err := syscall.ParseSocketControlMessage(rd.oob)
- if err != nil {
- return nil, err
- }
- if len(scms) != 1 {
- return nil, errors.New("dbus: received more than one socket control message")
- }
- fds, err := syscall.ParseUnixRights(&scms[0])
- if err != nil {
- return nil, err
- }
- msg, err := DecodeMessage(bytes.NewBuffer(all))
- if err != nil {
- return nil, err
- }
- // substitute the values in the message body (which are indices for the
- // array receiver via OOB) with the actual values
- for i, v := range msg.Body {
- if j, ok := v.(UnixFDIndex); ok {
- if uint32(j) >= unixfds {
- return nil, InvalidMessageError("invalid index for unix fd")
- }
- msg.Body[i] = UnixFD(fds[j])
- }
- }
- return msg, nil
- }
- return DecodeMessage(bytes.NewBuffer(all))
-}
-
-func (t *unixTransport) SendMessage(msg *Message) error {
- fds := make([]int, 0)
- for i, v := range msg.Body {
- if fd, ok := v.(UnixFD); ok {
- msg.Body[i] = UnixFDIndex(len(fds))
- fds = append(fds, int(fd))
- }
- }
- if len(fds) != 0 {
- if !t.hasUnixFDs {
- return errors.New("dbus: unix fd passing not enabled")
- }
- msg.Headers[FieldUnixFDs] = MakeVariant(uint32(len(fds)))
- oob := syscall.UnixRights(fds...)
- buf := new(bytes.Buffer)
- msg.EncodeTo(buf, binary.LittleEndian)
- n, oobn, err := t.UnixConn.WriteMsgUnix(buf.Bytes(), oob, nil)
- if err != nil {
- return err
- }
- if n != buf.Len() || oobn != len(oob) {
- return io.ErrShortWrite
- }
- } else {
- if err := msg.EncodeTo(t, binary.LittleEndian); err != nil {
- return nil
- }
- }
- return nil
-}
-
-func (t *unixTransport) SupportsUnixFDs() bool {
- return true
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/transport_unixcred_dragonfly.go b/containerd/vendor/github.com/godbus/dbus/transport_unixcred_dragonfly.go
deleted file mode 100644
index a8cd393..0000000
--- a/containerd/vendor/github.com/godbus/dbus/transport_unixcred_dragonfly.go
+++ /dev/null
@@ -1,95 +0,0 @@
-// The UnixCredentials system call is currently only implemented on Linux
-// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
-// https://golang.org/s/go1.4-syscall
-// http://code.google.com/p/go/source/browse/unix/sockcmsg_linux.go?repo=sys
-
-// Local implementation of the UnixCredentials system call for DragonFly BSD
-
-package dbus
-
-/*
-#include
-*/
-import "C"
-
-import (
- "io"
- "os"
- "syscall"
- "unsafe"
-)
-
-// http://golang.org/src/pkg/syscall/ztypes_linux_amd64.go
-// http://golang.org/src/pkg/syscall/ztypes_dragonfly_amd64.go
-type Ucred struct {
- Pid int32
- Uid uint32
- Gid uint32
-}
-
-// http://golang.org/src/pkg/syscall/types_linux.go
-// http://golang.org/src/pkg/syscall/types_dragonfly.go
-// https://github.com/DragonFlyBSD/DragonFlyBSD/blob/master/sys/sys/ucred.h
-const (
- SizeofUcred = C.sizeof_struct_ucred
-)
-
-// http://golang.org/src/pkg/syscall/sockcmsg_unix.go
-func cmsgAlignOf(salen int) int {
- // From http://golang.org/src/pkg/syscall/sockcmsg_unix.go
- //salign := sizeofPtr
- // NOTE: It seems like 64-bit Darwin and DragonFly BSD kernels
- // still require 32-bit aligned access to network subsystem.
- //if darwin64Bit || dragonfly64Bit {
- // salign = 4
- //}
- salign := 4
- return (salen + salign - 1) & ^(salign - 1)
-}
-
-// http://golang.org/src/pkg/syscall/sockcmsg_unix.go
-func cmsgData(h *syscall.Cmsghdr) unsafe.Pointer {
- return unsafe.Pointer(uintptr(unsafe.Pointer(h)) + uintptr(cmsgAlignOf(syscall.SizeofCmsghdr)))
-}
-
-// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
-// UnixCredentials encodes credentials into a socket control message
-// for sending to another process. This can be used for
-// authentication.
-func UnixCredentials(ucred *Ucred) []byte {
- b := make([]byte, syscall.CmsgSpace(SizeofUcred))
- h := (*syscall.Cmsghdr)(unsafe.Pointer(&b[0]))
- h.Level = syscall.SOL_SOCKET
- h.Type = syscall.SCM_CREDS
- h.SetLen(syscall.CmsgLen(SizeofUcred))
- *((*Ucred)(cmsgData(h))) = *ucred
- return b
-}
-
-// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
-// ParseUnixCredentials decodes a socket control message that contains
-// credentials in a Ucred structure. To receive such a message, the
-// SO_PASSCRED option must be enabled on the socket.
-func ParseUnixCredentials(m *syscall.SocketControlMessage) (*Ucred, error) {
- if m.Header.Level != syscall.SOL_SOCKET {
- return nil, syscall.EINVAL
- }
- if m.Header.Type != syscall.SCM_CREDS {
- return nil, syscall.EINVAL
- }
- ucred := *(*Ucred)(unsafe.Pointer(&m.Data[0]))
- return &ucred, nil
-}
-
-func (t *unixTransport) SendNullByte() error {
- ucred := &Ucred{Pid: int32(os.Getpid()), Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid())}
- b := UnixCredentials(ucred)
- _, oobn, err := t.UnixConn.WriteMsgUnix([]byte{0}, b, nil)
- if err != nil {
- return err
- }
- if oobn != len(b) {
- return io.ErrShortWrite
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/transport_unixcred_linux.go b/containerd/vendor/github.com/godbus/dbus/transport_unixcred_linux.go
deleted file mode 100644
index d9dfdf6..0000000
--- a/containerd/vendor/github.com/godbus/dbus/transport_unixcred_linux.go
+++ /dev/null
@@ -1,25 +0,0 @@
-// The UnixCredentials system call is currently only implemented on Linux
-// http://golang.org/src/pkg/syscall/sockcmsg_linux.go
-// https://golang.org/s/go1.4-syscall
-// http://code.google.com/p/go/source/browse/unix/sockcmsg_linux.go?repo=sys
-
-package dbus
-
-import (
- "io"
- "os"
- "syscall"
-)
-
-func (t *unixTransport) SendNullByte() error {
- ucred := &syscall.Ucred{Pid: int32(os.Getpid()), Uid: uint32(os.Getuid()), Gid: uint32(os.Getgid())}
- b := syscall.UnixCredentials(ucred)
- _, oobn, err := t.UnixConn.WriteMsgUnix([]byte{0}, b, nil)
- if err != nil {
- return err
- }
- if oobn != len(b) {
- return io.ErrShortWrite
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/variant.go b/containerd/vendor/github.com/godbus/dbus/variant.go
deleted file mode 100644
index b7b13ae..0000000
--- a/containerd/vendor/github.com/godbus/dbus/variant.go
+++ /dev/null
@@ -1,139 +0,0 @@
-package dbus
-
-import (
- "bytes"
- "fmt"
- "reflect"
- "sort"
- "strconv"
-)
-
-// Variant represents the D-Bus variant type.
-type Variant struct {
- sig Signature
- value interface{}
-}
-
-// MakeVariant converts the given value to a Variant. It panics if v cannot be
-// represented as a D-Bus type.
-func MakeVariant(v interface{}) Variant {
- return Variant{SignatureOf(v), v}
-}
-
-// ParseVariant parses the given string as a variant as described at
-// https://developer.gnome.org/glib/unstable/gvariant-text.html. If sig is not
-// empty, it is taken to be the expected signature for the variant.
-func ParseVariant(s string, sig Signature) (Variant, error) {
- tokens := varLex(s)
- p := &varParser{tokens: tokens}
- n, err := varMakeNode(p)
- if err != nil {
- return Variant{}, err
- }
- if sig.str == "" {
- sig, err = varInfer(n)
- if err != nil {
- return Variant{}, err
- }
- }
- v, err := n.Value(sig)
- if err != nil {
- return Variant{}, err
- }
- return MakeVariant(v), nil
-}
-
-// format returns a formatted version of v and whether this string can be parsed
-// unambigously.
-func (v Variant) format() (string, bool) {
- switch v.sig.str[0] {
- case 'b', 'i':
- return fmt.Sprint(v.value), true
- case 'n', 'q', 'u', 'x', 't', 'd', 'h':
- return fmt.Sprint(v.value), false
- case 's':
- return strconv.Quote(v.value.(string)), true
- case 'o':
- return strconv.Quote(string(v.value.(ObjectPath))), false
- case 'g':
- return strconv.Quote(v.value.(Signature).str), false
- case 'v':
- s, unamb := v.value.(Variant).format()
- if !unamb {
- return "<@" + v.value.(Variant).sig.str + " " + s + ">", true
- }
- return "<" + s + ">", true
- case 'y':
- return fmt.Sprintf("%#x", v.value.(byte)), false
- }
- rv := reflect.ValueOf(v.value)
- switch rv.Kind() {
- case reflect.Slice:
- if rv.Len() == 0 {
- return "[]", false
- }
- unamb := true
- buf := bytes.NewBuffer([]byte("["))
- for i := 0; i < rv.Len(); i++ {
- // TODO: slooow
- s, b := MakeVariant(rv.Index(i).Interface()).format()
- unamb = unamb && b
- buf.WriteString(s)
- if i != rv.Len()-1 {
- buf.WriteString(", ")
- }
- }
- buf.WriteByte(']')
- return buf.String(), unamb
- case reflect.Map:
- if rv.Len() == 0 {
- return "{}", false
- }
- unamb := true
- var buf bytes.Buffer
- kvs := make([]string, rv.Len())
- for i, k := range rv.MapKeys() {
- s, b := MakeVariant(k.Interface()).format()
- unamb = unamb && b
- buf.Reset()
- buf.WriteString(s)
- buf.WriteString(": ")
- s, b = MakeVariant(rv.MapIndex(k).Interface()).format()
- unamb = unamb && b
- buf.WriteString(s)
- kvs[i] = buf.String()
- }
- buf.Reset()
- buf.WriteByte('{')
- sort.Strings(kvs)
- for i, kv := range kvs {
- if i > 0 {
- buf.WriteString(", ")
- }
- buf.WriteString(kv)
- }
- buf.WriteByte('}')
- return buf.String(), unamb
- }
- return `"INVALID"`, true
-}
-
-// Signature returns the D-Bus signature of the underlying value of v.
-func (v Variant) Signature() Signature {
- return v.sig
-}
-
-// String returns the string representation of the underlying value of v as
-// described at https://developer.gnome.org/glib/unstable/gvariant-text.html.
-func (v Variant) String() string {
- s, unamb := v.format()
- if !unamb {
- return "@" + v.sig.str + " " + s
- }
- return s
-}
-
-// Value returns the underlying value of v.
-func (v Variant) Value() interface{} {
- return v.value
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/variant_lexer.go b/containerd/vendor/github.com/godbus/dbus/variant_lexer.go
deleted file mode 100644
index 332007d..0000000
--- a/containerd/vendor/github.com/godbus/dbus/variant_lexer.go
+++ /dev/null
@@ -1,284 +0,0 @@
-package dbus
-
-import (
- "fmt"
- "strings"
- "unicode"
- "unicode/utf8"
-)
-
-// Heavily inspired by the lexer from text/template.
-
-type varToken struct {
- typ varTokenType
- val string
-}
-
-type varTokenType byte
-
-const (
- tokEOF varTokenType = iota
- tokError
- tokNumber
- tokString
- tokBool
- tokArrayStart
- tokArrayEnd
- tokDictStart
- tokDictEnd
- tokVariantStart
- tokVariantEnd
- tokComma
- tokColon
- tokType
- tokByteString
-)
-
-type varLexer struct {
- input string
- start int
- pos int
- width int
- tokens []varToken
-}
-
-type lexState func(*varLexer) lexState
-
-func varLex(s string) []varToken {
- l := &varLexer{input: s}
- l.run()
- return l.tokens
-}
-
-func (l *varLexer) accept(valid string) bool {
- if strings.IndexRune(valid, l.next()) >= 0 {
- return true
- }
- l.backup()
- return false
-}
-
-func (l *varLexer) backup() {
- l.pos -= l.width
-}
-
-func (l *varLexer) emit(t varTokenType) {
- l.tokens = append(l.tokens, varToken{t, l.input[l.start:l.pos]})
- l.start = l.pos
-}
-
-func (l *varLexer) errorf(format string, v ...interface{}) lexState {
- l.tokens = append(l.tokens, varToken{
- tokError,
- fmt.Sprintf(format, v...),
- })
- return nil
-}
-
-func (l *varLexer) ignore() {
- l.start = l.pos
-}
-
-func (l *varLexer) next() rune {
- var r rune
-
- if l.pos >= len(l.input) {
- l.width = 0
- return -1
- }
- r, l.width = utf8.DecodeRuneInString(l.input[l.pos:])
- l.pos += l.width
- return r
-}
-
-func (l *varLexer) run() {
- for state := varLexNormal; state != nil; {
- state = state(l)
- }
-}
-
-func (l *varLexer) peek() rune {
- r := l.next()
- l.backup()
- return r
-}
-
-func varLexNormal(l *varLexer) lexState {
- for {
- r := l.next()
- switch {
- case r == -1:
- l.emit(tokEOF)
- return nil
- case r == '[':
- l.emit(tokArrayStart)
- case r == ']':
- l.emit(tokArrayEnd)
- case r == '{':
- l.emit(tokDictStart)
- case r == '}':
- l.emit(tokDictEnd)
- case r == '<':
- l.emit(tokVariantStart)
- case r == '>':
- l.emit(tokVariantEnd)
- case r == ':':
- l.emit(tokColon)
- case r == ',':
- l.emit(tokComma)
- case r == '\'' || r == '"':
- l.backup()
- return varLexString
- case r == '@':
- l.backup()
- return varLexType
- case unicode.IsSpace(r):
- l.ignore()
- case unicode.IsNumber(r) || r == '+' || r == '-':
- l.backup()
- return varLexNumber
- case r == 'b':
- pos := l.start
- if n := l.peek(); n == '"' || n == '\'' {
- return varLexByteString
- }
- // not a byte string; try to parse it as a type or bool below
- l.pos = pos + 1
- l.width = 1
- fallthrough
- default:
- // either a bool or a type. Try bools first.
- l.backup()
- if l.pos+4 <= len(l.input) {
- if l.input[l.pos:l.pos+4] == "true" {
- l.pos += 4
- l.emit(tokBool)
- continue
- }
- }
- if l.pos+5 <= len(l.input) {
- if l.input[l.pos:l.pos+5] == "false" {
- l.pos += 5
- l.emit(tokBool)
- continue
- }
- }
- // must be a type.
- return varLexType
- }
- }
-}
-
-var varTypeMap = map[string]string{
- "boolean": "b",
- "byte": "y",
- "int16": "n",
- "uint16": "q",
- "int32": "i",
- "uint32": "u",
- "int64": "x",
- "uint64": "t",
- "double": "f",
- "string": "s",
- "objectpath": "o",
- "signature": "g",
-}
-
-func varLexByteString(l *varLexer) lexState {
- q := l.next()
-Loop:
- for {
- switch l.next() {
- case '\\':
- if r := l.next(); r != -1 {
- break
- }
- fallthrough
- case -1:
- return l.errorf("unterminated bytestring")
- case q:
- break Loop
- }
- }
- l.emit(tokByteString)
- return varLexNormal
-}
-
-func varLexNumber(l *varLexer) lexState {
- l.accept("+-")
- digits := "0123456789"
- if l.accept("0") {
- if l.accept("x") {
- digits = "0123456789abcdefABCDEF"
- } else {
- digits = "01234567"
- }
- }
- for strings.IndexRune(digits, l.next()) >= 0 {
- }
- l.backup()
- if l.accept(".") {
- for strings.IndexRune(digits, l.next()) >= 0 {
- }
- l.backup()
- }
- if l.accept("eE") {
- l.accept("+-")
- for strings.IndexRune("0123456789", l.next()) >= 0 {
- }
- l.backup()
- }
- if r := l.peek(); unicode.IsLetter(r) {
- l.next()
- return l.errorf("bad number syntax: %q", l.input[l.start:l.pos])
- }
- l.emit(tokNumber)
- return varLexNormal
-}
-
-func varLexString(l *varLexer) lexState {
- q := l.next()
-Loop:
- for {
- switch l.next() {
- case '\\':
- if r := l.next(); r != -1 {
- break
- }
- fallthrough
- case -1:
- return l.errorf("unterminated string")
- case q:
- break Loop
- }
- }
- l.emit(tokString)
- return varLexNormal
-}
-
-func varLexType(l *varLexer) lexState {
- at := l.accept("@")
- for {
- r := l.next()
- if r == -1 {
- break
- }
- if unicode.IsSpace(r) {
- l.backup()
- break
- }
- }
- if at {
- if _, err := ParseSignature(l.input[l.start+1 : l.pos]); err != nil {
- return l.errorf("%s", err)
- }
- } else {
- if _, ok := varTypeMap[l.input[l.start:l.pos]]; ok {
- l.emit(tokType)
- return varLexNormal
- }
- return l.errorf("unrecognized type %q", l.input[l.start:l.pos])
- }
- l.emit(tokType)
- return varLexNormal
-}
diff --git a/containerd/vendor/github.com/godbus/dbus/variant_parser.go b/containerd/vendor/github.com/godbus/dbus/variant_parser.go
deleted file mode 100644
index d20f5da..0000000
--- a/containerd/vendor/github.com/godbus/dbus/variant_parser.go
+++ /dev/null
@@ -1,817 +0,0 @@
-package dbus
-
-import (
- "bytes"
- "errors"
- "fmt"
- "io"
- "reflect"
- "strconv"
- "strings"
- "unicode/utf8"
-)
-
-type varParser struct {
- tokens []varToken
- i int
-}
-
-func (p *varParser) backup() {
- p.i--
-}
-
-func (p *varParser) next() varToken {
- if p.i < len(p.tokens) {
- t := p.tokens[p.i]
- p.i++
- return t
- }
- return varToken{typ: tokEOF}
-}
-
-type varNode interface {
- Infer() (Signature, error)
- String() string
- Sigs() sigSet
- Value(Signature) (interface{}, error)
-}
-
-func varMakeNode(p *varParser) (varNode, error) {
- var sig Signature
-
- for {
- t := p.next()
- switch t.typ {
- case tokEOF:
- return nil, io.ErrUnexpectedEOF
- case tokError:
- return nil, errors.New(t.val)
- case tokNumber:
- return varMakeNumNode(t, sig)
- case tokString:
- return varMakeStringNode(t, sig)
- case tokBool:
- if sig.str != "" && sig.str != "b" {
- return nil, varTypeError{t.val, sig}
- }
- b, err := strconv.ParseBool(t.val)
- if err != nil {
- return nil, err
- }
- return boolNode(b), nil
- case tokArrayStart:
- return varMakeArrayNode(p, sig)
- case tokVariantStart:
- return varMakeVariantNode(p, sig)
- case tokDictStart:
- return varMakeDictNode(p, sig)
- case tokType:
- if sig.str != "" {
- return nil, errors.New("unexpected type annotation")
- }
- if t.val[0] == '@' {
- sig.str = t.val[1:]
- } else {
- sig.str = varTypeMap[t.val]
- }
- case tokByteString:
- if sig.str != "" && sig.str != "ay" {
- return nil, varTypeError{t.val, sig}
- }
- b, err := varParseByteString(t.val)
- if err != nil {
- return nil, err
- }
- return byteStringNode(b), nil
- default:
- return nil, fmt.Errorf("unexpected %q", t.val)
- }
- }
-}
-
-type varTypeError struct {
- val string
- sig Signature
-}
-
-func (e varTypeError) Error() string {
- return fmt.Sprintf("dbus: can't parse %q as type %q", e.val, e.sig.str)
-}
-
-type sigSet map[Signature]bool
-
-func (s sigSet) Empty() bool {
- return len(s) == 0
-}
-
-func (s sigSet) Intersect(s2 sigSet) sigSet {
- r := make(sigSet)
- for k := range s {
- if s2[k] {
- r[k] = true
- }
- }
- return r
-}
-
-func (s sigSet) Single() (Signature, bool) {
- if len(s) == 1 {
- for k := range s {
- return k, true
- }
- }
- return Signature{}, false
-}
-
-func (s sigSet) ToArray() sigSet {
- r := make(sigSet, len(s))
- for k := range s {
- r[Signature{"a" + k.str}] = true
- }
- return r
-}
-
-type numNode struct {
- sig Signature
- str string
- val interface{}
-}
-
-var numSigSet = sigSet{
- Signature{"y"}: true,
- Signature{"n"}: true,
- Signature{"q"}: true,
- Signature{"i"}: true,
- Signature{"u"}: true,
- Signature{"x"}: true,
- Signature{"t"}: true,
- Signature{"d"}: true,
-}
-
-func (n numNode) Infer() (Signature, error) {
- if strings.ContainsAny(n.str, ".e") {
- return Signature{"d"}, nil
- }
- return Signature{"i"}, nil
-}
-
-func (n numNode) String() string {
- return n.str
-}
-
-func (n numNode) Sigs() sigSet {
- if n.sig.str != "" {
- return sigSet{n.sig: true}
- }
- if strings.ContainsAny(n.str, ".e") {
- return sigSet{Signature{"d"}: true}
- }
- return numSigSet
-}
-
-func (n numNode) Value(sig Signature) (interface{}, error) {
- if n.sig.str != "" && n.sig != sig {
- return nil, varTypeError{n.str, sig}
- }
- if n.val != nil {
- return n.val, nil
- }
- return varNumAs(n.str, sig)
-}
-
-func varMakeNumNode(tok varToken, sig Signature) (varNode, error) {
- if sig.str == "" {
- return numNode{str: tok.val}, nil
- }
- num, err := varNumAs(tok.val, sig)
- if err != nil {
- return nil, err
- }
- return numNode{sig: sig, val: num}, nil
-}
-
-func varNumAs(s string, sig Signature) (interface{}, error) {
- isUnsigned := false
- size := 32
- switch sig.str {
- case "n":
- size = 16
- case "i":
- case "x":
- size = 64
- case "y":
- size = 8
- isUnsigned = true
- case "q":
- size = 16
- isUnsigned = true
- case "u":
- isUnsigned = true
- case "t":
- size = 64
- isUnsigned = true
- case "d":
- d, err := strconv.ParseFloat(s, 64)
- if err != nil {
- return nil, err
- }
- return d, nil
- default:
- return nil, varTypeError{s, sig}
- }
- base := 10
- if strings.HasPrefix(s, "0x") {
- base = 16
- s = s[2:]
- }
- if strings.HasPrefix(s, "0") && len(s) != 1 {
- base = 8
- s = s[1:]
- }
- if isUnsigned {
- i, err := strconv.ParseUint(s, base, size)
- if err != nil {
- return nil, err
- }
- var v interface{} = i
- switch sig.str {
- case "y":
- v = byte(i)
- case "q":
- v = uint16(i)
- case "u":
- v = uint32(i)
- }
- return v, nil
- }
- i, err := strconv.ParseInt(s, base, size)
- if err != nil {
- return nil, err
- }
- var v interface{} = i
- switch sig.str {
- case "n":
- v = int16(i)
- case "i":
- v = int32(i)
- }
- return v, nil
-}
-
-type stringNode struct {
- sig Signature
- str string // parsed
- val interface{} // has correct type
-}
-
-var stringSigSet = sigSet{
- Signature{"s"}: true,
- Signature{"g"}: true,
- Signature{"o"}: true,
-}
-
-func (n stringNode) Infer() (Signature, error) {
- return Signature{"s"}, nil
-}
-
-func (n stringNode) String() string {
- return n.str
-}
-
-func (n stringNode) Sigs() sigSet {
- if n.sig.str != "" {
- return sigSet{n.sig: true}
- }
- return stringSigSet
-}
-
-func (n stringNode) Value(sig Signature) (interface{}, error) {
- if n.sig.str != "" && n.sig != sig {
- return nil, varTypeError{n.str, sig}
- }
- if n.val != nil {
- return n.val, nil
- }
- switch {
- case sig.str == "g":
- return Signature{n.str}, nil
- case sig.str == "o":
- return ObjectPath(n.str), nil
- case sig.str == "s":
- return n.str, nil
- default:
- return nil, varTypeError{n.str, sig}
- }
-}
-
-func varMakeStringNode(tok varToken, sig Signature) (varNode, error) {
- if sig.str != "" && sig.str != "s" && sig.str != "g" && sig.str != "o" {
- return nil, fmt.Errorf("invalid type %q for string", sig.str)
- }
- s, err := varParseString(tok.val)
- if err != nil {
- return nil, err
- }
- n := stringNode{str: s}
- if sig.str == "" {
- return stringNode{str: s}, nil
- }
- n.sig = sig
- switch sig.str {
- case "o":
- n.val = ObjectPath(s)
- case "g":
- n.val = Signature{s}
- case "s":
- n.val = s
- }
- return n, nil
-}
-
-func varParseString(s string) (string, error) {
- // quotes are guaranteed to be there
- s = s[1 : len(s)-1]
- buf := new(bytes.Buffer)
- for len(s) != 0 {
- r, size := utf8.DecodeRuneInString(s)
- if r == utf8.RuneError && size == 1 {
- return "", errors.New("invalid UTF-8")
- }
- s = s[size:]
- if r != '\\' {
- buf.WriteRune(r)
- continue
- }
- r, size = utf8.DecodeRuneInString(s)
- if r == utf8.RuneError && size == 1 {
- return "", errors.New("invalid UTF-8")
- }
- s = s[size:]
- switch r {
- case 'a':
- buf.WriteRune(0x7)
- case 'b':
- buf.WriteRune(0x8)
- case 'f':
- buf.WriteRune(0xc)
- case 'n':
- buf.WriteRune('\n')
- case 'r':
- buf.WriteRune('\r')
- case 't':
- buf.WriteRune('\t')
- case '\n':
- case 'u':
- if len(s) < 4 {
- return "", errors.New("short unicode escape")
- }
- r, err := strconv.ParseUint(s[:4], 16, 32)
- if err != nil {
- return "", err
- }
- buf.WriteRune(rune(r))
- s = s[4:]
- case 'U':
- if len(s) < 8 {
- return "", errors.New("short unicode escape")
- }
- r, err := strconv.ParseUint(s[:8], 16, 32)
- if err != nil {
- return "", err
- }
- buf.WriteRune(rune(r))
- s = s[8:]
- default:
- buf.WriteRune(r)
- }
- }
- return buf.String(), nil
-}
-
-var boolSigSet = sigSet{Signature{"b"}: true}
-
-type boolNode bool
-
-func (boolNode) Infer() (Signature, error) {
- return Signature{"b"}, nil
-}
-
-func (b boolNode) String() string {
- if b {
- return "true"
- }
- return "false"
-}
-
-func (boolNode) Sigs() sigSet {
- return boolSigSet
-}
-
-func (b boolNode) Value(sig Signature) (interface{}, error) {
- if sig.str != "b" {
- return nil, varTypeError{b.String(), sig}
- }
- return bool(b), nil
-}
-
-type arrayNode struct {
- set sigSet
- children []varNode
- val interface{}
-}
-
-func (n arrayNode) Infer() (Signature, error) {
- for _, v := range n.children {
- csig, err := varInfer(v)
- if err != nil {
- continue
- }
- return Signature{"a" + csig.str}, nil
- }
- return Signature{}, fmt.Errorf("can't infer type for %q", n.String())
-}
-
-func (n arrayNode) String() string {
- s := "["
- for i, v := range n.children {
- s += v.String()
- if i != len(n.children)-1 {
- s += ", "
- }
- }
- return s + "]"
-}
-
-func (n arrayNode) Sigs() sigSet {
- return n.set
-}
-
-func (n arrayNode) Value(sig Signature) (interface{}, error) {
- if n.set.Empty() {
- // no type information whatsoever, so this must be an empty slice
- return reflect.MakeSlice(typeFor(sig.str), 0, 0).Interface(), nil
- }
- if !n.set[sig] {
- return nil, varTypeError{n.String(), sig}
- }
- s := reflect.MakeSlice(typeFor(sig.str), len(n.children), len(n.children))
- for i, v := range n.children {
- rv, err := v.Value(Signature{sig.str[1:]})
- if err != nil {
- return nil, err
- }
- s.Index(i).Set(reflect.ValueOf(rv))
- }
- return s.Interface(), nil
-}
-
-func varMakeArrayNode(p *varParser, sig Signature) (varNode, error) {
- var n arrayNode
- if sig.str != "" {
- n.set = sigSet{sig: true}
- }
- if t := p.next(); t.typ == tokArrayEnd {
- return n, nil
- } else {
- p.backup()
- }
-Loop:
- for {
- t := p.next()
- switch t.typ {
- case tokEOF:
- return nil, io.ErrUnexpectedEOF
- case tokError:
- return nil, errors.New(t.val)
- }
- p.backup()
- cn, err := varMakeNode(p)
- if err != nil {
- return nil, err
- }
- if cset := cn.Sigs(); !cset.Empty() {
- if n.set.Empty() {
- n.set = cset.ToArray()
- } else {
- nset := cset.ToArray().Intersect(n.set)
- if nset.Empty() {
- return nil, fmt.Errorf("can't parse %q with given type information", cn.String())
- }
- n.set = nset
- }
- }
- n.children = append(n.children, cn)
- switch t := p.next(); t.typ {
- case tokEOF:
- return nil, io.ErrUnexpectedEOF
- case tokError:
- return nil, errors.New(t.val)
- case tokArrayEnd:
- break Loop
- case tokComma:
- continue
- default:
- return nil, fmt.Errorf("unexpected %q", t.val)
- }
- }
- return n, nil
-}
-
-type variantNode struct {
- n varNode
-}
-
-var variantSet = sigSet{
- Signature{"v"}: true,
-}
-
-func (variantNode) Infer() (Signature, error) {
- return Signature{"v"}, nil
-}
-
-func (n variantNode) String() string {
- return "<" + n.n.String() + ">"
-}
-
-func (variantNode) Sigs() sigSet {
- return variantSet
-}
-
-func (n variantNode) Value(sig Signature) (interface{}, error) {
- if sig.str != "v" {
- return nil, varTypeError{n.String(), sig}
- }
- sig, err := varInfer(n.n)
- if err != nil {
- return nil, err
- }
- v, err := n.n.Value(sig)
- if err != nil {
- return nil, err
- }
- return MakeVariant(v), nil
-}
-
-func varMakeVariantNode(p *varParser, sig Signature) (varNode, error) {
- n, err := varMakeNode(p)
- if err != nil {
- return nil, err
- }
- if t := p.next(); t.typ != tokVariantEnd {
- return nil, fmt.Errorf("unexpected %q", t.val)
- }
- vn := variantNode{n}
- if sig.str != "" && sig.str != "v" {
- return nil, varTypeError{vn.String(), sig}
- }
- return variantNode{n}, nil
-}
-
-type dictEntry struct {
- key, val varNode
-}
-
-type dictNode struct {
- kset, vset sigSet
- children []dictEntry
- val interface{}
-}
-
-func (n dictNode) Infer() (Signature, error) {
- for _, v := range n.children {
- ksig, err := varInfer(v.key)
- if err != nil {
- continue
- }
- vsig, err := varInfer(v.val)
- if err != nil {
- continue
- }
- return Signature{"a{" + ksig.str + vsig.str + "}"}, nil
- }
- return Signature{}, fmt.Errorf("can't infer type for %q", n.String())
-}
-
-func (n dictNode) String() string {
- s := "{"
- for i, v := range n.children {
- s += v.key.String() + ": " + v.val.String()
- if i != len(n.children)-1 {
- s += ", "
- }
- }
- return s + "}"
-}
-
-func (n dictNode) Sigs() sigSet {
- r := sigSet{}
- for k := range n.kset {
- for v := range n.vset {
- sig := "a{" + k.str + v.str + "}"
- r[Signature{sig}] = true
- }
- }
- return r
-}
-
-func (n dictNode) Value(sig Signature) (interface{}, error) {
- set := n.Sigs()
- if set.Empty() {
- // no type information -> empty dict
- return reflect.MakeMap(typeFor(sig.str)).Interface(), nil
- }
- if !set[sig] {
- return nil, varTypeError{n.String(), sig}
- }
- m := reflect.MakeMap(typeFor(sig.str))
- ksig := Signature{sig.str[2:3]}
- vsig := Signature{sig.str[3 : len(sig.str)-1]}
- for _, v := range n.children {
- kv, err := v.key.Value(ksig)
- if err != nil {
- return nil, err
- }
- vv, err := v.val.Value(vsig)
- if err != nil {
- return nil, err
- }
- m.SetMapIndex(reflect.ValueOf(kv), reflect.ValueOf(vv))
- }
- return m.Interface(), nil
-}
-
-func varMakeDictNode(p *varParser, sig Signature) (varNode, error) {
- var n dictNode
-
- if sig.str != "" {
- if len(sig.str) < 5 {
- return nil, fmt.Errorf("invalid signature %q for dict type", sig)
- }
- ksig := Signature{string(sig.str[2])}
- vsig := Signature{sig.str[3 : len(sig.str)-1]}
- n.kset = sigSet{ksig: true}
- n.vset = sigSet{vsig: true}
- }
- if t := p.next(); t.typ == tokDictEnd {
- return n, nil
- } else {
- p.backup()
- }
-Loop:
- for {
- t := p.next()
- switch t.typ {
- case tokEOF:
- return nil, io.ErrUnexpectedEOF
- case tokError:
- return nil, errors.New(t.val)
- }
- p.backup()
- kn, err := varMakeNode(p)
- if err != nil {
- return nil, err
- }
- if kset := kn.Sigs(); !kset.Empty() {
- if n.kset.Empty() {
- n.kset = kset
- } else {
- n.kset = kset.Intersect(n.kset)
- if n.kset.Empty() {
- return nil, fmt.Errorf("can't parse %q with given type information", kn.String())
- }
- }
- }
- t = p.next()
- switch t.typ {
- case tokEOF:
- return nil, io.ErrUnexpectedEOF
- case tokError:
- return nil, errors.New(t.val)
- case tokColon:
- default:
- return nil, fmt.Errorf("unexpected %q", t.val)
- }
- t = p.next()
- switch t.typ {
- case tokEOF:
- return nil, io.ErrUnexpectedEOF
- case tokError:
- return nil, errors.New(t.val)
- }
- p.backup()
- vn, err := varMakeNode(p)
- if err != nil {
- return nil, err
- }
- if vset := vn.Sigs(); !vset.Empty() {
- if n.vset.Empty() {
- n.vset = vset
- } else {
- n.vset = n.vset.Intersect(vset)
- if n.vset.Empty() {
- return nil, fmt.Errorf("can't parse %q with given type information", vn.String())
- }
- }
- }
- n.children = append(n.children, dictEntry{kn, vn})
- t = p.next()
- switch t.typ {
- case tokEOF:
- return nil, io.ErrUnexpectedEOF
- case tokError:
- return nil, errors.New(t.val)
- case tokDictEnd:
- break Loop
- case tokComma:
- continue
- default:
- return nil, fmt.Errorf("unexpected %q", t.val)
- }
- }
- return n, nil
-}
-
-type byteStringNode []byte
-
-var byteStringSet = sigSet{
- Signature{"ay"}: true,
-}
-
-func (byteStringNode) Infer() (Signature, error) {
- return Signature{"ay"}, nil
-}
-
-func (b byteStringNode) String() string {
- return string(b)
-}
-
-func (b byteStringNode) Sigs() sigSet {
- return byteStringSet
-}
-
-func (b byteStringNode) Value(sig Signature) (interface{}, error) {
- if sig.str != "ay" {
- return nil, varTypeError{b.String(), sig}
- }
- return []byte(b), nil
-}
-
-func varParseByteString(s string) ([]byte, error) {
- // quotes and b at start are guaranteed to be there
- b := make([]byte, 0, 1)
- s = s[2 : len(s)-1]
- for len(s) != 0 {
- c := s[0]
- s = s[1:]
- if c != '\\' {
- b = append(b, c)
- continue
- }
- c = s[0]
- s = s[1:]
- switch c {
- case 'a':
- b = append(b, 0x7)
- case 'b':
- b = append(b, 0x8)
- case 'f':
- b = append(b, 0xc)
- case 'n':
- b = append(b, '\n')
- case 'r':
- b = append(b, '\r')
- case 't':
- b = append(b, '\t')
- case 'x':
- if len(s) < 2 {
- return nil, errors.New("short escape")
- }
- n, err := strconv.ParseUint(s[:2], 16, 8)
- if err != nil {
- return nil, err
- }
- b = append(b, byte(n))
- s = s[2:]
- case '0':
- if len(s) < 3 {
- return nil, errors.New("short escape")
- }
- n, err := strconv.ParseUint(s[:3], 8, 8)
- if err != nil {
- return nil, err
- }
- b = append(b, byte(n))
- s = s[3:]
- default:
- b = append(b, c)
- }
- }
- return append(b, 0), nil
-}
-
-func varInfer(n varNode) (Signature, error) {
- if sig, ok := n.Sigs().Single(); ok {
- return sig, nil
- }
- return n.Infer()
-}
diff --git a/containerd/vendor/github.com/golang/protobuf/proto/Makefile b/containerd/vendor/github.com/golang/protobuf/proto/Makefile
deleted file mode 100644
index fb838ed..0000000
--- a/containerd/vendor/github.com/golang/protobuf/proto/Makefile
+++ /dev/null
@@ -1,43 +0,0 @@
-# Go support for Protocol Buffers - Google's data interchange format
-#
-# Copyright 2010 The Go Authors. All rights reserved.
-# https://github.com/golang/protobuf
-#
-# 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 Google Inc. 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
-# OWNER 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.
-
-install:
- go install
-
-test: install generate-test-pbs
- go test
-
-
-generate-test-pbs:
- make install
- make -C testdata
- make -C proto3_proto
- make
diff --git a/containerd/vendor/github.com/golang/protobuf/proto/clone.go b/containerd/vendor/github.com/golang/protobuf/proto/clone.go
deleted file mode 100644
index 6c6a7d9..0000000
--- a/containerd/vendor/github.com/golang/protobuf/proto/clone.go
+++ /dev/null
@@ -1,197 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2011 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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
-// OWNER 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.
-
-// Protocol buffer deep copy and merge.
-// TODO: MessageSet and RawMessage.
-
-package proto
-
-import (
- "log"
- "reflect"
- "strings"
-)
-
-// Clone returns a deep copy of a protocol buffer.
-func Clone(pb Message) Message {
- in := reflect.ValueOf(pb)
- if in.IsNil() {
- return pb
- }
-
- out := reflect.New(in.Type().Elem())
- // out is empty so a merge is a deep copy.
- mergeStruct(out.Elem(), in.Elem())
- return out.Interface().(Message)
-}
-
-// Merge merges src into dst.
-// Required and optional fields that are set in src will be set to that value in dst.
-// Elements of repeated fields will be appended.
-// Merge panics if src and dst are not the same type, or if dst is nil.
-func Merge(dst, src Message) {
- in := reflect.ValueOf(src)
- out := reflect.ValueOf(dst)
- if out.IsNil() {
- panic("proto: nil destination")
- }
- if in.Type() != out.Type() {
- // Explicit test prior to mergeStruct so that mistyped nils will fail
- panic("proto: type mismatch")
- }
- if in.IsNil() {
- // Merging nil into non-nil is a quiet no-op
- return
- }
- mergeStruct(out.Elem(), in.Elem())
-}
-
-func mergeStruct(out, in reflect.Value) {
- for i := 0; i < in.NumField(); i++ {
- f := in.Type().Field(i)
- if strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
- mergeAny(out.Field(i), in.Field(i))
- }
-
- if emIn, ok := in.Addr().Interface().(extendableProto); ok {
- emOut := out.Addr().Interface().(extendableProto)
- mergeExtension(emOut.ExtensionMap(), emIn.ExtensionMap())
- }
-
- uf := in.FieldByName("XXX_unrecognized")
- if !uf.IsValid() {
- return
- }
- uin := uf.Bytes()
- if len(uin) > 0 {
- out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
- }
-}
-
-func mergeAny(out, in reflect.Value) {
- if in.Type() == protoMessageType {
- if !in.IsNil() {
- if out.IsNil() {
- out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
- } else {
- Merge(out.Interface().(Message), in.Interface().(Message))
- }
- }
- return
- }
- switch in.Kind() {
- case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
- reflect.String, reflect.Uint32, reflect.Uint64:
- out.Set(in)
- case reflect.Map:
- if in.Len() == 0 {
- return
- }
- if out.IsNil() {
- out.Set(reflect.MakeMap(in.Type()))
- }
- // For maps with value types of *T or []byte we need to deep copy each value.
- elemKind := in.Type().Elem().Kind()
- for _, key := range in.MapKeys() {
- var val reflect.Value
- switch elemKind {
- case reflect.Ptr:
- val = reflect.New(in.Type().Elem().Elem())
- mergeAny(val, in.MapIndex(key))
- case reflect.Slice:
- val = in.MapIndex(key)
- val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
- default:
- val = in.MapIndex(key)
- }
- out.SetMapIndex(key, val)
- }
- case reflect.Ptr:
- if in.IsNil() {
- return
- }
- if out.IsNil() {
- out.Set(reflect.New(in.Elem().Type()))
- }
- mergeAny(out.Elem(), in.Elem())
- case reflect.Slice:
- if in.IsNil() {
- return
- }
- if in.Type().Elem().Kind() == reflect.Uint8 {
- // []byte is a scalar bytes field, not a repeated field.
- // Make a deep copy.
- // Append to []byte{} instead of []byte(nil) so that we never end up
- // with a nil result.
- out.SetBytes(append([]byte{}, in.Bytes()...))
- return
- }
- n := in.Len()
- if out.IsNil() {
- out.Set(reflect.MakeSlice(in.Type(), 0, n))
- }
- switch in.Type().Elem().Kind() {
- case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
- reflect.String, reflect.Uint32, reflect.Uint64:
- out.Set(reflect.AppendSlice(out, in))
- default:
- for i := 0; i < n; i++ {
- x := reflect.Indirect(reflect.New(in.Type().Elem()))
- mergeAny(x, in.Index(i))
- out.Set(reflect.Append(out, x))
- }
- }
- case reflect.Struct:
- mergeStruct(out, in)
- default:
- // unknown type, so not a protocol buffer
- log.Printf("proto: don't know how to copy %v", in)
- }
-}
-
-func mergeExtension(out, in map[int32]Extension) {
- for extNum, eIn := range in {
- eOut := Extension{desc: eIn.desc}
- if eIn.value != nil {
- v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
- mergeAny(v, reflect.ValueOf(eIn.value))
- eOut.value = v.Interface()
- }
- if eIn.enc != nil {
- eOut.enc = make([]byte, len(eIn.enc))
- copy(eOut.enc, eIn.enc)
- }
-
- out[extNum] = eOut
- }
-}
diff --git a/containerd/vendor/github.com/golang/protobuf/proto/decode.go b/containerd/vendor/github.com/golang/protobuf/proto/decode.go
deleted file mode 100644
index 129792e..0000000
--- a/containerd/vendor/github.com/golang/protobuf/proto/decode.go
+++ /dev/null
@@ -1,821 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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
-// OWNER 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.
-
-package proto
-
-/*
- * Routines for decoding protocol buffer data to construct in-memory representations.
- */
-
-import (
- "errors"
- "fmt"
- "io"
- "os"
- "reflect"
-)
-
-// errOverflow is returned when an integer is too large to be represented.
-var errOverflow = errors.New("proto: integer overflow")
-
-// The fundamental decoders that interpret bytes on the wire.
-// Those that take integer types all return uint64 and are
-// therefore of type valueDecoder.
-
-// DecodeVarint reads a varint-encoded integer from the slice.
-// It returns the integer and the number of bytes consumed, or
-// zero if there is not enough.
-// This is the format for the
-// int32, int64, uint32, uint64, bool, and enum
-// protocol buffer types.
-func DecodeVarint(buf []byte) (x uint64, n int) {
- // x, n already 0
- for shift := uint(0); shift < 64; shift += 7 {
- if n >= len(buf) {
- return 0, 0
- }
- b := uint64(buf[n])
- n++
- x |= (b & 0x7F) << shift
- if (b & 0x80) == 0 {
- return x, n
- }
- }
-
- // The number is too large to represent in a 64-bit value.
- return 0, 0
-}
-
-// DecodeVarint reads a varint-encoded integer from the Buffer.
-// This is the format for the
-// int32, int64, uint32, uint64, bool, and enum
-// protocol buffer types.
-func (p *Buffer) DecodeVarint() (x uint64, err error) {
- // x, err already 0
-
- i := p.index
- l := len(p.buf)
-
- for shift := uint(0); shift < 64; shift += 7 {
- if i >= l {
- err = io.ErrUnexpectedEOF
- return
- }
- b := p.buf[i]
- i++
- x |= (uint64(b) & 0x7F) << shift
- if b < 0x80 {
- p.index = i
- return
- }
- }
-
- // The number is too large to represent in a 64-bit value.
- err = errOverflow
- return
-}
-
-// DecodeFixed64 reads a 64-bit integer from the Buffer.
-// This is the format for the
-// fixed64, sfixed64, and double protocol buffer types.
-func (p *Buffer) DecodeFixed64() (x uint64, err error) {
- // x, err already 0
- i := p.index + 8
- if i < 0 || i > len(p.buf) {
- err = io.ErrUnexpectedEOF
- return
- }
- p.index = i
-
- x = uint64(p.buf[i-8])
- x |= uint64(p.buf[i-7]) << 8
- x |= uint64(p.buf[i-6]) << 16
- x |= uint64(p.buf[i-5]) << 24
- x |= uint64(p.buf[i-4]) << 32
- x |= uint64(p.buf[i-3]) << 40
- x |= uint64(p.buf[i-2]) << 48
- x |= uint64(p.buf[i-1]) << 56
- return
-}
-
-// DecodeFixed32 reads a 32-bit integer from the Buffer.
-// This is the format for the
-// fixed32, sfixed32, and float protocol buffer types.
-func (p *Buffer) DecodeFixed32() (x uint64, err error) {
- // x, err already 0
- i := p.index + 4
- if i < 0 || i > len(p.buf) {
- err = io.ErrUnexpectedEOF
- return
- }
- p.index = i
-
- x = uint64(p.buf[i-4])
- x |= uint64(p.buf[i-3]) << 8
- x |= uint64(p.buf[i-2]) << 16
- x |= uint64(p.buf[i-1]) << 24
- return
-}
-
-// DecodeZigzag64 reads a zigzag-encoded 64-bit integer
-// from the Buffer.
-// This is the format used for the sint64 protocol buffer type.
-func (p *Buffer) DecodeZigzag64() (x uint64, err error) {
- x, err = p.DecodeVarint()
- if err != nil {
- return
- }
- x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63)
- return
-}
-
-// DecodeZigzag32 reads a zigzag-encoded 32-bit integer
-// from the Buffer.
-// This is the format used for the sint32 protocol buffer type.
-func (p *Buffer) DecodeZigzag32() (x uint64, err error) {
- x, err = p.DecodeVarint()
- if err != nil {
- return
- }
- x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31))
- return
-}
-
-// These are not ValueDecoders: they produce an array of bytes or a string.
-// bytes, embedded messages
-
-// DecodeRawBytes reads a count-delimited byte buffer from the Buffer.
-// This is the format used for the bytes protocol buffer
-// type and for embedded messages.
-func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) {
- n, err := p.DecodeVarint()
- if err != nil {
- return nil, err
- }
-
- nb := int(n)
- if nb < 0 {
- return nil, fmt.Errorf("proto: bad byte length %d", nb)
- }
- end := p.index + nb
- if end < p.index || end > len(p.buf) {
- return nil, io.ErrUnexpectedEOF
- }
-
- if !alloc {
- // todo: check if can get more uses of alloc=false
- buf = p.buf[p.index:end]
- p.index += nb
- return
- }
-
- buf = make([]byte, nb)
- copy(buf, p.buf[p.index:])
- p.index += nb
- return
-}
-
-// DecodeStringBytes reads an encoded string from the Buffer.
-// This is the format used for the proto2 string type.
-func (p *Buffer) DecodeStringBytes() (s string, err error) {
- buf, err := p.DecodeRawBytes(false)
- if err != nil {
- return
- }
- return string(buf), nil
-}
-
-// Skip the next item in the buffer. Its wire type is decoded and presented as an argument.
-// If the protocol buffer has extensions, and the field matches, add it as an extension.
-// Otherwise, if the XXX_unrecognized field exists, append the skipped data there.
-func (o *Buffer) skipAndSave(t reflect.Type, tag, wire int, base structPointer, unrecField field) error {
- oi := o.index
-
- err := o.skip(t, tag, wire)
- if err != nil {
- return err
- }
-
- if !unrecField.IsValid() {
- return nil
- }
-
- ptr := structPointer_Bytes(base, unrecField)
-
- // Add the skipped field to struct field
- obuf := o.buf
-
- o.buf = *ptr
- o.EncodeVarint(uint64(tag<<3 | wire))
- *ptr = append(o.buf, obuf[oi:o.index]...)
-
- o.buf = obuf
-
- return nil
-}
-
-// Skip the next item in the buffer. Its wire type is decoded and presented as an argument.
-func (o *Buffer) skip(t reflect.Type, tag, wire int) error {
-
- var u uint64
- var err error
-
- switch wire {
- case WireVarint:
- _, err = o.DecodeVarint()
- case WireFixed64:
- _, err = o.DecodeFixed64()
- case WireBytes:
- _, err = o.DecodeRawBytes(false)
- case WireFixed32:
- _, err = o.DecodeFixed32()
- case WireStartGroup:
- for {
- u, err = o.DecodeVarint()
- if err != nil {
- break
- }
- fwire := int(u & 0x7)
- if fwire == WireEndGroup {
- break
- }
- ftag := int(u >> 3)
- err = o.skip(t, ftag, fwire)
- if err != nil {
- break
- }
- }
- default:
- err = fmt.Errorf("proto: can't skip unknown wire type %d for %s", wire, t)
- }
- return err
-}
-
-// Unmarshaler is the interface representing objects that can
-// unmarshal themselves. The method should reset the receiver before
-// decoding starts. The argument points to data that may be
-// overwritten, so implementations should not keep references to the
-// buffer.
-type Unmarshaler interface {
- Unmarshal([]byte) error
-}
-
-// Unmarshal parses the protocol buffer representation in buf and places the
-// decoded result in pb. If the struct underlying pb does not match
-// the data in buf, the results can be unpredictable.
-//
-// Unmarshal resets pb before starting to unmarshal, so any
-// existing data in pb is always removed. Use UnmarshalMerge
-// to preserve and append to existing data.
-func Unmarshal(buf []byte, pb Message) error {
- pb.Reset()
- return UnmarshalMerge(buf, pb)
-}
-
-// UnmarshalMerge parses the protocol buffer representation in buf and
-// writes the decoded result to pb. If the struct underlying pb does not match
-// the data in buf, the results can be unpredictable.
-//
-// UnmarshalMerge merges into existing data in pb.
-// Most code should use Unmarshal instead.
-func UnmarshalMerge(buf []byte, pb Message) error {
- // If the object can unmarshal itself, let it.
- if u, ok := pb.(Unmarshaler); ok {
- return u.Unmarshal(buf)
- }
- return NewBuffer(buf).Unmarshal(pb)
-}
-
-// Unmarshal parses the protocol buffer representation in the
-// Buffer and places the decoded result in pb. If the struct
-// underlying pb does not match the data in the buffer, the results can be
-// unpredictable.
-func (p *Buffer) Unmarshal(pb Message) error {
- // If the object can unmarshal itself, let it.
- if u, ok := pb.(Unmarshaler); ok {
- err := u.Unmarshal(p.buf[p.index:])
- p.index = len(p.buf)
- return err
- }
-
- typ, base, err := getbase(pb)
- if err != nil {
- return err
- }
-
- err = p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), false, base)
-
- if collectStats {
- stats.Decode++
- }
-
- return err
-}
-
-// unmarshalType does the work of unmarshaling a structure.
-func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group bool, base structPointer) error {
- var state errorState
- required, reqFields := prop.reqCount, uint64(0)
-
- var err error
- for err == nil && o.index < len(o.buf) {
- oi := o.index
- var u uint64
- u, err = o.DecodeVarint()
- if err != nil {
- break
- }
- wire := int(u & 0x7)
- if wire == WireEndGroup {
- if is_group {
- return nil // input is satisfied
- }
- return fmt.Errorf("proto: %s: wiretype end group for non-group", st)
- }
- tag := int(u >> 3)
- if tag <= 0 {
- return fmt.Errorf("proto: %s: illegal tag %d (wire type %d)", st, tag, wire)
- }
- fieldnum, ok := prop.decoderTags.get(tag)
- if !ok {
- // Maybe it's an extension?
- if prop.extendable {
- if e := structPointer_Interface(base, st).(extendableProto); isExtensionField(e, int32(tag)) {
- if err = o.skip(st, tag, wire); err == nil {
- ext := e.ExtensionMap()[int32(tag)] // may be missing
- ext.enc = append(ext.enc, o.buf[oi:o.index]...)
- e.ExtensionMap()[int32(tag)] = ext
- }
- continue
- }
- }
- err = o.skipAndSave(st, tag, wire, base, prop.unrecField)
- continue
- }
- p := prop.Prop[fieldnum]
-
- if p.dec == nil {
- fmt.Fprintf(os.Stderr, "proto: no protobuf decoder for %s.%s\n", st, st.Field(fieldnum).Name)
- continue
- }
- dec := p.dec
- if wire != WireStartGroup && wire != p.WireType {
- if wire == WireBytes && p.packedDec != nil {
- // a packable field
- dec = p.packedDec
- } else {
- err = fmt.Errorf("proto: bad wiretype for field %s.%s: got wiretype %d, want %d", st, st.Field(fieldnum).Name, wire, p.WireType)
- continue
- }
- }
- decErr := dec(o, p, base)
- if decErr != nil && !state.shouldContinue(decErr, p) {
- err = decErr
- }
- if err == nil && p.Required {
- // Successfully decoded a required field.
- if tag <= 64 {
- // use bitmap for fields 1-64 to catch field reuse.
- var mask uint64 = 1 << uint64(tag-1)
- if reqFields&mask == 0 {
- // new required field
- reqFields |= mask
- required--
- }
- } else {
- // This is imprecise. It can be fooled by a required field
- // with a tag > 64 that is encoded twice; that's very rare.
- // A fully correct implementation would require allocating
- // a data structure, which we would like to avoid.
- required--
- }
- }
- }
- if err == nil {
- if is_group {
- return io.ErrUnexpectedEOF
- }
- if state.err != nil {
- return state.err
- }
- if required > 0 {
- // Not enough information to determine the exact field. If we use extra
- // CPU, we could determine the field only if the missing required field
- // has a tag <= 64 and we check reqFields.
- return &RequiredNotSetError{"{Unknown}"}
- }
- }
- return err
-}
-
-// Individual type decoders
-// For each,
-// u is the decoded value,
-// v is a pointer to the field (pointer) in the struct
-
-// Sizes of the pools to allocate inside the Buffer.
-// The goal is modest amortization and allocation
-// on at least 16-byte boundaries.
-const (
- boolPoolSize = 16
- uint32PoolSize = 8
- uint64PoolSize = 4
-)
-
-// Decode a bool.
-func (o *Buffer) dec_bool(p *Properties, base structPointer) error {
- u, err := p.valDec(o)
- if err != nil {
- return err
- }
- if len(o.bools) == 0 {
- o.bools = make([]bool, boolPoolSize)
- }
- o.bools[0] = u != 0
- *structPointer_Bool(base, p.field) = &o.bools[0]
- o.bools = o.bools[1:]
- return nil
-}
-
-func (o *Buffer) dec_proto3_bool(p *Properties, base structPointer) error {
- u, err := p.valDec(o)
- if err != nil {
- return err
- }
- *structPointer_BoolVal(base, p.field) = u != 0
- return nil
-}
-
-// Decode an int32.
-func (o *Buffer) dec_int32(p *Properties, base structPointer) error {
- u, err := p.valDec(o)
- if err != nil {
- return err
- }
- word32_Set(structPointer_Word32(base, p.field), o, uint32(u))
- return nil
-}
-
-func (o *Buffer) dec_proto3_int32(p *Properties, base structPointer) error {
- u, err := p.valDec(o)
- if err != nil {
- return err
- }
- word32Val_Set(structPointer_Word32Val(base, p.field), uint32(u))
- return nil
-}
-
-// Decode an int64.
-func (o *Buffer) dec_int64(p *Properties, base structPointer) error {
- u, err := p.valDec(o)
- if err != nil {
- return err
- }
- word64_Set(structPointer_Word64(base, p.field), o, u)
- return nil
-}
-
-func (o *Buffer) dec_proto3_int64(p *Properties, base structPointer) error {
- u, err := p.valDec(o)
- if err != nil {
- return err
- }
- word64Val_Set(structPointer_Word64Val(base, p.field), o, u)
- return nil
-}
-
-// Decode a string.
-func (o *Buffer) dec_string(p *Properties, base structPointer) error {
- s, err := o.DecodeStringBytes()
- if err != nil {
- return err
- }
- *structPointer_String(base, p.field) = &s
- return nil
-}
-
-func (o *Buffer) dec_proto3_string(p *Properties, base structPointer) error {
- s, err := o.DecodeStringBytes()
- if err != nil {
- return err
- }
- *structPointer_StringVal(base, p.field) = s
- return nil
-}
-
-// Decode a slice of bytes ([]byte).
-func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error {
- b, err := o.DecodeRawBytes(true)
- if err != nil {
- return err
- }
- *structPointer_Bytes(base, p.field) = b
- return nil
-}
-
-// Decode a slice of bools ([]bool).
-func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error {
- u, err := p.valDec(o)
- if err != nil {
- return err
- }
- v := structPointer_BoolSlice(base, p.field)
- *v = append(*v, u != 0)
- return nil
-}
-
-// Decode a slice of bools ([]bool) in packed format.
-func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error {
- v := structPointer_BoolSlice(base, p.field)
-
- nn, err := o.DecodeVarint()
- if err != nil {
- return err
- }
- nb := int(nn) // number of bytes of encoded bools
-
- y := *v
- for i := 0; i < nb; i++ {
- u, err := p.valDec(o)
- if err != nil {
- return err
- }
- y = append(y, u != 0)
- }
-
- *v = y
- return nil
-}
-
-// Decode a slice of int32s ([]int32).
-func (o *Buffer) dec_slice_int32(p *Properties, base structPointer) error {
- u, err := p.valDec(o)
- if err != nil {
- return err
- }
- structPointer_Word32Slice(base, p.field).Append(uint32(u))
- return nil
-}
-
-// Decode a slice of int32s ([]int32) in packed format.
-func (o *Buffer) dec_slice_packed_int32(p *Properties, base structPointer) error {
- v := structPointer_Word32Slice(base, p.field)
-
- nn, err := o.DecodeVarint()
- if err != nil {
- return err
- }
- nb := int(nn) // number of bytes of encoded int32s
-
- fin := o.index + nb
- if fin < o.index {
- return errOverflow
- }
- for o.index < fin {
- u, err := p.valDec(o)
- if err != nil {
- return err
- }
- v.Append(uint32(u))
- }
- return nil
-}
-
-// Decode a slice of int64s ([]int64).
-func (o *Buffer) dec_slice_int64(p *Properties, base structPointer) error {
- u, err := p.valDec(o)
- if err != nil {
- return err
- }
-
- structPointer_Word64Slice(base, p.field).Append(u)
- return nil
-}
-
-// Decode a slice of int64s ([]int64) in packed format.
-func (o *Buffer) dec_slice_packed_int64(p *Properties, base structPointer) error {
- v := structPointer_Word64Slice(base, p.field)
-
- nn, err := o.DecodeVarint()
- if err != nil {
- return err
- }
- nb := int(nn) // number of bytes of encoded int64s
-
- fin := o.index + nb
- if fin < o.index {
- return errOverflow
- }
- for o.index < fin {
- u, err := p.valDec(o)
- if err != nil {
- return err
- }
- v.Append(u)
- }
- return nil
-}
-
-// Decode a slice of strings ([]string).
-func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error {
- s, err := o.DecodeStringBytes()
- if err != nil {
- return err
- }
- v := structPointer_StringSlice(base, p.field)
- *v = append(*v, s)
- return nil
-}
-
-// Decode a slice of slice of bytes ([][]byte).
-func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error {
- b, err := o.DecodeRawBytes(true)
- if err != nil {
- return err
- }
- v := structPointer_BytesSlice(base, p.field)
- *v = append(*v, b)
- return nil
-}
-
-// Decode a map field.
-func (o *Buffer) dec_new_map(p *Properties, base structPointer) error {
- raw, err := o.DecodeRawBytes(false)
- if err != nil {
- return err
- }
- oi := o.index // index at the end of this map entry
- o.index -= len(raw) // move buffer back to start of map entry
-
- mptr := structPointer_Map(base, p.field, p.mtype) // *map[K]V
- if mptr.Elem().IsNil() {
- mptr.Elem().Set(reflect.MakeMap(mptr.Type().Elem()))
- }
- v := mptr.Elem() // map[K]V
-
- // Prepare addressable doubly-indirect placeholders for the key and value types.
- // See enc_new_map for why.
- keyptr := reflect.New(reflect.PtrTo(p.mtype.Key())).Elem() // addressable *K
- keybase := toStructPointer(keyptr.Addr()) // **K
-
- var valbase structPointer
- var valptr reflect.Value
- switch p.mtype.Elem().Kind() {
- case reflect.Slice:
- // []byte
- var dummy []byte
- valptr = reflect.ValueOf(&dummy) // *[]byte
- valbase = toStructPointer(valptr) // *[]byte
- case reflect.Ptr:
- // message; valptr is **Msg; need to allocate the intermediate pointer
- valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V
- valptr.Set(reflect.New(valptr.Type().Elem()))
- valbase = toStructPointer(valptr)
- default:
- // everything else
- valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V
- valbase = toStructPointer(valptr.Addr()) // **V
- }
-
- // Decode.
- // This parses a restricted wire format, namely the encoding of a message
- // with two fields. See enc_new_map for the format.
- for o.index < oi {
- // tagcode for key and value properties are always a single byte
- // because they have tags 1 and 2.
- tagcode := o.buf[o.index]
- o.index++
- switch tagcode {
- case p.mkeyprop.tagcode[0]:
- if err := p.mkeyprop.dec(o, p.mkeyprop, keybase); err != nil {
- return err
- }
- case p.mvalprop.tagcode[0]:
- if err := p.mvalprop.dec(o, p.mvalprop, valbase); err != nil {
- return err
- }
- default:
- // TODO: Should we silently skip this instead?
- return fmt.Errorf("proto: bad map data tag %d", raw[0])
- }
- }
-
- v.SetMapIndex(keyptr.Elem(), valptr.Elem())
- return nil
-}
-
-// Decode a group.
-func (o *Buffer) dec_struct_group(p *Properties, base structPointer) error {
- bas := structPointer_GetStructPointer(base, p.field)
- if structPointer_IsNil(bas) {
- // allocate new nested message
- bas = toStructPointer(reflect.New(p.stype))
- structPointer_SetStructPointer(base, p.field, bas)
- }
- return o.unmarshalType(p.stype, p.sprop, true, bas)
-}
-
-// Decode an embedded message.
-func (o *Buffer) dec_struct_message(p *Properties, base structPointer) (err error) {
- raw, e := o.DecodeRawBytes(false)
- if e != nil {
- return e
- }
-
- bas := structPointer_GetStructPointer(base, p.field)
- if structPointer_IsNil(bas) {
- // allocate new nested message
- bas = toStructPointer(reflect.New(p.stype))
- structPointer_SetStructPointer(base, p.field, bas)
- }
-
- // If the object can unmarshal itself, let it.
- if p.isUnmarshaler {
- iv := structPointer_Interface(bas, p.stype)
- return iv.(Unmarshaler).Unmarshal(raw)
- }
-
- obuf := o.buf
- oi := o.index
- o.buf = raw
- o.index = 0
-
- err = o.unmarshalType(p.stype, p.sprop, false, bas)
- o.buf = obuf
- o.index = oi
-
- return err
-}
-
-// Decode a slice of embedded messages.
-func (o *Buffer) dec_slice_struct_message(p *Properties, base structPointer) error {
- return o.dec_slice_struct(p, false, base)
-}
-
-// Decode a slice of embedded groups.
-func (o *Buffer) dec_slice_struct_group(p *Properties, base structPointer) error {
- return o.dec_slice_struct(p, true, base)
-}
-
-// Decode a slice of structs ([]*struct).
-func (o *Buffer) dec_slice_struct(p *Properties, is_group bool, base structPointer) error {
- v := reflect.New(p.stype)
- bas := toStructPointer(v)
- structPointer_StructPointerSlice(base, p.field).Append(bas)
-
- if is_group {
- err := o.unmarshalType(p.stype, p.sprop, is_group, bas)
- return err
- }
-
- raw, err := o.DecodeRawBytes(false)
- if err != nil {
- return err
- }
-
- // If the object can unmarshal itself, let it.
- if p.isUnmarshaler {
- iv := v.Interface()
- return iv.(Unmarshaler).Unmarshal(raw)
- }
-
- obuf := o.buf
- oi := o.index
- o.buf = raw
- o.index = 0
-
- err = o.unmarshalType(p.stype, p.sprop, is_group, bas)
-
- o.buf = obuf
- o.index = oi
-
- return err
-}
diff --git a/containerd/vendor/github.com/golang/protobuf/proto/encode.go b/containerd/vendor/github.com/golang/protobuf/proto/encode.go
deleted file mode 100644
index cd826e9..0000000
--- a/containerd/vendor/github.com/golang/protobuf/proto/encode.go
+++ /dev/null
@@ -1,1286 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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
-// OWNER 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.
-
-package proto
-
-/*
- * Routines for encoding data into the wire format for protocol buffers.
- */
-
-import (
- "errors"
- "fmt"
- "reflect"
- "sort"
-)
-
-// RequiredNotSetError is the error returned if Marshal is called with
-// a protocol buffer struct whose required fields have not
-// all been initialized. It is also the error returned if Unmarshal is
-// called with an encoded protocol buffer that does not include all the
-// required fields.
-//
-// When printed, RequiredNotSetError reports the first unset required field in a
-// message. If the field cannot be precisely determined, it is reported as
-// "{Unknown}".
-type RequiredNotSetError struct {
- field string
-}
-
-func (e *RequiredNotSetError) Error() string {
- return fmt.Sprintf("proto: required field %q not set", e.field)
-}
-
-var (
- // errRepeatedHasNil is the error returned if Marshal is called with
- // a struct with a repeated field containing a nil element.
- errRepeatedHasNil = errors.New("proto: repeated field has nil element")
-
- // ErrNil is the error returned if Marshal is called with nil.
- ErrNil = errors.New("proto: Marshal called with nil")
-)
-
-// The fundamental encoders that put bytes on the wire.
-// Those that take integer types all accept uint64 and are
-// therefore of type valueEncoder.
-
-const maxVarintBytes = 10 // maximum length of a varint
-
-// EncodeVarint returns the varint encoding of x.
-// This is the format for the
-// int32, int64, uint32, uint64, bool, and enum
-// protocol buffer types.
-// Not used by the package itself, but helpful to clients
-// wishing to use the same encoding.
-func EncodeVarint(x uint64) []byte {
- var buf [maxVarintBytes]byte
- var n int
- for n = 0; x > 127; n++ {
- buf[n] = 0x80 | uint8(x&0x7F)
- x >>= 7
- }
- buf[n] = uint8(x)
- n++
- return buf[0:n]
-}
-
-// EncodeVarint writes a varint-encoded integer to the Buffer.
-// This is the format for the
-// int32, int64, uint32, uint64, bool, and enum
-// protocol buffer types.
-func (p *Buffer) EncodeVarint(x uint64) error {
- for x >= 1<<7 {
- p.buf = append(p.buf, uint8(x&0x7f|0x80))
- x >>= 7
- }
- p.buf = append(p.buf, uint8(x))
- return nil
-}
-
-func sizeVarint(x uint64) (n int) {
- for {
- n++
- x >>= 7
- if x == 0 {
- break
- }
- }
- return n
-}
-
-// EncodeFixed64 writes a 64-bit integer to the Buffer.
-// This is the format for the
-// fixed64, sfixed64, and double protocol buffer types.
-func (p *Buffer) EncodeFixed64(x uint64) error {
- p.buf = append(p.buf,
- uint8(x),
- uint8(x>>8),
- uint8(x>>16),
- uint8(x>>24),
- uint8(x>>32),
- uint8(x>>40),
- uint8(x>>48),
- uint8(x>>56))
- return nil
-}
-
-func sizeFixed64(x uint64) int {
- return 8
-}
-
-// EncodeFixed32 writes a 32-bit integer to the Buffer.
-// This is the format for the
-// fixed32, sfixed32, and float protocol buffer types.
-func (p *Buffer) EncodeFixed32(x uint64) error {
- p.buf = append(p.buf,
- uint8(x),
- uint8(x>>8),
- uint8(x>>16),
- uint8(x>>24))
- return nil
-}
-
-func sizeFixed32(x uint64) int {
- return 4
-}
-
-// EncodeZigzag64 writes a zigzag-encoded 64-bit integer
-// to the Buffer.
-// This is the format used for the sint64 protocol buffer type.
-func (p *Buffer) EncodeZigzag64(x uint64) error {
- // use signed number to get arithmetic right shift.
- return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
-}
-
-func sizeZigzag64(x uint64) int {
- return sizeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
-}
-
-// EncodeZigzag32 writes a zigzag-encoded 32-bit integer
-// to the Buffer.
-// This is the format used for the sint32 protocol buffer type.
-func (p *Buffer) EncodeZigzag32(x uint64) error {
- // use signed number to get arithmetic right shift.
- return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
-}
-
-func sizeZigzag32(x uint64) int {
- return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
-}
-
-// EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
-// This is the format used for the bytes protocol buffer
-// type and for embedded messages.
-func (p *Buffer) EncodeRawBytes(b []byte) error {
- p.EncodeVarint(uint64(len(b)))
- p.buf = append(p.buf, b...)
- return nil
-}
-
-func sizeRawBytes(b []byte) int {
- return sizeVarint(uint64(len(b))) +
- len(b)
-}
-
-// EncodeStringBytes writes an encoded string to the Buffer.
-// This is the format used for the proto2 string type.
-func (p *Buffer) EncodeStringBytes(s string) error {
- p.EncodeVarint(uint64(len(s)))
- p.buf = append(p.buf, s...)
- return nil
-}
-
-func sizeStringBytes(s string) int {
- return sizeVarint(uint64(len(s))) +
- len(s)
-}
-
-// Marshaler is the interface representing objects that can marshal themselves.
-type Marshaler interface {
- Marshal() ([]byte, error)
-}
-
-// Marshal takes the protocol buffer
-// and encodes it into the wire format, returning the data.
-func Marshal(pb Message) ([]byte, error) {
- // Can the object marshal itself?
- if m, ok := pb.(Marshaler); ok {
- return m.Marshal()
- }
- p := NewBuffer(nil)
- err := p.Marshal(pb)
- var state errorState
- if err != nil && !state.shouldContinue(err, nil) {
- return nil, err
- }
- if p.buf == nil && err == nil {
- // Return a non-nil slice on success.
- return []byte{}, nil
- }
- return p.buf, err
-}
-
-// Marshal takes the protocol buffer
-// and encodes it into the wire format, writing the result to the
-// Buffer.
-func (p *Buffer) Marshal(pb Message) error {
- // Can the object marshal itself?
- if m, ok := pb.(Marshaler); ok {
- data, err := m.Marshal()
- if err != nil {
- return err
- }
- p.buf = append(p.buf, data...)
- return nil
- }
-
- t, base, err := getbase(pb)
- if structPointer_IsNil(base) {
- return ErrNil
- }
- if err == nil {
- err = p.enc_struct(GetProperties(t.Elem()), base)
- }
-
- if collectStats {
- stats.Encode++
- }
-
- return err
-}
-
-// Size returns the encoded size of a protocol buffer.
-func Size(pb Message) (n int) {
- // Can the object marshal itself? If so, Size is slow.
- // TODO: add Size to Marshaler, or add a Sizer interface.
- if m, ok := pb.(Marshaler); ok {
- b, _ := m.Marshal()
- return len(b)
- }
-
- t, base, err := getbase(pb)
- if structPointer_IsNil(base) {
- return 0
- }
- if err == nil {
- n = size_struct(GetProperties(t.Elem()), base)
- }
-
- if collectStats {
- stats.Size++
- }
-
- return
-}
-
-// Individual type encoders.
-
-// Encode a bool.
-func (o *Buffer) enc_bool(p *Properties, base structPointer) error {
- v := *structPointer_Bool(base, p.field)
- if v == nil {
- return ErrNil
- }
- x := 0
- if *v {
- x = 1
- }
- o.buf = append(o.buf, p.tagcode...)
- p.valEnc(o, uint64(x))
- return nil
-}
-
-func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error {
- v := *structPointer_BoolVal(base, p.field)
- if !v {
- return ErrNil
- }
- o.buf = append(o.buf, p.tagcode...)
- p.valEnc(o, 1)
- return nil
-}
-
-func size_bool(p *Properties, base structPointer) int {
- v := *structPointer_Bool(base, p.field)
- if v == nil {
- return 0
- }
- return len(p.tagcode) + 1 // each bool takes exactly one byte
-}
-
-func size_proto3_bool(p *Properties, base structPointer) int {
- v := *structPointer_BoolVal(base, p.field)
- if !v {
- return 0
- }
- return len(p.tagcode) + 1 // each bool takes exactly one byte
-}
-
-// Encode an int32.
-func (o *Buffer) enc_int32(p *Properties, base structPointer) error {
- v := structPointer_Word32(base, p.field)
- if word32_IsNil(v) {
- return ErrNil
- }
- x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
- o.buf = append(o.buf, p.tagcode...)
- p.valEnc(o, uint64(x))
- return nil
-}
-
-func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error {
- v := structPointer_Word32Val(base, p.field)
- x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
- if x == 0 {
- return ErrNil
- }
- o.buf = append(o.buf, p.tagcode...)
- p.valEnc(o, uint64(x))
- return nil
-}
-
-func size_int32(p *Properties, base structPointer) (n int) {
- v := structPointer_Word32(base, p.field)
- if word32_IsNil(v) {
- return 0
- }
- x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
- n += len(p.tagcode)
- n += p.valSize(uint64(x))
- return
-}
-
-func size_proto3_int32(p *Properties, base structPointer) (n int) {
- v := structPointer_Word32Val(base, p.field)
- x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
- if x == 0 {
- return 0
- }
- n += len(p.tagcode)
- n += p.valSize(uint64(x))
- return
-}
-
-// Encode a uint32.
-// Exactly the same as int32, except for no sign extension.
-func (o *Buffer) enc_uint32(p *Properties, base structPointer) error {
- v := structPointer_Word32(base, p.field)
- if word32_IsNil(v) {
- return ErrNil
- }
- x := word32_Get(v)
- o.buf = append(o.buf, p.tagcode...)
- p.valEnc(o, uint64(x))
- return nil
-}
-
-func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error {
- v := structPointer_Word32Val(base, p.field)
- x := word32Val_Get(v)
- if x == 0 {
- return ErrNil
- }
- o.buf = append(o.buf, p.tagcode...)
- p.valEnc(o, uint64(x))
- return nil
-}
-
-func size_uint32(p *Properties, base structPointer) (n int) {
- v := structPointer_Word32(base, p.field)
- if word32_IsNil(v) {
- return 0
- }
- x := word32_Get(v)
- n += len(p.tagcode)
- n += p.valSize(uint64(x))
- return
-}
-
-func size_proto3_uint32(p *Properties, base structPointer) (n int) {
- v := structPointer_Word32Val(base, p.field)
- x := word32Val_Get(v)
- if x == 0 {
- return 0
- }
- n += len(p.tagcode)
- n += p.valSize(uint64(x))
- return
-}
-
-// Encode an int64.
-func (o *Buffer) enc_int64(p *Properties, base structPointer) error {
- v := structPointer_Word64(base, p.field)
- if word64_IsNil(v) {
- return ErrNil
- }
- x := word64_Get(v)
- o.buf = append(o.buf, p.tagcode...)
- p.valEnc(o, x)
- return nil
-}
-
-func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error {
- v := structPointer_Word64Val(base, p.field)
- x := word64Val_Get(v)
- if x == 0 {
- return ErrNil
- }
- o.buf = append(o.buf, p.tagcode...)
- p.valEnc(o, x)
- return nil
-}
-
-func size_int64(p *Properties, base structPointer) (n int) {
- v := structPointer_Word64(base, p.field)
- if word64_IsNil(v) {
- return 0
- }
- x := word64_Get(v)
- n += len(p.tagcode)
- n += p.valSize(x)
- return
-}
-
-func size_proto3_int64(p *Properties, base structPointer) (n int) {
- v := structPointer_Word64Val(base, p.field)
- x := word64Val_Get(v)
- if x == 0 {
- return 0
- }
- n += len(p.tagcode)
- n += p.valSize(x)
- return
-}
-
-// Encode a string.
-func (o *Buffer) enc_string(p *Properties, base structPointer) error {
- v := *structPointer_String(base, p.field)
- if v == nil {
- return ErrNil
- }
- x := *v
- o.buf = append(o.buf, p.tagcode...)
- o.EncodeStringBytes(x)
- return nil
-}
-
-func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error {
- v := *structPointer_StringVal(base, p.field)
- if v == "" {
- return ErrNil
- }
- o.buf = append(o.buf, p.tagcode...)
- o.EncodeStringBytes(v)
- return nil
-}
-
-func size_string(p *Properties, base structPointer) (n int) {
- v := *structPointer_String(base, p.field)
- if v == nil {
- return 0
- }
- x := *v
- n += len(p.tagcode)
- n += sizeStringBytes(x)
- return
-}
-
-func size_proto3_string(p *Properties, base structPointer) (n int) {
- v := *structPointer_StringVal(base, p.field)
- if v == "" {
- return 0
- }
- n += len(p.tagcode)
- n += sizeStringBytes(v)
- return
-}
-
-// All protocol buffer fields are nillable, but be careful.
-func isNil(v reflect.Value) bool {
- switch v.Kind() {
- case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
- return v.IsNil()
- }
- return false
-}
-
-// Encode a message struct.
-func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error {
- var state errorState
- structp := structPointer_GetStructPointer(base, p.field)
- if structPointer_IsNil(structp) {
- return ErrNil
- }
-
- // Can the object marshal itself?
- if p.isMarshaler {
- m := structPointer_Interface(structp, p.stype).(Marshaler)
- data, err := m.Marshal()
- if err != nil && !state.shouldContinue(err, nil) {
- return err
- }
- o.buf = append(o.buf, p.tagcode...)
- o.EncodeRawBytes(data)
- return nil
- }
-
- o.buf = append(o.buf, p.tagcode...)
- return o.enc_len_struct(p.sprop, structp, &state)
-}
-
-func size_struct_message(p *Properties, base structPointer) int {
- structp := structPointer_GetStructPointer(base, p.field)
- if structPointer_IsNil(structp) {
- return 0
- }
-
- // Can the object marshal itself?
- if p.isMarshaler {
- m := structPointer_Interface(structp, p.stype).(Marshaler)
- data, _ := m.Marshal()
- n0 := len(p.tagcode)
- n1 := sizeRawBytes(data)
- return n0 + n1
- }
-
- n0 := len(p.tagcode)
- n1 := size_struct(p.sprop, structp)
- n2 := sizeVarint(uint64(n1)) // size of encoded length
- return n0 + n1 + n2
-}
-
-// Encode a group struct.
-func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error {
- var state errorState
- b := structPointer_GetStructPointer(base, p.field)
- if structPointer_IsNil(b) {
- return ErrNil
- }
-
- o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
- err := o.enc_struct(p.sprop, b)
- if err != nil && !state.shouldContinue(err, nil) {
- return err
- }
- o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
- return state.err
-}
-
-func size_struct_group(p *Properties, base structPointer) (n int) {
- b := structPointer_GetStructPointer(base, p.field)
- if structPointer_IsNil(b) {
- return 0
- }
-
- n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup))
- n += size_struct(p.sprop, b)
- n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup))
- return
-}
-
-// Encode a slice of bools ([]bool).
-func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error {
- s := *structPointer_BoolSlice(base, p.field)
- l := len(s)
- if l == 0 {
- return ErrNil
- }
- for _, x := range s {
- o.buf = append(o.buf, p.tagcode...)
- v := uint64(0)
- if x {
- v = 1
- }
- p.valEnc(o, v)
- }
- return nil
-}
-
-func size_slice_bool(p *Properties, base structPointer) int {
- s := *structPointer_BoolSlice(base, p.field)
- l := len(s)
- if l == 0 {
- return 0
- }
- return l * (len(p.tagcode) + 1) // each bool takes exactly one byte
-}
-
-// Encode a slice of bools ([]bool) in packed format.
-func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error {
- s := *structPointer_BoolSlice(base, p.field)
- l := len(s)
- if l == 0 {
- return ErrNil
- }
- o.buf = append(o.buf, p.tagcode...)
- o.EncodeVarint(uint64(l)) // each bool takes exactly one byte
- for _, x := range s {
- v := uint64(0)
- if x {
- v = 1
- }
- p.valEnc(o, v)
- }
- return nil
-}
-
-func size_slice_packed_bool(p *Properties, base structPointer) (n int) {
- s := *structPointer_BoolSlice(base, p.field)
- l := len(s)
- if l == 0 {
- return 0
- }
- n += len(p.tagcode)
- n += sizeVarint(uint64(l))
- n += l // each bool takes exactly one byte
- return
-}
-
-// Encode a slice of bytes ([]byte).
-func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error {
- s := *structPointer_Bytes(base, p.field)
- if s == nil {
- return ErrNil
- }
- o.buf = append(o.buf, p.tagcode...)
- o.EncodeRawBytes(s)
- return nil
-}
-
-func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error {
- s := *structPointer_Bytes(base, p.field)
- if len(s) == 0 {
- return ErrNil
- }
- o.buf = append(o.buf, p.tagcode...)
- o.EncodeRawBytes(s)
- return nil
-}
-
-func size_slice_byte(p *Properties, base structPointer) (n int) {
- s := *structPointer_Bytes(base, p.field)
- if s == nil {
- return 0
- }
- n += len(p.tagcode)
- n += sizeRawBytes(s)
- return
-}
-
-func size_proto3_slice_byte(p *Properties, base structPointer) (n int) {
- s := *structPointer_Bytes(base, p.field)
- if len(s) == 0 {
- return 0
- }
- n += len(p.tagcode)
- n += sizeRawBytes(s)
- return
-}
-
-// Encode a slice of int32s ([]int32).
-func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error {
- s := structPointer_Word32Slice(base, p.field)
- l := s.Len()
- if l == 0 {
- return ErrNil
- }
- for i := 0; i < l; i++ {
- o.buf = append(o.buf, p.tagcode...)
- x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
- p.valEnc(o, uint64(x))
- }
- return nil
-}
-
-func size_slice_int32(p *Properties, base structPointer) (n int) {
- s := structPointer_Word32Slice(base, p.field)
- l := s.Len()
- if l == 0 {
- return 0
- }
- for i := 0; i < l; i++ {
- n += len(p.tagcode)
- x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
- n += p.valSize(uint64(x))
- }
- return
-}
-
-// Encode a slice of int32s ([]int32) in packed format.
-func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error {
- s := structPointer_Word32Slice(base, p.field)
- l := s.Len()
- if l == 0 {
- return ErrNil
- }
- // TODO: Reuse a Buffer.
- buf := NewBuffer(nil)
- for i := 0; i < l; i++ {
- x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
- p.valEnc(buf, uint64(x))
- }
-
- o.buf = append(o.buf, p.tagcode...)
- o.EncodeVarint(uint64(len(buf.buf)))
- o.buf = append(o.buf, buf.buf...)
- return nil
-}
-
-func size_slice_packed_int32(p *Properties, base structPointer) (n int) {
- s := structPointer_Word32Slice(base, p.field)
- l := s.Len()
- if l == 0 {
- return 0
- }
- var bufSize int
- for i := 0; i < l; i++ {
- x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
- bufSize += p.valSize(uint64(x))
- }
-
- n += len(p.tagcode)
- n += sizeVarint(uint64(bufSize))
- n += bufSize
- return
-}
-
-// Encode a slice of uint32s ([]uint32).
-// Exactly the same as int32, except for no sign extension.
-func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error {
- s := structPointer_Word32Slice(base, p.field)
- l := s.Len()
- if l == 0 {
- return ErrNil
- }
- for i := 0; i < l; i++ {
- o.buf = append(o.buf, p.tagcode...)
- x := s.Index(i)
- p.valEnc(o, uint64(x))
- }
- return nil
-}
-
-func size_slice_uint32(p *Properties, base structPointer) (n int) {
- s := structPointer_Word32Slice(base, p.field)
- l := s.Len()
- if l == 0 {
- return 0
- }
- for i := 0; i < l; i++ {
- n += len(p.tagcode)
- x := s.Index(i)
- n += p.valSize(uint64(x))
- }
- return
-}
-
-// Encode a slice of uint32s ([]uint32) in packed format.
-// Exactly the same as int32, except for no sign extension.
-func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error {
- s := structPointer_Word32Slice(base, p.field)
- l := s.Len()
- if l == 0 {
- return ErrNil
- }
- // TODO: Reuse a Buffer.
- buf := NewBuffer(nil)
- for i := 0; i < l; i++ {
- p.valEnc(buf, uint64(s.Index(i)))
- }
-
- o.buf = append(o.buf, p.tagcode...)
- o.EncodeVarint(uint64(len(buf.buf)))
- o.buf = append(o.buf, buf.buf...)
- return nil
-}
-
-func size_slice_packed_uint32(p *Properties, base structPointer) (n int) {
- s := structPointer_Word32Slice(base, p.field)
- l := s.Len()
- if l == 0 {
- return 0
- }
- var bufSize int
- for i := 0; i < l; i++ {
- bufSize += p.valSize(uint64(s.Index(i)))
- }
-
- n += len(p.tagcode)
- n += sizeVarint(uint64(bufSize))
- n += bufSize
- return
-}
-
-// Encode a slice of int64s ([]int64).
-func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error {
- s := structPointer_Word64Slice(base, p.field)
- l := s.Len()
- if l == 0 {
- return ErrNil
- }
- for i := 0; i < l; i++ {
- o.buf = append(o.buf, p.tagcode...)
- p.valEnc(o, s.Index(i))
- }
- return nil
-}
-
-func size_slice_int64(p *Properties, base structPointer) (n int) {
- s := structPointer_Word64Slice(base, p.field)
- l := s.Len()
- if l == 0 {
- return 0
- }
- for i := 0; i < l; i++ {
- n += len(p.tagcode)
- n += p.valSize(s.Index(i))
- }
- return
-}
-
-// Encode a slice of int64s ([]int64) in packed format.
-func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error {
- s := structPointer_Word64Slice(base, p.field)
- l := s.Len()
- if l == 0 {
- return ErrNil
- }
- // TODO: Reuse a Buffer.
- buf := NewBuffer(nil)
- for i := 0; i < l; i++ {
- p.valEnc(buf, s.Index(i))
- }
-
- o.buf = append(o.buf, p.tagcode...)
- o.EncodeVarint(uint64(len(buf.buf)))
- o.buf = append(o.buf, buf.buf...)
- return nil
-}
-
-func size_slice_packed_int64(p *Properties, base structPointer) (n int) {
- s := structPointer_Word64Slice(base, p.field)
- l := s.Len()
- if l == 0 {
- return 0
- }
- var bufSize int
- for i := 0; i < l; i++ {
- bufSize += p.valSize(s.Index(i))
- }
-
- n += len(p.tagcode)
- n += sizeVarint(uint64(bufSize))
- n += bufSize
- return
-}
-
-// Encode a slice of slice of bytes ([][]byte).
-func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error {
- ss := *structPointer_BytesSlice(base, p.field)
- l := len(ss)
- if l == 0 {
- return ErrNil
- }
- for i := 0; i < l; i++ {
- o.buf = append(o.buf, p.tagcode...)
- o.EncodeRawBytes(ss[i])
- }
- return nil
-}
-
-func size_slice_slice_byte(p *Properties, base structPointer) (n int) {
- ss := *structPointer_BytesSlice(base, p.field)
- l := len(ss)
- if l == 0 {
- return 0
- }
- n += l * len(p.tagcode)
- for i := 0; i < l; i++ {
- n += sizeRawBytes(ss[i])
- }
- return
-}
-
-// Encode a slice of strings ([]string).
-func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error {
- ss := *structPointer_StringSlice(base, p.field)
- l := len(ss)
- for i := 0; i < l; i++ {
- o.buf = append(o.buf, p.tagcode...)
- o.EncodeStringBytes(ss[i])
- }
- return nil
-}
-
-func size_slice_string(p *Properties, base structPointer) (n int) {
- ss := *structPointer_StringSlice(base, p.field)
- l := len(ss)
- n += l * len(p.tagcode)
- for i := 0; i < l; i++ {
- n += sizeStringBytes(ss[i])
- }
- return
-}
-
-// Encode a slice of message structs ([]*struct).
-func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error {
- var state errorState
- s := structPointer_StructPointerSlice(base, p.field)
- l := s.Len()
-
- for i := 0; i < l; i++ {
- structp := s.Index(i)
- if structPointer_IsNil(structp) {
- return errRepeatedHasNil
- }
-
- // Can the object marshal itself?
- if p.isMarshaler {
- m := structPointer_Interface(structp, p.stype).(Marshaler)
- data, err := m.Marshal()
- if err != nil && !state.shouldContinue(err, nil) {
- return err
- }
- o.buf = append(o.buf, p.tagcode...)
- o.EncodeRawBytes(data)
- continue
- }
-
- o.buf = append(o.buf, p.tagcode...)
- err := o.enc_len_struct(p.sprop, structp, &state)
- if err != nil && !state.shouldContinue(err, nil) {
- if err == ErrNil {
- return errRepeatedHasNil
- }
- return err
- }
- }
- return state.err
-}
-
-func size_slice_struct_message(p *Properties, base structPointer) (n int) {
- s := structPointer_StructPointerSlice(base, p.field)
- l := s.Len()
- n += l * len(p.tagcode)
- for i := 0; i < l; i++ {
- structp := s.Index(i)
- if structPointer_IsNil(structp) {
- return // return the size up to this point
- }
-
- // Can the object marshal itself?
- if p.isMarshaler {
- m := structPointer_Interface(structp, p.stype).(Marshaler)
- data, _ := m.Marshal()
- n += len(p.tagcode)
- n += sizeRawBytes(data)
- continue
- }
-
- n0 := size_struct(p.sprop, structp)
- n1 := sizeVarint(uint64(n0)) // size of encoded length
- n += n0 + n1
- }
- return
-}
-
-// Encode a slice of group structs ([]*struct).
-func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error {
- var state errorState
- s := structPointer_StructPointerSlice(base, p.field)
- l := s.Len()
-
- for i := 0; i < l; i++ {
- b := s.Index(i)
- if structPointer_IsNil(b) {
- return errRepeatedHasNil
- }
-
- o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
-
- err := o.enc_struct(p.sprop, b)
-
- if err != nil && !state.shouldContinue(err, nil) {
- if err == ErrNil {
- return errRepeatedHasNil
- }
- return err
- }
-
- o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
- }
- return state.err
-}
-
-func size_slice_struct_group(p *Properties, base structPointer) (n int) {
- s := structPointer_StructPointerSlice(base, p.field)
- l := s.Len()
-
- n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup))
- n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup))
- for i := 0; i < l; i++ {
- b := s.Index(i)
- if structPointer_IsNil(b) {
- return // return size up to this point
- }
-
- n += size_struct(p.sprop, b)
- }
- return
-}
-
-// Encode an extension map.
-func (o *Buffer) enc_map(p *Properties, base structPointer) error {
- v := *structPointer_ExtMap(base, p.field)
- if err := encodeExtensionMap(v); err != nil {
- return err
- }
- // Fast-path for common cases: zero or one extensions.
- if len(v) <= 1 {
- for _, e := range v {
- o.buf = append(o.buf, e.enc...)
- }
- return nil
- }
-
- // Sort keys to provide a deterministic encoding.
- keys := make([]int, 0, len(v))
- for k := range v {
- keys = append(keys, int(k))
- }
- sort.Ints(keys)
-
- for _, k := range keys {
- o.buf = append(o.buf, v[int32(k)].enc...)
- }
- return nil
-}
-
-func size_map(p *Properties, base structPointer) int {
- v := *structPointer_ExtMap(base, p.field)
- return sizeExtensionMap(v)
-}
-
-// Encode a map field.
-func (o *Buffer) enc_new_map(p *Properties, base structPointer) error {
- var state errorState // XXX: or do we need to plumb this through?
-
- /*
- A map defined as
- map map_field = N;
- is encoded in the same way as
- message MapFieldEntry {
- key_type key = 1;
- value_type value = 2;
- }
- repeated MapFieldEntry map_field = N;
- */
-
- v := structPointer_Map(base, p.field, p.mtype).Elem() // map[K]V
- if v.Len() == 0 {
- return nil
- }
-
- keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)
-
- enc := func() error {
- if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil {
- return err
- }
- if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil {
- return err
- }
- return nil
- }
-
- keys := v.MapKeys()
- sort.Sort(mapKeys(keys))
- for _, key := range keys {
- val := v.MapIndex(key)
-
- keycopy.Set(key)
- valcopy.Set(val)
-
- o.buf = append(o.buf, p.tagcode...)
- if err := o.enc_len_thing(enc, &state); err != nil {
- return err
- }
- }
- return nil
-}
-
-func size_new_map(p *Properties, base structPointer) int {
- v := structPointer_Map(base, p.field, p.mtype).Elem() // map[K]V
-
- keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)
-
- n := 0
- for _, key := range v.MapKeys() {
- val := v.MapIndex(key)
- keycopy.Set(key)
- valcopy.Set(val)
-
- // Tag codes are two bytes per map entry.
- n += 2
- n += p.mkeyprop.size(p.mkeyprop, keybase)
- n += p.mvalprop.size(p.mvalprop, valbase)
- }
- return n
-}
-
-// mapEncodeScratch returns a new reflect.Value matching the map's value type,
-// and a structPointer suitable for passing to an encoder or sizer.
-func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) {
- // Prepare addressable doubly-indirect placeholders for the key and value types.
- // This is needed because the element-type encoders expect **T, but the map iteration produces T.
-
- keycopy = reflect.New(mapType.Key()).Elem() // addressable K
- keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K
- keyptr.Set(keycopy.Addr()) //
- keybase = toStructPointer(keyptr.Addr()) // **K
-
- // Value types are more varied and require special handling.
- switch mapType.Elem().Kind() {
- case reflect.Slice:
- // []byte
- var dummy []byte
- valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte
- valbase = toStructPointer(valcopy.Addr())
- case reflect.Ptr:
- // message; the generated field type is map[K]*Msg (so V is *Msg),
- // so we only need one level of indirection.
- valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
- valbase = toStructPointer(valcopy.Addr())
- default:
- // everything else
- valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
- valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V
- valptr.Set(valcopy.Addr()) //
- valbase = toStructPointer(valptr.Addr()) // **V
- }
- return
-}
-
-// Encode a struct.
-func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error {
- var state errorState
- // Encode fields in tag order so that decoders may use optimizations
- // that depend on the ordering.
- // https://developers.google.com/protocol-buffers/docs/encoding#order
- for _, i := range prop.order {
- p := prop.Prop[i]
- if p.enc != nil {
- err := p.enc(o, p, base)
- if err != nil {
- if err == ErrNil {
- if p.Required && state.err == nil {
- state.err = &RequiredNotSetError{p.Name}
- }
- } else if err == errRepeatedHasNil {
- // Give more context to nil values in repeated fields.
- return errors.New("repeated field " + p.OrigName + " has nil element")
- } else if !state.shouldContinue(err, p) {
- return err
- }
- }
- }
- }
-
- // Add unrecognized fields at the end.
- if prop.unrecField.IsValid() {
- v := *structPointer_Bytes(base, prop.unrecField)
- if len(v) > 0 {
- o.buf = append(o.buf, v...)
- }
- }
-
- return state.err
-}
-
-func size_struct(prop *StructProperties, base structPointer) (n int) {
- for _, i := range prop.order {
- p := prop.Prop[i]
- if p.size != nil {
- n += p.size(p, base)
- }
- }
-
- // Add unrecognized fields at the end.
- if prop.unrecField.IsValid() {
- v := *structPointer_Bytes(base, prop.unrecField)
- n += len(v)
- }
-
- return
-}
-
-var zeroes [20]byte // longer than any conceivable sizeVarint
-
-// Encode a struct, preceded by its encoded length (as a varint).
-func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error {
- return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state)
-}
-
-// Encode something, preceded by its encoded length (as a varint).
-func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error {
- iLen := len(o.buf)
- o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length
- iMsg := len(o.buf)
- err := enc()
- if err != nil && !state.shouldContinue(err, nil) {
- return err
- }
- lMsg := len(o.buf) - iMsg
- lLen := sizeVarint(uint64(lMsg))
- switch x := lLen - (iMsg - iLen); {
- case x > 0: // actual length is x bytes larger than the space we reserved
- // Move msg x bytes right.
- o.buf = append(o.buf, zeroes[:x]...)
- copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
- case x < 0: // actual length is x bytes smaller than the space we reserved
- // Move msg x bytes left.
- copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
- o.buf = o.buf[:len(o.buf)+x] // x is negative
- }
- // Encode the length in the reserved space.
- o.buf = o.buf[:iLen]
- o.EncodeVarint(uint64(lMsg))
- o.buf = o.buf[:len(o.buf)+lMsg]
- return state.err
-}
-
-// errorState maintains the first error that occurs and updates that error
-// with additional context.
-type errorState struct {
- err error
-}
-
-// shouldContinue reports whether encoding should continue upon encountering the
-// given error. If the error is RequiredNotSetError, shouldContinue returns true
-// and, if this is the first appearance of that error, remembers it for future
-// reporting.
-//
-// If prop is not nil, it may update any error with additional context about the
-// field with the error.
-func (s *errorState) shouldContinue(err error, prop *Properties) bool {
- // Ignore unset required fields.
- reqNotSet, ok := err.(*RequiredNotSetError)
- if !ok {
- return false
- }
- if s.err == nil {
- if prop != nil {
- err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field}
- }
- s.err = err
- }
- return true
-}
diff --git a/containerd/vendor/github.com/golang/protobuf/proto/equal.go b/containerd/vendor/github.com/golang/protobuf/proto/equal.go
deleted file mode 100644
index d8673a3..0000000
--- a/containerd/vendor/github.com/golang/protobuf/proto/equal.go
+++ /dev/null
@@ -1,256 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2011 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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
-// OWNER 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.
-
-// Protocol buffer comparison.
-// TODO: MessageSet.
-
-package proto
-
-import (
- "bytes"
- "log"
- "reflect"
- "strings"
-)
-
-/*
-Equal returns true iff protocol buffers a and b are equal.
-The arguments must both be pointers to protocol buffer structs.
-
-Equality is defined in this way:
- - Two messages are equal iff they are the same type,
- corresponding fields are equal, unknown field sets
- are equal, and extensions sets are equal.
- - Two set scalar fields are equal iff their values are equal.
- If the fields are of a floating-point type, remember that
- NaN != x for all x, including NaN.
- - Two repeated fields are equal iff their lengths are the same,
- and their corresponding elements are equal (a "bytes" field,
- although represented by []byte, is not a repeated field)
- - Two unset fields are equal.
- - Two unknown field sets are equal if their current
- encoded state is equal.
- - Two extension sets are equal iff they have corresponding
- elements that are pairwise equal.
- - Every other combination of things are not equal.
-
-The return value is undefined if a and b are not protocol buffers.
-*/
-func Equal(a, b Message) bool {
- if a == nil || b == nil {
- return a == b
- }
- v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b)
- if v1.Type() != v2.Type() {
- return false
- }
- if v1.Kind() == reflect.Ptr {
- if v1.IsNil() {
- return v2.IsNil()
- }
- if v2.IsNil() {
- return false
- }
- v1, v2 = v1.Elem(), v2.Elem()
- }
- if v1.Kind() != reflect.Struct {
- return false
- }
- return equalStruct(v1, v2)
-}
-
-// v1 and v2 are known to have the same type.
-func equalStruct(v1, v2 reflect.Value) bool {
- for i := 0; i < v1.NumField(); i++ {
- f := v1.Type().Field(i)
- if strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
- f1, f2 := v1.Field(i), v2.Field(i)
- if f.Type.Kind() == reflect.Ptr {
- if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 {
- // both unset
- continue
- } else if n1 != n2 {
- // set/unset mismatch
- return false
- }
- b1, ok := f1.Interface().(raw)
- if ok {
- b2 := f2.Interface().(raw)
- // RawMessage
- if !bytes.Equal(b1.Bytes(), b2.Bytes()) {
- return false
- }
- continue
- }
- f1, f2 = f1.Elem(), f2.Elem()
- }
- if !equalAny(f1, f2) {
- return false
- }
- }
-
- if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() {
- em2 := v2.FieldByName("XXX_extensions")
- if !equalExtensions(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) {
- return false
- }
- }
-
- uf := v1.FieldByName("XXX_unrecognized")
- if !uf.IsValid() {
- return true
- }
-
- u1 := uf.Bytes()
- u2 := v2.FieldByName("XXX_unrecognized").Bytes()
- if !bytes.Equal(u1, u2) {
- return false
- }
-
- return true
-}
-
-// v1 and v2 are known to have the same type.
-func equalAny(v1, v2 reflect.Value) bool {
- if v1.Type() == protoMessageType {
- m1, _ := v1.Interface().(Message)
- m2, _ := v2.Interface().(Message)
- return Equal(m1, m2)
- }
- switch v1.Kind() {
- case reflect.Bool:
- return v1.Bool() == v2.Bool()
- case reflect.Float32, reflect.Float64:
- return v1.Float() == v2.Float()
- case reflect.Int32, reflect.Int64:
- return v1.Int() == v2.Int()
- case reflect.Map:
- if v1.Len() != v2.Len() {
- return false
- }
- for _, key := range v1.MapKeys() {
- val2 := v2.MapIndex(key)
- if !val2.IsValid() {
- // This key was not found in the second map.
- return false
- }
- if !equalAny(v1.MapIndex(key), val2) {
- return false
- }
- }
- return true
- case reflect.Ptr:
- return equalAny(v1.Elem(), v2.Elem())
- case reflect.Slice:
- if v1.Type().Elem().Kind() == reflect.Uint8 {
- // short circuit: []byte
- if v1.IsNil() != v2.IsNil() {
- return false
- }
- return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte))
- }
-
- if v1.Len() != v2.Len() {
- return false
- }
- for i := 0; i < v1.Len(); i++ {
- if !equalAny(v1.Index(i), v2.Index(i)) {
- return false
- }
- }
- return true
- case reflect.String:
- return v1.Interface().(string) == v2.Interface().(string)
- case reflect.Struct:
- return equalStruct(v1, v2)
- case reflect.Uint32, reflect.Uint64:
- return v1.Uint() == v2.Uint()
- }
-
- // unknown type, so not a protocol buffer
- log.Printf("proto: don't know how to compare %v", v1)
- return false
-}
-
-// base is the struct type that the extensions are based on.
-// em1 and em2 are extension maps.
-func equalExtensions(base reflect.Type, em1, em2 map[int32]Extension) bool {
- if len(em1) != len(em2) {
- return false
- }
-
- for extNum, e1 := range em1 {
- e2, ok := em2[extNum]
- if !ok {
- return false
- }
-
- m1, m2 := e1.value, e2.value
-
- if m1 != nil && m2 != nil {
- // Both are unencoded.
- if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2)) {
- return false
- }
- continue
- }
-
- // At least one is encoded. To do a semantically correct comparison
- // we need to unmarshal them first.
- var desc *ExtensionDesc
- if m := extensionMaps[base]; m != nil {
- desc = m[extNum]
- }
- if desc == nil {
- log.Printf("proto: don't know how to compare extension %d of %v", extNum, base)
- continue
- }
- var err error
- if m1 == nil {
- m1, err = decodeExtension(e1.enc, desc)
- }
- if m2 == nil && err == nil {
- m2, err = decodeExtension(e2.enc, desc)
- }
- if err != nil {
- // The encoded form is invalid.
- log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err)
- return false
- }
- if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2)) {
- return false
- }
- }
-
- return true
-}
diff --git a/containerd/vendor/github.com/golang/protobuf/proto/extensions.go b/containerd/vendor/github.com/golang/protobuf/proto/extensions.go
deleted file mode 100644
index 5f62dff..0000000
--- a/containerd/vendor/github.com/golang/protobuf/proto/extensions.go
+++ /dev/null
@@ -1,362 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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
-// OWNER 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.
-
-package proto
-
-/*
- * Types and routines for supporting protocol buffer extensions.
- */
-
-import (
- "errors"
- "fmt"
- "reflect"
- "strconv"
- "sync"
-)
-
-// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message.
-var ErrMissingExtension = errors.New("proto: missing extension")
-
-// ExtensionRange represents a range of message extensions for a protocol buffer.
-// Used in code generated by the protocol compiler.
-type ExtensionRange struct {
- Start, End int32 // both inclusive
-}
-
-// extendableProto is an interface implemented by any protocol buffer that may be extended.
-type extendableProto interface {
- Message
- ExtensionRangeArray() []ExtensionRange
- ExtensionMap() map[int32]Extension
-}
-
-var extendableProtoType = reflect.TypeOf((*extendableProto)(nil)).Elem()
-
-// ExtensionDesc represents an extension specification.
-// Used in generated code from the protocol compiler.
-type ExtensionDesc struct {
- ExtendedType Message // nil pointer to the type that is being extended
- ExtensionType interface{} // nil pointer to the extension type
- Field int32 // field number
- Name string // fully-qualified name of extension, for text formatting
- Tag string // protobuf tag style
-}
-
-func (ed *ExtensionDesc) repeated() bool {
- t := reflect.TypeOf(ed.ExtensionType)
- return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
-}
-
-// Extension represents an extension in a message.
-type Extension struct {
- // When an extension is stored in a message using SetExtension
- // only desc and value are set. When the message is marshaled
- // enc will be set to the encoded form of the message.
- //
- // When a message is unmarshaled and contains extensions, each
- // extension will have only enc set. When such an extension is
- // accessed using GetExtension (or GetExtensions) desc and value
- // will be set.
- desc *ExtensionDesc
- value interface{}
- enc []byte
-}
-
-// SetRawExtension is for testing only.
-func SetRawExtension(base extendableProto, id int32, b []byte) {
- base.ExtensionMap()[id] = Extension{enc: b}
-}
-
-// isExtensionField returns true iff the given field number is in an extension range.
-func isExtensionField(pb extendableProto, field int32) bool {
- for _, er := range pb.ExtensionRangeArray() {
- if er.Start <= field && field <= er.End {
- return true
- }
- }
- return false
-}
-
-// checkExtensionTypes checks that the given extension is valid for pb.
-func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error {
- // Check the extended type.
- if a, b := reflect.TypeOf(pb), reflect.TypeOf(extension.ExtendedType); a != b {
- return errors.New("proto: bad extended type; " + b.String() + " does not extend " + a.String())
- }
- // Check the range.
- if !isExtensionField(pb, extension.Field) {
- return errors.New("proto: bad extension number; not in declared ranges")
- }
- return nil
-}
-
-// extPropKey is sufficient to uniquely identify an extension.
-type extPropKey struct {
- base reflect.Type
- field int32
-}
-
-var extProp = struct {
- sync.RWMutex
- m map[extPropKey]*Properties
-}{
- m: make(map[extPropKey]*Properties),
-}
-
-func extensionProperties(ed *ExtensionDesc) *Properties {
- key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field}
-
- extProp.RLock()
- if prop, ok := extProp.m[key]; ok {
- extProp.RUnlock()
- return prop
- }
- extProp.RUnlock()
-
- extProp.Lock()
- defer extProp.Unlock()
- // Check again.
- if prop, ok := extProp.m[key]; ok {
- return prop
- }
-
- prop := new(Properties)
- prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil)
- extProp.m[key] = prop
- return prop
-}
-
-// encodeExtensionMap encodes any unmarshaled (unencoded) extensions in m.
-func encodeExtensionMap(m map[int32]Extension) error {
- for k, e := range m {
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
-
- et := reflect.TypeOf(e.desc.ExtensionType)
- props := extensionProperties(e.desc)
-
- p := NewBuffer(nil)
- // If e.value has type T, the encoder expects a *struct{ X T }.
- // Pass a *T with a zero field and hope it all works out.
- x := reflect.New(et)
- x.Elem().Set(reflect.ValueOf(e.value))
- if err := props.enc(p, props, toStructPointer(x)); err != nil {
- return err
- }
- e.enc = p.buf
- m[k] = e
- }
- return nil
-}
-
-func sizeExtensionMap(m map[int32]Extension) (n int) {
- for _, e := range m {
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- n += len(e.enc)
- continue
- }
-
- // We don't skip extensions that have an encoded form set,
- // because the extension value may have been mutated after
- // the last time this function was called.
-
- et := reflect.TypeOf(e.desc.ExtensionType)
- props := extensionProperties(e.desc)
-
- // If e.value has type T, the encoder expects a *struct{ X T }.
- // Pass a *T with a zero field and hope it all works out.
- x := reflect.New(et)
- x.Elem().Set(reflect.ValueOf(e.value))
- n += props.size(props, toStructPointer(x))
- }
- return
-}
-
-// HasExtension returns whether the given extension is present in pb.
-func HasExtension(pb extendableProto, extension *ExtensionDesc) bool {
- // TODO: Check types, field numbers, etc.?
- _, ok := pb.ExtensionMap()[extension.Field]
- return ok
-}
-
-// ClearExtension removes the given extension from pb.
-func ClearExtension(pb extendableProto, extension *ExtensionDesc) {
- // TODO: Check types, field numbers, etc.?
- delete(pb.ExtensionMap(), extension.Field)
-}
-
-// GetExtension parses and returns the given extension of pb.
-// If the extension is not present it returns ErrMissingExtension.
-func GetExtension(pb extendableProto, extension *ExtensionDesc) (interface{}, error) {
- if err := checkExtensionTypes(pb, extension); err != nil {
- return nil, err
- }
-
- emap := pb.ExtensionMap()
- e, ok := emap[extension.Field]
- if !ok {
- return nil, ErrMissingExtension
- }
- if e.value != nil {
- // Already decoded. Check the descriptor, though.
- if e.desc != extension {
- // This shouldn't happen. If it does, it means that
- // GetExtension was called twice with two different
- // descriptors with the same field number.
- return nil, errors.New("proto: descriptor conflict")
- }
- return e.value, nil
- }
-
- v, err := decodeExtension(e.enc, extension)
- if err != nil {
- return nil, err
- }
-
- // Remember the decoded version and drop the encoded version.
- // That way it is safe to mutate what we return.
- e.value = v
- e.desc = extension
- e.enc = nil
- emap[extension.Field] = e
- return e.value, nil
-}
-
-// decodeExtension decodes an extension encoded in b.
-func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) {
- o := NewBuffer(b)
-
- t := reflect.TypeOf(extension.ExtensionType)
- rep := extension.repeated()
-
- props := extensionProperties(extension)
-
- // t is a pointer to a struct, pointer to basic type or a slice.
- // Allocate a "field" to store the pointer/slice itself; the
- // pointer/slice will be stored here. We pass
- // the address of this field to props.dec.
- // This passes a zero field and a *t and lets props.dec
- // interpret it as a *struct{ x t }.
- value := reflect.New(t).Elem()
-
- for {
- // Discard wire type and field number varint. It isn't needed.
- if _, err := o.DecodeVarint(); err != nil {
- return nil, err
- }
-
- if err := props.dec(o, props, toStructPointer(value.Addr())); err != nil {
- return nil, err
- }
-
- if !rep || o.index >= len(o.buf) {
- break
- }
- }
- return value.Interface(), nil
-}
-
-// GetExtensions returns a slice of the extensions present in pb that are also listed in es.
-// The returned slice has the same length as es; missing extensions will appear as nil elements.
-func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) {
- epb, ok := pb.(extendableProto)
- if !ok {
- err = errors.New("proto: not an extendable proto")
- return
- }
- extensions = make([]interface{}, len(es))
- for i, e := range es {
- extensions[i], err = GetExtension(epb, e)
- if err == ErrMissingExtension {
- err = nil
- }
- if err != nil {
- return
- }
- }
- return
-}
-
-// SetExtension sets the specified extension of pb to the specified value.
-func SetExtension(pb extendableProto, extension *ExtensionDesc, value interface{}) error {
- if err := checkExtensionTypes(pb, extension); err != nil {
- return err
- }
- typ := reflect.TypeOf(extension.ExtensionType)
- if typ != reflect.TypeOf(value) {
- return errors.New("proto: bad extension value type")
- }
- // nil extension values need to be caught early, because the
- // encoder can't distinguish an ErrNil due to a nil extension
- // from an ErrNil due to a missing field. Extensions are
- // always optional, so the encoder would just swallow the error
- // and drop all the extensions from the encoded message.
- if reflect.ValueOf(value).IsNil() {
- return fmt.Errorf("proto: SetExtension called with nil value of type %T", value)
- }
-
- pb.ExtensionMap()[extension.Field] = Extension{desc: extension, value: value}
- return nil
-}
-
-// A global registry of extensions.
-// The generated code will register the generated descriptors by calling RegisterExtension.
-
-var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc)
-
-// RegisterExtension is called from the generated code.
-func RegisterExtension(desc *ExtensionDesc) {
- st := reflect.TypeOf(desc.ExtendedType).Elem()
- m := extensionMaps[st]
- if m == nil {
- m = make(map[int32]*ExtensionDesc)
- extensionMaps[st] = m
- }
- if _, ok := m[desc.Field]; ok {
- panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field)))
- }
- m[desc.Field] = desc
-}
-
-// RegisteredExtensions returns a map of the registered extensions of a
-// protocol buffer struct, indexed by the extension number.
-// The argument pb should be a nil pointer to the struct type.
-func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc {
- return extensionMaps[reflect.TypeOf(pb).Elem()]
-}
diff --git a/containerd/vendor/github.com/golang/protobuf/proto/lib.go b/containerd/vendor/github.com/golang/protobuf/proto/lib.go
deleted file mode 100644
index f81052f..0000000
--- a/containerd/vendor/github.com/golang/protobuf/proto/lib.go
+++ /dev/null
@@ -1,759 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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
-// OWNER 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.
-
-/*
- Package proto 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.
- 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 by the enclosing message's name, or by the
- enum's type name if it is a top-level enum. Enum types have a String
- method, and a Enum method to assist in message construction.
- - Nested messages, 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.
- - Marshal and Unmarshal are functions to encode and decode the wire format.
-
- The simplest way to describe this is to see an example.
- Given file test.proto, containing
-
- 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;
- }
- }
-
- The resulting file, test.pb.go, is:
-
- package example
-
- import proto "github.com/golang/protobuf/proto"
- import math "math"
-
- type FOO int32
- const (
- FOO_X FOO = 17
- )
- var FOO_name = map[int32]string{
- 17: "X",
- }
- var FOO_value = map[string]int32{
- "X": 17,
- }
-
- func (x FOO) Enum() *FOO {
- p := new(FOO)
- *p = x
- return p
- }
- func (x FOO) String() string {
- return proto.EnumName(FOO_name, int32(x))
- }
- func (x *FOO) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FOO_value, data)
- if err != nil {
- return err
- }
- *x = FOO(value)
- return nil
- }
-
- type Test struct {
- Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
- Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
- Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
- Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
- XXX_unrecognized []byte `json:"-"`
- }
- func (m *Test) Reset() { *m = Test{} }
- func (m *Test) String() string { return proto.CompactTextString(m) }
- func (*Test) ProtoMessage() {}
- const Default_Test_Type int32 = 77
-
- func (m *Test) GetLabel() string {
- if m != nil && m.Label != nil {
- return *m.Label
- }
- return ""
- }
-
- func (m *Test) GetType() int32 {
- if m != nil && m.Type != nil {
- return *m.Type
- }
- return Default_Test_Type
- }
-
- func (m *Test) GetOptionalgroup() *Test_OptionalGroup {
- if m != nil {
- return m.Optionalgroup
- }
- return nil
- }
-
- type Test_OptionalGroup struct {
- RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
- }
- func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} }
- func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) }
-
- func (m *Test_OptionalGroup) GetRequiredField() string {
- if m != nil && m.RequiredField != nil {
- return *m.RequiredField
- }
- return ""
- }
-
- func init() {
- proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
- }
-
- To create and play with a Test object:
-
- package main
-
- import (
- "log"
-
- "github.com/golang/protobuf/proto"
- pb "./example.pb"
- )
-
- func main() {
- test := &pb.Test{
- Label: proto.String("hello"),
- Type: proto.Int32(17),
- Optionalgroup: &pb.Test_OptionalGroup{
- RequiredField: proto.String("good bye"),
- },
- }
- data, err := proto.Marshal(test)
- if err != nil {
- log.Fatal("marshaling error: ", err)
- }
- newTest := &pb.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.
- }
-*/
-package proto
-
-import (
- "encoding/json"
- "fmt"
- "log"
- "reflect"
- "strconv"
- "sync"
-)
-
-// Message is implemented by generated protocol buffer messages.
-type Message interface {
- Reset()
- String() string
- ProtoMessage()
-}
-
-// Stats records allocation details about the protocol buffer encoders
-// and decoders. Useful for tuning the library itself.
-type Stats struct {
- Emalloc uint64 // mallocs in encode
- Dmalloc uint64 // mallocs in decode
- Encode uint64 // number of encodes
- Decode uint64 // number of decodes
- Chit uint64 // number of cache hits
- Cmiss uint64 // number of cache misses
- Size uint64 // number of sizes
-}
-
-// Set to true to enable stats collection.
-const collectStats = false
-
-var stats Stats
-
-// GetStats returns a copy of the global Stats structure.
-func GetStats() Stats { return stats }
-
-// A Buffer is a buffer manager for marshaling and unmarshaling
-// protocol buffers. It may be reused between invocations to
-// reduce memory usage. It is not necessary to use a Buffer;
-// the global functions Marshal and Unmarshal create a
-// temporary Buffer and are fine for most applications.
-type Buffer struct {
- buf []byte // encode/decode byte stream
- index int // write point
-
- // pools of basic types to amortize allocation.
- bools []bool
- uint32s []uint32
- uint64s []uint64
-
- // extra pools, only used with pointer_reflect.go
- int32s []int32
- int64s []int64
- float32s []float32
- float64s []float64
-}
-
-// NewBuffer allocates a new Buffer and initializes its internal data to
-// the contents of the argument slice.
-func NewBuffer(e []byte) *Buffer {
- return &Buffer{buf: e}
-}
-
-// Reset resets the Buffer, ready for marshaling a new protocol buffer.
-func (p *Buffer) Reset() {
- p.buf = p.buf[0:0] // for reading/writing
- p.index = 0 // for reading
-}
-
-// SetBuf replaces the internal buffer with the slice,
-// ready for unmarshaling the contents of the slice.
-func (p *Buffer) SetBuf(s []byte) {
- p.buf = s
- p.index = 0
-}
-
-// Bytes returns the contents of the Buffer.
-func (p *Buffer) Bytes() []byte { return p.buf }
-
-/*
- * Helper routines for simplifying the creation of optional fields of basic type.
- */
-
-// Bool is a helper routine that allocates a new bool value
-// to store v and returns a pointer to it.
-func Bool(v bool) *bool {
- return &v
-}
-
-// Int32 is a helper routine that allocates a new int32 value
-// to store v and returns a pointer to it.
-func Int32(v int32) *int32 {
- return &v
-}
-
-// Int is a helper routine that allocates a new int32 value
-// to store v and returns a pointer to it, but unlike Int32
-// its argument value is an int.
-func Int(v int) *int32 {
- p := new(int32)
- *p = int32(v)
- return p
-}
-
-// Int64 is a helper routine that allocates a new int64 value
-// to store v and returns a pointer to it.
-func Int64(v int64) *int64 {
- return &v
-}
-
-// Float32 is a helper routine that allocates a new float32 value
-// to store v and returns a pointer to it.
-func Float32(v float32) *float32 {
- return &v
-}
-
-// Float64 is a helper routine that allocates a new float64 value
-// to store v and returns a pointer to it.
-func Float64(v float64) *float64 {
- return &v
-}
-
-// Uint32 is a helper routine that allocates a new uint32 value
-// to store v and returns a pointer to it.
-func Uint32(v uint32) *uint32 {
- return &v
-}
-
-// Uint64 is a helper routine that allocates a new uint64 value
-// to store v and returns a pointer to it.
-func Uint64(v uint64) *uint64 {
- return &v
-}
-
-// String is a helper routine that allocates a new string value
-// to store v and returns a pointer to it.
-func String(v string) *string {
- return &v
-}
-
-// EnumName is a helper function to simplify printing protocol buffer enums
-// by name. Given an enum map and a value, it returns a useful string.
-func EnumName(m map[int32]string, v int32) string {
- s, ok := m[v]
- if ok {
- return s
- }
- return strconv.Itoa(int(v))
-}
-
-// UnmarshalJSONEnum is a helper function to simplify recovering enum int values
-// from their JSON-encoded representation. Given a map from the enum's symbolic
-// names to its int values, and a byte buffer containing the JSON-encoded
-// value, it returns an int32 that can be cast to the enum type by the caller.
-//
-// The function can deal with both JSON representations, numeric and symbolic.
-func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
- if data[0] == '"' {
- // New style: enums are strings.
- var repr string
- if err := json.Unmarshal(data, &repr); err != nil {
- return -1, err
- }
- val, ok := m[repr]
- if !ok {
- return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
- }
- return val, nil
- }
- // Old style: enums are ints.
- var val int32
- if err := json.Unmarshal(data, &val); err != nil {
- return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
- }
- return val, nil
-}
-
-// DebugPrint dumps the encoded data in b in a debugging format with a header
-// including the string s. Used in testing but made available for general debugging.
-func (o *Buffer) DebugPrint(s string, b []byte) {
- var u uint64
-
- obuf := o.buf
- index := o.index
- o.buf = b
- o.index = 0
- depth := 0
-
- fmt.Printf("\n--- %s ---\n", s)
-
-out:
- for {
- for i := 0; i < depth; i++ {
- fmt.Print(" ")
- }
-
- index := o.index
- if index == len(o.buf) {
- break
- }
-
- op, err := o.DecodeVarint()
- if err != nil {
- fmt.Printf("%3d: fetching op err %v\n", index, err)
- break out
- }
- tag := op >> 3
- wire := op & 7
-
- switch wire {
- default:
- fmt.Printf("%3d: t=%3d unknown wire=%d\n",
- index, tag, wire)
- break out
-
- case WireBytes:
- var r []byte
-
- r, err = o.DecodeRawBytes(false)
- if err != nil {
- break out
- }
- fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
- if len(r) <= 6 {
- for i := 0; i < len(r); i++ {
- fmt.Printf(" %.2x", r[i])
- }
- } else {
- for i := 0; i < 3; i++ {
- fmt.Printf(" %.2x", r[i])
- }
- fmt.Printf(" ..")
- for i := len(r) - 3; i < len(r); i++ {
- fmt.Printf(" %.2x", r[i])
- }
- }
- fmt.Printf("\n")
-
- case WireFixed32:
- u, err = o.DecodeFixed32()
- if err != nil {
- fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
- break out
- }
- fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
-
- case WireFixed64:
- u, err = o.DecodeFixed64()
- if err != nil {
- fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
- break out
- }
- fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
- break
-
- case WireVarint:
- u, err = o.DecodeVarint()
- if err != nil {
- fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
- break out
- }
- fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
-
- case WireStartGroup:
- if err != nil {
- fmt.Printf("%3d: t=%3d start err %v\n", index, tag, err)
- break out
- }
- fmt.Printf("%3d: t=%3d start\n", index, tag)
- depth++
-
- case WireEndGroup:
- depth--
- if err != nil {
- fmt.Printf("%3d: t=%3d end err %v\n", index, tag, err)
- break out
- }
- fmt.Printf("%3d: t=%3d end\n", index, tag)
- }
- }
-
- if depth != 0 {
- fmt.Printf("%3d: start-end not balanced %d\n", o.index, depth)
- }
- fmt.Printf("\n")
-
- o.buf = obuf
- o.index = index
-}
-
-// SetDefaults sets unset protocol buffer fields to their default values.
-// It only modifies fields that are both unset and have defined defaults.
-// It recursively sets default values in any non-nil sub-messages.
-func SetDefaults(pb Message) {
- setDefaults(reflect.ValueOf(pb), true, false)
-}
-
-// v is a pointer to a struct.
-func setDefaults(v reflect.Value, recur, zeros bool) {
- v = v.Elem()
-
- defaultMu.RLock()
- dm, ok := defaults[v.Type()]
- defaultMu.RUnlock()
- if !ok {
- dm = buildDefaultMessage(v.Type())
- defaultMu.Lock()
- defaults[v.Type()] = dm
- defaultMu.Unlock()
- }
-
- for _, sf := range dm.scalars {
- f := v.Field(sf.index)
- if !f.IsNil() {
- // field already set
- continue
- }
- dv := sf.value
- if dv == nil && !zeros {
- // no explicit default, and don't want to set zeros
- continue
- }
- fptr := f.Addr().Interface() // **T
- // TODO: Consider batching the allocations we do here.
- switch sf.kind {
- case reflect.Bool:
- b := new(bool)
- if dv != nil {
- *b = dv.(bool)
- }
- *(fptr.(**bool)) = b
- case reflect.Float32:
- f := new(float32)
- if dv != nil {
- *f = dv.(float32)
- }
- *(fptr.(**float32)) = f
- case reflect.Float64:
- f := new(float64)
- if dv != nil {
- *f = dv.(float64)
- }
- *(fptr.(**float64)) = f
- case reflect.Int32:
- // might be an enum
- if ft := f.Type(); ft != int32PtrType {
- // enum
- f.Set(reflect.New(ft.Elem()))
- if dv != nil {
- f.Elem().SetInt(int64(dv.(int32)))
- }
- } else {
- // int32 field
- i := new(int32)
- if dv != nil {
- *i = dv.(int32)
- }
- *(fptr.(**int32)) = i
- }
- case reflect.Int64:
- i := new(int64)
- if dv != nil {
- *i = dv.(int64)
- }
- *(fptr.(**int64)) = i
- case reflect.String:
- s := new(string)
- if dv != nil {
- *s = dv.(string)
- }
- *(fptr.(**string)) = s
- case reflect.Uint8:
- // exceptional case: []byte
- var b []byte
- if dv != nil {
- db := dv.([]byte)
- b = make([]byte, len(db))
- copy(b, db)
- } else {
- b = []byte{}
- }
- *(fptr.(*[]byte)) = b
- case reflect.Uint32:
- u := new(uint32)
- if dv != nil {
- *u = dv.(uint32)
- }
- *(fptr.(**uint32)) = u
- case reflect.Uint64:
- u := new(uint64)
- if dv != nil {
- *u = dv.(uint64)
- }
- *(fptr.(**uint64)) = u
- default:
- log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
- }
- }
-
- for _, ni := range dm.nested {
- f := v.Field(ni)
- if f.IsNil() {
- continue
- }
- // f is *T or []*T
- if f.Kind() == reflect.Ptr {
- setDefaults(f, recur, zeros)
- } else {
- for i := 0; i < f.Len(); i++ {
- e := f.Index(i)
- if e.IsNil() {
- continue
- }
- setDefaults(e, recur, zeros)
- }
- }
- }
-}
-
-var (
- // defaults maps a protocol buffer struct type to a slice of the fields,
- // with its scalar fields set to their proto-declared non-zero default values.
- defaultMu sync.RWMutex
- defaults = make(map[reflect.Type]defaultMessage)
-
- int32PtrType = reflect.TypeOf((*int32)(nil))
-)
-
-// defaultMessage represents information about the default values of a message.
-type defaultMessage struct {
- scalars []scalarField
- nested []int // struct field index of nested messages
-}
-
-type scalarField struct {
- index int // struct field index
- kind reflect.Kind // element type (the T in *T or []T)
- value interface{} // the proto-declared default value, or nil
-}
-
-func ptrToStruct(t reflect.Type) bool {
- return t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct
-}
-
-// t is a struct type.
-func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
- sprop := GetProperties(t)
- for _, prop := range sprop.Prop {
- fi, ok := sprop.decoderTags.get(prop.Tag)
- if !ok {
- // XXX_unrecognized
- continue
- }
- ft := t.Field(fi).Type
-
- // nested messages
- if ptrToStruct(ft) || (ft.Kind() == reflect.Slice && ptrToStruct(ft.Elem())) {
- dm.nested = append(dm.nested, fi)
- continue
- }
-
- sf := scalarField{
- index: fi,
- kind: ft.Elem().Kind(),
- }
-
- // scalar fields without defaults
- if !prop.HasDefault {
- dm.scalars = append(dm.scalars, sf)
- continue
- }
-
- // a scalar field: either *T or []byte
- switch ft.Elem().Kind() {
- case reflect.Bool:
- x, err := strconv.ParseBool(prop.Default)
- if err != nil {
- log.Printf("proto: bad default bool %q: %v", prop.Default, err)
- continue
- }
- sf.value = x
- case reflect.Float32:
- x, err := strconv.ParseFloat(prop.Default, 32)
- if err != nil {
- log.Printf("proto: bad default float32 %q: %v", prop.Default, err)
- continue
- }
- sf.value = float32(x)
- case reflect.Float64:
- x, err := strconv.ParseFloat(prop.Default, 64)
- if err != nil {
- log.Printf("proto: bad default float64 %q: %v", prop.Default, err)
- continue
- }
- sf.value = x
- case reflect.Int32:
- x, err := strconv.ParseInt(prop.Default, 10, 32)
- if err != nil {
- log.Printf("proto: bad default int32 %q: %v", prop.Default, err)
- continue
- }
- sf.value = int32(x)
- case reflect.Int64:
- x, err := strconv.ParseInt(prop.Default, 10, 64)
- if err != nil {
- log.Printf("proto: bad default int64 %q: %v", prop.Default, err)
- continue
- }
- sf.value = x
- case reflect.String:
- sf.value = prop.Default
- case reflect.Uint8:
- // []byte (not *uint8)
- sf.value = []byte(prop.Default)
- case reflect.Uint32:
- x, err := strconv.ParseUint(prop.Default, 10, 32)
- if err != nil {
- log.Printf("proto: bad default uint32 %q: %v", prop.Default, err)
- continue
- }
- sf.value = uint32(x)
- case reflect.Uint64:
- x, err := strconv.ParseUint(prop.Default, 10, 64)
- if err != nil {
- log.Printf("proto: bad default uint64 %q: %v", prop.Default, err)
- continue
- }
- sf.value = x
- default:
- log.Printf("proto: unhandled def kind %v", ft.Elem().Kind())
- continue
- }
-
- dm.scalars = append(dm.scalars, sf)
- }
-
- return dm
-}
-
-// Map fields may have key types of non-float scalars, strings and enums.
-// The easiest way to sort them in some deterministic order is to use fmt.
-// If this turns out to be inefficient we can always consider other options,
-// such as doing a Schwartzian transform.
-
-type mapKeys []reflect.Value
-
-func (s mapKeys) Len() int { return len(s) }
-func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
-func (s mapKeys) Less(i, j int) bool {
- return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface())
-}
diff --git a/containerd/vendor/github.com/golang/protobuf/proto/message_set.go b/containerd/vendor/github.com/golang/protobuf/proto/message_set.go
deleted file mode 100644
index 9d912bc..0000000
--- a/containerd/vendor/github.com/golang/protobuf/proto/message_set.go
+++ /dev/null
@@ -1,287 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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
-// OWNER 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.
-
-package proto
-
-/*
- * Support for message sets.
- */
-
-import (
- "bytes"
- "encoding/json"
- "errors"
- "fmt"
- "reflect"
- "sort"
-)
-
-// ErrNoMessageTypeId occurs when a protocol buffer does not have a message type ID.
-// A message type ID is required for storing a protocol buffer in a message set.
-var ErrNoMessageTypeId = errors.New("proto does not have a message type ID")
-
-// The first two types (_MessageSet_Item and MessageSet)
-// model what the protocol compiler produces for the following protocol message:
-// message MessageSet {
-// repeated group Item = 1 {
-// required int32 type_id = 2;
-// required string message = 3;
-// };
-// }
-// That is the MessageSet wire format. We can't use a proto to generate these
-// because that would introduce a circular dependency between it and this package.
-//
-// When a proto1 proto has a field that looks like:
-// optional message info = 3;
-// the protocol compiler produces a field in the generated struct that looks like:
-// Info *_proto_.MessageSet `protobuf:"bytes,3,opt,name=info"`
-// The package is automatically inserted so there is no need for that proto file to
-// import this package.
-
-type _MessageSet_Item struct {
- TypeId *int32 `protobuf:"varint,2,req,name=type_id"`
- Message []byte `protobuf:"bytes,3,req,name=message"`
-}
-
-type MessageSet struct {
- Item []*_MessageSet_Item `protobuf:"group,1,rep"`
- XXX_unrecognized []byte
- // TODO: caching?
-}
-
-// Make sure MessageSet is a Message.
-var _ Message = (*MessageSet)(nil)
-
-// messageTypeIder is an interface satisfied by a protocol buffer type
-// that may be stored in a MessageSet.
-type messageTypeIder interface {
- MessageTypeId() int32
-}
-
-func (ms *MessageSet) find(pb Message) *_MessageSet_Item {
- mti, ok := pb.(messageTypeIder)
- if !ok {
- return nil
- }
- id := mti.MessageTypeId()
- for _, item := range ms.Item {
- if *item.TypeId == id {
- return item
- }
- }
- return nil
-}
-
-func (ms *MessageSet) Has(pb Message) bool {
- if ms.find(pb) != nil {
- return true
- }
- return false
-}
-
-func (ms *MessageSet) Unmarshal(pb Message) error {
- if item := ms.find(pb); item != nil {
- return Unmarshal(item.Message, pb)
- }
- if _, ok := pb.(messageTypeIder); !ok {
- return ErrNoMessageTypeId
- }
- return nil // TODO: return error instead?
-}
-
-func (ms *MessageSet) Marshal(pb Message) error {
- msg, err := Marshal(pb)
- if err != nil {
- return err
- }
- if item := ms.find(pb); item != nil {
- // reuse existing item
- item.Message = msg
- return nil
- }
-
- mti, ok := pb.(messageTypeIder)
- if !ok {
- return ErrNoMessageTypeId
- }
-
- mtid := mti.MessageTypeId()
- ms.Item = append(ms.Item, &_MessageSet_Item{
- TypeId: &mtid,
- Message: msg,
- })
- return nil
-}
-
-func (ms *MessageSet) Reset() { *ms = MessageSet{} }
-func (ms *MessageSet) String() string { return CompactTextString(ms) }
-func (*MessageSet) ProtoMessage() {}
-
-// Support for the message_set_wire_format message option.
-
-func skipVarint(buf []byte) []byte {
- i := 0
- for ; buf[i]&0x80 != 0; i++ {
- }
- return buf[i+1:]
-}
-
-// MarshalMessageSet encodes the extension map represented by m in the message set wire format.
-// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option.
-func MarshalMessageSet(m map[int32]Extension) ([]byte, error) {
- if err := encodeExtensionMap(m); err != nil {
- return nil, err
- }
-
- // Sort extension IDs to provide a deterministic encoding.
- // See also enc_map in encode.go.
- ids := make([]int, 0, len(m))
- for id := range m {
- ids = append(ids, int(id))
- }
- sort.Ints(ids)
-
- ms := &MessageSet{Item: make([]*_MessageSet_Item, 0, len(m))}
- for _, id := range ids {
- e := m[int32(id)]
- // Remove the wire type and field number varint, as well as the length varint.
- msg := skipVarint(skipVarint(e.enc))
-
- ms.Item = append(ms.Item, &_MessageSet_Item{
- TypeId: Int32(int32(id)),
- Message: msg,
- })
- }
- return Marshal(ms)
-}
-
-// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format.
-// It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option.
-func UnmarshalMessageSet(buf []byte, m map[int32]Extension) error {
- ms := new(MessageSet)
- if err := Unmarshal(buf, ms); err != nil {
- return err
- }
- for _, item := range ms.Item {
- id := *item.TypeId
- msg := item.Message
-
- // Restore wire type and field number varint, plus length varint.
- // Be careful to preserve duplicate items.
- b := EncodeVarint(uint64(id)<<3 | WireBytes)
- if ext, ok := m[id]; ok {
- // Existing data; rip off the tag and length varint
- // so we join the new data correctly.
- // We can assume that ext.enc is set because we are unmarshaling.
- o := ext.enc[len(b):] // skip wire type and field number
- _, n := DecodeVarint(o) // calculate length of length varint
- o = o[n:] // skip length varint
- msg = append(o, msg...) // join old data and new data
- }
- b = append(b, EncodeVarint(uint64(len(msg)))...)
- b = append(b, msg...)
-
- m[id] = Extension{enc: b}
- }
- return nil
-}
-
-// MarshalMessageSetJSON encodes the extension map represented by m in JSON format.
-// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
-func MarshalMessageSetJSON(m map[int32]Extension) ([]byte, error) {
- var b bytes.Buffer
- b.WriteByte('{')
-
- // Process the map in key order for deterministic output.
- ids := make([]int32, 0, len(m))
- for id := range m {
- ids = append(ids, id)
- }
- sort.Sort(int32Slice(ids)) // int32Slice defined in text.go
-
- for i, id := range ids {
- ext := m[id]
- if i > 0 {
- b.WriteByte(',')
- }
-
- msd, ok := messageSetMap[id]
- if !ok {
- // Unknown type; we can't render it, so skip it.
- continue
- }
- fmt.Fprintf(&b, `"[%s]":`, msd.name)
-
- x := ext.value
- if x == nil {
- x = reflect.New(msd.t.Elem()).Interface()
- if err := Unmarshal(ext.enc, x.(Message)); err != nil {
- return nil, err
- }
- }
- d, err := json.Marshal(x)
- if err != nil {
- return nil, err
- }
- b.Write(d)
- }
- b.WriteByte('}')
- return b.Bytes(), nil
-}
-
-// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format.
-// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
-func UnmarshalMessageSetJSON(buf []byte, m map[int32]Extension) error {
- // Common-case fast path.
- if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) {
- return nil
- }
-
- // This is fairly tricky, and it's not clear that it is needed.
- return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented")
-}
-
-// A global registry of types that can be used in a MessageSet.
-
-var messageSetMap = make(map[int32]messageSetDesc)
-
-type messageSetDesc struct {
- t reflect.Type // pointer to struct
- name string
-}
-
-// RegisterMessageSetType is called from the generated code.
-func RegisterMessageSetType(m Message, fieldNum int32, name string) {
- messageSetMap[fieldNum] = messageSetDesc{
- t: reflect.TypeOf(m),
- name: name,
- }
-}
diff --git a/containerd/vendor/github.com/golang/protobuf/proto/pointer_reflect.go b/containerd/vendor/github.com/golang/protobuf/proto/pointer_reflect.go
deleted file mode 100644
index c68b125..0000000
--- a/containerd/vendor/github.com/golang/protobuf/proto/pointer_reflect.go
+++ /dev/null
@@ -1,479 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2012 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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
-// OWNER 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.
-
-// +build appengine
-
-// This file contains an implementation of proto field accesses using package reflect.
-// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can
-// be used on App Engine.
-
-package proto
-
-import (
- "math"
- "reflect"
-)
-
-// A structPointer is a pointer to a struct.
-type structPointer struct {
- v reflect.Value
-}
-
-// toStructPointer returns a structPointer equivalent to the given reflect value.
-// The reflect value must itself be a pointer to a struct.
-func toStructPointer(v reflect.Value) structPointer {
- return structPointer{v}
-}
-
-// IsNil reports whether p is nil.
-func structPointer_IsNil(p structPointer) bool {
- return p.v.IsNil()
-}
-
-// Interface returns the struct pointer as an interface value.
-func structPointer_Interface(p structPointer, _ reflect.Type) interface{} {
- return p.v.Interface()
-}
-
-// A field identifies a field in a struct, accessible from a structPointer.
-// In this implementation, a field is identified by the sequence of field indices
-// passed to reflect's FieldByIndex.
-type field []int
-
-// toField returns a field equivalent to the given reflect field.
-func toField(f *reflect.StructField) field {
- return f.Index
-}
-
-// invalidField is an invalid field identifier.
-var invalidField = field(nil)
-
-// IsValid reports whether the field identifier is valid.
-func (f field) IsValid() bool { return f != nil }
-
-// field returns the given field in the struct as a reflect value.
-func structPointer_field(p structPointer, f field) reflect.Value {
- // Special case: an extension map entry with a value of type T
- // passes a *T to the struct-handling code with a zero field,
- // expecting that it will be treated as equivalent to *struct{ X T },
- // which has the same memory layout. We have to handle that case
- // specially, because reflect will panic if we call FieldByIndex on a
- // non-struct.
- if f == nil {
- return p.v.Elem()
- }
-
- return p.v.Elem().FieldByIndex(f)
-}
-
-// ifield returns the given field in the struct as an interface value.
-func structPointer_ifield(p structPointer, f field) interface{} {
- return structPointer_field(p, f).Addr().Interface()
-}
-
-// Bytes returns the address of a []byte field in the struct.
-func structPointer_Bytes(p structPointer, f field) *[]byte {
- return structPointer_ifield(p, f).(*[]byte)
-}
-
-// BytesSlice returns the address of a [][]byte field in the struct.
-func structPointer_BytesSlice(p structPointer, f field) *[][]byte {
- return structPointer_ifield(p, f).(*[][]byte)
-}
-
-// Bool returns the address of a *bool field in the struct.
-func structPointer_Bool(p structPointer, f field) **bool {
- return structPointer_ifield(p, f).(**bool)
-}
-
-// BoolVal returns the address of a bool field in the struct.
-func structPointer_BoolVal(p structPointer, f field) *bool {
- return structPointer_ifield(p, f).(*bool)
-}
-
-// BoolSlice returns the address of a []bool field in the struct.
-func structPointer_BoolSlice(p structPointer, f field) *[]bool {
- return structPointer_ifield(p, f).(*[]bool)
-}
-
-// String returns the address of a *string field in the struct.
-func structPointer_String(p structPointer, f field) **string {
- return structPointer_ifield(p, f).(**string)
-}
-
-// StringVal returns the address of a string field in the struct.
-func structPointer_StringVal(p structPointer, f field) *string {
- return structPointer_ifield(p, f).(*string)
-}
-
-// StringSlice returns the address of a []string field in the struct.
-func structPointer_StringSlice(p structPointer, f field) *[]string {
- return structPointer_ifield(p, f).(*[]string)
-}
-
-// ExtMap returns the address of an extension map field in the struct.
-func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension {
- return structPointer_ifield(p, f).(*map[int32]Extension)
-}
-
-// Map returns the reflect.Value for the address of a map field in the struct.
-func structPointer_Map(p structPointer, f field, typ reflect.Type) reflect.Value {
- return structPointer_field(p, f).Addr()
-}
-
-// SetStructPointer writes a *struct field in the struct.
-func structPointer_SetStructPointer(p structPointer, f field, q structPointer) {
- structPointer_field(p, f).Set(q.v)
-}
-
-// GetStructPointer reads a *struct field in the struct.
-func structPointer_GetStructPointer(p structPointer, f field) structPointer {
- return structPointer{structPointer_field(p, f)}
-}
-
-// StructPointerSlice the address of a []*struct field in the struct.
-func structPointer_StructPointerSlice(p structPointer, f field) structPointerSlice {
- return structPointerSlice{structPointer_field(p, f)}
-}
-
-// A structPointerSlice represents the address of a slice of pointers to structs
-// (themselves messages or groups). That is, v.Type() is *[]*struct{...}.
-type structPointerSlice struct {
- v reflect.Value
-}
-
-func (p structPointerSlice) Len() int { return p.v.Len() }
-func (p structPointerSlice) Index(i int) structPointer { return structPointer{p.v.Index(i)} }
-func (p structPointerSlice) Append(q structPointer) {
- p.v.Set(reflect.Append(p.v, q.v))
-}
-
-var (
- int32Type = reflect.TypeOf(int32(0))
- uint32Type = reflect.TypeOf(uint32(0))
- float32Type = reflect.TypeOf(float32(0))
- int64Type = reflect.TypeOf(int64(0))
- uint64Type = reflect.TypeOf(uint64(0))
- float64Type = reflect.TypeOf(float64(0))
-)
-
-// A word32 represents a field of type *int32, *uint32, *float32, or *enum.
-// That is, v.Type() is *int32, *uint32, *float32, or *enum and v is assignable.
-type word32 struct {
- v reflect.Value
-}
-
-// IsNil reports whether p is nil.
-func word32_IsNil(p word32) bool {
- return p.v.IsNil()
-}
-
-// Set sets p to point at a newly allocated word with bits set to x.
-func word32_Set(p word32, o *Buffer, x uint32) {
- t := p.v.Type().Elem()
- switch t {
- case int32Type:
- if len(o.int32s) == 0 {
- o.int32s = make([]int32, uint32PoolSize)
- }
- o.int32s[0] = int32(x)
- p.v.Set(reflect.ValueOf(&o.int32s[0]))
- o.int32s = o.int32s[1:]
- return
- case uint32Type:
- if len(o.uint32s) == 0 {
- o.uint32s = make([]uint32, uint32PoolSize)
- }
- o.uint32s[0] = x
- p.v.Set(reflect.ValueOf(&o.uint32s[0]))
- o.uint32s = o.uint32s[1:]
- return
- case float32Type:
- if len(o.float32s) == 0 {
- o.float32s = make([]float32, uint32PoolSize)
- }
- o.float32s[0] = math.Float32frombits(x)
- p.v.Set(reflect.ValueOf(&o.float32s[0]))
- o.float32s = o.float32s[1:]
- return
- }
-
- // must be enum
- p.v.Set(reflect.New(t))
- p.v.Elem().SetInt(int64(int32(x)))
-}
-
-// Get gets the bits pointed at by p, as a uint32.
-func word32_Get(p word32) uint32 {
- elem := p.v.Elem()
- switch elem.Kind() {
- case reflect.Int32:
- return uint32(elem.Int())
- case reflect.Uint32:
- return uint32(elem.Uint())
- case reflect.Float32:
- return math.Float32bits(float32(elem.Float()))
- }
- panic("unreachable")
-}
-
-// Word32 returns a reference to a *int32, *uint32, *float32, or *enum field in the struct.
-func structPointer_Word32(p structPointer, f field) word32 {
- return word32{structPointer_field(p, f)}
-}
-
-// A word32Val represents a field of type int32, uint32, float32, or enum.
-// That is, v.Type() is int32, uint32, float32, or enum and v is assignable.
-type word32Val struct {
- v reflect.Value
-}
-
-// Set sets *p to x.
-func word32Val_Set(p word32Val, x uint32) {
- switch p.v.Type() {
- case int32Type:
- p.v.SetInt(int64(x))
- return
- case uint32Type:
- p.v.SetUint(uint64(x))
- return
- case float32Type:
- p.v.SetFloat(float64(math.Float32frombits(x)))
- return
- }
-
- // must be enum
- p.v.SetInt(int64(int32(x)))
-}
-
-// Get gets the bits pointed at by p, as a uint32.
-func word32Val_Get(p word32Val) uint32 {
- elem := p.v
- switch elem.Kind() {
- case reflect.Int32:
- return uint32(elem.Int())
- case reflect.Uint32:
- return uint32(elem.Uint())
- case reflect.Float32:
- return math.Float32bits(float32(elem.Float()))
- }
- panic("unreachable")
-}
-
-// Word32Val returns a reference to a int32, uint32, float32, or enum field in the struct.
-func structPointer_Word32Val(p structPointer, f field) word32Val {
- return word32Val{structPointer_field(p, f)}
-}
-
-// A word32Slice is a slice of 32-bit values.
-// That is, v.Type() is []int32, []uint32, []float32, or []enum.
-type word32Slice struct {
- v reflect.Value
-}
-
-func (p word32Slice) Append(x uint32) {
- n, m := p.v.Len(), p.v.Cap()
- if n < m {
- p.v.SetLen(n + 1)
- } else {
- t := p.v.Type().Elem()
- p.v.Set(reflect.Append(p.v, reflect.Zero(t)))
- }
- elem := p.v.Index(n)
- switch elem.Kind() {
- case reflect.Int32:
- elem.SetInt(int64(int32(x)))
- case reflect.Uint32:
- elem.SetUint(uint64(x))
- case reflect.Float32:
- elem.SetFloat(float64(math.Float32frombits(x)))
- }
-}
-
-func (p word32Slice) Len() int {
- return p.v.Len()
-}
-
-func (p word32Slice) Index(i int) uint32 {
- elem := p.v.Index(i)
- switch elem.Kind() {
- case reflect.Int32:
- return uint32(elem.Int())
- case reflect.Uint32:
- return uint32(elem.Uint())
- case reflect.Float32:
- return math.Float32bits(float32(elem.Float()))
- }
- panic("unreachable")
-}
-
-// Word32Slice returns a reference to a []int32, []uint32, []float32, or []enum field in the struct.
-func structPointer_Word32Slice(p structPointer, f field) word32Slice {
- return word32Slice{structPointer_field(p, f)}
-}
-
-// word64 is like word32 but for 64-bit values.
-type word64 struct {
- v reflect.Value
-}
-
-func word64_Set(p word64, o *Buffer, x uint64) {
- t := p.v.Type().Elem()
- switch t {
- case int64Type:
- if len(o.int64s) == 0 {
- o.int64s = make([]int64, uint64PoolSize)
- }
- o.int64s[0] = int64(x)
- p.v.Set(reflect.ValueOf(&o.int64s[0]))
- o.int64s = o.int64s[1:]
- return
- case uint64Type:
- if len(o.uint64s) == 0 {
- o.uint64s = make([]uint64, uint64PoolSize)
- }
- o.uint64s[0] = x
- p.v.Set(reflect.ValueOf(&o.uint64s[0]))
- o.uint64s = o.uint64s[1:]
- return
- case float64Type:
- if len(o.float64s) == 0 {
- o.float64s = make([]float64, uint64PoolSize)
- }
- o.float64s[0] = math.Float64frombits(x)
- p.v.Set(reflect.ValueOf(&o.float64s[0]))
- o.float64s = o.float64s[1:]
- return
- }
- panic("unreachable")
-}
-
-func word64_IsNil(p word64) bool {
- return p.v.IsNil()
-}
-
-func word64_Get(p word64) uint64 {
- elem := p.v.Elem()
- switch elem.Kind() {
- case reflect.Int64:
- return uint64(elem.Int())
- case reflect.Uint64:
- return elem.Uint()
- case reflect.Float64:
- return math.Float64bits(elem.Float())
- }
- panic("unreachable")
-}
-
-func structPointer_Word64(p structPointer, f field) word64 {
- return word64{structPointer_field(p, f)}
-}
-
-// word64Val is like word32Val but for 64-bit values.
-type word64Val struct {
- v reflect.Value
-}
-
-func word64Val_Set(p word64Val, o *Buffer, x uint64) {
- switch p.v.Type() {
- case int64Type:
- p.v.SetInt(int64(x))
- return
- case uint64Type:
- p.v.SetUint(x)
- return
- case float64Type:
- p.v.SetFloat(math.Float64frombits(x))
- return
- }
- panic("unreachable")
-}
-
-func word64Val_Get(p word64Val) uint64 {
- elem := p.v
- switch elem.Kind() {
- case reflect.Int64:
- return uint64(elem.Int())
- case reflect.Uint64:
- return elem.Uint()
- case reflect.Float64:
- return math.Float64bits(elem.Float())
- }
- panic("unreachable")
-}
-
-func structPointer_Word64Val(p structPointer, f field) word64Val {
- return word64Val{structPointer_field(p, f)}
-}
-
-type word64Slice struct {
- v reflect.Value
-}
-
-func (p word64Slice) Append(x uint64) {
- n, m := p.v.Len(), p.v.Cap()
- if n < m {
- p.v.SetLen(n + 1)
- } else {
- t := p.v.Type().Elem()
- p.v.Set(reflect.Append(p.v, reflect.Zero(t)))
- }
- elem := p.v.Index(n)
- switch elem.Kind() {
- case reflect.Int64:
- elem.SetInt(int64(int64(x)))
- case reflect.Uint64:
- elem.SetUint(uint64(x))
- case reflect.Float64:
- elem.SetFloat(float64(math.Float64frombits(x)))
- }
-}
-
-func (p word64Slice) Len() int {
- return p.v.Len()
-}
-
-func (p word64Slice) Index(i int) uint64 {
- elem := p.v.Index(i)
- switch elem.Kind() {
- case reflect.Int64:
- return uint64(elem.Int())
- case reflect.Uint64:
- return uint64(elem.Uint())
- case reflect.Float64:
- return math.Float64bits(float64(elem.Float()))
- }
- panic("unreachable")
-}
-
-func structPointer_Word64Slice(p structPointer, f field) word64Slice {
- return word64Slice{structPointer_field(p, f)}
-}
diff --git a/containerd/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go b/containerd/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go
deleted file mode 100644
index 48bc0fa..0000000
--- a/containerd/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go
+++ /dev/null
@@ -1,266 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2012 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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
-// OWNER 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.
-
-// +build !appengine
-
-// This file contains the implementation of the proto field accesses using package unsafe.
-
-package proto
-
-import (
- "reflect"
- "unsafe"
-)
-
-// NOTE: These type_Foo functions would more idiomatically be methods,
-// but Go does not allow methods on pointer types, and we must preserve
-// some pointer type for the garbage collector. We use these
-// funcs with clunky names as our poor approximation to methods.
-//
-// An alternative would be
-// type structPointer struct { p unsafe.Pointer }
-// but that does not registerize as well.
-
-// A structPointer is a pointer to a struct.
-type structPointer unsafe.Pointer
-
-// toStructPointer returns a structPointer equivalent to the given reflect value.
-func toStructPointer(v reflect.Value) structPointer {
- return structPointer(unsafe.Pointer(v.Pointer()))
-}
-
-// IsNil reports whether p is nil.
-func structPointer_IsNil(p structPointer) bool {
- return p == nil
-}
-
-// Interface returns the struct pointer, assumed to have element type t,
-// as an interface value.
-func structPointer_Interface(p structPointer, t reflect.Type) interface{} {
- return reflect.NewAt(t, unsafe.Pointer(p)).Interface()
-}
-
-// A field identifies a field in a struct, accessible from a structPointer.
-// In this implementation, a field is identified by its byte offset from the start of the struct.
-type field uintptr
-
-// toField returns a field equivalent to the given reflect field.
-func toField(f *reflect.StructField) field {
- return field(f.Offset)
-}
-
-// invalidField is an invalid field identifier.
-const invalidField = ^field(0)
-
-// IsValid reports whether the field identifier is valid.
-func (f field) IsValid() bool {
- return f != ^field(0)
-}
-
-// Bytes returns the address of a []byte field in the struct.
-func structPointer_Bytes(p structPointer, f field) *[]byte {
- return (*[]byte)(unsafe.Pointer(uintptr(p) + uintptr(f)))
-}
-
-// BytesSlice returns the address of a [][]byte field in the struct.
-func structPointer_BytesSlice(p structPointer, f field) *[][]byte {
- return (*[][]byte)(unsafe.Pointer(uintptr(p) + uintptr(f)))
-}
-
-// Bool returns the address of a *bool field in the struct.
-func structPointer_Bool(p structPointer, f field) **bool {
- return (**bool)(unsafe.Pointer(uintptr(p) + uintptr(f)))
-}
-
-// BoolVal returns the address of a bool field in the struct.
-func structPointer_BoolVal(p structPointer, f field) *bool {
- return (*bool)(unsafe.Pointer(uintptr(p) + uintptr(f)))
-}
-
-// BoolSlice returns the address of a []bool field in the struct.
-func structPointer_BoolSlice(p structPointer, f field) *[]bool {
- return (*[]bool)(unsafe.Pointer(uintptr(p) + uintptr(f)))
-}
-
-// String returns the address of a *string field in the struct.
-func structPointer_String(p structPointer, f field) **string {
- return (**string)(unsafe.Pointer(uintptr(p) + uintptr(f)))
-}
-
-// StringVal returns the address of a string field in the struct.
-func structPointer_StringVal(p structPointer, f field) *string {
- return (*string)(unsafe.Pointer(uintptr(p) + uintptr(f)))
-}
-
-// StringSlice returns the address of a []string field in the struct.
-func structPointer_StringSlice(p structPointer, f field) *[]string {
- return (*[]string)(unsafe.Pointer(uintptr(p) + uintptr(f)))
-}
-
-// ExtMap returns the address of an extension map field in the struct.
-func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension {
- return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f)))
-}
-
-// Map returns the reflect.Value for the address of a map field in the struct.
-func structPointer_Map(p structPointer, f field, typ reflect.Type) reflect.Value {
- return reflect.NewAt(typ, unsafe.Pointer(uintptr(p)+uintptr(f)))
-}
-
-// SetStructPointer writes a *struct field in the struct.
-func structPointer_SetStructPointer(p structPointer, f field, q structPointer) {
- *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) = q
-}
-
-// GetStructPointer reads a *struct field in the struct.
-func structPointer_GetStructPointer(p structPointer, f field) structPointer {
- return *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f)))
-}
-
-// StructPointerSlice the address of a []*struct field in the struct.
-func structPointer_StructPointerSlice(p structPointer, f field) *structPointerSlice {
- return (*structPointerSlice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
-}
-
-// A structPointerSlice represents a slice of pointers to structs (themselves submessages or groups).
-type structPointerSlice []structPointer
-
-func (v *structPointerSlice) Len() int { return len(*v) }
-func (v *structPointerSlice) Index(i int) structPointer { return (*v)[i] }
-func (v *structPointerSlice) Append(p structPointer) { *v = append(*v, p) }
-
-// A word32 is the address of a "pointer to 32-bit value" field.
-type word32 **uint32
-
-// IsNil reports whether *v is nil.
-func word32_IsNil(p word32) bool {
- return *p == nil
-}
-
-// Set sets *v to point at a newly allocated word set to x.
-func word32_Set(p word32, o *Buffer, x uint32) {
- if len(o.uint32s) == 0 {
- o.uint32s = make([]uint32, uint32PoolSize)
- }
- o.uint32s[0] = x
- *p = &o.uint32s[0]
- o.uint32s = o.uint32s[1:]
-}
-
-// Get gets the value pointed at by *v.
-func word32_Get(p word32) uint32 {
- return **p
-}
-
-// Word32 returns the address of a *int32, *uint32, *float32, or *enum field in the struct.
-func structPointer_Word32(p structPointer, f field) word32 {
- return word32((**uint32)(unsafe.Pointer(uintptr(p) + uintptr(f))))
-}
-
-// A word32Val is the address of a 32-bit value field.
-type word32Val *uint32
-
-// Set sets *p to x.
-func word32Val_Set(p word32Val, x uint32) {
- *p = x
-}
-
-// Get gets the value pointed at by p.
-func word32Val_Get(p word32Val) uint32 {
- return *p
-}
-
-// Word32Val returns the address of a *int32, *uint32, *float32, or *enum field in the struct.
-func structPointer_Word32Val(p structPointer, f field) word32Val {
- return word32Val((*uint32)(unsafe.Pointer(uintptr(p) + uintptr(f))))
-}
-
-// A word32Slice is a slice of 32-bit values.
-type word32Slice []uint32
-
-func (v *word32Slice) Append(x uint32) { *v = append(*v, x) }
-func (v *word32Slice) Len() int { return len(*v) }
-func (v *word32Slice) Index(i int) uint32 { return (*v)[i] }
-
-// Word32Slice returns the address of a []int32, []uint32, []float32, or []enum field in the struct.
-func structPointer_Word32Slice(p structPointer, f field) *word32Slice {
- return (*word32Slice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
-}
-
-// word64 is like word32 but for 64-bit values.
-type word64 **uint64
-
-func word64_Set(p word64, o *Buffer, x uint64) {
- if len(o.uint64s) == 0 {
- o.uint64s = make([]uint64, uint64PoolSize)
- }
- o.uint64s[0] = x
- *p = &o.uint64s[0]
- o.uint64s = o.uint64s[1:]
-}
-
-func word64_IsNil(p word64) bool {
- return *p == nil
-}
-
-func word64_Get(p word64) uint64 {
- return **p
-}
-
-func structPointer_Word64(p structPointer, f field) word64 {
- return word64((**uint64)(unsafe.Pointer(uintptr(p) + uintptr(f))))
-}
-
-// word64Val is like word32Val but for 64-bit values.
-type word64Val *uint64
-
-func word64Val_Set(p word64Val, o *Buffer, x uint64) {
- *p = x
-}
-
-func word64Val_Get(p word64Val) uint64 {
- return *p
-}
-
-func structPointer_Word64Val(p structPointer, f field) word64Val {
- return word64Val((*uint64)(unsafe.Pointer(uintptr(p) + uintptr(f))))
-}
-
-// word64Slice is like word32Slice but for 64-bit values.
-type word64Slice []uint64
-
-func (v *word64Slice) Append(x uint64) { *v = append(*v, x) }
-func (v *word64Slice) Len() int { return len(*v) }
-func (v *word64Slice) Index(i int) uint64 { return (*v)[i] }
-
-func structPointer_Word64Slice(p structPointer, f field) *word64Slice {
- return (*word64Slice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
-}
diff --git a/containerd/vendor/github.com/golang/protobuf/proto/properties.go b/containerd/vendor/github.com/golang/protobuf/proto/properties.go
deleted file mode 100644
index 7216544..0000000
--- a/containerd/vendor/github.com/golang/protobuf/proto/properties.go
+++ /dev/null
@@ -1,737 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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
-// OWNER 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.
-
-package proto
-
-/*
- * Routines for encoding data into the wire format for protocol buffers.
- */
-
-import (
- "fmt"
- "os"
- "reflect"
- "sort"
- "strconv"
- "strings"
- "sync"
-)
-
-const debug bool = false
-
-// Constants that identify the encoding of a value on the wire.
-const (
- WireVarint = 0
- WireFixed64 = 1
- WireBytes = 2
- WireStartGroup = 3
- WireEndGroup = 4
- WireFixed32 = 5
-)
-
-const startSize = 10 // initial slice/string sizes
-
-// Encoders are defined in encode.go
-// An encoder outputs the full representation of a field, including its
-// tag and encoder type.
-type encoder func(p *Buffer, prop *Properties, base structPointer) error
-
-// A valueEncoder encodes a single integer in a particular encoding.
-type valueEncoder func(o *Buffer, x uint64) error
-
-// Sizers are defined in encode.go
-// A sizer returns the encoded size of a field, including its tag and encoder
-// type.
-type sizer func(prop *Properties, base structPointer) int
-
-// A valueSizer returns the encoded size of a single integer in a particular
-// encoding.
-type valueSizer func(x uint64) int
-
-// Decoders are defined in decode.go
-// A decoder creates a value from its wire representation.
-// Unrecognized subelements are saved in unrec.
-type decoder func(p *Buffer, prop *Properties, base structPointer) error
-
-// A valueDecoder decodes a single integer in a particular encoding.
-type valueDecoder func(o *Buffer) (x uint64, err error)
-
-// tagMap is an optimization over map[int]int for typical protocol buffer
-// use-cases. Encoded protocol buffers are often in tag order with small tag
-// numbers.
-type tagMap struct {
- fastTags []int
- slowTags map[int]int
-}
-
-// tagMapFastLimit is the upper bound on the tag number that will be stored in
-// the tagMap slice rather than its map.
-const tagMapFastLimit = 1024
-
-func (p *tagMap) get(t int) (int, bool) {
- if t > 0 && t < tagMapFastLimit {
- if t >= len(p.fastTags) {
- return 0, false
- }
- fi := p.fastTags[t]
- return fi, fi >= 0
- }
- fi, ok := p.slowTags[t]
- return fi, ok
-}
-
-func (p *tagMap) put(t int, fi int) {
- if t > 0 && t < tagMapFastLimit {
- for len(p.fastTags) < t+1 {
- p.fastTags = append(p.fastTags, -1)
- }
- p.fastTags[t] = fi
- return
- }
- if p.slowTags == nil {
- p.slowTags = make(map[int]int)
- }
- p.slowTags[t] = fi
-}
-
-// StructProperties represents properties for all the fields of a struct.
-// decoderTags and decoderOrigNames should only be used by the decoder.
-type StructProperties struct {
- Prop []*Properties // properties for each field
- reqCount int // required count
- decoderTags tagMap // map from proto tag to struct field number
- decoderOrigNames map[string]int // map from original name to struct field number
- order []int // list of struct field numbers in tag order
- unrecField field // field id of the XXX_unrecognized []byte field
- extendable bool // is this an extendable proto
-}
-
-// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec.
-// See encode.go, (*Buffer).enc_struct.
-
-func (sp *StructProperties) Len() int { return len(sp.order) }
-func (sp *StructProperties) Less(i, j int) bool {
- return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag
-}
-func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] }
-
-// Properties represents the protocol-specific behavior of a single struct field.
-type Properties struct {
- Name string // name of the field, for error messages
- OrigName string // original name before protocol compiler (always set)
- Wire string
- WireType int
- Tag int
- Required bool
- Optional bool
- Repeated bool
- Packed bool // relevant for repeated primitives only
- Enum string // set for enum types only
- proto3 bool // whether this is known to be a proto3 field; set for []byte only
-
- Default string // default value
- HasDefault bool // whether an explicit default was provided
- def_uint64 uint64
-
- enc encoder
- valEnc valueEncoder // set for bool and numeric types only
- field field
- tagcode []byte // encoding of EncodeVarint((Tag<<3)|WireType)
- tagbuf [8]byte
- stype reflect.Type // set for struct types only
- sprop *StructProperties // set for struct types only
- isMarshaler bool
- isUnmarshaler bool
-
- mtype reflect.Type // set for map types only
- mkeyprop *Properties // set for map types only
- mvalprop *Properties // set for map types only
-
- size sizer
- valSize valueSizer // set for bool and numeric types only
-
- dec decoder
- valDec valueDecoder // set for bool and numeric types only
-
- // If this is a packable field, this will be the decoder for the packed version of the field.
- packedDec decoder
-}
-
-// String formats the properties in the protobuf struct field tag style.
-func (p *Properties) String() string {
- s := p.Wire
- s = ","
- s += strconv.Itoa(p.Tag)
- if p.Required {
- s += ",req"
- }
- if p.Optional {
- s += ",opt"
- }
- if p.Repeated {
- s += ",rep"
- }
- if p.Packed {
- s += ",packed"
- }
- if p.OrigName != p.Name {
- s += ",name=" + p.OrigName
- }
- if p.proto3 {
- s += ",proto3"
- }
- if len(p.Enum) > 0 {
- s += ",enum=" + p.Enum
- }
- if p.HasDefault {
- s += ",def=" + p.Default
- }
- return s
-}
-
-// Parse populates p by parsing a string in the protobuf struct field tag style.
-func (p *Properties) Parse(s string) {
- // "bytes,49,opt,name=foo,def=hello!"
- fields := strings.Split(s, ",") // breaks def=, but handled below.
- if len(fields) < 2 {
- fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s)
- return
- }
-
- p.Wire = fields[0]
- switch p.Wire {
- case "varint":
- p.WireType = WireVarint
- p.valEnc = (*Buffer).EncodeVarint
- p.valDec = (*Buffer).DecodeVarint
- p.valSize = sizeVarint
- case "fixed32":
- p.WireType = WireFixed32
- p.valEnc = (*Buffer).EncodeFixed32
- p.valDec = (*Buffer).DecodeFixed32
- p.valSize = sizeFixed32
- case "fixed64":
- p.WireType = WireFixed64
- p.valEnc = (*Buffer).EncodeFixed64
- p.valDec = (*Buffer).DecodeFixed64
- p.valSize = sizeFixed64
- case "zigzag32":
- p.WireType = WireVarint
- p.valEnc = (*Buffer).EncodeZigzag32
- p.valDec = (*Buffer).DecodeZigzag32
- p.valSize = sizeZigzag32
- case "zigzag64":
- p.WireType = WireVarint
- p.valEnc = (*Buffer).EncodeZigzag64
- p.valDec = (*Buffer).DecodeZigzag64
- p.valSize = sizeZigzag64
- case "bytes", "group":
- p.WireType = WireBytes
- // no numeric converter for non-numeric types
- default:
- fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s)
- return
- }
-
- var err error
- p.Tag, err = strconv.Atoi(fields[1])
- if err != nil {
- return
- }
-
- for i := 2; i < len(fields); i++ {
- f := fields[i]
- switch {
- case f == "req":
- p.Required = true
- case f == "opt":
- p.Optional = true
- case f == "rep":
- p.Repeated = true
- case f == "packed":
- p.Packed = true
- case strings.HasPrefix(f, "name="):
- p.OrigName = f[5:]
- case strings.HasPrefix(f, "enum="):
- p.Enum = f[5:]
- case f == "proto3":
- p.proto3 = true
- case strings.HasPrefix(f, "def="):
- p.HasDefault = true
- p.Default = f[4:] // rest of string
- if i+1 < len(fields) {
- // Commas aren't escaped, and def is always last.
- p.Default += "," + strings.Join(fields[i+1:], ",")
- break
- }
- }
- }
-}
-
-func logNoSliceEnc(t1, t2 reflect.Type) {
- fmt.Fprintf(os.Stderr, "proto: no slice oenc for %T = []%T\n", t1, t2)
-}
-
-var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem()
-
-// Initialize the fields for encoding and decoding.
-func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lockGetProp bool) {
- p.enc = nil
- p.dec = nil
- p.size = nil
-
- switch t1 := typ; t1.Kind() {
- default:
- fmt.Fprintf(os.Stderr, "proto: no coders for %v\n", t1)
-
- // proto3 scalar types
-
- case reflect.Bool:
- p.enc = (*Buffer).enc_proto3_bool
- p.dec = (*Buffer).dec_proto3_bool
- p.size = size_proto3_bool
- case reflect.Int32:
- p.enc = (*Buffer).enc_proto3_int32
- p.dec = (*Buffer).dec_proto3_int32
- p.size = size_proto3_int32
- case reflect.Uint32:
- p.enc = (*Buffer).enc_proto3_uint32
- p.dec = (*Buffer).dec_proto3_int32 // can reuse
- p.size = size_proto3_uint32
- case reflect.Int64, reflect.Uint64:
- p.enc = (*Buffer).enc_proto3_int64
- p.dec = (*Buffer).dec_proto3_int64
- p.size = size_proto3_int64
- case reflect.Float32:
- p.enc = (*Buffer).enc_proto3_uint32 // can just treat them as bits
- p.dec = (*Buffer).dec_proto3_int32
- p.size = size_proto3_uint32
- case reflect.Float64:
- p.enc = (*Buffer).enc_proto3_int64 // can just treat them as bits
- p.dec = (*Buffer).dec_proto3_int64
- p.size = size_proto3_int64
- case reflect.String:
- p.enc = (*Buffer).enc_proto3_string
- p.dec = (*Buffer).dec_proto3_string
- p.size = size_proto3_string
-
- case reflect.Ptr:
- switch t2 := t1.Elem(); t2.Kind() {
- default:
- fmt.Fprintf(os.Stderr, "proto: no encoder function for %v -> %v\n", t1, t2)
- break
- case reflect.Bool:
- p.enc = (*Buffer).enc_bool
- p.dec = (*Buffer).dec_bool
- p.size = size_bool
- case reflect.Int32:
- p.enc = (*Buffer).enc_int32
- p.dec = (*Buffer).dec_int32
- p.size = size_int32
- case reflect.Uint32:
- p.enc = (*Buffer).enc_uint32
- p.dec = (*Buffer).dec_int32 // can reuse
- p.size = size_uint32
- case reflect.Int64, reflect.Uint64:
- p.enc = (*Buffer).enc_int64
- p.dec = (*Buffer).dec_int64
- p.size = size_int64
- case reflect.Float32:
- p.enc = (*Buffer).enc_uint32 // can just treat them as bits
- p.dec = (*Buffer).dec_int32
- p.size = size_uint32
- case reflect.Float64:
- p.enc = (*Buffer).enc_int64 // can just treat them as bits
- p.dec = (*Buffer).dec_int64
- p.size = size_int64
- case reflect.String:
- p.enc = (*Buffer).enc_string
- p.dec = (*Buffer).dec_string
- p.size = size_string
- case reflect.Struct:
- p.stype = t1.Elem()
- p.isMarshaler = isMarshaler(t1)
- p.isUnmarshaler = isUnmarshaler(t1)
- if p.Wire == "bytes" {
- p.enc = (*Buffer).enc_struct_message
- p.dec = (*Buffer).dec_struct_message
- p.size = size_struct_message
- } else {
- p.enc = (*Buffer).enc_struct_group
- p.dec = (*Buffer).dec_struct_group
- p.size = size_struct_group
- }
- }
-
- case reflect.Slice:
- switch t2 := t1.Elem(); t2.Kind() {
- default:
- logNoSliceEnc(t1, t2)
- break
- case reflect.Bool:
- if p.Packed {
- p.enc = (*Buffer).enc_slice_packed_bool
- p.size = size_slice_packed_bool
- } else {
- p.enc = (*Buffer).enc_slice_bool
- p.size = size_slice_bool
- }
- p.dec = (*Buffer).dec_slice_bool
- p.packedDec = (*Buffer).dec_slice_packed_bool
- case reflect.Int32:
- if p.Packed {
- p.enc = (*Buffer).enc_slice_packed_int32
- p.size = size_slice_packed_int32
- } else {
- p.enc = (*Buffer).enc_slice_int32
- p.size = size_slice_int32
- }
- p.dec = (*Buffer).dec_slice_int32
- p.packedDec = (*Buffer).dec_slice_packed_int32
- case reflect.Uint32:
- if p.Packed {
- p.enc = (*Buffer).enc_slice_packed_uint32
- p.size = size_slice_packed_uint32
- } else {
- p.enc = (*Buffer).enc_slice_uint32
- p.size = size_slice_uint32
- }
- p.dec = (*Buffer).dec_slice_int32
- p.packedDec = (*Buffer).dec_slice_packed_int32
- case reflect.Int64, reflect.Uint64:
- if p.Packed {
- p.enc = (*Buffer).enc_slice_packed_int64
- p.size = size_slice_packed_int64
- } else {
- p.enc = (*Buffer).enc_slice_int64
- p.size = size_slice_int64
- }
- p.dec = (*Buffer).dec_slice_int64
- p.packedDec = (*Buffer).dec_slice_packed_int64
- case reflect.Uint8:
- p.enc = (*Buffer).enc_slice_byte
- p.dec = (*Buffer).dec_slice_byte
- p.size = size_slice_byte
- if p.proto3 {
- p.enc = (*Buffer).enc_proto3_slice_byte
- p.size = size_proto3_slice_byte
- }
- case reflect.Float32, reflect.Float64:
- switch t2.Bits() {
- case 32:
- // can just treat them as bits
- if p.Packed {
- p.enc = (*Buffer).enc_slice_packed_uint32
- p.size = size_slice_packed_uint32
- } else {
- p.enc = (*Buffer).enc_slice_uint32
- p.size = size_slice_uint32
- }
- p.dec = (*Buffer).dec_slice_int32
- p.packedDec = (*Buffer).dec_slice_packed_int32
- case 64:
- // can just treat them as bits
- if p.Packed {
- p.enc = (*Buffer).enc_slice_packed_int64
- p.size = size_slice_packed_int64
- } else {
- p.enc = (*Buffer).enc_slice_int64
- p.size = size_slice_int64
- }
- p.dec = (*Buffer).dec_slice_int64
- p.packedDec = (*Buffer).dec_slice_packed_int64
- default:
- logNoSliceEnc(t1, t2)
- break
- }
- case reflect.String:
- p.enc = (*Buffer).enc_slice_string
- p.dec = (*Buffer).dec_slice_string
- p.size = size_slice_string
- case reflect.Ptr:
- switch t3 := t2.Elem(); t3.Kind() {
- default:
- fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3)
- break
- case reflect.Struct:
- p.stype = t2.Elem()
- p.isMarshaler = isMarshaler(t2)
- p.isUnmarshaler = isUnmarshaler(t2)
- if p.Wire == "bytes" {
- p.enc = (*Buffer).enc_slice_struct_message
- p.dec = (*Buffer).dec_slice_struct_message
- p.size = size_slice_struct_message
- } else {
- p.enc = (*Buffer).enc_slice_struct_group
- p.dec = (*Buffer).dec_slice_struct_group
- p.size = size_slice_struct_group
- }
- }
- case reflect.Slice:
- switch t2.Elem().Kind() {
- default:
- fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem())
- break
- case reflect.Uint8:
- p.enc = (*Buffer).enc_slice_slice_byte
- p.dec = (*Buffer).dec_slice_slice_byte
- p.size = size_slice_slice_byte
- }
- }
-
- case reflect.Map:
- p.enc = (*Buffer).enc_new_map
- p.dec = (*Buffer).dec_new_map
- p.size = size_new_map
-
- p.mtype = t1
- p.mkeyprop = &Properties{}
- p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp)
- p.mvalprop = &Properties{}
- vtype := p.mtype.Elem()
- if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice {
- // The value type is not a message (*T) or bytes ([]byte),
- // so we need encoders for the pointer to this type.
- vtype = reflect.PtrTo(vtype)
- }
- p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp)
- }
-
- // precalculate tag code
- wire := p.WireType
- if p.Packed {
- wire = WireBytes
- }
- x := uint32(p.Tag)<<3 | uint32(wire)
- i := 0
- for i = 0; x > 127; i++ {
- p.tagbuf[i] = 0x80 | uint8(x&0x7F)
- x >>= 7
- }
- p.tagbuf[i] = uint8(x)
- p.tagcode = p.tagbuf[0 : i+1]
-
- if p.stype != nil {
- if lockGetProp {
- p.sprop = GetProperties(p.stype)
- } else {
- p.sprop = getPropertiesLocked(p.stype)
- }
- }
-}
-
-var (
- marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
- unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
-)
-
-// isMarshaler reports whether type t implements Marshaler.
-func isMarshaler(t reflect.Type) bool {
- // We're checking for (likely) pointer-receiver methods
- // so if t is not a pointer, something is very wrong.
- // The calls above only invoke isMarshaler on pointer types.
- if t.Kind() != reflect.Ptr {
- panic("proto: misuse of isMarshaler")
- }
- return t.Implements(marshalerType)
-}
-
-// isUnmarshaler reports whether type t implements Unmarshaler.
-func isUnmarshaler(t reflect.Type) bool {
- // We're checking for (likely) pointer-receiver methods
- // so if t is not a pointer, something is very wrong.
- // The calls above only invoke isUnmarshaler on pointer types.
- if t.Kind() != reflect.Ptr {
- panic("proto: misuse of isUnmarshaler")
- }
- return t.Implements(unmarshalerType)
-}
-
-// Init populates the properties from a protocol buffer struct tag.
-func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) {
- p.init(typ, name, tag, f, true)
-}
-
-func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) {
- // "bytes,49,opt,def=hello!"
- p.Name = name
- p.OrigName = name
- if f != nil {
- p.field = toField(f)
- }
- if tag == "" {
- return
- }
- p.Parse(tag)
- p.setEncAndDec(typ, f, lockGetProp)
-}
-
-var (
- propertiesMu sync.RWMutex
- propertiesMap = make(map[reflect.Type]*StructProperties)
-)
-
-// GetProperties returns the list of properties for the type represented by t.
-// t must represent a generated struct type of a protocol message.
-func GetProperties(t reflect.Type) *StructProperties {
- if t.Kind() != reflect.Struct {
- panic("proto: type must have kind struct")
- }
-
- // Most calls to GetProperties in a long-running program will be
- // retrieving details for types we have seen before.
- propertiesMu.RLock()
- sprop, ok := propertiesMap[t]
- propertiesMu.RUnlock()
- if ok {
- if collectStats {
- stats.Chit++
- }
- return sprop
- }
-
- propertiesMu.Lock()
- sprop = getPropertiesLocked(t)
- propertiesMu.Unlock()
- return sprop
-}
-
-// getPropertiesLocked requires that propertiesMu is held.
-func getPropertiesLocked(t reflect.Type) *StructProperties {
- if prop, ok := propertiesMap[t]; ok {
- if collectStats {
- stats.Chit++
- }
- return prop
- }
- if collectStats {
- stats.Cmiss++
- }
-
- prop := new(StructProperties)
- // in case of recursive protos, fill this in now.
- propertiesMap[t] = prop
-
- // build properties
- prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType)
- prop.unrecField = invalidField
- prop.Prop = make([]*Properties, t.NumField())
- prop.order = make([]int, t.NumField())
-
- for i := 0; i < t.NumField(); i++ {
- f := t.Field(i)
- p := new(Properties)
- name := f.Name
- p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false)
-
- if f.Name == "XXX_extensions" { // special case
- p.enc = (*Buffer).enc_map
- p.dec = nil // not needed
- p.size = size_map
- }
- if f.Name == "XXX_unrecognized" { // special case
- prop.unrecField = toField(&f)
- }
- prop.Prop[i] = p
- prop.order[i] = i
- if debug {
- print(i, " ", f.Name, " ", t.String(), " ")
- if p.Tag > 0 {
- print(p.String())
- }
- print("\n")
- }
- if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") {
- fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]")
- }
- }
-
- // Re-order prop.order.
- sort.Sort(prop)
-
- // build required counts
- // build tags
- reqCount := 0
- prop.decoderOrigNames = make(map[string]int)
- for i, p := range prop.Prop {
- if strings.HasPrefix(p.Name, "XXX_") {
- // Internal fields should not appear in tags/origNames maps.
- // They are handled specially when encoding and decoding.
- continue
- }
- if p.Required {
- reqCount++
- }
- prop.decoderTags.put(p.Tag, i)
- prop.decoderOrigNames[p.OrigName] = i
- }
- prop.reqCount = reqCount
-
- return prop
-}
-
-// Return the Properties object for the x[0]'th field of the structure.
-func propByIndex(t reflect.Type, x []int) *Properties {
- if len(x) != 1 {
- fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t)
- return nil
- }
- prop := GetProperties(t)
- return prop.Prop[x[0]]
-}
-
-// Get the address and type of a pointer to a struct from an interface.
-func getbase(pb Message) (t reflect.Type, b structPointer, err error) {
- if pb == nil {
- err = ErrNil
- return
- }
- // get the reflect type of the pointer to the struct.
- t = reflect.TypeOf(pb)
- // get the address of the struct.
- value := reflect.ValueOf(pb)
- b = toStructPointer(value)
- return
-}
-
-// A global registry of enum types.
-// The generated code will register the generated maps by calling RegisterEnum.
-
-var enumValueMaps = make(map[string]map[string]int32)
-
-// RegisterEnum is called from the generated code to install the enum descriptor
-// maps into the global table to aid parsing text format protocol buffers.
-func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) {
- if _, ok := enumValueMaps[typeName]; ok {
- panic("proto: duplicate enum registered: " + typeName)
- }
- enumValueMaps[typeName] = valueMap
-}
diff --git a/containerd/vendor/github.com/golang/protobuf/proto/proto3_proto/Makefile b/containerd/vendor/github.com/golang/protobuf/proto/proto3_proto/Makefile
deleted file mode 100644
index 75144b5..0000000
--- a/containerd/vendor/github.com/golang/protobuf/proto/proto3_proto/Makefile
+++ /dev/null
@@ -1,44 +0,0 @@
-# Go support for Protocol Buffers - Google's data interchange format
-#
-# Copyright 2014 The Go Authors. All rights reserved.
-# https://github.com/golang/protobuf
-#
-# 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 Google Inc. 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
-# OWNER 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.
-
-
-include ../../Make.protobuf
-
-all: regenerate
-
-regenerate:
- rm -f proto3.pb.go
- make proto3.pb.go
-
-# The following rules are just aids to development. Not needed for typical testing.
-
-diff: regenerate
- git diff proto3.pb.go
diff --git a/containerd/vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.proto b/containerd/vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.proto
deleted file mode 100644
index 3e327de..0000000
--- a/containerd/vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.proto
+++ /dev/null
@@ -1,58 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2014 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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
-// OWNER 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.
-
-syntax = "proto3";
-
-package proto3_proto;
-
-message Message {
- enum Humour {
- UNKNOWN = 0;
- PUNS = 1;
- SLAPSTICK = 2;
- BILL_BAILEY = 3;
- }
-
- string name = 1;
- Humour hilarity = 2;
- uint32 height_in_cm = 3;
- bytes data = 4;
- int64 result_count = 7;
- bool true_scotsman = 8;
- float score = 9;
-
- repeated uint64 key = 5;
- Nested nested = 6;
-}
-
-message Nested {
- string bunny = 1;
-}
diff --git a/containerd/vendor/github.com/golang/protobuf/proto/text.go b/containerd/vendor/github.com/golang/protobuf/proto/text.go
deleted file mode 100644
index 720eac4..0000000
--- a/containerd/vendor/github.com/golang/protobuf/proto/text.go
+++ /dev/null
@@ -1,789 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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
-// OWNER 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.
-
-package proto
-
-// Functions for writing the text protocol buffer format.
-
-import (
- "bufio"
- "bytes"
- "encoding"
- "fmt"
- "io"
- "log"
- "math"
- "os"
- "reflect"
- "sort"
- "strings"
-)
-
-var (
- newline = []byte("\n")
- spaces = []byte(" ")
- gtNewline = []byte(">\n")
- endBraceNewline = []byte("}\n")
- backslashN = []byte{'\\', 'n'}
- backslashR = []byte{'\\', 'r'}
- backslashT = []byte{'\\', 't'}
- backslashDQ = []byte{'\\', '"'}
- backslashBS = []byte{'\\', '\\'}
- posInf = []byte("inf")
- negInf = []byte("-inf")
- nan = []byte("nan")
-)
-
-type writer interface {
- io.Writer
- WriteByte(byte) error
-}
-
-// textWriter is an io.Writer that tracks its indentation level.
-type textWriter struct {
- ind int
- complete bool // if the current position is a complete line
- compact bool // whether to write out as a one-liner
- w writer
-}
-
-func (w *textWriter) WriteString(s string) (n int, err error) {
- if !strings.Contains(s, "\n") {
- if !w.compact && w.complete {
- w.writeIndent()
- }
- w.complete = false
- return io.WriteString(w.w, s)
- }
- // WriteString is typically called without newlines, so this
- // codepath and its copy are rare. We copy to avoid
- // duplicating all of Write's logic here.
- return w.Write([]byte(s))
-}
-
-func (w *textWriter) Write(p []byte) (n int, err error) {
- newlines := bytes.Count(p, newline)
- if newlines == 0 {
- if !w.compact && w.complete {
- w.writeIndent()
- }
- n, err = w.w.Write(p)
- w.complete = false
- return n, err
- }
-
- frags := bytes.SplitN(p, newline, newlines+1)
- if w.compact {
- for i, frag := range frags {
- if i > 0 {
- if err := w.w.WriteByte(' '); err != nil {
- return n, err
- }
- n++
- }
- nn, err := w.w.Write(frag)
- n += nn
- if err != nil {
- return n, err
- }
- }
- return n, nil
- }
-
- for i, frag := range frags {
- if w.complete {
- w.writeIndent()
- }
- nn, err := w.w.Write(frag)
- n += nn
- if err != nil {
- return n, err
- }
- if i+1 < len(frags) {
- if err := w.w.WriteByte('\n'); err != nil {
- return n, err
- }
- n++
- }
- }
- w.complete = len(frags[len(frags)-1]) == 0
- return n, nil
-}
-
-func (w *textWriter) WriteByte(c byte) error {
- if w.compact && c == '\n' {
- c = ' '
- }
- if !w.compact && w.complete {
- w.writeIndent()
- }
- err := w.w.WriteByte(c)
- w.complete = c == '\n'
- return err
-}
-
-func (w *textWriter) indent() { w.ind++ }
-
-func (w *textWriter) unindent() {
- if w.ind == 0 {
- log.Printf("proto: textWriter unindented too far")
- return
- }
- w.ind--
-}
-
-func writeName(w *textWriter, props *Properties) error {
- if _, err := w.WriteString(props.OrigName); err != nil {
- return err
- }
- if props.Wire != "group" {
- return w.WriteByte(':')
- }
- return nil
-}
-
-var (
- messageSetType = reflect.TypeOf((*MessageSet)(nil)).Elem()
-)
-
-// raw is the interface satisfied by RawMessage.
-type raw interface {
- Bytes() []byte
-}
-
-func writeStruct(w *textWriter, sv reflect.Value) error {
- if sv.Type() == messageSetType {
- return writeMessageSet(w, sv.Addr().Interface().(*MessageSet))
- }
-
- st := sv.Type()
- sprops := GetProperties(st)
- for i := 0; i < sv.NumField(); i++ {
- fv := sv.Field(i)
- props := sprops.Prop[i]
- name := st.Field(i).Name
-
- if strings.HasPrefix(name, "XXX_") {
- // There are two XXX_ fields:
- // XXX_unrecognized []byte
- // XXX_extensions map[int32]proto.Extension
- // The first is handled here;
- // the second is handled at the bottom of this function.
- if name == "XXX_unrecognized" && !fv.IsNil() {
- if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil {
- return err
- }
- }
- continue
- }
- if fv.Kind() == reflect.Ptr && fv.IsNil() {
- // Field not filled in. This could be an optional field or
- // a required field that wasn't filled in. Either way, there
- // isn't anything we can show for it.
- continue
- }
- if fv.Kind() == reflect.Slice && fv.IsNil() {
- // Repeated field that is empty, or a bytes field that is unused.
- continue
- }
-
- if props.Repeated && fv.Kind() == reflect.Slice {
- // Repeated field.
- for j := 0; j < fv.Len(); j++ {
- if err := writeName(w, props); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- v := fv.Index(j)
- if v.Kind() == reflect.Ptr && v.IsNil() {
- // A nil message in a repeated field is not valid,
- // but we can handle that more gracefully than panicking.
- if _, err := w.Write([]byte("\n")); err != nil {
- return err
- }
- continue
- }
- if err := writeAny(w, v, props); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- continue
- }
- if fv.Kind() == reflect.Map {
- // Map fields are rendered as a repeated struct with key/value fields.
- keys := fv.MapKeys() // TODO: should we sort these for deterministic output?
- sort.Sort(mapKeys(keys))
- for _, key := range keys {
- val := fv.MapIndex(key)
- if err := writeName(w, props); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- // open struct
- if err := w.WriteByte('<'); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- w.indent()
- // key
- if _, err := w.WriteString("key:"); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- if err := writeAny(w, key, props.mkeyprop); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- // value
- if _, err := w.WriteString("value:"); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- if err := writeAny(w, val, props.mvalprop); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- // close struct
- w.unindent()
- if err := w.WriteByte('>'); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- continue
- }
- if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 {
- // empty bytes field
- continue
- }
- if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice {
- // proto3 non-repeated scalar field; skip if zero value
- switch fv.Kind() {
- case reflect.Bool:
- if !fv.Bool() {
- continue
- }
- case reflect.Int32, reflect.Int64:
- if fv.Int() == 0 {
- continue
- }
- case reflect.Uint32, reflect.Uint64:
- if fv.Uint() == 0 {
- continue
- }
- case reflect.Float32, reflect.Float64:
- if fv.Float() == 0 {
- continue
- }
- case reflect.String:
- if fv.String() == "" {
- continue
- }
- }
- }
-
- if err := writeName(w, props); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- if b, ok := fv.Interface().(raw); ok {
- if err := writeRaw(w, b.Bytes()); err != nil {
- return err
- }
- continue
- }
-
- // Enums have a String method, so writeAny will work fine.
- if err := writeAny(w, fv, props); err != nil {
- return err
- }
-
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
-
- // Extensions (the XXX_extensions field).
- pv := sv.Addr()
- if pv.Type().Implements(extendableProtoType) {
- if err := writeExtensions(w, pv); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-// writeRaw writes an uninterpreted raw message.
-func writeRaw(w *textWriter, b []byte) error {
- if err := w.WriteByte('<'); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- w.indent()
- if err := writeUnknownStruct(w, b); err != nil {
- return err
- }
- w.unindent()
- if err := w.WriteByte('>'); err != nil {
- return err
- }
- return nil
-}
-
-// writeAny writes an arbitrary field.
-func writeAny(w *textWriter, v reflect.Value, props *Properties) error {
- v = reflect.Indirect(v)
-
- // Floats have special cases.
- if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
- x := v.Float()
- var b []byte
- switch {
- case math.IsInf(x, 1):
- b = posInf
- case math.IsInf(x, -1):
- b = negInf
- case math.IsNaN(x):
- b = nan
- }
- if b != nil {
- _, err := w.Write(b)
- return err
- }
- // Other values are handled below.
- }
-
- // We don't attempt to serialise every possible value type; only those
- // that can occur in protocol buffers.
- switch v.Kind() {
- case reflect.Slice:
- // Should only be a []byte; repeated fields are handled in writeStruct.
- if err := writeString(w, string(v.Interface().([]byte))); err != nil {
- return err
- }
- case reflect.String:
- if err := writeString(w, v.String()); err != nil {
- return err
- }
- case reflect.Struct:
- // Required/optional group/message.
- var bra, ket byte = '<', '>'
- if props != nil && props.Wire == "group" {
- bra, ket = '{', '}'
- }
- if err := w.WriteByte(bra); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- w.indent()
- if tm, ok := v.Interface().(encoding.TextMarshaler); ok {
- text, err := tm.MarshalText()
- if err != nil {
- return err
- }
- if _, err = w.Write(text); err != nil {
- return err
- }
- } else if err := writeStruct(w, v); err != nil {
- return err
- }
- w.unindent()
- if err := w.WriteByte(ket); err != nil {
- return err
- }
- default:
- _, err := fmt.Fprint(w, v.Interface())
- return err
- }
- return nil
-}
-
-// equivalent to C's isprint.
-func isprint(c byte) bool {
- return c >= 0x20 && c < 0x7f
-}
-
-// writeString writes a string in the protocol buffer text format.
-// It is similar to strconv.Quote except we don't use Go escape sequences,
-// we treat the string as a byte sequence, and we use octal escapes.
-// These differences are to maintain interoperability with the other
-// languages' implementations of the text format.
-func writeString(w *textWriter, s string) error {
- // use WriteByte here to get any needed indent
- if err := w.WriteByte('"'); err != nil {
- return err
- }
- // Loop over the bytes, not the runes.
- for i := 0; i < len(s); i++ {
- var err error
- // Divergence from C++: we don't escape apostrophes.
- // There's no need to escape them, and the C++ parser
- // copes with a naked apostrophe.
- switch c := s[i]; c {
- case '\n':
- _, err = w.w.Write(backslashN)
- case '\r':
- _, err = w.w.Write(backslashR)
- case '\t':
- _, err = w.w.Write(backslashT)
- case '"':
- _, err = w.w.Write(backslashDQ)
- case '\\':
- _, err = w.w.Write(backslashBS)
- default:
- if isprint(c) {
- err = w.w.WriteByte(c)
- } else {
- _, err = fmt.Fprintf(w.w, "\\%03o", c)
- }
- }
- if err != nil {
- return err
- }
- }
- return w.WriteByte('"')
-}
-
-func writeMessageSet(w *textWriter, ms *MessageSet) error {
- for _, item := range ms.Item {
- id := *item.TypeId
- if msd, ok := messageSetMap[id]; ok {
- // Known message set type.
- if _, err := fmt.Fprintf(w, "[%s]: <\n", msd.name); err != nil {
- return err
- }
- w.indent()
-
- pb := reflect.New(msd.t.Elem())
- if err := Unmarshal(item.Message, pb.Interface().(Message)); err != nil {
- if _, err := fmt.Fprintf(w, "/* bad message: %v */\n", err); err != nil {
- return err
- }
- } else {
- if err := writeStruct(w, pb.Elem()); err != nil {
- return err
- }
- }
- } else {
- // Unknown type.
- if _, err := fmt.Fprintf(w, "[%d]: <\n", id); err != nil {
- return err
- }
- w.indent()
- if err := writeUnknownStruct(w, item.Message); err != nil {
- return err
- }
- }
- w.unindent()
- if _, err := w.Write(gtNewline); err != nil {
- return err
- }
- }
- return nil
-}
-
-func writeUnknownStruct(w *textWriter, data []byte) (err error) {
- if !w.compact {
- if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
- return err
- }
- }
- b := NewBuffer(data)
- for b.index < len(b.buf) {
- x, err := b.DecodeVarint()
- if err != nil {
- _, err := fmt.Fprintf(w, "/* %v */\n", err)
- return err
- }
- wire, tag := x&7, x>>3
- if wire == WireEndGroup {
- w.unindent()
- if _, err := w.Write(endBraceNewline); err != nil {
- return err
- }
- continue
- }
- if _, err := fmt.Fprint(w, tag); err != nil {
- return err
- }
- if wire != WireStartGroup {
- if err := w.WriteByte(':'); err != nil {
- return err
- }
- }
- if !w.compact || wire == WireStartGroup {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- switch wire {
- case WireBytes:
- buf, e := b.DecodeRawBytes(false)
- if e == nil {
- _, err = fmt.Fprintf(w, "%q", buf)
- } else {
- _, err = fmt.Fprintf(w, "/* %v */", e)
- }
- case WireFixed32:
- x, err = b.DecodeFixed32()
- err = writeUnknownInt(w, x, err)
- case WireFixed64:
- x, err = b.DecodeFixed64()
- err = writeUnknownInt(w, x, err)
- case WireStartGroup:
- err = w.WriteByte('{')
- w.indent()
- case WireVarint:
- x, err = b.DecodeVarint()
- err = writeUnknownInt(w, x, err)
- default:
- _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire)
- }
- if err != nil {
- return err
- }
- if err = w.WriteByte('\n'); err != nil {
- return err
- }
- }
- return nil
-}
-
-func writeUnknownInt(w *textWriter, x uint64, err error) error {
- if err == nil {
- _, err = fmt.Fprint(w, x)
- } else {
- _, err = fmt.Fprintf(w, "/* %v */", err)
- }
- return err
-}
-
-type int32Slice []int32
-
-func (s int32Slice) Len() int { return len(s) }
-func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
-func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
-
-// writeExtensions writes all the extensions in pv.
-// pv is assumed to be a pointer to a protocol message struct that is extendable.
-func writeExtensions(w *textWriter, pv reflect.Value) error {
- emap := extensionMaps[pv.Type().Elem()]
- ep := pv.Interface().(extendableProto)
-
- // Order the extensions by ID.
- // This isn't strictly necessary, but it will give us
- // canonical output, which will also make testing easier.
- m := ep.ExtensionMap()
- ids := make([]int32, 0, len(m))
- for id := range m {
- ids = append(ids, id)
- }
- sort.Sort(int32Slice(ids))
-
- for _, extNum := range ids {
- ext := m[extNum]
- var desc *ExtensionDesc
- if emap != nil {
- desc = emap[extNum]
- }
- if desc == nil {
- // Unknown extension.
- if err := writeUnknownStruct(w, ext.enc); err != nil {
- return err
- }
- continue
- }
-
- pb, err := GetExtension(ep, desc)
- if err != nil {
- if _, err := fmt.Fprintln(os.Stderr, "proto: failed getting extension: ", err); err != nil {
- return err
- }
- continue
- }
-
- // Repeated extensions will appear as a slice.
- if !desc.repeated() {
- if err := writeExtension(w, desc.Name, pb); err != nil {
- return err
- }
- } else {
- v := reflect.ValueOf(pb)
- for i := 0; i < v.Len(); i++ {
- if err := writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
- return err
- }
- }
- }
- }
- return nil
-}
-
-func writeExtension(w *textWriter, name string, pb interface{}) error {
- if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- if err := writeAny(w, reflect.ValueOf(pb), nil); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- return nil
-}
-
-func (w *textWriter) writeIndent() {
- if !w.complete {
- return
- }
- remain := w.ind * 2
- for remain > 0 {
- n := remain
- if n > len(spaces) {
- n = len(spaces)
- }
- w.w.Write(spaces[:n])
- remain -= n
- }
- w.complete = false
-}
-
-func marshalText(w io.Writer, pb Message, compact bool) error {
- val := reflect.ValueOf(pb)
- if pb == nil || val.IsNil() {
- w.Write([]byte(""))
- return nil
- }
- var bw *bufio.Writer
- ww, ok := w.(writer)
- if !ok {
- bw = bufio.NewWriter(w)
- ww = bw
- }
- aw := &textWriter{
- w: ww,
- complete: true,
- compact: compact,
- }
-
- if tm, ok := pb.(encoding.TextMarshaler); ok {
- text, err := tm.MarshalText()
- if err != nil {
- return err
- }
- if _, err = aw.Write(text); err != nil {
- return err
- }
- if bw != nil {
- return bw.Flush()
- }
- return nil
- }
- // Dereference the received pointer so we don't have outer < and >.
- v := reflect.Indirect(val)
- if err := writeStruct(aw, v); err != nil {
- return err
- }
- if bw != nil {
- return bw.Flush()
- }
- return nil
-}
-
-// MarshalText writes a given protocol buffer in text format.
-// The only errors returned are from w.
-func MarshalText(w io.Writer, pb Message) error {
- return marshalText(w, pb, false)
-}
-
-// MarshalTextString is the same as MarshalText, but returns the string directly.
-func MarshalTextString(pb Message) string {
- var buf bytes.Buffer
- marshalText(&buf, pb, false)
- return buf.String()
-}
-
-// CompactText writes a given protocol buffer in compact text format (one line).
-func CompactText(w io.Writer, pb Message) error { return marshalText(w, pb, true) }
-
-// CompactTextString is the same as CompactText, but returns the string directly.
-func CompactTextString(pb Message) string {
- var buf bytes.Buffer
- marshalText(&buf, pb, true)
- return buf.String()
-}
diff --git a/containerd/vendor/github.com/golang/protobuf/proto/text_parser.go b/containerd/vendor/github.com/golang/protobuf/proto/text_parser.go
deleted file mode 100644
index d1caeff..0000000
--- a/containerd/vendor/github.com/golang/protobuf/proto/text_parser.go
+++ /dev/null
@@ -1,757 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// 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 Google Inc. 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
-// OWNER 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.
-
-package proto
-
-// Functions for parsing the Text protocol buffer format.
-// TODO: message sets.
-
-import (
- "encoding"
- "errors"
- "fmt"
- "reflect"
- "strconv"
- "strings"
- "unicode/utf8"
-)
-
-type ParseError struct {
- Message string
- Line int // 1-based line number
- Offset int // 0-based byte offset from start of input
-}
-
-func (p *ParseError) Error() string {
- if p.Line == 1 {
- // show offset only for first line
- return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
- }
- return fmt.Sprintf("line %d: %v", p.Line, p.Message)
-}
-
-type token struct {
- value string
- err *ParseError
- line int // line number
- offset int // byte number from start of input, not start of line
- unquoted string // the unquoted version of value, if it was a quoted string
-}
-
-func (t *token) String() string {
- if t.err == nil {
- return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
- }
- return fmt.Sprintf("parse error: %v", t.err)
-}
-
-type textParser struct {
- s string // remaining input
- done bool // whether the parsing is finished (success or error)
- backed bool // whether back() was called
- offset, line int
- cur token
-}
-
-func newTextParser(s string) *textParser {
- p := new(textParser)
- p.s = s
- p.line = 1
- p.cur.line = 1
- return p
-}
-
-func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
- pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
- p.cur.err = pe
- p.done = true
- return pe
-}
-
-// Numbers and identifiers are matched by [-+._A-Za-z0-9]
-func isIdentOrNumberChar(c byte) bool {
- switch {
- case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
- return true
- case '0' <= c && c <= '9':
- return true
- }
- switch c {
- case '-', '+', '.', '_':
- return true
- }
- return false
-}
-
-func isWhitespace(c byte) bool {
- switch c {
- case ' ', '\t', '\n', '\r':
- return true
- }
- return false
-}
-
-func (p *textParser) skipWhitespace() {
- i := 0
- for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
- if p.s[i] == '#' {
- // comment; skip to end of line or input
- for i < len(p.s) && p.s[i] != '\n' {
- i++
- }
- if i == len(p.s) {
- break
- }
- }
- if p.s[i] == '\n' {
- p.line++
- }
- i++
- }
- p.offset += i
- p.s = p.s[i:len(p.s)]
- if len(p.s) == 0 {
- p.done = true
- }
-}
-
-func (p *textParser) advance() {
- // Skip whitespace
- p.skipWhitespace()
- if p.done {
- return
- }
-
- // Start of non-whitespace
- p.cur.err = nil
- p.cur.offset, p.cur.line = p.offset, p.line
- p.cur.unquoted = ""
- switch p.s[0] {
- case '<', '>', '{', '}', ':', '[', ']', ';', ',':
- // Single symbol
- p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
- case '"', '\'':
- // Quoted string
- i := 1
- for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' {
- if p.s[i] == '\\' && i+1 < len(p.s) {
- // skip escaped char
- i++
- }
- i++
- }
- if i >= len(p.s) || p.s[i] != p.s[0] {
- p.errorf("unmatched quote")
- return
- }
- unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
- if err != nil {
- p.errorf("invalid quoted string %v", p.s[0:i+1])
- return
- }
- p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
- p.cur.unquoted = unq
- default:
- i := 0
- for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
- i++
- }
- if i == 0 {
- p.errorf("unexpected byte %#x", p.s[0])
- return
- }
- p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
- }
- p.offset += len(p.cur.value)
-}
-
-var (
- errBadUTF8 = errors.New("proto: bad UTF-8")
- errBadHex = errors.New("proto: bad hexadecimal")
-)
-
-func unquoteC(s string, quote rune) (string, error) {
- // This is based on C++'s tokenizer.cc.
- // Despite its name, this is *not* parsing C syntax.
- // For instance, "\0" is an invalid quoted string.
-
- // Avoid allocation in trivial cases.
- simple := true
- for _, r := range s {
- if r == '\\' || r == quote {
- simple = false
- break
- }
- }
- if simple {
- return s, nil
- }
-
- buf := make([]byte, 0, 3*len(s)/2)
- for len(s) > 0 {
- r, n := utf8.DecodeRuneInString(s)
- if r == utf8.RuneError && n == 1 {
- return "", errBadUTF8
- }
- s = s[n:]
- if r != '\\' {
- if r < utf8.RuneSelf {
- buf = append(buf, byte(r))
- } else {
- buf = append(buf, string(r)...)
- }
- continue
- }
-
- ch, tail, err := unescape(s)
- if err != nil {
- return "", err
- }
- buf = append(buf, ch...)
- s = tail
- }
- return string(buf), nil
-}
-
-func unescape(s string) (ch string, tail string, err error) {
- r, n := utf8.DecodeRuneInString(s)
- if r == utf8.RuneError && n == 1 {
- return "", "", errBadUTF8
- }
- s = s[n:]
- switch r {
- case 'a':
- return "\a", s, nil
- case 'b':
- return "\b", s, nil
- case 'f':
- return "\f", s, nil
- case 'n':
- return "\n", s, nil
- case 'r':
- return "\r", s, nil
- case 't':
- return "\t", s, nil
- case 'v':
- return "\v", s, nil
- case '?':
- return "?", s, nil // trigraph workaround
- case '\'', '"', '\\':
- return string(r), s, nil
- case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X':
- if len(s) < 2 {
- return "", "", fmt.Errorf(`\%c requires 2 following digits`, r)
- }
- base := 8
- ss := s[:2]
- s = s[2:]
- if r == 'x' || r == 'X' {
- base = 16
- } else {
- ss = string(r) + ss
- }
- i, err := strconv.ParseUint(ss, base, 8)
- if err != nil {
- return "", "", err
- }
- return string([]byte{byte(i)}), s, nil
- case 'u', 'U':
- n := 4
- if r == 'U' {
- n = 8
- }
- if len(s) < n {
- return "", "", fmt.Errorf(`\%c requires %d digits`, r, n)
- }
-
- bs := make([]byte, n/2)
- for i := 0; i < n; i += 2 {
- a, ok1 := unhex(s[i])
- b, ok2 := unhex(s[i+1])
- if !ok1 || !ok2 {
- return "", "", errBadHex
- }
- bs[i/2] = a<<4 | b
- }
- s = s[n:]
- return string(bs), s, nil
- }
- return "", "", fmt.Errorf(`unknown escape \%c`, r)
-}
-
-// Adapted from src/pkg/strconv/quote.go.
-func unhex(b byte) (v byte, ok bool) {
- switch {
- case '0' <= b && b <= '9':
- return b - '0', true
- case 'a' <= b && b <= 'f':
- return b - 'a' + 10, true
- case 'A' <= b && b <= 'F':
- return b - 'A' + 10, true
- }
- return 0, false
-}
-
-// Back off the parser by one token. Can only be done between calls to next().
-// It makes the next advance() a no-op.
-func (p *textParser) back() { p.backed = true }
-
-// Advances the parser and returns the new current token.
-func (p *textParser) next() *token {
- if p.backed || p.done {
- p.backed = false
- return &p.cur
- }
- p.advance()
- if p.done {
- p.cur.value = ""
- } else if len(p.cur.value) > 0 && p.cur.value[0] == '"' {
- // Look for multiple quoted strings separated by whitespace,
- // and concatenate them.
- cat := p.cur
- for {
- p.skipWhitespace()
- if p.done || p.s[0] != '"' {
- break
- }
- p.advance()
- if p.cur.err != nil {
- return &p.cur
- }
- cat.value += " " + p.cur.value
- cat.unquoted += p.cur.unquoted
- }
- p.done = false // parser may have seen EOF, but we want to return cat
- p.cur = cat
- }
- return &p.cur
-}
-
-func (p *textParser) consumeToken(s string) error {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value != s {
- p.back()
- return p.errorf("expected %q, found %q", s, tok.value)
- }
- return nil
-}
-
-// Return a RequiredNotSetError indicating which required field was not set.
-func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError {
- st := sv.Type()
- sprops := GetProperties(st)
- for i := 0; i < st.NumField(); i++ {
- if !isNil(sv.Field(i)) {
- continue
- }
-
- props := sprops.Prop[i]
- if props.Required {
- return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)}
- }
- }
- return &RequiredNotSetError{fmt.Sprintf("%v.", st)} // should not happen
-}
-
-// Returns the index in the struct for the named field, as well as the parsed tag properties.
-func structFieldByName(st reflect.Type, name string) (int, *Properties, bool) {
- sprops := GetProperties(st)
- i, ok := sprops.decoderOrigNames[name]
- if ok {
- return i, sprops.Prop[i], true
- }
- return -1, nil, false
-}
-
-// Consume a ':' from the input stream (if the next token is a colon),
-// returning an error if a colon is needed but not present.
-func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value != ":" {
- // Colon is optional when the field is a group or message.
- needColon := true
- switch props.Wire {
- case "group":
- needColon = false
- case "bytes":
- // A "bytes" field is either a message, a string, or a repeated field;
- // those three become *T, *string and []T respectively, so we can check for
- // this field being a pointer to a non-string.
- if typ.Kind() == reflect.Ptr {
- // *T or *string
- if typ.Elem().Kind() == reflect.String {
- break
- }
- } else if typ.Kind() == reflect.Slice {
- // []T or []*T
- if typ.Elem().Kind() != reflect.Ptr {
- break
- }
- } else if typ.Kind() == reflect.String {
- // The proto3 exception is for a string field,
- // which requires a colon.
- break
- }
- needColon = false
- }
- if needColon {
- return p.errorf("expected ':', found %q", tok.value)
- }
- p.back()
- }
- return nil
-}
-
-func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
- st := sv.Type()
- reqCount := GetProperties(st).reqCount
- var reqFieldErr error
- fieldSet := make(map[string]bool)
- // A struct is a sequence of "name: value", terminated by one of
- // '>' or '}', or the end of the input. A name may also be
- // "[extension]".
- for {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value == terminator {
- break
- }
- if tok.value == "[" {
- // Looks like an extension.
- //
- // TODO: Check whether we need to handle
- // namespace rooted names (e.g. ".something.Foo").
- tok = p.next()
- if tok.err != nil {
- return tok.err
- }
- var desc *ExtensionDesc
- // This could be faster, but it's functional.
- // TODO: Do something smarter than a linear scan.
- for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
- if d.Name == tok.value {
- desc = d
- break
- }
- }
- if desc == nil {
- return p.errorf("unrecognized extension %q", tok.value)
- }
- // Check the extension terminator.
- tok = p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value != "]" {
- return p.errorf("unrecognized extension terminator %q", tok.value)
- }
-
- props := &Properties{}
- props.Parse(desc.Tag)
-
- typ := reflect.TypeOf(desc.ExtensionType)
- if err := p.checkForColon(props, typ); err != nil {
- return err
- }
-
- rep := desc.repeated()
-
- // Read the extension structure, and set it in
- // the value we're constructing.
- var ext reflect.Value
- if !rep {
- ext = reflect.New(typ).Elem()
- } else {
- ext = reflect.New(typ.Elem()).Elem()
- }
- if err := p.readAny(ext, props); err != nil {
- if _, ok := err.(*RequiredNotSetError); !ok {
- return err
- }
- reqFieldErr = err
- }
- ep := sv.Addr().Interface().(extendableProto)
- if !rep {
- SetExtension(ep, desc, ext.Interface())
- } else {
- old, err := GetExtension(ep, desc)
- var sl reflect.Value
- if err == nil {
- sl = reflect.ValueOf(old) // existing slice
- } else {
- sl = reflect.MakeSlice(typ, 0, 1)
- }
- sl = reflect.Append(sl, ext)
- SetExtension(ep, desc, sl.Interface())
- }
- } else {
- // This is a normal, non-extension field.
- name := tok.value
- fi, props, ok := structFieldByName(st, name)
- if !ok {
- return p.errorf("unknown field name %q in %v", name, st)
- }
-
- dst := sv.Field(fi)
-
- if dst.Kind() == reflect.Map {
- // Consume any colon.
- if err := p.checkForColon(props, dst.Type()); err != nil {
- return err
- }
-
- // Construct the map if it doesn't already exist.
- if dst.IsNil() {
- dst.Set(reflect.MakeMap(dst.Type()))
- }
- key := reflect.New(dst.Type().Key()).Elem()
- val := reflect.New(dst.Type().Elem()).Elem()
-
- // The map entry should be this sequence of tokens:
- // < key : KEY value : VALUE >
- // Technically the "key" and "value" could come in any order,
- // but in practice they won't.
-
- tok := p.next()
- var terminator string
- switch tok.value {
- case "<":
- terminator = ">"
- case "{":
- terminator = "}"
- default:
- return p.errorf("expected '{' or '<', found %q", tok.value)
- }
- if err := p.consumeToken("key"); err != nil {
- return err
- }
- if err := p.consumeToken(":"); err != nil {
- return err
- }
- if err := p.readAny(key, props.mkeyprop); err != nil {
- return err
- }
- if err := p.consumeToken("value"); err != nil {
- return err
- }
- if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil {
- return err
- }
- if err := p.readAny(val, props.mvalprop); err != nil {
- return err
- }
- if err := p.consumeToken(terminator); err != nil {
- return err
- }
-
- dst.SetMapIndex(key, val)
- continue
- }
-
- // Check that it's not already set if it's not a repeated field.
- if !props.Repeated && fieldSet[name] {
- return p.errorf("non-repeated field %q was repeated", name)
- }
-
- if err := p.checkForColon(props, st.Field(fi).Type); err != nil {
- return err
- }
-
- // Parse into the field.
- fieldSet[name] = true
- if err := p.readAny(dst, props); err != nil {
- if _, ok := err.(*RequiredNotSetError); !ok {
- return err
- }
- reqFieldErr = err
- } else if props.Required {
- reqCount--
- }
- }
-
- // For backward compatibility, permit a semicolon or comma after a field.
- tok = p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value != ";" && tok.value != "," {
- p.back()
- }
- }
-
- if reqCount > 0 {
- return p.missingRequiredFieldError(sv)
- }
- return reqFieldErr
-}
-
-func (p *textParser) readAny(v reflect.Value, props *Properties) error {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value == "" {
- return p.errorf("unexpected EOF")
- }
-
- switch fv := v; fv.Kind() {
- case reflect.Slice:
- at := v.Type()
- if at.Elem().Kind() == reflect.Uint8 {
- // Special case for []byte
- if tok.value[0] != '"' && tok.value[0] != '\'' {
- // Deliberately written out here, as the error after
- // this switch statement would write "invalid []byte: ...",
- // which is not as user-friendly.
- return p.errorf("invalid string: %v", tok.value)
- }
- bytes := []byte(tok.unquoted)
- fv.Set(reflect.ValueOf(bytes))
- return nil
- }
- // Repeated field. May already exist.
- flen := fv.Len()
- if flen == fv.Cap() {
- nav := reflect.MakeSlice(at, flen, 2*flen+1)
- reflect.Copy(nav, fv)
- fv.Set(nav)
- }
- fv.SetLen(flen + 1)
-
- // Read one.
- p.back()
- return p.readAny(fv.Index(flen), props)
- case reflect.Bool:
- // Either "true", "false", 1 or 0.
- switch tok.value {
- case "true", "1":
- fv.SetBool(true)
- return nil
- case "false", "0":
- fv.SetBool(false)
- return nil
- }
- case reflect.Float32, reflect.Float64:
- v := tok.value
- // Ignore 'f' for compatibility with output generated by C++, but don't
- // remove 'f' when the value is "-inf" or "inf".
- if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
- v = v[:len(v)-1]
- }
- if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
- fv.SetFloat(f)
- return nil
- }
- case reflect.Int32:
- if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
- fv.SetInt(x)
- return nil
- }
-
- if len(props.Enum) == 0 {
- break
- }
- m, ok := enumValueMaps[props.Enum]
- if !ok {
- break
- }
- x, ok := m[tok.value]
- if !ok {
- break
- }
- fv.SetInt(int64(x))
- return nil
- case reflect.Int64:
- if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
- fv.SetInt(x)
- return nil
- }
-
- case reflect.Ptr:
- // A basic field (indirected through pointer), or a repeated message/group
- p.back()
- fv.Set(reflect.New(fv.Type().Elem()))
- return p.readAny(fv.Elem(), props)
- case reflect.String:
- if tok.value[0] == '"' || tok.value[0] == '\'' {
- fv.SetString(tok.unquoted)
- return nil
- }
- case reflect.Struct:
- var terminator string
- switch tok.value {
- case "{":
- terminator = "}"
- case "<":
- terminator = ">"
- default:
- return p.errorf("expected '{' or '<', found %q", tok.value)
- }
- // TODO: Handle nested messages which implement encoding.TextUnmarshaler.
- return p.readStruct(fv, terminator)
- case reflect.Uint32:
- if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
- fv.SetUint(uint64(x))
- return nil
- }
- case reflect.Uint64:
- if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
- fv.SetUint(x)
- return nil
- }
- }
- return p.errorf("invalid %v: %v", v.Type(), tok.value)
-}
-
-// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb
-// before starting to unmarshal, so any existing data in pb is always removed.
-// If a required field is not set and no other error occurs,
-// UnmarshalText returns *RequiredNotSetError.
-func UnmarshalText(s string, pb Message) error {
- if um, ok := pb.(encoding.TextUnmarshaler); ok {
- err := um.UnmarshalText([]byte(s))
- return err
- }
- pb.Reset()
- v := reflect.ValueOf(pb)
- if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil {
- return pe
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/gorilla/context/.travis.yml b/containerd/vendor/github.com/gorilla/context/.travis.yml
deleted file mode 100644
index 6796581..0000000
--- a/containerd/vendor/github.com/gorilla/context/.travis.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-language: go
-
-go:
- - 1.0
- - 1.1
- - 1.2
- - 1.3
- - 1.4
- - tip
diff --git a/containerd/vendor/github.com/gorilla/context/LICENSE b/containerd/vendor/github.com/gorilla/context/LICENSE
deleted file mode 100644
index 0e5fb87..0000000
--- a/containerd/vendor/github.com/gorilla/context/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2012 Rodrigo Moraes. 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 Google Inc. 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
-OWNER 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.
diff --git a/containerd/vendor/github.com/gorilla/context/README.md b/containerd/vendor/github.com/gorilla/context/README.md
deleted file mode 100644
index c60a31b..0000000
--- a/containerd/vendor/github.com/gorilla/context/README.md
+++ /dev/null
@@ -1,7 +0,0 @@
-context
-=======
-[![Build Status](https://travis-ci.org/gorilla/context.png?branch=master)](https://travis-ci.org/gorilla/context)
-
-gorilla/context is a general purpose registry for global request variables.
-
-Read the full documentation here: http://www.gorillatoolkit.org/pkg/context
diff --git a/containerd/vendor/github.com/gorilla/context/context.go b/containerd/vendor/github.com/gorilla/context/context.go
deleted file mode 100644
index 81cb128..0000000
--- a/containerd/vendor/github.com/gorilla/context/context.go
+++ /dev/null
@@ -1,143 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package context
-
-import (
- "net/http"
- "sync"
- "time"
-)
-
-var (
- mutex sync.RWMutex
- data = make(map[*http.Request]map[interface{}]interface{})
- datat = make(map[*http.Request]int64)
-)
-
-// Set stores a value for a given key in a given request.
-func Set(r *http.Request, key, val interface{}) {
- mutex.Lock()
- if data[r] == nil {
- data[r] = make(map[interface{}]interface{})
- datat[r] = time.Now().Unix()
- }
- data[r][key] = val
- mutex.Unlock()
-}
-
-// Get returns a value stored for a given key in a given request.
-func Get(r *http.Request, key interface{}) interface{} {
- mutex.RLock()
- if ctx := data[r]; ctx != nil {
- value := ctx[key]
- mutex.RUnlock()
- return value
- }
- mutex.RUnlock()
- return nil
-}
-
-// GetOk returns stored value and presence state like multi-value return of map access.
-func GetOk(r *http.Request, key interface{}) (interface{}, bool) {
- mutex.RLock()
- if _, ok := data[r]; ok {
- value, ok := data[r][key]
- mutex.RUnlock()
- return value, ok
- }
- mutex.RUnlock()
- return nil, false
-}
-
-// GetAll returns all stored values for the request as a map. Nil is returned for invalid requests.
-func GetAll(r *http.Request) map[interface{}]interface{} {
- mutex.RLock()
- if context, ok := data[r]; ok {
- result := make(map[interface{}]interface{}, len(context))
- for k, v := range context {
- result[k] = v
- }
- mutex.RUnlock()
- return result
- }
- mutex.RUnlock()
- return nil
-}
-
-// GetAllOk returns all stored values for the request as a map and a boolean value that indicates if
-// the request was registered.
-func GetAllOk(r *http.Request) (map[interface{}]interface{}, bool) {
- mutex.RLock()
- context, ok := data[r]
- result := make(map[interface{}]interface{}, len(context))
- for k, v := range context {
- result[k] = v
- }
- mutex.RUnlock()
- return result, ok
-}
-
-// Delete removes a value stored for a given key in a given request.
-func Delete(r *http.Request, key interface{}) {
- mutex.Lock()
- if data[r] != nil {
- delete(data[r], key)
- }
- mutex.Unlock()
-}
-
-// Clear removes all values stored for a given request.
-//
-// This is usually called by a handler wrapper to clean up request
-// variables at the end of a request lifetime. See ClearHandler().
-func Clear(r *http.Request) {
- mutex.Lock()
- clear(r)
- mutex.Unlock()
-}
-
-// clear is Clear without the lock.
-func clear(r *http.Request) {
- delete(data, r)
- delete(datat, r)
-}
-
-// Purge removes request data stored for longer than maxAge, in seconds.
-// It returns the amount of requests removed.
-//
-// If maxAge <= 0, all request data is removed.
-//
-// This is only used for sanity check: in case context cleaning was not
-// properly set some request data can be kept forever, consuming an increasing
-// amount of memory. In case this is detected, Purge() must be called
-// periodically until the problem is fixed.
-func Purge(maxAge int) int {
- mutex.Lock()
- count := 0
- if maxAge <= 0 {
- count = len(data)
- data = make(map[*http.Request]map[interface{}]interface{})
- datat = make(map[*http.Request]int64)
- } else {
- min := time.Now().Unix() - int64(maxAge)
- for r := range data {
- if datat[r] < min {
- clear(r)
- count++
- }
- }
- }
- mutex.Unlock()
- return count
-}
-
-// ClearHandler wraps an http.Handler and clears request values at the end
-// of a request lifetime.
-func ClearHandler(h http.Handler) http.Handler {
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- defer Clear(r)
- h.ServeHTTP(w, r)
- })
-}
diff --git a/containerd/vendor/github.com/gorilla/context/doc.go b/containerd/vendor/github.com/gorilla/context/doc.go
deleted file mode 100644
index 73c7400..0000000
--- a/containerd/vendor/github.com/gorilla/context/doc.go
+++ /dev/null
@@ -1,82 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-/*
-Package context stores values shared during a request lifetime.
-
-For example, a router can set variables extracted from the URL and later
-application handlers can access those values, or it can be used to store
-sessions values to be saved at the end of a request. There are several
-others common uses.
-
-The idea was posted by Brad Fitzpatrick to the go-nuts mailing list:
-
- http://groups.google.com/group/golang-nuts/msg/e2d679d303aa5d53
-
-Here's the basic usage: first define the keys that you will need. The key
-type is interface{} so a key can be of any type that supports equality.
-Here we define a key using a custom int type to avoid name collisions:
-
- package foo
-
- import (
- "github.com/gorilla/context"
- )
-
- type key int
-
- const MyKey key = 0
-
-Then set a variable. Variables are bound to an http.Request object, so you
-need a request instance to set a value:
-
- context.Set(r, MyKey, "bar")
-
-The application can later access the variable using the same key you provided:
-
- func MyHandler(w http.ResponseWriter, r *http.Request) {
- // val is "bar".
- val := context.Get(r, foo.MyKey)
-
- // returns ("bar", true)
- val, ok := context.GetOk(r, foo.MyKey)
- // ...
- }
-
-And that's all about the basic usage. We discuss some other ideas below.
-
-Any type can be stored in the context. To enforce a given type, make the key
-private and wrap Get() and Set() to accept and return values of a specific
-type:
-
- type key int
-
- const mykey key = 0
-
- // GetMyKey returns a value for this package from the request values.
- func GetMyKey(r *http.Request) SomeType {
- if rv := context.Get(r, mykey); rv != nil {
- return rv.(SomeType)
- }
- return nil
- }
-
- // SetMyKey sets a value for this package in the request values.
- func SetMyKey(r *http.Request, val SomeType) {
- context.Set(r, mykey, val)
- }
-
-Variables must be cleared at the end of a request, to remove all values
-that were stored. This can be done in an http.Handler, after a request was
-served. Just call Clear() passing the request:
-
- context.Clear(r)
-
-...or use ClearHandler(), which conveniently wraps an http.Handler to clear
-variables at the end of a request lifetime.
-
-The Routers from the packages gorilla/mux and gorilla/pat call Clear()
-so if you are using either of them you don't need to clear the context manually.
-*/
-package context
diff --git a/containerd/vendor/github.com/gorilla/mux/.travis.yml b/containerd/vendor/github.com/gorilla/mux/.travis.yml
deleted file mode 100644
index f983b60..0000000
--- a/containerd/vendor/github.com/gorilla/mux/.travis.yml
+++ /dev/null
@@ -1,8 +0,0 @@
-language: go
-sudo: false
-
-go:
- - 1.3
- - 1.4
- - 1.5
- - tip
diff --git a/containerd/vendor/github.com/gorilla/mux/LICENSE b/containerd/vendor/github.com/gorilla/mux/LICENSE
deleted file mode 100644
index 0e5fb87..0000000
--- a/containerd/vendor/github.com/gorilla/mux/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2012 Rodrigo Moraes. 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 Google Inc. 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
-OWNER 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.
diff --git a/containerd/vendor/github.com/gorilla/mux/README.md b/containerd/vendor/github.com/gorilla/mux/README.md
deleted file mode 100644
index 55dd4e5..0000000
--- a/containerd/vendor/github.com/gorilla/mux/README.md
+++ /dev/null
@@ -1,235 +0,0 @@
-mux
-===
-[![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux)
-[![Build Status](https://travis-ci.org/gorilla/mux.png?branch=master)](https://travis-ci.org/gorilla/mux)
-
-Package gorilla/mux implements a request router and dispatcher.
-
-The name mux stands for "HTTP request multiplexer". Like the standard
-http.ServeMux, mux.Router matches incoming requests against a list of
-registered routes and calls a handler for the route that matches the URL
-or other conditions. The main features are:
-
- * Requests can be matched based on URL host, path, path prefix, schemes,
- header and query values, HTTP methods or using custom matchers.
- * URL hosts and paths can have variables with an optional regular
- expression.
- * Registered URLs can be built, or "reversed", which helps maintaining
- references to resources.
- * Routes can be used as subrouters: nested routes are only tested if the
- parent route matches. This is useful to define groups of routes that
- share common conditions like a host, a path prefix or other repeated
- attributes. As a bonus, this optimizes request matching.
- * It implements the http.Handler interface so it is compatible with the
- standard http.ServeMux.
-
-Let's start registering a couple of URL paths and handlers:
-
- func main() {
- r := mux.NewRouter()
- r.HandleFunc("/", HomeHandler)
- r.HandleFunc("/products", ProductsHandler)
- r.HandleFunc("/articles", ArticlesHandler)
- http.Handle("/", r)
- }
-
-Here we register three routes mapping URL paths to handlers. This is
-equivalent to how http.HandleFunc() works: if an incoming request URL matches
-one of the paths, the corresponding handler is called passing
-(http.ResponseWriter, *http.Request) as parameters.
-
-Paths can have variables. They are defined using the format {name} or
-{name:pattern}. If a regular expression pattern is not defined, the matched
-variable will be anything until the next slash. For example:
-
- r := mux.NewRouter()
- r.HandleFunc("/products/{key}", ProductHandler)
- r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
- r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
-
-The names are used to create a map of route variables which can be retrieved
-calling mux.Vars():
-
- vars := mux.Vars(request)
- category := vars["category"]
-
-And this is all you need to know about the basic usage. More advanced options
-are explained below.
-
-Routes can also be restricted to a domain or subdomain. Just define a host
-pattern to be matched. They can also have variables:
-
- r := mux.NewRouter()
- // Only matches if domain is "www.example.com".
- r.Host("www.example.com")
- // Matches a dynamic subdomain.
- r.Host("{subdomain:[a-z]+}.domain.com")
-
-There are several other matchers that can be added. To match path prefixes:
-
- r.PathPrefix("/products/")
-
-...or HTTP methods:
-
- r.Methods("GET", "POST")
-
-...or URL schemes:
-
- r.Schemes("https")
-
-...or header values:
-
- r.Headers("X-Requested-With", "XMLHttpRequest")
-
-...or query values:
-
- r.Queries("key", "value")
-
-...or to use a custom matcher function:
-
- r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
- return r.ProtoMajor == 0
- })
-
-...and finally, it is possible to combine several matchers in a single route:
-
- r.HandleFunc("/products", ProductsHandler).
- Host("www.example.com").
- Methods("GET").
- Schemes("http")
-
-Setting the same matching conditions again and again can be boring, so we have
-a way to group several routes that share the same requirements.
-We call it "subrouting".
-
-For example, let's say we have several URLs that should only match when the
-host is `www.example.com`. Create a route for that host and get a "subrouter"
-from it:
-
- r := mux.NewRouter()
- s := r.Host("www.example.com").Subrouter()
-
-Then register routes in the subrouter:
-
- s.HandleFunc("/products/", ProductsHandler)
- s.HandleFunc("/products/{key}", ProductHandler)
- s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
-
-The three URL paths we registered above will only be tested if the domain is
-`www.example.com`, because the subrouter is tested first. This is not
-only convenient, but also optimizes request matching. You can create
-subrouters combining any attribute matchers accepted by a route.
-
-Subrouters can be used to create domain or path "namespaces": you define
-subrouters in a central place and then parts of the app can register its
-paths relatively to a given subrouter.
-
-There's one more thing about subroutes. When a subrouter has a path prefix,
-the inner routes use it as base for their paths:
-
- r := mux.NewRouter()
- s := r.PathPrefix("/products").Subrouter()
- // "/products/"
- s.HandleFunc("/", ProductsHandler)
- // "/products/{key}/"
- s.HandleFunc("/{key}/", ProductHandler)
- // "/products/{key}/details"
- s.HandleFunc("/{key}/details", ProductDetailsHandler)
-
-Now let's see how to build registered URLs.
-
-Routes can be named. All routes that define a name can have their URLs built,
-or "reversed". We define a name calling Name() on a route. For example:
-
- r := mux.NewRouter()
- r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
- Name("article")
-
-To build a URL, get the route and call the URL() method, passing a sequence of
-key/value pairs for the route variables. For the previous route, we would do:
-
- url, err := r.Get("article").URL("category", "technology", "id", "42")
-
-...and the result will be a url.URL with the following path:
-
- "/articles/technology/42"
-
-This also works for host variables:
-
- r := mux.NewRouter()
- r.Host("{subdomain}.domain.com").
- Path("/articles/{category}/{id:[0-9]+}").
- HandlerFunc(ArticleHandler).
- Name("article")
-
- // url.String() will be "http://news.domain.com/articles/technology/42"
- url, err := r.Get("article").URL("subdomain", "news",
- "category", "technology",
- "id", "42")
-
-All variables defined in the route are required, and their values must
-conform to the corresponding patterns. These requirements guarantee that a
-generated URL will always match a registered route -- the only exception is
-for explicitly defined "build-only" routes which never match.
-
-Regex support also exists for matching Headers within a route. For example, we could do:
-
- r.HeadersRegexp("Content-Type", "application/(text|json)")
-
-...and the route will match both requests with a Content-Type of `application/json` as well as
-`application/text`
-
-There's also a way to build only the URL host or path for a route:
-use the methods URLHost() or URLPath() instead. For the previous route,
-we would do:
-
- // "http://news.domain.com/"
- host, err := r.Get("article").URLHost("subdomain", "news")
-
- // "/articles/technology/42"
- path, err := r.Get("article").URLPath("category", "technology", "id", "42")
-
-And if you use subrouters, host and path defined separately can be built
-as well:
-
- r := mux.NewRouter()
- s := r.Host("{subdomain}.domain.com").Subrouter()
- s.Path("/articles/{category}/{id:[0-9]+}").
- HandlerFunc(ArticleHandler).
- Name("article")
-
- // "http://news.domain.com/articles/technology/42"
- url, err := r.Get("article").URL("subdomain", "news",
- "category", "technology",
- "id", "42")
-
-## Full Example
-
-Here's a complete, runnable example of a small mux based server:
-
-```go
-package main
-
-import (
- "net/http"
-
- "github.com/gorilla/mux"
-)
-
-func YourHandler(w http.ResponseWriter, r *http.Request) {
- w.Write([]byte("Gorilla!\n"))
-}
-
-func main() {
- r := mux.NewRouter()
- // Routes consist of a path and a handler function.
- r.HandleFunc("/", YourHandler)
-
- // Bind to a port and pass our router in
- http.ListenAndServe(":8000", r)
-}
-```
-
-## License
-
-BSD licensed. See the LICENSE file for details.
diff --git a/containerd/vendor/github.com/gorilla/mux/doc.go b/containerd/vendor/github.com/gorilla/mux/doc.go
deleted file mode 100644
index 49798cb..0000000
--- a/containerd/vendor/github.com/gorilla/mux/doc.go
+++ /dev/null
@@ -1,206 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-/*
-Package gorilla/mux implements a request router and dispatcher.
-
-The name mux stands for "HTTP request multiplexer". Like the standard
-http.ServeMux, mux.Router matches incoming requests against a list of
-registered routes and calls a handler for the route that matches the URL
-or other conditions. The main features are:
-
- * Requests can be matched based on URL host, path, path prefix, schemes,
- header and query values, HTTP methods or using custom matchers.
- * URL hosts and paths can have variables with an optional regular
- expression.
- * Registered URLs can be built, or "reversed", which helps maintaining
- references to resources.
- * Routes can be used as subrouters: nested routes are only tested if the
- parent route matches. This is useful to define groups of routes that
- share common conditions like a host, a path prefix or other repeated
- attributes. As a bonus, this optimizes request matching.
- * It implements the http.Handler interface so it is compatible with the
- standard http.ServeMux.
-
-Let's start registering a couple of URL paths and handlers:
-
- func main() {
- r := mux.NewRouter()
- r.HandleFunc("/", HomeHandler)
- r.HandleFunc("/products", ProductsHandler)
- r.HandleFunc("/articles", ArticlesHandler)
- http.Handle("/", r)
- }
-
-Here we register three routes mapping URL paths to handlers. This is
-equivalent to how http.HandleFunc() works: if an incoming request URL matches
-one of the paths, the corresponding handler is called passing
-(http.ResponseWriter, *http.Request) as parameters.
-
-Paths can have variables. They are defined using the format {name} or
-{name:pattern}. If a regular expression pattern is not defined, the matched
-variable will be anything until the next slash. For example:
-
- r := mux.NewRouter()
- r.HandleFunc("/products/{key}", ProductHandler)
- r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
- r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
-
-The names are used to create a map of route variables which can be retrieved
-calling mux.Vars():
-
- vars := mux.Vars(request)
- category := vars["category"]
-
-And this is all you need to know about the basic usage. More advanced options
-are explained below.
-
-Routes can also be restricted to a domain or subdomain. Just define a host
-pattern to be matched. They can also have variables:
-
- r := mux.NewRouter()
- // Only matches if domain is "www.example.com".
- r.Host("www.example.com")
- // Matches a dynamic subdomain.
- r.Host("{subdomain:[a-z]+}.domain.com")
-
-There are several other matchers that can be added. To match path prefixes:
-
- r.PathPrefix("/products/")
-
-...or HTTP methods:
-
- r.Methods("GET", "POST")
-
-...or URL schemes:
-
- r.Schemes("https")
-
-...or header values:
-
- r.Headers("X-Requested-With", "XMLHttpRequest")
-
-...or query values:
-
- r.Queries("key", "value")
-
-...or to use a custom matcher function:
-
- r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
- return r.ProtoMajor == 0
- })
-
-...and finally, it is possible to combine several matchers in a single route:
-
- r.HandleFunc("/products", ProductsHandler).
- Host("www.example.com").
- Methods("GET").
- Schemes("http")
-
-Setting the same matching conditions again and again can be boring, so we have
-a way to group several routes that share the same requirements.
-We call it "subrouting".
-
-For example, let's say we have several URLs that should only match when the
-host is "www.example.com". Create a route for that host and get a "subrouter"
-from it:
-
- r := mux.NewRouter()
- s := r.Host("www.example.com").Subrouter()
-
-Then register routes in the subrouter:
-
- s.HandleFunc("/products/", ProductsHandler)
- s.HandleFunc("/products/{key}", ProductHandler)
- s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
-
-The three URL paths we registered above will only be tested if the domain is
-"www.example.com", because the subrouter is tested first. This is not
-only convenient, but also optimizes request matching. You can create
-subrouters combining any attribute matchers accepted by a route.
-
-Subrouters can be used to create domain or path "namespaces": you define
-subrouters in a central place and then parts of the app can register its
-paths relatively to a given subrouter.
-
-There's one more thing about subroutes. When a subrouter has a path prefix,
-the inner routes use it as base for their paths:
-
- r := mux.NewRouter()
- s := r.PathPrefix("/products").Subrouter()
- // "/products/"
- s.HandleFunc("/", ProductsHandler)
- // "/products/{key}/"
- s.HandleFunc("/{key}/", ProductHandler)
- // "/products/{key}/details"
- s.HandleFunc("/{key}/details", ProductDetailsHandler)
-
-Now let's see how to build registered URLs.
-
-Routes can be named. All routes that define a name can have their URLs built,
-or "reversed". We define a name calling Name() on a route. For example:
-
- r := mux.NewRouter()
- r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
- Name("article")
-
-To build a URL, get the route and call the URL() method, passing a sequence of
-key/value pairs for the route variables. For the previous route, we would do:
-
- url, err := r.Get("article").URL("category", "technology", "id", "42")
-
-...and the result will be a url.URL with the following path:
-
- "/articles/technology/42"
-
-This also works for host variables:
-
- r := mux.NewRouter()
- r.Host("{subdomain}.domain.com").
- Path("/articles/{category}/{id:[0-9]+}").
- HandlerFunc(ArticleHandler).
- Name("article")
-
- // url.String() will be "http://news.domain.com/articles/technology/42"
- url, err := r.Get("article").URL("subdomain", "news",
- "category", "technology",
- "id", "42")
-
-All variables defined in the route are required, and their values must
-conform to the corresponding patterns. These requirements guarantee that a
-generated URL will always match a registered route -- the only exception is
-for explicitly defined "build-only" routes which never match.
-
-Regex support also exists for matching Headers within a route. For example, we could do:
-
- r.HeadersRegexp("Content-Type", "application/(text|json)")
-
-...and the route will match both requests with a Content-Type of `application/json` as well as
-`application/text`
-
-There's also a way to build only the URL host or path for a route:
-use the methods URLHost() or URLPath() instead. For the previous route,
-we would do:
-
- // "http://news.domain.com/"
- host, err := r.Get("article").URLHost("subdomain", "news")
-
- // "/articles/technology/42"
- path, err := r.Get("article").URLPath("category", "technology", "id", "42")
-
-And if you use subrouters, host and path defined separately can be built
-as well:
-
- r := mux.NewRouter()
- s := r.Host("{subdomain}.domain.com").Subrouter()
- s.Path("/articles/{category}/{id:[0-9]+}").
- HandlerFunc(ArticleHandler).
- Name("article")
-
- // "http://news.domain.com/articles/technology/42"
- url, err := r.Get("article").URL("subdomain", "news",
- "category", "technology",
- "id", "42")
-*/
-package mux
diff --git a/containerd/vendor/github.com/gorilla/mux/mux.go b/containerd/vendor/github.com/gorilla/mux/mux.go
deleted file mode 100644
index 68c4ea5..0000000
--- a/containerd/vendor/github.com/gorilla/mux/mux.go
+++ /dev/null
@@ -1,474 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package mux
-
-import (
- "errors"
- "fmt"
- "net/http"
- "path"
- "regexp"
-
- "github.com/gorilla/context"
-)
-
-// NewRouter returns a new router instance.
-func NewRouter() *Router {
- return &Router{namedRoutes: make(map[string]*Route), KeepContext: false}
-}
-
-// Router registers routes to be matched and dispatches a handler.
-//
-// It implements the http.Handler interface, so it can be registered to serve
-// requests:
-//
-// var router = mux.NewRouter()
-//
-// func main() {
-// http.Handle("/", router)
-// }
-//
-// Or, for Google App Engine, register it in a init() function:
-//
-// func init() {
-// http.Handle("/", router)
-// }
-//
-// This will send all incoming requests to the router.
-type Router struct {
- // Configurable Handler to be used when no route matches.
- NotFoundHandler http.Handler
- // Parent route, if this is a subrouter.
- parent parentRoute
- // Routes to be matched, in order.
- routes []*Route
- // Routes by name for URL building.
- namedRoutes map[string]*Route
- // See Router.StrictSlash(). This defines the flag for new routes.
- strictSlash bool
- // If true, do not clear the request context after handling the request
- KeepContext bool
-}
-
-// Match matches registered routes against the request.
-func (r *Router) Match(req *http.Request, match *RouteMatch) bool {
- for _, route := range r.routes {
- if route.Match(req, match) {
- return true
- }
- }
- return false
-}
-
-// ServeHTTP dispatches the handler registered in the matched route.
-//
-// When there is a match, the route variables can be retrieved calling
-// mux.Vars(request).
-func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
- // Clean path to canonical form and redirect.
- if p := cleanPath(req.URL.Path); p != req.URL.Path {
-
- // Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query.
- // This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue:
- // http://code.google.com/p/go/issues/detail?id=5252
- url := *req.URL
- url.Path = p
- p = url.String()
-
- w.Header().Set("Location", p)
- w.WriteHeader(http.StatusMovedPermanently)
- return
- }
- var match RouteMatch
- var handler http.Handler
- if r.Match(req, &match) {
- handler = match.Handler
- setVars(req, match.Vars)
- setCurrentRoute(req, match.Route)
- }
- if handler == nil {
- handler = r.NotFoundHandler
- if handler == nil {
- handler = http.NotFoundHandler()
- }
- }
- if !r.KeepContext {
- defer context.Clear(req)
- }
- handler.ServeHTTP(w, req)
-}
-
-// Get returns a route registered with the given name.
-func (r *Router) Get(name string) *Route {
- return r.getNamedRoutes()[name]
-}
-
-// GetRoute returns a route registered with the given name. This method
-// was renamed to Get() and remains here for backwards compatibility.
-func (r *Router) GetRoute(name string) *Route {
- return r.getNamedRoutes()[name]
-}
-
-// StrictSlash defines the trailing slash behavior for new routes. The initial
-// value is false.
-//
-// When true, if the route path is "/path/", accessing "/path" will redirect
-// to the former and vice versa. In other words, your application will always
-// see the path as specified in the route.
-//
-// When false, if the route path is "/path", accessing "/path/" will not match
-// this route and vice versa.
-//
-// Special case: when a route sets a path prefix using the PathPrefix() method,
-// strict slash is ignored for that route because the redirect behavior can't
-// be determined from a prefix alone. However, any subrouters created from that
-// route inherit the original StrictSlash setting.
-func (r *Router) StrictSlash(value bool) *Router {
- r.strictSlash = value
- return r
-}
-
-// ----------------------------------------------------------------------------
-// parentRoute
-// ----------------------------------------------------------------------------
-
-// getNamedRoutes returns the map where named routes are registered.
-func (r *Router) getNamedRoutes() map[string]*Route {
- if r.namedRoutes == nil {
- if r.parent != nil {
- r.namedRoutes = r.parent.getNamedRoutes()
- } else {
- r.namedRoutes = make(map[string]*Route)
- }
- }
- return r.namedRoutes
-}
-
-// getRegexpGroup returns regexp definitions from the parent route, if any.
-func (r *Router) getRegexpGroup() *routeRegexpGroup {
- if r.parent != nil {
- return r.parent.getRegexpGroup()
- }
- return nil
-}
-
-func (r *Router) buildVars(m map[string]string) map[string]string {
- if r.parent != nil {
- m = r.parent.buildVars(m)
- }
- return m
-}
-
-// ----------------------------------------------------------------------------
-// Route factories
-// ----------------------------------------------------------------------------
-
-// NewRoute registers an empty route.
-func (r *Router) NewRoute() *Route {
- route := &Route{parent: r, strictSlash: r.strictSlash}
- r.routes = append(r.routes, route)
- return route
-}
-
-// Handle registers a new route with a matcher for the URL path.
-// See Route.Path() and Route.Handler().
-func (r *Router) Handle(path string, handler http.Handler) *Route {
- return r.NewRoute().Path(path).Handler(handler)
-}
-
-// HandleFunc registers a new route with a matcher for the URL path.
-// See Route.Path() and Route.HandlerFunc().
-func (r *Router) HandleFunc(path string, f func(http.ResponseWriter,
- *http.Request)) *Route {
- return r.NewRoute().Path(path).HandlerFunc(f)
-}
-
-// Headers registers a new route with a matcher for request header values.
-// See Route.Headers().
-func (r *Router) Headers(pairs ...string) *Route {
- return r.NewRoute().Headers(pairs...)
-}
-
-// Host registers a new route with a matcher for the URL host.
-// See Route.Host().
-func (r *Router) Host(tpl string) *Route {
- return r.NewRoute().Host(tpl)
-}
-
-// MatcherFunc registers a new route with a custom matcher function.
-// See Route.MatcherFunc().
-func (r *Router) MatcherFunc(f MatcherFunc) *Route {
- return r.NewRoute().MatcherFunc(f)
-}
-
-// Methods registers a new route with a matcher for HTTP methods.
-// See Route.Methods().
-func (r *Router) Methods(methods ...string) *Route {
- return r.NewRoute().Methods(methods...)
-}
-
-// Path registers a new route with a matcher for the URL path.
-// See Route.Path().
-func (r *Router) Path(tpl string) *Route {
- return r.NewRoute().Path(tpl)
-}
-
-// PathPrefix registers a new route with a matcher for the URL path prefix.
-// See Route.PathPrefix().
-func (r *Router) PathPrefix(tpl string) *Route {
- return r.NewRoute().PathPrefix(tpl)
-}
-
-// Queries registers a new route with a matcher for URL query values.
-// See Route.Queries().
-func (r *Router) Queries(pairs ...string) *Route {
- return r.NewRoute().Queries(pairs...)
-}
-
-// Schemes registers a new route with a matcher for URL schemes.
-// See Route.Schemes().
-func (r *Router) Schemes(schemes ...string) *Route {
- return r.NewRoute().Schemes(schemes...)
-}
-
-// BuildVars registers a new route with a custom function for modifying
-// route variables before building a URL.
-func (r *Router) BuildVarsFunc(f BuildVarsFunc) *Route {
- return r.NewRoute().BuildVarsFunc(f)
-}
-
-// Walk walks the router and all its sub-routers, calling walkFn for each route
-// in the tree. The routes are walked in the order they were added. Sub-routers
-// are explored depth-first.
-func (r *Router) Walk(walkFn WalkFunc) error {
- return r.walk(walkFn, []*Route{})
-}
-
-// SkipRouter is used as a return value from WalkFuncs to indicate that the
-// router that walk is about to descend down to should be skipped.
-var SkipRouter = errors.New("skip this router")
-
-// WalkFunc is the type of the function called for each route visited by Walk.
-// At every invocation, it is given the current route, and the current router,
-// and a list of ancestor routes that lead to the current route.
-type WalkFunc func(route *Route, router *Router, ancestors []*Route) error
-
-func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error {
- for _, t := range r.routes {
- if t.regexp == nil || t.regexp.path == nil || t.regexp.path.template == "" {
- continue
- }
-
- err := walkFn(t, r, ancestors)
- if err == SkipRouter {
- continue
- }
- for _, sr := range t.matchers {
- if h, ok := sr.(*Router); ok {
- err := h.walk(walkFn, ancestors)
- if err != nil {
- return err
- }
- }
- }
- if h, ok := t.handler.(*Router); ok {
- ancestors = append(ancestors, t)
- err := h.walk(walkFn, ancestors)
- if err != nil {
- return err
- }
- ancestors = ancestors[:len(ancestors)-1]
- }
- }
- return nil
-}
-
-// ----------------------------------------------------------------------------
-// Context
-// ----------------------------------------------------------------------------
-
-// RouteMatch stores information about a matched route.
-type RouteMatch struct {
- Route *Route
- Handler http.Handler
- Vars map[string]string
-}
-
-type contextKey int
-
-const (
- varsKey contextKey = iota
- routeKey
-)
-
-// Vars returns the route variables for the current request, if any.
-func Vars(r *http.Request) map[string]string {
- if rv := context.Get(r, varsKey); rv != nil {
- return rv.(map[string]string)
- }
- return nil
-}
-
-// CurrentRoute returns the matched route for the current request, if any.
-// This only works when called inside the handler of the matched route
-// because the matched route is stored in the request context which is cleared
-// after the handler returns, unless the KeepContext option is set on the
-// Router.
-func CurrentRoute(r *http.Request) *Route {
- if rv := context.Get(r, routeKey); rv != nil {
- return rv.(*Route)
- }
- return nil
-}
-
-func setVars(r *http.Request, val interface{}) {
- context.Set(r, varsKey, val)
-}
-
-func setCurrentRoute(r *http.Request, val interface{}) {
- context.Set(r, routeKey, val)
-}
-
-// ----------------------------------------------------------------------------
-// Helpers
-// ----------------------------------------------------------------------------
-
-// cleanPath returns the canonical path for p, eliminating . and .. elements.
-// Borrowed from the net/http package.
-func cleanPath(p string) string {
- if p == "" {
- return "/"
- }
- if p[0] != '/' {
- p = "/" + p
- }
- np := path.Clean(p)
- // path.Clean removes trailing slash except for root;
- // put the trailing slash back if necessary.
- if p[len(p)-1] == '/' && np != "/" {
- np += "/"
- }
- return np
-}
-
-// uniqueVars returns an error if two slices contain duplicated strings.
-func uniqueVars(s1, s2 []string) error {
- for _, v1 := range s1 {
- for _, v2 := range s2 {
- if v1 == v2 {
- return fmt.Errorf("mux: duplicated route variable %q", v2)
- }
- }
- }
- return nil
-}
-
-// checkPairs returns the count of strings passed in, and an error if
-// the count is not an even number.
-func checkPairs(pairs ...string) (int, error) {
- length := len(pairs)
- if length%2 != 0 {
- return length, fmt.Errorf(
- "mux: number of parameters must be multiple of 2, got %v", pairs)
- }
- return length, nil
-}
-
-// mapFromPairsToString converts variadic string parameters to a
-// string to string map.
-func mapFromPairsToString(pairs ...string) (map[string]string, error) {
- length, err := checkPairs(pairs...)
- if err != nil {
- return nil, err
- }
- m := make(map[string]string, length/2)
- for i := 0; i < length; i += 2 {
- m[pairs[i]] = pairs[i+1]
- }
- return m, nil
-}
-
-// mapFromPairsToRegex converts variadic string paramers to a
-// string to regex map.
-func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) {
- length, err := checkPairs(pairs...)
- if err != nil {
- return nil, err
- }
- m := make(map[string]*regexp.Regexp, length/2)
- for i := 0; i < length; i += 2 {
- regex, err := regexp.Compile(pairs[i+1])
- if err != nil {
- return nil, err
- }
- m[pairs[i]] = regex
- }
- return m, nil
-}
-
-// matchInArray returns true if the given string value is in the array.
-func matchInArray(arr []string, value string) bool {
- for _, v := range arr {
- if v == value {
- return true
- }
- }
- return false
-}
-
-// matchMapWithString returns true if the given key/value pairs exist in a given map.
-func matchMapWithString(toCheck map[string]string, toMatch map[string][]string, canonicalKey bool) bool {
- for k, v := range toCheck {
- // Check if key exists.
- if canonicalKey {
- k = http.CanonicalHeaderKey(k)
- }
- if values := toMatch[k]; values == nil {
- return false
- } else if v != "" {
- // If value was defined as an empty string we only check that the
- // key exists. Otherwise we also check for equality.
- valueExists := false
- for _, value := range values {
- if v == value {
- valueExists = true
- break
- }
- }
- if !valueExists {
- return false
- }
- }
- }
- return true
-}
-
-// matchMapWithRegex returns true if the given key/value pairs exist in a given map compiled against
-// the given regex
-func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]string, canonicalKey bool) bool {
- for k, v := range toCheck {
- // Check if key exists.
- if canonicalKey {
- k = http.CanonicalHeaderKey(k)
- }
- if values := toMatch[k]; values == nil {
- return false
- } else if v != nil {
- // If value was defined as an empty string we only check that the
- // key exists. Otherwise we also check for equality.
- valueExists := false
- for _, value := range values {
- if v.MatchString(value) {
- valueExists = true
- break
- }
- }
- if !valueExists {
- return false
- }
- }
- }
- return true
-}
diff --git a/containerd/vendor/github.com/gorilla/mux/regexp.go b/containerd/vendor/github.com/gorilla/mux/regexp.go
deleted file mode 100644
index 06728dd..0000000
--- a/containerd/vendor/github.com/gorilla/mux/regexp.go
+++ /dev/null
@@ -1,317 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package mux
-
-import (
- "bytes"
- "fmt"
- "net/http"
- "net/url"
- "regexp"
- "strconv"
- "strings"
-)
-
-// newRouteRegexp parses a route template and returns a routeRegexp,
-// used to match a host, a path or a query string.
-//
-// It will extract named variables, assemble a regexp to be matched, create
-// a "reverse" template to build URLs and compile regexps to validate variable
-// values used in URL building.
-//
-// Previously we accepted only Python-like identifiers for variable
-// names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that
-// name and pattern can't be empty, and names can't contain a colon.
-func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash bool) (*routeRegexp, error) {
- // Check if it is well-formed.
- idxs, errBraces := braceIndices(tpl)
- if errBraces != nil {
- return nil, errBraces
- }
- // Backup the original.
- template := tpl
- // Now let's parse it.
- defaultPattern := "[^/]+"
- if matchQuery {
- defaultPattern = "[^?&]*"
- } else if matchHost {
- defaultPattern = "[^.]+"
- matchPrefix = false
- }
- // Only match strict slash if not matching
- if matchPrefix || matchHost || matchQuery {
- strictSlash = false
- }
- // Set a flag for strictSlash.
- endSlash := false
- if strictSlash && strings.HasSuffix(tpl, "/") {
- tpl = tpl[:len(tpl)-1]
- endSlash = true
- }
- varsN := make([]string, len(idxs)/2)
- varsR := make([]*regexp.Regexp, len(idxs)/2)
- pattern := bytes.NewBufferString("")
- pattern.WriteByte('^')
- reverse := bytes.NewBufferString("")
- var end int
- var err error
- for i := 0; i < len(idxs); i += 2 {
- // Set all values we are interested in.
- raw := tpl[end:idxs[i]]
- end = idxs[i+1]
- parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2)
- name := parts[0]
- patt := defaultPattern
- if len(parts) == 2 {
- patt = parts[1]
- }
- // Name or pattern can't be empty.
- if name == "" || patt == "" {
- return nil, fmt.Errorf("mux: missing name or pattern in %q",
- tpl[idxs[i]:end])
- }
- // Build the regexp pattern.
- varIdx := i / 2
- fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(varIdx), patt)
- // Build the reverse template.
- fmt.Fprintf(reverse, "%s%%s", raw)
-
- // Append variable name and compiled pattern.
- varsN[varIdx] = name
- varsR[varIdx], err = regexp.Compile(fmt.Sprintf("^%s$", patt))
- if err != nil {
- return nil, err
- }
- }
- // Add the remaining.
- raw := tpl[end:]
- pattern.WriteString(regexp.QuoteMeta(raw))
- if strictSlash {
- pattern.WriteString("[/]?")
- }
- if matchQuery {
- // Add the default pattern if the query value is empty
- if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" {
- pattern.WriteString(defaultPattern)
- }
- }
- if !matchPrefix {
- pattern.WriteByte('$')
- }
- reverse.WriteString(raw)
- if endSlash {
- reverse.WriteByte('/')
- }
- // Compile full regexp.
- reg, errCompile := regexp.Compile(pattern.String())
- if errCompile != nil {
- return nil, errCompile
- }
- // Done!
- return &routeRegexp{
- template: template,
- matchHost: matchHost,
- matchQuery: matchQuery,
- strictSlash: strictSlash,
- regexp: reg,
- reverse: reverse.String(),
- varsN: varsN,
- varsR: varsR,
- }, nil
-}
-
-// routeRegexp stores a regexp to match a host or path and information to
-// collect and validate route variables.
-type routeRegexp struct {
- // The unmodified template.
- template string
- // True for host match, false for path or query string match.
- matchHost bool
- // True for query string match, false for path and host match.
- matchQuery bool
- // The strictSlash value defined on the route, but disabled if PathPrefix was used.
- strictSlash bool
- // Expanded regexp.
- regexp *regexp.Regexp
- // Reverse template.
- reverse string
- // Variable names.
- varsN []string
- // Variable regexps (validators).
- varsR []*regexp.Regexp
-}
-
-// Match matches the regexp against the URL host or path.
-func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool {
- if !r.matchHost {
- if r.matchQuery {
- return r.matchQueryString(req)
- } else {
- return r.regexp.MatchString(req.URL.Path)
- }
- }
- return r.regexp.MatchString(getHost(req))
-}
-
-// url builds a URL part using the given values.
-func (r *routeRegexp) url(values map[string]string) (string, error) {
- urlValues := make([]interface{}, len(r.varsN))
- for k, v := range r.varsN {
- value, ok := values[v]
- if !ok {
- return "", fmt.Errorf("mux: missing route variable %q", v)
- }
- urlValues[k] = value
- }
- rv := fmt.Sprintf(r.reverse, urlValues...)
- if !r.regexp.MatchString(rv) {
- // The URL is checked against the full regexp, instead of checking
- // individual variables. This is faster but to provide a good error
- // message, we check individual regexps if the URL doesn't match.
- for k, v := range r.varsN {
- if !r.varsR[k].MatchString(values[v]) {
- return "", fmt.Errorf(
- "mux: variable %q doesn't match, expected %q", values[v],
- r.varsR[k].String())
- }
- }
- }
- return rv, nil
-}
-
-// getUrlQuery returns a single query parameter from a request URL.
-// For a URL with foo=bar&baz=ding, we return only the relevant key
-// value pair for the routeRegexp.
-func (r *routeRegexp) getUrlQuery(req *http.Request) string {
- if !r.matchQuery {
- return ""
- }
- templateKey := strings.SplitN(r.template, "=", 2)[0]
- for key, vals := range req.URL.Query() {
- if key == templateKey && len(vals) > 0 {
- return key + "=" + vals[0]
- }
- }
- return ""
-}
-
-func (r *routeRegexp) matchQueryString(req *http.Request) bool {
- return r.regexp.MatchString(r.getUrlQuery(req))
-}
-
-// braceIndices returns the first level curly brace indices from a string.
-// It returns an error in case of unbalanced braces.
-func braceIndices(s string) ([]int, error) {
- var level, idx int
- idxs := make([]int, 0)
- for i := 0; i < len(s); i++ {
- switch s[i] {
- case '{':
- if level++; level == 1 {
- idx = i
- }
- case '}':
- if level--; level == 0 {
- idxs = append(idxs, idx, i+1)
- } else if level < 0 {
- return nil, fmt.Errorf("mux: unbalanced braces in %q", s)
- }
- }
- }
- if level != 0 {
- return nil, fmt.Errorf("mux: unbalanced braces in %q", s)
- }
- return idxs, nil
-}
-
-// varGroupName builds a capturing group name for the indexed variable.
-func varGroupName(idx int) string {
- return "v" + strconv.Itoa(idx)
-}
-
-// ----------------------------------------------------------------------------
-// routeRegexpGroup
-// ----------------------------------------------------------------------------
-
-// routeRegexpGroup groups the route matchers that carry variables.
-type routeRegexpGroup struct {
- host *routeRegexp
- path *routeRegexp
- queries []*routeRegexp
-}
-
-// setMatch extracts the variables from the URL once a route matches.
-func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) {
- // Store host variables.
- if v.host != nil {
- hostVars := v.host.regexp.FindStringSubmatch(getHost(req))
- if hostVars != nil {
- subexpNames := v.host.regexp.SubexpNames()
- varName := 0
- for i, name := range subexpNames[1:] {
- if name != "" && name == varGroupName(varName) {
- m.Vars[v.host.varsN[varName]] = hostVars[i+1]
- varName++
- }
- }
- }
- }
- // Store path variables.
- if v.path != nil {
- pathVars := v.path.regexp.FindStringSubmatch(req.URL.Path)
- if pathVars != nil {
- subexpNames := v.path.regexp.SubexpNames()
- varName := 0
- for i, name := range subexpNames[1:] {
- if name != "" && name == varGroupName(varName) {
- m.Vars[v.path.varsN[varName]] = pathVars[i+1]
- varName++
- }
- }
- // Check if we should redirect.
- if v.path.strictSlash {
- p1 := strings.HasSuffix(req.URL.Path, "/")
- p2 := strings.HasSuffix(v.path.template, "/")
- if p1 != p2 {
- u, _ := url.Parse(req.URL.String())
- if p1 {
- u.Path = u.Path[:len(u.Path)-1]
- } else {
- u.Path += "/"
- }
- m.Handler = http.RedirectHandler(u.String(), 301)
- }
- }
- }
- }
- // Store query string variables.
- for _, q := range v.queries {
- queryVars := q.regexp.FindStringSubmatch(q.getUrlQuery(req))
- if queryVars != nil {
- subexpNames := q.regexp.SubexpNames()
- varName := 0
- for i, name := range subexpNames[1:] {
- if name != "" && name == varGroupName(varName) {
- m.Vars[q.varsN[varName]] = queryVars[i+1]
- varName++
- }
- }
- }
- }
-}
-
-// getHost tries its best to return the request host.
-func getHost(r *http.Request) string {
- if r.URL.IsAbs() {
- return r.URL.Host
- }
- host := r.Host
- // Slice off any port information.
- if i := strings.Index(host, ":"); i != -1 {
- host = host[:i]
- }
- return host
-
-}
diff --git a/containerd/vendor/github.com/gorilla/mux/route.go b/containerd/vendor/github.com/gorilla/mux/route.go
deleted file mode 100644
index 913432c..0000000
--- a/containerd/vendor/github.com/gorilla/mux/route.go
+++ /dev/null
@@ -1,595 +0,0 @@
-// Copyright 2012 The Gorilla Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package mux
-
-import (
- "errors"
- "fmt"
- "net/http"
- "net/url"
- "regexp"
- "strings"
-)
-
-// Route stores information to match a request and build URLs.
-type Route struct {
- // Parent where the route was registered (a Router).
- parent parentRoute
- // Request handler for the route.
- handler http.Handler
- // List of matchers.
- matchers []matcher
- // Manager for the variables from host and path.
- regexp *routeRegexpGroup
- // If true, when the path pattern is "/path/", accessing "/path" will
- // redirect to the former and vice versa.
- strictSlash bool
- // If true, this route never matches: it is only used to build URLs.
- buildOnly bool
- // The name used to build URLs.
- name string
- // Error resulted from building a route.
- err error
-
- buildVarsFunc BuildVarsFunc
-}
-
-// Match matches the route against the request.
-func (r *Route) Match(req *http.Request, match *RouteMatch) bool {
- if r.buildOnly || r.err != nil {
- return false
- }
- // Match everything.
- for _, m := range r.matchers {
- if matched := m.Match(req, match); !matched {
- return false
- }
- }
- // Yay, we have a match. Let's collect some info about it.
- if match.Route == nil {
- match.Route = r
- }
- if match.Handler == nil {
- match.Handler = r.handler
- }
- if match.Vars == nil {
- match.Vars = make(map[string]string)
- }
- // Set variables.
- if r.regexp != nil {
- r.regexp.setMatch(req, match, r)
- }
- return true
-}
-
-// ----------------------------------------------------------------------------
-// Route attributes
-// ----------------------------------------------------------------------------
-
-// GetError returns an error resulted from building the route, if any.
-func (r *Route) GetError() error {
- return r.err
-}
-
-// BuildOnly sets the route to never match: it is only used to build URLs.
-func (r *Route) BuildOnly() *Route {
- r.buildOnly = true
- return r
-}
-
-// Handler --------------------------------------------------------------------
-
-// Handler sets a handler for the route.
-func (r *Route) Handler(handler http.Handler) *Route {
- if r.err == nil {
- r.handler = handler
- }
- return r
-}
-
-// HandlerFunc sets a handler function for the route.
-func (r *Route) HandlerFunc(f func(http.ResponseWriter, *http.Request)) *Route {
- return r.Handler(http.HandlerFunc(f))
-}
-
-// GetHandler returns the handler for the route, if any.
-func (r *Route) GetHandler() http.Handler {
- return r.handler
-}
-
-// Name -----------------------------------------------------------------------
-
-// Name sets the name for the route, used to build URLs.
-// If the name was registered already it will be overwritten.
-func (r *Route) Name(name string) *Route {
- if r.name != "" {
- r.err = fmt.Errorf("mux: route already has name %q, can't set %q",
- r.name, name)
- }
- if r.err == nil {
- r.name = name
- r.getNamedRoutes()[name] = r
- }
- return r
-}
-
-// GetName returns the name for the route, if any.
-func (r *Route) GetName() string {
- return r.name
-}
-
-// ----------------------------------------------------------------------------
-// Matchers
-// ----------------------------------------------------------------------------
-
-// matcher types try to match a request.
-type matcher interface {
- Match(*http.Request, *RouteMatch) bool
-}
-
-// addMatcher adds a matcher to the route.
-func (r *Route) addMatcher(m matcher) *Route {
- if r.err == nil {
- r.matchers = append(r.matchers, m)
- }
- return r
-}
-
-// addRegexpMatcher adds a host or path matcher and builder to a route.
-func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery bool) error {
- if r.err != nil {
- return r.err
- }
- r.regexp = r.getRegexpGroup()
- if !matchHost && !matchQuery {
- if len(tpl) == 0 || tpl[0] != '/' {
- return fmt.Errorf("mux: path must start with a slash, got %q", tpl)
- }
- if r.regexp.path != nil {
- tpl = strings.TrimRight(r.regexp.path.template, "/") + tpl
- }
- }
- rr, err := newRouteRegexp(tpl, matchHost, matchPrefix, matchQuery, r.strictSlash)
- if err != nil {
- return err
- }
- for _, q := range r.regexp.queries {
- if err = uniqueVars(rr.varsN, q.varsN); err != nil {
- return err
- }
- }
- if matchHost {
- if r.regexp.path != nil {
- if err = uniqueVars(rr.varsN, r.regexp.path.varsN); err != nil {
- return err
- }
- }
- r.regexp.host = rr
- } else {
- if r.regexp.host != nil {
- if err = uniqueVars(rr.varsN, r.regexp.host.varsN); err != nil {
- return err
- }
- }
- if matchQuery {
- r.regexp.queries = append(r.regexp.queries, rr)
- } else {
- r.regexp.path = rr
- }
- }
- r.addMatcher(rr)
- return nil
-}
-
-// Headers --------------------------------------------------------------------
-
-// headerMatcher matches the request against header values.
-type headerMatcher map[string]string
-
-func (m headerMatcher) Match(r *http.Request, match *RouteMatch) bool {
- return matchMapWithString(m, r.Header, true)
-}
-
-// Headers adds a matcher for request header values.
-// It accepts a sequence of key/value pairs to be matched. For example:
-//
-// r := mux.NewRouter()
-// r.Headers("Content-Type", "application/json",
-// "X-Requested-With", "XMLHttpRequest")
-//
-// The above route will only match if both request header values match.
-// If the value is an empty string, it will match any value if the key is set.
-func (r *Route) Headers(pairs ...string) *Route {
- if r.err == nil {
- var headers map[string]string
- headers, r.err = mapFromPairsToString(pairs...)
- return r.addMatcher(headerMatcher(headers))
- }
- return r
-}
-
-// headerRegexMatcher matches the request against the route given a regex for the header
-type headerRegexMatcher map[string]*regexp.Regexp
-
-func (m headerRegexMatcher) Match(r *http.Request, match *RouteMatch) bool {
- return matchMapWithRegex(m, r.Header, true)
-}
-
-// Regular expressions can be used with headers as well.
-// It accepts a sequence of key/value pairs, where the value has regex support. For example
-// r := mux.NewRouter()
-// r.HeadersRegexp("Content-Type", "application/(text|json)",
-// "X-Requested-With", "XMLHttpRequest")
-//
-// The above route will only match if both the request header matches both regular expressions.
-// It the value is an empty string, it will match any value if the key is set.
-func (r *Route) HeadersRegexp(pairs ...string) *Route {
- if r.err == nil {
- var headers map[string]*regexp.Regexp
- headers, r.err = mapFromPairsToRegex(pairs...)
- return r.addMatcher(headerRegexMatcher(headers))
- }
- return r
-}
-
-// Host -----------------------------------------------------------------------
-
-// Host adds a matcher for the URL host.
-// It accepts a template with zero or more URL variables enclosed by {}.
-// Variables can define an optional regexp pattern to be matched:
-//
-// - {name} matches anything until the next dot.
-//
-// - {name:pattern} matches the given regexp pattern.
-//
-// For example:
-//
-// r := mux.NewRouter()
-// r.Host("www.example.com")
-// r.Host("{subdomain}.domain.com")
-// r.Host("{subdomain:[a-z]+}.domain.com")
-//
-// Variable names must be unique in a given route. They can be retrieved
-// calling mux.Vars(request).
-func (r *Route) Host(tpl string) *Route {
- r.err = r.addRegexpMatcher(tpl, true, false, false)
- return r
-}
-
-// MatcherFunc ----------------------------------------------------------------
-
-// MatcherFunc is the function signature used by custom matchers.
-type MatcherFunc func(*http.Request, *RouteMatch) bool
-
-func (m MatcherFunc) Match(r *http.Request, match *RouteMatch) bool {
- return m(r, match)
-}
-
-// MatcherFunc adds a custom function to be used as request matcher.
-func (r *Route) MatcherFunc(f MatcherFunc) *Route {
- return r.addMatcher(f)
-}
-
-// Methods --------------------------------------------------------------------
-
-// methodMatcher matches the request against HTTP methods.
-type methodMatcher []string
-
-func (m methodMatcher) Match(r *http.Request, match *RouteMatch) bool {
- return matchInArray(m, r.Method)
-}
-
-// Methods adds a matcher for HTTP methods.
-// It accepts a sequence of one or more methods to be matched, e.g.:
-// "GET", "POST", "PUT".
-func (r *Route) Methods(methods ...string) *Route {
- for k, v := range methods {
- methods[k] = strings.ToUpper(v)
- }
- return r.addMatcher(methodMatcher(methods))
-}
-
-// Path -----------------------------------------------------------------------
-
-// Path adds a matcher for the URL path.
-// It accepts a template with zero or more URL variables enclosed by {}. The
-// template must start with a "/".
-// Variables can define an optional regexp pattern to be matched:
-//
-// - {name} matches anything until the next slash.
-//
-// - {name:pattern} matches the given regexp pattern.
-//
-// For example:
-//
-// r := mux.NewRouter()
-// r.Path("/products/").Handler(ProductsHandler)
-// r.Path("/products/{key}").Handler(ProductsHandler)
-// r.Path("/articles/{category}/{id:[0-9]+}").
-// Handler(ArticleHandler)
-//
-// Variable names must be unique in a given route. They can be retrieved
-// calling mux.Vars(request).
-func (r *Route) Path(tpl string) *Route {
- r.err = r.addRegexpMatcher(tpl, false, false, false)
- return r
-}
-
-// PathPrefix -----------------------------------------------------------------
-
-// PathPrefix adds a matcher for the URL path prefix. This matches if the given
-// template is a prefix of the full URL path. See Route.Path() for details on
-// the tpl argument.
-//
-// Note that it does not treat slashes specially ("/foobar/" will be matched by
-// the prefix "/foo") so you may want to use a trailing slash here.
-//
-// Also note that the setting of Router.StrictSlash() has no effect on routes
-// with a PathPrefix matcher.
-func (r *Route) PathPrefix(tpl string) *Route {
- r.err = r.addRegexpMatcher(tpl, false, true, false)
- return r
-}
-
-// Query ----------------------------------------------------------------------
-
-// Queries adds a matcher for URL query values.
-// It accepts a sequence of key/value pairs. Values may define variables.
-// For example:
-//
-// r := mux.NewRouter()
-// r.Queries("foo", "bar", "id", "{id:[0-9]+}")
-//
-// The above route will only match if the URL contains the defined queries
-// values, e.g.: ?foo=bar&id=42.
-//
-// It the value is an empty string, it will match any value if the key is set.
-//
-// Variables can define an optional regexp pattern to be matched:
-//
-// - {name} matches anything until the next slash.
-//
-// - {name:pattern} matches the given regexp pattern.
-func (r *Route) Queries(pairs ...string) *Route {
- length := len(pairs)
- if length%2 != 0 {
- r.err = fmt.Errorf(
- "mux: number of parameters must be multiple of 2, got %v", pairs)
- return nil
- }
- for i := 0; i < length; i += 2 {
- if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], false, false, true); r.err != nil {
- return r
- }
- }
-
- return r
-}
-
-// Schemes --------------------------------------------------------------------
-
-// schemeMatcher matches the request against URL schemes.
-type schemeMatcher []string
-
-func (m schemeMatcher) Match(r *http.Request, match *RouteMatch) bool {
- return matchInArray(m, r.URL.Scheme)
-}
-
-// Schemes adds a matcher for URL schemes.
-// It accepts a sequence of schemes to be matched, e.g.: "http", "https".
-func (r *Route) Schemes(schemes ...string) *Route {
- for k, v := range schemes {
- schemes[k] = strings.ToLower(v)
- }
- return r.addMatcher(schemeMatcher(schemes))
-}
-
-// BuildVarsFunc --------------------------------------------------------------
-
-// BuildVarsFunc is the function signature used by custom build variable
-// functions (which can modify route variables before a route's URL is built).
-type BuildVarsFunc func(map[string]string) map[string]string
-
-// BuildVarsFunc adds a custom function to be used to modify build variables
-// before a route's URL is built.
-func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route {
- r.buildVarsFunc = f
- return r
-}
-
-// Subrouter ------------------------------------------------------------------
-
-// Subrouter creates a subrouter for the route.
-//
-// It will test the inner routes only if the parent route matched. For example:
-//
-// r := mux.NewRouter()
-// s := r.Host("www.example.com").Subrouter()
-// s.HandleFunc("/products/", ProductsHandler)
-// s.HandleFunc("/products/{key}", ProductHandler)
-// s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
-//
-// Here, the routes registered in the subrouter won't be tested if the host
-// doesn't match.
-func (r *Route) Subrouter() *Router {
- router := &Router{parent: r, strictSlash: r.strictSlash}
- r.addMatcher(router)
- return router
-}
-
-// ----------------------------------------------------------------------------
-// URL building
-// ----------------------------------------------------------------------------
-
-// URL builds a URL for the route.
-//
-// It accepts a sequence of key/value pairs for the route variables. For
-// example, given this route:
-//
-// r := mux.NewRouter()
-// r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
-// Name("article")
-//
-// ...a URL for it can be built using:
-//
-// url, err := r.Get("article").URL("category", "technology", "id", "42")
-//
-// ...which will return an url.URL with the following path:
-//
-// "/articles/technology/42"
-//
-// This also works for host variables:
-//
-// r := mux.NewRouter()
-// r.Host("{subdomain}.domain.com").
-// HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
-// Name("article")
-//
-// // url.String() will be "http://news.domain.com/articles/technology/42"
-// url, err := r.Get("article").URL("subdomain", "news",
-// "category", "technology",
-// "id", "42")
-//
-// All variables defined in the route are required, and their values must
-// conform to the corresponding patterns.
-func (r *Route) URL(pairs ...string) (*url.URL, error) {
- if r.err != nil {
- return nil, r.err
- }
- if r.regexp == nil {
- return nil, errors.New("mux: route doesn't have a host or path")
- }
- values, err := r.prepareVars(pairs...)
- if err != nil {
- return nil, err
- }
- var scheme, host, path string
- if r.regexp.host != nil {
- // Set a default scheme.
- scheme = "http"
- if host, err = r.regexp.host.url(values); err != nil {
- return nil, err
- }
- }
- if r.regexp.path != nil {
- if path, err = r.regexp.path.url(values); err != nil {
- return nil, err
- }
- }
- return &url.URL{
- Scheme: scheme,
- Host: host,
- Path: path,
- }, nil
-}
-
-// URLHost builds the host part of the URL for a route. See Route.URL().
-//
-// The route must have a host defined.
-func (r *Route) URLHost(pairs ...string) (*url.URL, error) {
- if r.err != nil {
- return nil, r.err
- }
- if r.regexp == nil || r.regexp.host == nil {
- return nil, errors.New("mux: route doesn't have a host")
- }
- values, err := r.prepareVars(pairs...)
- if err != nil {
- return nil, err
- }
- host, err := r.regexp.host.url(values)
- if err != nil {
- return nil, err
- }
- return &url.URL{
- Scheme: "http",
- Host: host,
- }, nil
-}
-
-// URLPath builds the path part of the URL for a route. See Route.URL().
-//
-// The route must have a path defined.
-func (r *Route) URLPath(pairs ...string) (*url.URL, error) {
- if r.err != nil {
- return nil, r.err
- }
- if r.regexp == nil || r.regexp.path == nil {
- return nil, errors.New("mux: route doesn't have a path")
- }
- values, err := r.prepareVars(pairs...)
- if err != nil {
- return nil, err
- }
- path, err := r.regexp.path.url(values)
- if err != nil {
- return nil, err
- }
- return &url.URL{
- Path: path,
- }, nil
-}
-
-// prepareVars converts the route variable pairs into a map. If the route has a
-// BuildVarsFunc, it is invoked.
-func (r *Route) prepareVars(pairs ...string) (map[string]string, error) {
- m, err := mapFromPairsToString(pairs...)
- if err != nil {
- return nil, err
- }
- return r.buildVars(m), nil
-}
-
-func (r *Route) buildVars(m map[string]string) map[string]string {
- if r.parent != nil {
- m = r.parent.buildVars(m)
- }
- if r.buildVarsFunc != nil {
- m = r.buildVarsFunc(m)
- }
- return m
-}
-
-// ----------------------------------------------------------------------------
-// parentRoute
-// ----------------------------------------------------------------------------
-
-// parentRoute allows routes to know about parent host and path definitions.
-type parentRoute interface {
- getNamedRoutes() map[string]*Route
- getRegexpGroup() *routeRegexpGroup
- buildVars(map[string]string) map[string]string
-}
-
-// getNamedRoutes returns the map where named routes are registered.
-func (r *Route) getNamedRoutes() map[string]*Route {
- if r.parent == nil {
- // During tests router is not always set.
- r.parent = NewRouter()
- }
- return r.parent.getNamedRoutes()
-}
-
-// getRegexpGroup returns regexp definitions from this route.
-func (r *Route) getRegexpGroup() *routeRegexpGroup {
- if r.regexp == nil {
- if r.parent == nil {
- // During tests router is not always set.
- r.parent = NewRouter()
- }
- regexp := r.parent.getRegexpGroup()
- if regexp == nil {
- r.regexp = new(routeRegexpGroup)
- } else {
- // Copy.
- r.regexp = &routeRegexpGroup{
- host: regexp.host,
- path: regexp.path,
- queries: regexp.queries,
- }
- }
- }
- return r.regexp
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/README.md b/containerd/vendor/github.com/opencontainers/runc/libcontainer/README.md
deleted file mode 100644
index 295edb4..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/README.md
+++ /dev/null
@@ -1,152 +0,0 @@
-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
-
-To create a container you first have to initialize an instance of a factory
-that will handle the creation and initialization for a container.
-
-Because containers are spawned in a two step process you will need to provide
-arguments to a binary that will be executed as the init process for the container.
-To use the current binary that is spawning the containers and acting as the parent
-you can use `os.Args[0]` and we have a command called `init` setup.
-
-```go
-root, err := libcontainer.New("/var/lib/container", libcontainer.InitArgs(os.Args[0], "init"))
-if err != nil {
- log.Fatal(err)
-}
-```
-
-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
-config := &configs.Config{
- Rootfs: 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.NEWNET},
- }),
- Cgroups: &configs.Cgroup{
- Name: "test-container",
- Parent: "system",
- AllowAllDevices: false,
- AllowedDevices: configs.DefaultAllowedDevices,
- },
-
- Devices: configs.DefaultAutoCreatedDevices,
- Hostname: "testing",
- Networks: []*configs.Network{
- {
- Type: "loopback",
- Address: "127.0.0.1/0",
- Gateway: "localhost",
- },
- },
- Rlimits: []configs.Rlimit{
- {
- Type: syscall.RLIMIT_NOFILE,
- Hard: uint64(1024),
- Soft: uint64(1024),
- },
- },
-}
-```
-
-Once you have the configuration populated you can create a container:
-
-```go
-container, err := root.Create("container-id", config)
-```
-
-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.Start(process)
-if err != nil {
- log.Fatal(err)
-}
-
-// wait for the process to finish.
-status, err := process.Wait()
-if err != nil {
- log.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()
-```
-
-
-#### 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/containerd/vendor/github.com/opencontainers/runc/libcontainer/SPEC.md b/containerd/vendor/github.com/opencontainers/runc/libcontainer/SPEC.md
deleted file mode 100644
index fad1dd7..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/SPEC.md
+++ /dev/null
@@ -1,334 +0,0 @@
-## Container Specification - v1
-
-This is the standard configuration for version 1 containers. It includes
-namespaces, standard filesystem setup, a default Linux capability set, and
-information about resource reservations. It also has information about any
-populated environment settings for the processes running inside a container.
-
-Along with the configuration of how a container is created the standard also
-discusses actions that can be performed on a container to manage and inspect
-information about the processes running inside.
-
-The v1 profile is meant to be able to accommodate the majority of applications
-with a strong security configuration.
-
-### System Requirements and Compatibility
-
-Minimum requirements:
-* Kernel version - 3.10 recommended 2.6.2x minimum(with backported patches)
-* Mounted cgroups with each subsystem in its own hierarchy
-
-
-### Namespaces
-
-| Flag | Enabled |
-| ------------ | ------- |
-| CLONE_NEWPID | 1 |
-| CLONE_NEWUTS | 1 |
-| CLONE_NEWIPC | 1 |
-| CLONE_NEWNET | 1 |
-| CLONE_NEWNS | 1 |
-| CLONE_NEWUSER | 1 |
-
-Namespaces are created for the container via the `clone` syscall.
-
-
-### Filesystem
-
-A root filesystem must be provided to a container for execution. The container
-will use this root filesystem (rootfs) to jail and spawn processes inside where
-the binaries and system libraries are local to that directory. Any binaries
-to be executed must be contained within this rootfs.
-
-Mounts that happen inside the container are automatically cleaned up when the
-container exits as the mount namespace is destroyed and the kernel will
-unmount all the mounts that were setup within that namespace.
-
-For a container to execute properly there are certain filesystems that
-are required to be mounted within the rootfs that the runtime will setup.
-
-| Path | Type | Flags | Data |
-| ----------- | ------ | -------------------------------------- | ---------------------------------------- |
-| /proc | proc | MS_NOEXEC,MS_NOSUID,MS_NODEV | |
-| /dev | tmpfs | MS_NOEXEC,MS_STRICTATIME | mode=755 |
-| /dev/shm | tmpfs | MS_NOEXEC,MS_NOSUID,MS_NODEV | mode=1777,size=65536k |
-| /dev/mqueue | mqueue | MS_NOEXEC,MS_NOSUID,MS_NODEV | |
-| /dev/pts | devpts | MS_NOEXEC,MS_NOSUID | newinstance,ptmxmode=0666,mode=620,gid=5 |
-| /sys | sysfs | MS_NOEXEC,MS_NOSUID,MS_NODEV,MS_RDONLY | |
-
-
-After a container's filesystems are mounted within the newly created
-mount namespace `/dev` will need to be populated with a set of device nodes.
-It is expected that a rootfs does not need to have any device nodes specified
-for `/dev` witin the rootfs as the container will setup the correct devices
-that are required for executing a container's process.
-
-| Path | Mode | Access |
-| ------------ | ---- | ---------- |
-| /dev/null | 0666 | rwm |
-| /dev/zero | 0666 | rwm |
-| /dev/full | 0666 | rwm |
-| /dev/tty | 0666 | rwm |
-| /dev/random | 0666 | rwm |
-| /dev/urandom | 0666 | rwm |
-| /dev/fuse | 0666 | rwm |
-
-
-**ptmx**
-`/dev/ptmx` will need to be a symlink to the host's `/dev/ptmx` within
-the container.
-
-The use of a pseudo TTY is optional within a container and it should support both.
-If a pseudo is provided to the container `/dev/console` will need to be
-setup by binding the console in `/dev/` after it has been populated and mounted
-in tmpfs.
-
-| Source | Destination | UID GID | Mode | Type |
-| --------------- | ------------ | ------- | ---- | ---- |
-| *pty host path* | /dev/console | 0 0 | 0600 | bind |
-
-
-After `/dev/null` has been setup we check for any external links between
-the container's io, STDIN, STDOUT, STDERR. If the container's io is pointing
-to `/dev/null` outside the container we close and `dup2` the the `/dev/null`
-that is local to the container's rootfs.
-
-
-After the container has `/proc` mounted a few standard symlinks are setup
-within `/dev/` for the io.
-
-| Source | Destination |
-| --------------- | ----------- |
-| /proc/self/fd | /dev/fd |
-| /proc/self/fd/0 | /dev/stdin |
-| /proc/self/fd/1 | /dev/stdout |
-| /proc/self/fd/2 | /dev/stderr |
-
-A `pivot_root` is used to change the root for the process, effectively
-jailing the process inside the rootfs.
-
-```c
-put_old = mkdir(...);
-pivot_root(rootfs, put_old);
-chdir("/");
-unmount(put_old, MS_DETACH);
-rmdir(put_old);
-```
-
-For container's running with a rootfs inside `ramfs` a `MS_MOVE` combined
-with a `chroot` is required as `pivot_root` is not supported in `ramfs`.
-
-```c
-mount(rootfs, "/", NULL, MS_MOVE, NULL);
-chroot(".");
-chdir("/");
-```
-
-The `umask` is set back to `0022` after the filesystem setup has been completed.
-
-### Resources
-
-Cgroups are used to handle resource allocation for containers. This includes
-system resources like cpu, memory, and device access.
-
-| Subsystem | Enabled |
-| ---------- | ------- |
-| devices | 1 |
-| memory | 1 |
-| cpu | 1 |
-| cpuacct | 1 |
-| cpuset | 1 |
-| blkio | 1 |
-| perf_event | 1 |
-| freezer | 1 |
-| hugetlb | 1 |
-
-
-All cgroup subsystem are joined so that statistics can be collected from
-each of the subsystems. Freezer does not expose any stats but is joined
-so that containers can be paused and resumed.
-
-The parent process of the container's init must place the init pid inside
-the correct cgroups before the initialization begins. This is done so
-that no processes or threads escape the cgroups. This sync is
-done via a pipe ( specified in the runtime section below ) that the container's
-init process will block waiting for the parent to finish setup.
-
-### Security
-
-The standard set of Linux capabilities that are set in a container
-provide a good default for security and flexibility for the applications.
-
-
-| Capability | Enabled |
-| -------------------- | ------- |
-| CAP_NET_RAW | 1 |
-| CAP_NET_BIND_SERVICE | 1 |
-| CAP_AUDIT_READ | 1 |
-| CAP_AUDIT_WRITE | 1 |
-| CAP_DAC_OVERRIDE | 1 |
-| CAP_SETFCAP | 1 |
-| CAP_SETPCAP | 1 |
-| CAP_SETGID | 1 |
-| CAP_SETUID | 1 |
-| CAP_MKNOD | 1 |
-| CAP_CHOWN | 1 |
-| CAP_FOWNER | 1 |
-| CAP_FSETID | 1 |
-| CAP_KILL | 1 |
-| CAP_SYS_CHROOT | 1 |
-| CAP_NET_BROADCAST | 0 |
-| CAP_SYS_MODULE | 0 |
-| CAP_SYS_RAWIO | 0 |
-| CAP_SYS_PACCT | 0 |
-| CAP_SYS_ADMIN | 0 |
-| CAP_SYS_NICE | 0 |
-| CAP_SYS_RESOURCE | 0 |
-| CAP_SYS_TIME | 0 |
-| CAP_SYS_TTY_CONFIG | 0 |
-| CAP_AUDIT_CONTROL | 0 |
-| CAP_MAC_OVERRIDE | 0 |
-| CAP_MAC_ADMIN | 0 |
-| CAP_NET_ADMIN | 0 |
-| CAP_SYSLOG | 0 |
-| CAP_DAC_READ_SEARCH | 0 |
-| CAP_LINUX_IMMUTABLE | 0 |
-| CAP_IPC_LOCK | 0 |
-| CAP_IPC_OWNER | 0 |
-| CAP_SYS_PTRACE | 0 |
-| CAP_SYS_BOOT | 0 |
-| CAP_LEASE | 0 |
-| CAP_WAKE_ALARM | 0 |
-| CAP_BLOCK_SUSPE | 0 |
-
-
-Additional security layers like [apparmor](https://wiki.ubuntu.com/AppArmor)
-and [selinux](http://selinuxproject.org/page/Main_Page) can be used with
-the containers. A container should support setting an apparmor profile or
-selinux process and mount labels if provided in the configuration.
-
-Standard apparmor profile:
-```c
-#include
-profile flags=(attach_disconnected,mediate_deleted) {
- #include
- network,
- capability,
- file,
- umount,
-
- deny @{PROC}/sys/fs/** wklx,
- deny @{PROC}/sysrq-trigger rwklx,
- deny @{PROC}/mem rwklx,
- deny @{PROC}/kmem rwklx,
- deny @{PROC}/sys/kernel/[^s][^h][^m]* wklx,
- deny @{PROC}/sys/kernel/*/** wklx,
-
- deny mount,
-
- deny /sys/[^f]*/** wklx,
- deny /sys/f[^s]*/** wklx,
- deny /sys/fs/[^c]*/** wklx,
- deny /sys/fs/c[^g]*/** wklx,
- deny /sys/fs/cg[^r]*/** wklx,
- deny /sys/firmware/efi/efivars/** rwklx,
- deny /sys/kernel/security/** rwklx,
-}
-```
-
-*TODO: seccomp work is being done to find a good default config*
-
-### Runtime and Init Process
-
-During container creation the parent process needs to talk to the container's init
-process and have a form of synchronization. This is accomplished by creating
-a pipe that is passed to the container's init. When the init process first spawns
-it will block on its side of the pipe until the parent closes its side. This
-allows the parent to have time to set the new process inside a cgroup hierarchy
-and/or write any uid/gid mappings required for user namespaces.
-The pipe is passed to the init process via FD 3.
-
-The application consuming libcontainer should be compiled statically. libcontainer
-does not define any init process and the arguments provided are used to `exec` the
-process inside the application. There should be no long running init within the
-container spec.
-
-If a pseudo tty is provided to a container it will open and `dup2` the console
-as the container's STDIN, STDOUT, STDERR as well as mounting the console
-as `/dev/console`.
-
-An extra set of mounts are provided to a container and setup for use. A container's
-rootfs can contain some non portable files inside that can cause side effects during
-execution of a process. These files are usually created and populated with the container
-specific information via the runtime.
-
-**Extra runtime files:**
-* /etc/hosts
-* /etc/resolv.conf
-* /etc/hostname
-* /etc/localtime
-
-
-#### Defaults
-
-There are a few defaults that can be overridden by users, but in their omission
-these apply to processes within a container.
-
-| Type | Value |
-| ------------------- | ------------------------------ |
-| Parent Death Signal | SIGKILL |
-| UID | 0 |
-| GID | 0 |
-| GROUPS | 0, NULL |
-| CWD | "/" |
-| $HOME | Current user's home dir or "/" |
-| Readonly rootfs | false |
-| Pseudo TTY | false |
-
-
-## Actions
-
-After a container is created there is a standard set of actions that can
-be done to the container. These actions are part of the public API for
-a container.
-
-| Action | Description |
-| -------------- | ------------------------------------------------------------------ |
-| Get processes | Return all the pids for processes running inside a container |
-| Get Stats | Return resource statistics for the container as a whole |
-| Wait | Wait waits on the container's init process ( pid 1 ) |
-| Wait Process | Wait on any of the container's processes returning the exit status |
-| Destroy | Kill the container's init process and remove any filesystem state |
-| Signal | Send a signal to the container's init process |
-| Signal Process | Send a signal to any of the container's processes |
-| Pause | Pause all processes inside the container |
-| Resume | Resume all processes inside the container if paused |
-| Exec | Execute a new process inside of the container ( requires setns ) |
-| Set | Setup configs of the container after it's created |
-
-### Execute a new process inside of a running container.
-
-User can execute a new process inside of a running container. Any binaries to be
-executed must be accessible within the container's rootfs.
-
-The started process will run inside the container's rootfs. Any changes
-made by the process to the container's filesystem will persist after the
-process finished executing.
-
-The started process will join all the container's existing namespaces. When the
-container is paused, the process will also be paused and will resume when
-the container is unpaused. The started process will only run when the container's
-primary process (PID 1) is running, and will not be restarted when the container
-is restarted.
-
-#### Planned additions
-
-The started process will have its own cgroups nested inside the container's
-cgroups. This is used for process tracking and optionally resource allocation
-handling for the new process. Freezer cgroup is required, the rest of the cgroups
-are optional. The process executor must place its pid inside the correct
-cgroups before starting the process. This is done so that no child processes or
-threads can escape the cgroups.
-
-When the process is stopped, the process executor will try (in a best-effort way)
-to stop all its children and remove the sub-cgroups.
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/apparmor/apparmor.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/apparmor/apparmor.go
deleted file mode 100644
index 22c17f5..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/apparmor/apparmor.go
+++ /dev/null
@@ -1,38 +0,0 @@
-// +build apparmor,linux
-
-package apparmor
-
-// #cgo LDFLAGS: -lapparmor
-// #include
-// #include
-import "C"
-import (
- "io/ioutil"
- "os"
- "unsafe"
-)
-
-// IsEnabled returns true if apparmor is enabled for the host.
-func IsEnabled() bool {
- if _, err := os.Stat("/sys/kernel/security/apparmor"); err == nil && os.Getenv("container") == "" {
- if _, err = os.Stat("/sbin/apparmor_parser"); err == nil {
- buf, err := ioutil.ReadFile("/sys/module/apparmor/parameters/enabled")
- return err == nil && len(buf) > 1 && buf[0] == 'Y'
- }
- }
- return false
-}
-
-// ApplyProfile will apply the profile with the specified name to the process after
-// the next exec.
-func ApplyProfile(name string) error {
- if name == "" {
- return nil
- }
- cName := C.CString(name)
- defer C.free(unsafe.Pointer(cName))
- if _, err := C.aa_change_onexec(cName); err != nil {
- return err
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/apparmor/apparmor_disabled.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/apparmor/apparmor_disabled.go
deleted file mode 100644
index 937bf91..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/apparmor/apparmor_disabled.go
+++ /dev/null
@@ -1,11 +0,0 @@
-// +build !apparmor !linux
-
-package apparmor
-
-func IsEnabled() bool {
- return false
-}
-
-func ApplyProfile(name string) error {
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/capabilities_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/capabilities_linux.go
deleted file mode 100644
index 4eda56d..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/capabilities_linux.go
+++ /dev/null
@@ -1,69 +0,0 @@
-// +build linux
-
-package libcontainer
-
-import (
- "fmt"
- "os"
- "strings"
-
- "github.com/syndtr/gocapability/capability"
-)
-
-const allCapabilityTypes = capability.CAPS | capability.BOUNDS
-
-var capabilityMap map[string]capability.Cap
-
-func init() {
- capabilityMap = make(map[string]capability.Cap)
- last := capability.CAP_LAST_CAP
- // workaround for RHEL6 which has no /proc/sys/kernel/cap_last_cap
- if last == capability.Cap(63) {
- last = capability.CAP_BLOCK_SUSPEND
- }
- for _, cap := range capability.List() {
- if cap > last {
- continue
- }
- capKey := fmt.Sprintf("CAP_%s", strings.ToUpper(cap.String()))
- capabilityMap[capKey] = cap
- }
-}
-
-func newCapWhitelist(caps []string) (*whitelist, error) {
- l := []capability.Cap{}
- for _, c := range caps {
- v, ok := capabilityMap[c]
- if !ok {
- return nil, fmt.Errorf("unknown capability %q", c)
- }
- l = append(l, v)
- }
- pid, err := capability.NewPid(os.Getpid())
- if err != nil {
- return nil, err
- }
- return &whitelist{
- keep: l,
- pid: pid,
- }, nil
-}
-
-type whitelist struct {
- pid capability.Capabilities
- keep []capability.Cap
-}
-
-// dropBoundingSet drops the capability bounding set to those specified in the whitelist.
-func (w *whitelist) dropBoundingSet() error {
- w.pid.Clear(capability.BOUNDS)
- w.pid.Set(capability.BOUNDS, w.keep...)
- return w.pid.Apply(capability.BOUNDS)
-}
-
-// drop drops all capabilities for the current process except those specified in the whitelist.
-func (w *whitelist) drop() error {
- w.pid.Clear(allCapabilityTypes)
- w.pid.Set(allCapabilityTypes, w.keep...)
- return w.pid.Apply(allCapabilityTypes)
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups.go
deleted file mode 100644
index a08e905..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// +build linux
-
-package cgroups
-
-import (
- "fmt"
-
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-type Manager interface {
- // Apply cgroup configuration to the process with the specified pid
- Apply(pid int) error
-
- // Returns the PIDs inside the cgroup set
- GetPids() ([]int, error)
-
- // Returns statistics for the cgroup set
- GetStats() (*Stats, error)
-
- // Toggles the freezer cgroup according with specified state
- Freeze(state configs.FreezerState) error
-
- // Destroys the cgroup set
- Destroy() error
-
- // NewCgroupManager() and LoadCgroupManager() require following attributes:
- // Paths map[string]string
- // Cgroups *cgroups.Cgroup
- // Paths maps cgroup subsystem to path at which it is mounted.
- // Cgroups specifies specific cgroup settings for the various subsystems
-
- // Returns cgroup paths to save in a state file and to be able to
- // restore the object later.
- GetPaths() map[string]string
-
- // Set the cgroup as configured.
- Set(container *configs.Config) error
-}
-
-type NotFoundError struct {
- Subsystem string
-}
-
-func (e *NotFoundError) Error() string {
- return fmt.Sprintf("mountpoint for %s not found", e.Subsystem)
-}
-
-func NewNotFoundError(sub string) error {
- return &NotFoundError{
- Subsystem: sub,
- }
-}
-
-func IsNotFound(err error) bool {
- if err == nil {
- return false
- }
- _, ok := err.(*NotFoundError)
- return ok
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups_unsupported.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups_unsupported.go
deleted file mode 100644
index 278d507..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/cgroups_unsupported.go
+++ /dev/null
@@ -1,3 +0,0 @@
-// +build !linux
-
-package cgroups
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/apply_raw.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/apply_raw.go
deleted file mode 100644
index f3ecd4b..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/apply_raw.go
+++ /dev/null
@@ -1,346 +0,0 @@
-// +build linux
-
-package fs
-
-import (
- "errors"
- "fmt"
- "io"
- "io/ioutil"
- "os"
- "path/filepath"
- "strconv"
- "sync"
-
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-var (
- subsystems = subsystemSet{
- &CpusetGroup{},
- &DevicesGroup{},
- &MemoryGroup{},
- &CpuGroup{},
- &CpuacctGroup{},
- &BlkioGroup{},
- &HugetlbGroup{},
- &NetClsGroup{},
- &NetPrioGroup{},
- &PerfEventGroup{},
- &FreezerGroup{},
- }
- CgroupProcesses = "cgroup.procs"
- HugePageSizes, _ = cgroups.GetHugePageSize()
-)
-
-var errSubsystemDoesNotExist = errors.New("cgroup: subsystem does not exist")
-
-type subsystemSet []subsystem
-
-func (s subsystemSet) Get(name string) (subsystem, error) {
- for _, ss := range s {
- if ss.Name() == name {
- return ss, nil
- }
- }
- return nil, errSubsystemDoesNotExist
-}
-
-type subsystem interface {
- // Name returns the name of the subsystem.
- Name() string
- // Returns the stats, as 'stats', corresponding to the cgroup under 'path'.
- GetStats(path string, stats *cgroups.Stats) error
- // Removes the cgroup represented by 'data'.
- Remove(*data) error
- // Creates and joins the cgroup represented by data.
- Apply(*data) error
- // Set the cgroup represented by cgroup.
- Set(path string, cgroup *configs.Cgroup) error
-}
-
-type Manager struct {
- mu sync.Mutex
- Cgroups *configs.Cgroup
- Paths map[string]string
-}
-
-// The absolute path to the root of the cgroup hierarchies.
-var cgroupRootLock sync.Mutex
-var cgroupRoot string
-
-// Gets the cgroupRoot.
-func getCgroupRoot() (string, error) {
- cgroupRootLock.Lock()
- defer cgroupRootLock.Unlock()
-
- if cgroupRoot != "" {
- return cgroupRoot, nil
- }
-
- root, err := cgroups.FindCgroupMountpointDir()
- if err != nil {
- return "", err
- }
-
- if _, err := os.Stat(root); err != nil {
- return "", err
- }
-
- cgroupRoot = root
- return cgroupRoot, nil
-}
-
-type data struct {
- root string
- cgroup string
- c *configs.Cgroup
- pid int
-}
-
-func (m *Manager) Apply(pid int) (err error) {
- if m.Cgroups == nil {
- return nil
- }
-
- var c = m.Cgroups
-
- d, err := getCgroupData(m.Cgroups, pid)
- if err != nil {
- return err
- }
-
- paths := make(map[string]string)
- defer func() {
- if err != nil {
- cgroups.RemovePaths(paths)
- }
- }()
- for _, sys := range subsystems {
- if err := sys.Apply(d); err != nil {
- return err
- }
- // TODO: Apply should, ideally, be reentrant or be broken up into a separate
- // create and join phase so that the cgroup hierarchy for a container can be
- // created then join consists of writing the process pids to cgroup.procs
- p, err := d.path(sys.Name())
- if err != nil {
- if cgroups.IsNotFound(err) {
- continue
- }
- return err
- }
- paths[sys.Name()] = p
- }
- m.Paths = paths
-
- if paths["cpu"] != "" {
- if err := CheckCpushares(paths["cpu"], c.CpuShares); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (m *Manager) Destroy() error {
- m.mu.Lock()
- defer m.mu.Unlock()
- if err := cgroups.RemovePaths(m.Paths); err != nil {
- return err
- }
- m.Paths = make(map[string]string)
- return nil
-}
-
-func (m *Manager) GetPaths() map[string]string {
- m.mu.Lock()
- paths := m.Paths
- m.mu.Unlock()
- return paths
-}
-
-func (m *Manager) GetStats() (*cgroups.Stats, error) {
- m.mu.Lock()
- defer m.mu.Unlock()
- stats := cgroups.NewStats()
- for name, path := range m.Paths {
- sys, err := subsystems.Get(name)
- if err == errSubsystemDoesNotExist || !cgroups.PathExists(path) {
- continue
- }
- if err := sys.GetStats(path, stats); err != nil {
- return nil, err
- }
- }
- return stats, nil
-}
-
-func (m *Manager) Set(container *configs.Config) error {
- for name, path := range m.Paths {
- sys, err := subsystems.Get(name)
- if err == errSubsystemDoesNotExist || !cgroups.PathExists(path) {
- continue
- }
- if err := sys.Set(path, container.Cgroups); err != nil {
- return err
- }
- }
- return nil
-}
-
-// Freeze toggles the container's freezer cgroup depending on the state
-// provided
-func (m *Manager) Freeze(state configs.FreezerState) error {
- d, err := getCgroupData(m.Cgroups, 0)
- if err != nil {
- return err
- }
- dir, err := d.path("freezer")
- if err != nil {
- return err
- }
- prevState := m.Cgroups.Freezer
- m.Cgroups.Freezer = state
- freezer, err := subsystems.Get("freezer")
- if err != nil {
- return err
- }
- err = freezer.Set(dir, m.Cgroups)
- if err != nil {
- m.Cgroups.Freezer = prevState
- return err
- }
- return nil
-}
-
-func (m *Manager) GetPids() ([]int, error) {
- d, err := getCgroupData(m.Cgroups, 0)
- if err != nil {
- return nil, err
- }
-
- dir, err := d.path("devices")
- if err != nil {
- return nil, err
- }
-
- return cgroups.GetPids(dir)
-}
-
-func getCgroupData(c *configs.Cgroup, pid int) (*data, error) {
- root, err := getCgroupRoot()
- if err != nil {
- return nil, err
- }
-
- cgroup := c.Name
- if c.Parent != "" {
- cgroup = filepath.Join(c.Parent, cgroup)
- }
-
- return &data{
- root: root,
- cgroup: cgroup,
- c: c,
- pid: pid,
- }, nil
-}
-
-func (raw *data) parent(subsystem, mountpoint, root string) (string, error) {
- initPath, err := cgroups.GetThisCgroupDir(subsystem)
- if err != nil {
- return "", err
- }
- relDir, err := filepath.Rel(root, initPath)
- if err != nil {
- return "", err
- }
- return filepath.Join(mountpoint, relDir), nil
-}
-
-func (raw *data) path(subsystem string) (string, error) {
- mnt, root, err := cgroups.FindCgroupMountpointAndRoot(subsystem)
- // If we didn't mount the subsystem, there is no point we make the path.
- if err != nil {
- return "", err
- }
-
- // If the cgroup name/path is absolute do not look relative to the cgroup of the init process.
- if filepath.IsAbs(raw.cgroup) {
- return filepath.Join(raw.root, filepath.Base(mnt), raw.cgroup), nil
- }
-
- parent, err := raw.parent(subsystem, mnt, root)
- if err != nil {
- return "", err
- }
-
- return filepath.Join(parent, raw.cgroup), nil
-}
-
-func (raw *data) join(subsystem string) (string, error) {
- path, err := raw.path(subsystem)
- if err != nil {
- return "", err
- }
- if err := os.MkdirAll(path, 0755); err != nil {
- return "", err
- }
- if err := writeFile(path, CgroupProcesses, strconv.Itoa(raw.pid)); err != nil {
- return "", err
- }
- return path, nil
-}
-
-func writeFile(dir, file, data string) error {
- // Normally dir should not be empty, one case is that cgroup subsystem
- // is not mounted, we will get empty dir, and we want it fail here.
- if dir == "" {
- return fmt.Errorf("no such directory for %s.", file)
- }
- return ioutil.WriteFile(filepath.Join(dir, file), []byte(data), 0700)
-}
-
-func readFile(dir, file string) (string, error) {
- data, err := ioutil.ReadFile(filepath.Join(dir, file))
- return string(data), err
-}
-
-func removePath(p string, err error) error {
- if err != nil {
- return err
- }
- if p != "" {
- return os.RemoveAll(p)
- }
- return nil
-}
-
-func CheckCpushares(path string, c int64) error {
- var cpuShares int64
-
- if c == 0 {
- return nil
- }
-
- fd, err := os.Open(filepath.Join(path, "cpu.shares"))
- if err != nil {
- return err
- }
- defer fd.Close()
-
- _, err = fmt.Fscanf(fd, "%d", &cpuShares)
- if err != nil && err != io.EOF {
- return err
- }
-
- if c > cpuShares {
- return fmt.Errorf("The maximum allowed cpu-shares is %d", cpuShares)
- } else if c < cpuShares {
- return fmt.Errorf("The minimum allowed cpu-shares is %d", cpuShares)
- }
-
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/blkio.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/blkio.go
deleted file mode 100644
index 0cb65cb..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/blkio.go
+++ /dev/null
@@ -1,242 +0,0 @@
-// +build linux
-
-package fs
-
-import (
- "bufio"
- "fmt"
- "os"
- "path/filepath"
- "strconv"
- "strings"
-
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-type BlkioGroup struct {
-}
-
-func (s *BlkioGroup) Name() string {
- return "blkio"
-}
-
-func (s *BlkioGroup) Apply(d *data) error {
- dir, err := d.join("blkio")
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
-
- if err := s.Set(dir, d.c); err != nil {
- return err
- }
-
- return nil
-}
-
-func (s *BlkioGroup) Set(path string, cgroup *configs.Cgroup) error {
- if cgroup.BlkioWeight != 0 {
- if err := writeFile(path, "blkio.weight", strconv.FormatUint(uint64(cgroup.BlkioWeight), 10)); err != nil {
- return err
- }
- }
-
- if cgroup.BlkioLeafWeight != 0 {
- if err := writeFile(path, "blkio.leaf_weight", strconv.FormatUint(uint64(cgroup.BlkioLeafWeight), 10)); err != nil {
- return err
- }
- }
- for _, wd := range cgroup.BlkioWeightDevice {
- if err := writeFile(path, "blkio.weight_device", wd.WeightString()); err != nil {
- return err
- }
- if err := writeFile(path, "blkio.leaf_weight_device", wd.LeafWeightString()); err != nil {
- return err
- }
- }
- for _, td := range cgroup.BlkioThrottleReadBpsDevice {
- if err := writeFile(path, "blkio.throttle.read_bps_device", td.String()); err != nil {
- return err
- }
- }
- for _, td := range cgroup.BlkioThrottleWriteBpsDevice {
- if err := writeFile(path, "blkio.throttle.write_bps_device", td.String()); err != nil {
- return err
- }
- }
- for _, td := range cgroup.BlkioThrottleReadIOPSDevice {
- if err := writeFile(path, "blkio.throttle.read_iops_device", td.String()); err != nil {
- return err
- }
- }
- for _, td := range cgroup.BlkioThrottleWriteIOPSDevice {
- if err := writeFile(path, "blkio.throttle.write_iops_device", td.String()); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (s *BlkioGroup) Remove(d *data) error {
- return removePath(d.path("blkio"))
-}
-
-/*
-examples:
-
- blkio.sectors
- 8:0 6792
-
- blkio.io_service_bytes
- 8:0 Read 1282048
- 8:0 Write 2195456
- 8:0 Sync 2195456
- 8:0 Async 1282048
- 8:0 Total 3477504
- Total 3477504
-
- blkio.io_serviced
- 8:0 Read 124
- 8:0 Write 104
- 8:0 Sync 104
- 8:0 Async 124
- 8:0 Total 228
- Total 228
-
- blkio.io_queued
- 8:0 Read 0
- 8:0 Write 0
- 8:0 Sync 0
- 8:0 Async 0
- 8:0 Total 0
- Total 0
-*/
-
-func splitBlkioStatLine(r rune) bool {
- return r == ' ' || r == ':'
-}
-
-func getBlkioStat(path string) ([]cgroups.BlkioStatEntry, error) {
- var blkioStats []cgroups.BlkioStatEntry
- f, err := os.Open(path)
- if err != nil {
- if os.IsNotExist(err) {
- return blkioStats, nil
- }
- return nil, err
- }
- defer f.Close()
-
- sc := bufio.NewScanner(f)
- for sc.Scan() {
- // format: dev type amount
- fields := strings.FieldsFunc(sc.Text(), splitBlkioStatLine)
- if len(fields) < 3 {
- if len(fields) == 2 && fields[0] == "Total" {
- // skip total line
- continue
- } else {
- return nil, fmt.Errorf("Invalid line found while parsing %s: %s", path, sc.Text())
- }
- }
-
- v, err := strconv.ParseUint(fields[0], 10, 64)
- if err != nil {
- return nil, err
- }
- major := v
-
- v, err = strconv.ParseUint(fields[1], 10, 64)
- if err != nil {
- return nil, err
- }
- minor := v
-
- op := ""
- valueField := 2
- if len(fields) == 4 {
- op = fields[2]
- valueField = 3
- }
- v, err = strconv.ParseUint(fields[valueField], 10, 64)
- if err != nil {
- return nil, err
- }
- blkioStats = append(blkioStats, cgroups.BlkioStatEntry{Major: major, Minor: minor, Op: op, Value: v})
- }
-
- return blkioStats, nil
-}
-
-func (s *BlkioGroup) GetStats(path string, stats *cgroups.Stats) error {
- // Try to read CFQ stats available on all CFQ enabled kernels first
- if blkioStats, err := getBlkioStat(filepath.Join(path, "blkio.io_serviced_recursive")); err == nil && blkioStats != nil {
- return getCFQStats(path, stats)
- }
- return getStats(path, stats) // Use generic stats as fallback
-}
-
-func getCFQStats(path string, stats *cgroups.Stats) error {
- var blkioStats []cgroups.BlkioStatEntry
- var err error
-
- if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.sectors_recursive")); err != nil {
- return err
- }
- stats.BlkioStats.SectorsRecursive = blkioStats
-
- if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.io_service_bytes_recursive")); err != nil {
- return err
- }
- stats.BlkioStats.IoServiceBytesRecursive = blkioStats
-
- if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.io_serviced_recursive")); err != nil {
- return err
- }
- stats.BlkioStats.IoServicedRecursive = blkioStats
-
- if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.io_queued_recursive")); err != nil {
- return err
- }
- stats.BlkioStats.IoQueuedRecursive = blkioStats
-
- if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.io_service_time_recursive")); err != nil {
- return err
- }
- stats.BlkioStats.IoServiceTimeRecursive = blkioStats
-
- if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.io_wait_time_recursive")); err != nil {
- return err
- }
- stats.BlkioStats.IoWaitTimeRecursive = blkioStats
-
- if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.io_merged_recursive")); err != nil {
- return err
- }
- stats.BlkioStats.IoMergedRecursive = blkioStats
-
- if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.time_recursive")); err != nil {
- return err
- }
- stats.BlkioStats.IoTimeRecursive = blkioStats
-
- return nil
-}
-
-func getStats(path string, stats *cgroups.Stats) error {
- var blkioStats []cgroups.BlkioStatEntry
- var err error
-
- if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.throttle.io_service_bytes")); err != nil {
- return err
- }
- stats.BlkioStats.IoServiceBytesRecursive = blkioStats
-
- if blkioStats, err = getBlkioStat(filepath.Join(path, "blkio.throttle.io_serviced")); err != nil {
- return err
- }
- stats.BlkioStats.IoServicedRecursive = blkioStats
-
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpu.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpu.go
deleted file mode 100644
index 5161a7a..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpu.go
+++ /dev/null
@@ -1,99 +0,0 @@
-// +build linux
-
-package fs
-
-import (
- "bufio"
- "os"
- "path/filepath"
- "strconv"
-
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-type CpuGroup struct {
-}
-
-func (s *CpuGroup) Name() string {
- return "cpu"
-}
-
-func (s *CpuGroup) Apply(d *data) error {
- // We always want to join the cpu group, to allow fair cpu scheduling
- // on a container basis
- dir, err := d.join("cpu")
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
-
- if err := s.Set(dir, d.c); err != nil {
- return err
- }
-
- return nil
-}
-
-func (s *CpuGroup) Set(path string, cgroup *configs.Cgroup) error {
- if cgroup.CpuShares != 0 {
- if err := writeFile(path, "cpu.shares", strconv.FormatInt(cgroup.CpuShares, 10)); err != nil {
- return err
- }
- }
- if cgroup.CpuPeriod != 0 {
- if err := writeFile(path, "cpu.cfs_period_us", strconv.FormatInt(cgroup.CpuPeriod, 10)); err != nil {
- return err
- }
- }
- if cgroup.CpuQuota != 0 {
- if err := writeFile(path, "cpu.cfs_quota_us", strconv.FormatInt(cgroup.CpuQuota, 10)); err != nil {
- return err
- }
- }
- if cgroup.CpuRtPeriod != 0 {
- if err := writeFile(path, "cpu.rt_period_us", strconv.FormatInt(cgroup.CpuRtPeriod, 10)); err != nil {
- return err
- }
- }
- if cgroup.CpuRtRuntime != 0 {
- if err := writeFile(path, "cpu.rt_runtime_us", strconv.FormatInt(cgroup.CpuRtRuntime, 10)); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (s *CpuGroup) Remove(d *data) error {
- return removePath(d.path("cpu"))
-}
-
-func (s *CpuGroup) GetStats(path string, stats *cgroups.Stats) error {
- f, err := os.Open(filepath.Join(path, "cpu.stat"))
- if err != nil {
- if os.IsNotExist(err) {
- return nil
- }
- return err
- }
- defer f.Close()
-
- sc := bufio.NewScanner(f)
- for sc.Scan() {
- t, v, err := getCgroupParamKeyValue(sc.Text())
- if err != nil {
- return err
- }
- switch t {
- case "nr_periods":
- stats.CpuStats.ThrottlingData.Periods = v
-
- case "nr_throttled":
- stats.CpuStats.ThrottlingData.ThrottledPeriods = v
-
- case "throttled_time":
- stats.CpuStats.ThrottlingData.ThrottledTime = v
- }
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuacct.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuacct.go
deleted file mode 100644
index c855fb3..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuacct.go
+++ /dev/null
@@ -1,121 +0,0 @@
-// +build linux
-
-package fs
-
-import (
- "fmt"
- "io/ioutil"
- "path/filepath"
- "strconv"
- "strings"
-
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
- "github.com/opencontainers/runc/libcontainer/system"
-)
-
-const (
- cgroupCpuacctStat = "cpuacct.stat"
- nanosecondsInSecond = 1000000000
-)
-
-var clockTicks = uint64(system.GetClockTicks())
-
-type CpuacctGroup struct {
-}
-
-func (s *CpuacctGroup) Name() string {
- return "cpuacct"
-}
-
-func (s *CpuacctGroup) Apply(d *data) error {
- // we just want to join this group even though we don't set anything
- if _, err := d.join("cpuacct"); err != nil && !cgroups.IsNotFound(err) {
- return err
- }
-
- return nil
-}
-
-func (s *CpuacctGroup) Set(path string, cgroup *configs.Cgroup) error {
- return nil
-}
-
-func (s *CpuacctGroup) Remove(d *data) error {
- return removePath(d.path("cpuacct"))
-}
-
-func (s *CpuacctGroup) GetStats(path string, stats *cgroups.Stats) error {
- userModeUsage, kernelModeUsage, err := getCpuUsageBreakdown(path)
- if err != nil {
- return err
- }
-
- totalUsage, err := getCgroupParamUint(path, "cpuacct.usage")
- if err != nil {
- return err
- }
-
- percpuUsage, err := getPercpuUsage(path)
- if err != nil {
- return err
- }
-
- stats.CpuStats.CpuUsage.TotalUsage = totalUsage
- stats.CpuStats.CpuUsage.PercpuUsage = percpuUsage
- stats.CpuStats.CpuUsage.UsageInUsermode = userModeUsage
- stats.CpuStats.CpuUsage.UsageInKernelmode = kernelModeUsage
- return nil
-}
-
-// Returns user and kernel usage breakdown in nanoseconds.
-func getCpuUsageBreakdown(path string) (uint64, uint64, error) {
- userModeUsage := uint64(0)
- kernelModeUsage := uint64(0)
- const (
- userField = "user"
- systemField = "system"
- )
-
- // Expected format:
- // user
- // system
- data, err := ioutil.ReadFile(filepath.Join(path, cgroupCpuacctStat))
- if err != nil {
- return 0, 0, err
- }
- fields := strings.Fields(string(data))
- if len(fields) != 4 {
- return 0, 0, fmt.Errorf("failure - %s is expected to have 4 fields", filepath.Join(path, cgroupCpuacctStat))
- }
- if fields[0] != userField {
- return 0, 0, fmt.Errorf("unexpected field %q in %q, expected %q", fields[0], cgroupCpuacctStat, userField)
- }
- if fields[2] != systemField {
- return 0, 0, fmt.Errorf("unexpected field %q in %q, expected %q", fields[2], cgroupCpuacctStat, systemField)
- }
- if userModeUsage, err = strconv.ParseUint(fields[1], 10, 64); err != nil {
- return 0, 0, err
- }
- if kernelModeUsage, err = strconv.ParseUint(fields[3], 10, 64); err != nil {
- return 0, 0, err
- }
-
- return (userModeUsage * nanosecondsInSecond) / clockTicks, (kernelModeUsage * nanosecondsInSecond) / clockTicks, nil
-}
-
-func getPercpuUsage(path string) ([]uint64, error) {
- percpuUsage := []uint64{}
- data, err := ioutil.ReadFile(filepath.Join(path, "cpuacct.usage_percpu"))
- if err != nil {
- return percpuUsage, err
- }
- for _, value := range strings.Fields(string(data)) {
- value, err := strconv.ParseUint(value, 10, 64)
- if err != nil {
- return percpuUsage, fmt.Errorf("Unable to convert param value to uint64: %s", err)
- }
- percpuUsage = append(percpuUsage, value)
- }
- return percpuUsage, nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuset.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuset.go
deleted file mode 100644
index 19c27bd..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/cpuset.go
+++ /dev/null
@@ -1,138 +0,0 @@
-// +build linux
-
-package fs
-
-import (
- "bytes"
- "io/ioutil"
- "os"
- "path/filepath"
- "strconv"
-
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-type CpusetGroup struct {
-}
-
-func (s *CpusetGroup) Name() string {
- return "cpuset"
-}
-
-func (s *CpusetGroup) Apply(d *data) error {
- dir, err := d.path("cpuset")
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
- return s.ApplyDir(dir, d.c, d.pid)
-}
-
-func (s *CpusetGroup) Set(path string, cgroup *configs.Cgroup) error {
- if cgroup.CpusetCpus != "" {
- if err := writeFile(path, "cpuset.cpus", cgroup.CpusetCpus); err != nil {
- return err
- }
- }
- if cgroup.CpusetMems != "" {
- if err := writeFile(path, "cpuset.mems", cgroup.CpusetMems); err != nil {
- return err
- }
- }
- return nil
-}
-
-func (s *CpusetGroup) Remove(d *data) error {
- return removePath(d.path("cpuset"))
-}
-
-func (s *CpusetGroup) GetStats(path string, stats *cgroups.Stats) error {
- return nil
-}
-
-func (s *CpusetGroup) ApplyDir(dir string, cgroup *configs.Cgroup, pid int) error {
- // This might happen if we have no cpuset cgroup mounted.
- // Just do nothing and don't fail.
- if dir == "" {
- return nil
- }
- root, err := getCgroupRoot()
- if err != nil {
- return err
- }
- if err := s.ensureParent(dir, root); err != nil {
- return err
- }
- // the default values inherit from parent cgroup are already set in
- // s.ensureParent, cover these if we have our own
- if err := s.Set(dir, cgroup); err != nil {
- return err
- }
- // because we are not using d.join we need to place the pid into the procs file
- // unlike the other subsystems
- if err := writeFile(dir, "cgroup.procs", strconv.Itoa(pid)); err != nil {
- return err
- }
-
- return nil
-}
-
-func (s *CpusetGroup) getSubsystemSettings(parent string) (cpus []byte, mems []byte, err error) {
- if cpus, err = ioutil.ReadFile(filepath.Join(parent, "cpuset.cpus")); err != nil {
- return
- }
- if mems, err = ioutil.ReadFile(filepath.Join(parent, "cpuset.mems")); err != nil {
- return
- }
- return cpus, mems, nil
-}
-
-// ensureParent makes sure that the parent directory of current is created
-// and populated with the proper cpus and mems files copied from
-// it's parent.
-func (s *CpusetGroup) ensureParent(current, root string) error {
- parent := filepath.Dir(current)
- if filepath.Clean(parent) == root {
- return nil
- }
- if err := s.ensureParent(parent, root); err != nil {
- return err
- }
- if err := os.MkdirAll(current, 0755); err != nil {
- return err
- }
- return s.copyIfNeeded(current, parent)
-}
-
-// copyIfNeeded copies the cpuset.cpus and cpuset.mems from the parent
-// directory to the current directory if the file's contents are 0
-func (s *CpusetGroup) copyIfNeeded(current, parent string) error {
- var (
- err error
- currentCpus, currentMems []byte
- parentCpus, parentMems []byte
- )
-
- if currentCpus, currentMems, err = s.getSubsystemSettings(current); err != nil {
- return err
- }
- if parentCpus, parentMems, err = s.getSubsystemSettings(parent); err != nil {
- return err
- }
-
- if s.isEmpty(currentCpus) {
- if err := writeFile(current, "cpuset.cpus", string(parentCpus)); err != nil {
- return err
- }
- }
- if s.isEmpty(currentMems) {
- if err := writeFile(current, "cpuset.mems", string(parentMems)); err != nil {
- return err
- }
- }
- return nil
-}
-
-func (s *CpusetGroup) isEmpty(b []byte) bool {
- return len(bytes.Trim(b, "\n")) == 0
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/devices.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/devices.go
deleted file mode 100644
index dfd2060..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/devices.go
+++ /dev/null
@@ -1,65 +0,0 @@
-// +build linux
-
-package fs
-
-import (
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-type DevicesGroup struct {
-}
-
-func (s *DevicesGroup) Name() string {
- return "devices"
-}
-
-func (s *DevicesGroup) Apply(d *data) error {
- dir, err := d.join("devices")
- if err != nil {
- // We will return error even it's `not found` error, devices
- // cgroup is hard requirement for container's security.
- return err
- }
-
- if err := s.Set(dir, d.c); err != nil {
- return err
- }
-
- return nil
-}
-
-func (s *DevicesGroup) Set(path string, cgroup *configs.Cgroup) error {
- if !cgroup.AllowAllDevices {
- if err := writeFile(path, "devices.deny", "a"); err != nil {
- return err
- }
-
- for _, dev := range cgroup.AllowedDevices {
- if err := writeFile(path, "devices.allow", dev.CgroupString()); err != nil {
- return err
- }
- }
- return nil
- }
-
- if err := writeFile(path, "devices.allow", "a"); err != nil {
- return err
- }
-
- for _, dev := range cgroup.DeniedDevices {
- if err := writeFile(path, "devices.deny", dev.CgroupString()); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (s *DevicesGroup) Remove(d *data) error {
- return removePath(d.path("devices"))
-}
-
-func (s *DevicesGroup) GetStats(path string, stats *cgroups.Stats) error {
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/freezer.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/freezer.go
deleted file mode 100644
index b6df93e..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/freezer.go
+++ /dev/null
@@ -1,66 +0,0 @@
-// +build linux
-
-package fs
-
-import (
- "fmt"
- "strings"
- "time"
-
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-type FreezerGroup struct {
-}
-
-func (s *FreezerGroup) Name() string {
- return "freezer"
-}
-
-func (s *FreezerGroup) Apply(d *data) error {
- dir, err := d.join("freezer")
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
-
- if err := s.Set(dir, d.c); err != nil {
- return err
- }
-
- return nil
-}
-
-func (s *FreezerGroup) Set(path string, cgroup *configs.Cgroup) error {
- switch cgroup.Freezer {
- case configs.Frozen, configs.Thawed:
- if err := writeFile(path, "freezer.state", string(cgroup.Freezer)); err != nil {
- return err
- }
-
- for {
- state, err := readFile(path, "freezer.state")
- if err != nil {
- return err
- }
- if strings.TrimSpace(state) == string(cgroup.Freezer) {
- break
- }
- time.Sleep(1 * time.Millisecond)
- }
- case configs.Undefined:
- return nil
- default:
- return fmt.Errorf("Invalid argument '%s' to freezer.state", string(cgroup.Freezer))
- }
-
- return nil
-}
-
-func (s *FreezerGroup) Remove(d *data) error {
- return removePath(d.path("freezer"))
-}
-
-func (s *FreezerGroup) GetStats(path string, stats *cgroups.Stats) error {
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/fs_unsupported.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/fs_unsupported.go
deleted file mode 100644
index 3ef9e03..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/fs_unsupported.go
+++ /dev/null
@@ -1,3 +0,0 @@
-// +build !linux
-
-package fs
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/hugetlb.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/hugetlb.go
deleted file mode 100644
index 1c2f7f7..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/hugetlb.go
+++ /dev/null
@@ -1,76 +0,0 @@
-// +build linux
-
-package fs
-
-import (
- "fmt"
- "strconv"
- "strings"
-
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-type HugetlbGroup struct {
-}
-
-func (s *HugetlbGroup) Name() string {
- return "hugetlb"
-}
-
-func (s *HugetlbGroup) Apply(d *data) error {
- dir, err := d.join("hugetlb")
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
-
- if err := s.Set(dir, d.c); err != nil {
- return err
- }
-
- return nil
-}
-
-func (s *HugetlbGroup) Set(path string, cgroup *configs.Cgroup) error {
- for _, hugetlb := range cgroup.HugetlbLimit {
- if err := writeFile(path, strings.Join([]string{"hugetlb", hugetlb.Pagesize, "limit_in_bytes"}, "."), strconv.FormatUint(hugetlb.Limit, 10)); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (s *HugetlbGroup) Remove(d *data) error {
- return removePath(d.path("hugetlb"))
-}
-
-func (s *HugetlbGroup) GetStats(path string, stats *cgroups.Stats) error {
- hugetlbStats := cgroups.HugetlbStats{}
- for _, pageSize := range HugePageSizes {
- usage := strings.Join([]string{"hugetlb", pageSize, "usage_in_bytes"}, ".")
- value, err := getCgroupParamUint(path, usage)
- if err != nil {
- return fmt.Errorf("failed to parse %s - %v", usage, err)
- }
- hugetlbStats.Usage = value
-
- maxUsage := strings.Join([]string{"hugetlb", pageSize, "max_usage_in_bytes"}, ".")
- value, err = getCgroupParamUint(path, maxUsage)
- if err != nil {
- return fmt.Errorf("failed to parse %s - %v", maxUsage, err)
- }
- hugetlbStats.MaxUsage = value
-
- failcnt := strings.Join([]string{"hugetlb", pageSize, "failcnt"}, ".")
- value, err = getCgroupParamUint(path, failcnt)
- if err != nil {
- return fmt.Errorf("failed to parse %s - %v", failcnt, err)
- }
- hugetlbStats.Failcnt = value
-
- stats.HugetlbStats[pageSize] = hugetlbStats
- }
-
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/memory.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/memory.go
deleted file mode 100644
index dd31849..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/memory.go
+++ /dev/null
@@ -1,187 +0,0 @@
-// +build linux
-
-package fs
-
-import (
- "bufio"
- "fmt"
- "os"
- "path/filepath"
- "strconv"
- "strings"
-
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-type MemoryGroup struct {
-}
-
-func (s *MemoryGroup) Name() string {
- return "memory"
-}
-
-func (s *MemoryGroup) Apply(d *data) (err error) {
- path, err := d.path("memory")
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
- if memoryAssigned(d.c) {
- if path != "" {
- if err := os.MkdirAll(path, 0755); err != nil {
- return err
- }
- }
-
- if err := s.Set(path, d.c); err != nil {
- return err
- }
- }
-
- defer func() {
- if err != nil {
- os.RemoveAll(path)
- }
- }()
-
- // We need to join memory cgroup after set memory limits, because
- // kmem.limit_in_bytes can only be set when the cgroup is empty.
- _, err = d.join("memory")
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
-
- return nil
-}
-
-func (s *MemoryGroup) Set(path string, cgroup *configs.Cgroup) error {
- if cgroup.Memory != 0 {
- if err := writeFile(path, "memory.limit_in_bytes", strconv.FormatInt(cgroup.Memory, 10)); err != nil {
- return err
- }
- }
- if cgroup.MemoryReservation != 0 {
- if err := writeFile(path, "memory.soft_limit_in_bytes", strconv.FormatInt(cgroup.MemoryReservation, 10)); err != nil {
- return err
- }
- }
- if cgroup.MemorySwap > 0 {
- if err := writeFile(path, "memory.memsw.limit_in_bytes", strconv.FormatInt(cgroup.MemorySwap, 10)); err != nil {
- return err
- }
- }
- if cgroup.KernelMemory > 0 {
- if err := writeFile(path, "memory.kmem.limit_in_bytes", strconv.FormatInt(cgroup.KernelMemory, 10)); err != nil {
- return err
- }
- }
-
- if cgroup.OomKillDisable {
- if err := writeFile(path, "memory.oom_control", "1"); err != nil {
- return err
- }
- }
- if cgroup.MemorySwappiness >= 0 && cgroup.MemorySwappiness <= 100 {
- if err := writeFile(path, "memory.swappiness", strconv.FormatInt(cgroup.MemorySwappiness, 10)); err != nil {
- return err
- }
- } else if cgroup.MemorySwappiness == -1 {
- return nil
- } else {
- return fmt.Errorf("invalid value:%d. valid memory swappiness range is 0-100", cgroup.MemorySwappiness)
- }
-
- return nil
-}
-
-func (s *MemoryGroup) Remove(d *data) error {
- return removePath(d.path("memory"))
-}
-
-func (s *MemoryGroup) GetStats(path string, stats *cgroups.Stats) error {
- // Set stats from memory.stat.
- statsFile, err := os.Open(filepath.Join(path, "memory.stat"))
- if err != nil {
- if os.IsNotExist(err) {
- return nil
- }
- return err
- }
- defer statsFile.Close()
-
- sc := bufio.NewScanner(statsFile)
- for sc.Scan() {
- t, v, err := getCgroupParamKeyValue(sc.Text())
- if err != nil {
- return fmt.Errorf("failed to parse memory.stat (%q) - %v", sc.Text(), err)
- }
- stats.MemoryStats.Stats[t] = v
- }
- stats.MemoryStats.Cache = stats.MemoryStats.Stats["cache"]
-
- memoryUsage, err := getMemoryData(path, "")
- if err != nil {
- return err
- }
- stats.MemoryStats.Usage = memoryUsage
- swapUsage, err := getMemoryData(path, "memsw")
- if err != nil {
- return err
- }
- stats.MemoryStats.SwapUsage = swapUsage
- kernelUsage, err := getMemoryData(path, "kmem")
- if err != nil {
- return err
- }
- stats.MemoryStats.KernelUsage = kernelUsage
-
- return nil
-}
-
-func memoryAssigned(cgroup *configs.Cgroup) bool {
- return cgroup.Memory != 0 ||
- cgroup.MemoryReservation != 0 ||
- cgroup.MemorySwap > 0 ||
- cgroup.KernelMemory > 0 ||
- cgroup.OomKillDisable ||
- cgroup.MemorySwappiness != -1
-}
-
-func getMemoryData(path, name string) (cgroups.MemoryData, error) {
- memoryData := cgroups.MemoryData{}
-
- moduleName := "memory"
- if name != "" {
- moduleName = strings.Join([]string{"memory", name}, ".")
- }
- usage := strings.Join([]string{moduleName, "usage_in_bytes"}, ".")
- maxUsage := strings.Join([]string{moduleName, "max_usage_in_bytes"}, ".")
- failcnt := strings.Join([]string{moduleName, "failcnt"}, ".")
-
- value, err := getCgroupParamUint(path, usage)
- if err != nil {
- if moduleName != "memory" && os.IsNotExist(err) {
- return cgroups.MemoryData{}, nil
- }
- return cgroups.MemoryData{}, fmt.Errorf("failed to parse %s - %v", usage, err)
- }
- memoryData.Usage = value
- value, err = getCgroupParamUint(path, maxUsage)
- if err != nil {
- if moduleName != "memory" && os.IsNotExist(err) {
- return cgroups.MemoryData{}, nil
- }
- return cgroups.MemoryData{}, fmt.Errorf("failed to parse %s - %v", maxUsage, err)
- }
- memoryData.MaxUsage = value
- value, err = getCgroupParamUint(path, failcnt)
- if err != nil {
- if moduleName != "memory" && os.IsNotExist(err) {
- return cgroups.MemoryData{}, nil
- }
- return cgroups.MemoryData{}, fmt.Errorf("failed to parse %s - %v", failcnt, err)
- }
- memoryData.Failcnt = value
-
- return memoryData, nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/name.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/name.go
deleted file mode 100644
index 264d0ee..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/name.go
+++ /dev/null
@@ -1,32 +0,0 @@
-// +build linux
-
-package fs
-
-import (
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-type NameGroup struct {
- GroupName string
-}
-
-func (s *NameGroup) Name() string {
- return s.GroupName
-}
-
-func (s *NameGroup) Apply(d *data) error {
- return nil
-}
-
-func (s *NameGroup) Set(path string, cgroup *configs.Cgroup) error {
- return nil
-}
-
-func (s *NameGroup) Remove(d *data) error {
- return nil
-}
-
-func (s *NameGroup) GetStats(path string, stats *cgroups.Stats) error {
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_cls.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_cls.go
deleted file mode 100644
index 35df2f5..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_cls.go
+++ /dev/null
@@ -1,46 +0,0 @@
-// +build linux
-
-package fs
-
-import (
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-type NetClsGroup struct {
-}
-
-func (s *NetClsGroup) Name() string {
- return "net_cls"
-}
-
-func (s *NetClsGroup) Apply(d *data) error {
- dir, err := d.join("net_cls")
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
-
- if err := s.Set(dir, d.c); err != nil {
- return err
- }
-
- return nil
-}
-
-func (s *NetClsGroup) Set(path string, cgroup *configs.Cgroup) error {
- if cgroup.NetClsClassid != "" {
- if err := writeFile(path, "net_cls.classid", cgroup.NetClsClassid); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (s *NetClsGroup) Remove(d *data) error {
- return removePath(d.path("net_cls"))
-}
-
-func (s *NetClsGroup) GetStats(path string, stats *cgroups.Stats) error {
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_prio.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_prio.go
deleted file mode 100644
index 294ff09..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/net_prio.go
+++ /dev/null
@@ -1,46 +0,0 @@
-// +build linux
-
-package fs
-
-import (
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-type NetPrioGroup struct {
-}
-
-func (s *NetPrioGroup) Name() string {
- return "net_prio"
-}
-
-func (s *NetPrioGroup) Apply(d *data) error {
- dir, err := d.join("net_prio")
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
-
- if err := s.Set(dir, d.c); err != nil {
- return err
- }
-
- return nil
-}
-
-func (s *NetPrioGroup) Set(path string, cgroup *configs.Cgroup) error {
- for _, prioMap := range cgroup.NetPrioIfpriomap {
- if err := writeFile(path, "net_prio.ifpriomap", prioMap.CgroupString()); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (s *NetPrioGroup) Remove(d *data) error {
- return removePath(d.path("net_prio"))
-}
-
-func (s *NetPrioGroup) GetStats(path string, stats *cgroups.Stats) error {
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/perf_event.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/perf_event.go
deleted file mode 100644
index 7bcb8df..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/perf_event.go
+++ /dev/null
@@ -1,35 +0,0 @@
-// +build linux
-
-package fs
-
-import (
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-type PerfEventGroup struct {
-}
-
-func (s *PerfEventGroup) Name() string {
- return "perf_event"
-}
-
-func (s *PerfEventGroup) Apply(d *data) error {
- // we just want to join this group even though we don't set anything
- if _, err := d.join("perf_event"); err != nil && !cgroups.IsNotFound(err) {
- return err
- }
- return nil
-}
-
-func (s *PerfEventGroup) Set(path string, cgroup *configs.Cgroup) error {
- return nil
-}
-
-func (s *PerfEventGroup) Remove(d *data) error {
- return removePath(d.path("perf_event"))
-}
-
-func (s *PerfEventGroup) GetStats(path string, stats *cgroups.Stats) error {
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/utils.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/utils.go
deleted file mode 100644
index 852b183..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/fs/utils.go
+++ /dev/null
@@ -1,79 +0,0 @@
-// +build linux
-
-package fs
-
-import (
- "errors"
- "fmt"
- "io/ioutil"
- "path/filepath"
- "strconv"
- "strings"
-)
-
-var (
- ErrNotSupportStat = errors.New("stats are not supported for subsystem")
- ErrNotValidFormat = errors.New("line is not a valid key value format")
-)
-
-// Saturates negative values at zero and returns a uint64.
-// Due to kernel bugs, some of the memory cgroup stats can be negative.
-func parseUint(s string, base, bitSize int) (uint64, error) {
- value, err := strconv.ParseUint(s, base, bitSize)
- if err != nil {
- intValue, intErr := strconv.ParseInt(s, base, bitSize)
- // 1. Handle negative values greater than MinInt64 (and)
- // 2. Handle negative values lesser than MinInt64
- if intErr == nil && intValue < 0 {
- return 0, nil
- } else if intErr != nil && intErr.(*strconv.NumError).Err == strconv.ErrRange && intValue < 0 {
- return 0, nil
- }
-
- return value, err
- }
-
- return value, nil
-}
-
-// Parses a cgroup param and returns as name, value
-// i.e. "io_service_bytes 1234" will return as io_service_bytes, 1234
-func getCgroupParamKeyValue(t string) (string, uint64, error) {
- parts := strings.Fields(t)
- switch len(parts) {
- case 2:
- value, err := parseUint(parts[1], 10, 64)
- if err != nil {
- return "", 0, fmt.Errorf("unable to convert param value (%q) to uint64: %v", parts[1], err)
- }
-
- return parts[0], value, nil
- default:
- return "", 0, ErrNotValidFormat
- }
-}
-
-// Gets a single uint64 value from the specified cgroup file.
-func getCgroupParamUint(cgroupPath, cgroupFile string) (uint64, error) {
- fileName := filepath.Join(cgroupPath, cgroupFile)
- contents, err := ioutil.ReadFile(fileName)
- if err != nil {
- return 0, err
- }
-
- res, err := parseUint(strings.TrimSpace(string(contents)), 10, 64)
- if err != nil {
- return res, fmt.Errorf("unable to parse %q as a uint from Cgroup file %q", string(contents), fileName)
- }
- return res, nil
-}
-
-// Gets a string value from the specified cgroup file
-func getCgroupParamString(cgroupPath, cgroupFile string) (string, error) {
- contents, err := ioutil.ReadFile(filepath.Join(cgroupPath, cgroupFile))
- if err != nil {
- return "", err
- }
-
- return strings.TrimSpace(string(contents)), nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/stats.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/stats.go
deleted file mode 100644
index bda32b2..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/stats.go
+++ /dev/null
@@ -1,92 +0,0 @@
-// +build linux
-
-package cgroups
-
-type ThrottlingData struct {
- // Number of periods with throttling active
- Periods uint64 `json:"periods,omitempty"`
- // Number of periods when the container hit its throttling limit.
- ThrottledPeriods uint64 `json:"throttled_periods,omitempty"`
- // Aggregate time the container was throttled for in nanoseconds.
- ThrottledTime uint64 `json:"throttled_time,omitempty"`
-}
-
-// All CPU stats are aggregate since container inception.
-type CpuUsage struct {
- // Total CPU time consumed.
- // Units: nanoseconds.
- TotalUsage uint64 `json:"total_usage,omitempty"`
- // Total CPU time consumed per core.
- // Units: nanoseconds.
- PercpuUsage []uint64 `json:"percpu_usage,omitempty"`
- // Time spent by tasks of the cgroup in kernel mode.
- // Units: nanoseconds.
- UsageInKernelmode uint64 `json:"usage_in_kernelmode"`
- // Time spent by tasks of the cgroup in user mode.
- // Units: nanoseconds.
- UsageInUsermode uint64 `json:"usage_in_usermode"`
-}
-
-type CpuStats struct {
- CpuUsage CpuUsage `json:"cpu_usage,omitempty"`
- ThrottlingData ThrottlingData `json:"throttling_data,omitempty"`
-}
-
-type MemoryData struct {
- Usage uint64 `json:"usage,omitempty"`
- MaxUsage uint64 `json:"max_usage,omitempty"`
- Failcnt uint64 `json:"failcnt"`
-}
-type MemoryStats struct {
- // memory used for cache
- Cache uint64 `json:"cache,omitempty"`
- // usage of memory
- Usage MemoryData `json:"usage,omitempty"`
- // usage of memory + swap
- SwapUsage MemoryData `json:"swap_usage,omitempty"`
- // usafe of kernel memory
- KernelUsage MemoryData `json:"kernel_usage,omitempty"`
- Stats map[string]uint64 `json:"stats,omitempty"`
-}
-
-type BlkioStatEntry struct {
- Major uint64 `json:"major,omitempty"`
- Minor uint64 `json:"minor,omitempty"`
- Op string `json:"op,omitempty"`
- Value uint64 `json:"value,omitempty"`
-}
-
-type BlkioStats struct {
- // number of bytes tranferred to and from the block device
- IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive,omitempty"`
- IoServicedRecursive []BlkioStatEntry `json:"io_serviced_recursive,omitempty"`
- IoQueuedRecursive []BlkioStatEntry `json:"io_queue_recursive,omitempty"`
- IoServiceTimeRecursive []BlkioStatEntry `json:"io_service_time_recursive,omitempty"`
- IoWaitTimeRecursive []BlkioStatEntry `json:"io_wait_time_recursive,omitempty"`
- IoMergedRecursive []BlkioStatEntry `json:"io_merged_recursive,omitempty"`
- IoTimeRecursive []BlkioStatEntry `json:"io_time_recursive,omitempty"`
- SectorsRecursive []BlkioStatEntry `json:"sectors_recursive,omitempty"`
-}
-
-type HugetlbStats struct {
- // current res_counter usage for hugetlb
- Usage uint64 `json:"usage,omitempty"`
- // maximum usage ever recorded.
- MaxUsage uint64 `json:"max_usage,omitempty"`
- // number of times htgetlb usage allocation failure.
- Failcnt uint64 `json:"failcnt"`
-}
-
-type Stats struct {
- CpuStats CpuStats `json:"cpu_stats,omitempty"`
- MemoryStats MemoryStats `json:"memory_stats,omitempty"`
- BlkioStats BlkioStats `json:"blkio_stats,omitempty"`
- // the map is in the format "size of hugepage: stats of the hugepage"
- HugetlbStats map[string]HugetlbStats `json:"hugetlb_stats,omitempty"`
-}
-
-func NewStats() *Stats {
- memoryStats := MemoryStats{Stats: make(map[string]uint64)}
- hugetlbStats := make(map[string]HugetlbStats)
- return &Stats{MemoryStats: memoryStats, HugetlbStats: hugetlbStats}
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_nosystemd.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_nosystemd.go
deleted file mode 100644
index fa3485f..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_nosystemd.go
+++ /dev/null
@@ -1,51 +0,0 @@
-// +build !linux
-
-package systemd
-
-import (
- "fmt"
-
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-type Manager struct {
- Cgroups *configs.Cgroup
- Paths map[string]string
-}
-
-func UseSystemd() bool {
- return false
-}
-
-func (m *Manager) Apply(pid int) error {
- return fmt.Errorf("Systemd not supported")
-}
-
-func (m *Manager) GetPids() ([]int, error) {
- return nil, fmt.Errorf("Systemd not supported")
-}
-
-func (m *Manager) Destroy() error {
- return fmt.Errorf("Systemd not supported")
-}
-
-func (m *Manager) GetPaths() map[string]string {
- return nil
-}
-
-func (m *Manager) GetStats() (*cgroups.Stats, error) {
- return nil, fmt.Errorf("Systemd not supported")
-}
-
-func (m *Manager) Set(container *configs.Config) error {
- return nil, fmt.Errorf("Systemd not supported")
-}
-
-func (m *Manager) Freeze(state configs.FreezerState) error {
- return fmt.Errorf("Systemd not supported")
-}
-
-func Freeze(c *configs.Cgroup, state configs.FreezerState) error {
- return fmt.Errorf("Systemd not supported")
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_systemd.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_systemd.go
deleted file mode 100644
index 7a422b3..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/systemd/apply_systemd.go
+++ /dev/null
@@ -1,644 +0,0 @@
-// +build linux
-
-package systemd
-
-import (
- "errors"
- "fmt"
- "io/ioutil"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "sync"
- "time"
-
- systemdDbus "github.com/coreos/go-systemd/dbus"
- systemdUtil "github.com/coreos/go-systemd/util"
- "github.com/godbus/dbus"
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/cgroups/fs"
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-type Manager struct {
- mu sync.Mutex
- Cgroups *configs.Cgroup
- Paths map[string]string
-}
-
-type subsystem interface {
- // Name returns the name of the subsystem.
- Name() string
- // Returns the stats, as 'stats', corresponding to the cgroup under 'path'.
- GetStats(path string, stats *cgroups.Stats) error
- // Set the cgroup represented by cgroup.
- Set(path string, cgroup *configs.Cgroup) error
-}
-
-var errSubsystemDoesNotExist = errors.New("cgroup: subsystem does not exist")
-
-type subsystemSet []subsystem
-
-func (s subsystemSet) Get(name string) (subsystem, error) {
- for _, ss := range s {
- if ss.Name() == name {
- return ss, nil
- }
- }
- return nil, errSubsystemDoesNotExist
-}
-
-var subsystems = subsystemSet{
- &fs.CpusetGroup{},
- &fs.DevicesGroup{},
- &fs.MemoryGroup{},
- &fs.CpuGroup{},
- &fs.CpuacctGroup{},
- &fs.BlkioGroup{},
- &fs.HugetlbGroup{},
- &fs.PerfEventGroup{},
- &fs.FreezerGroup{},
- &fs.NetPrioGroup{},
- &fs.NetClsGroup{},
- &fs.NameGroup{GroupName: "name=systemd"},
-}
-
-const (
- testScopeWait = 4
-)
-
-var (
- connLock sync.Mutex
- theConn *systemdDbus.Conn
- hasStartTransientUnit bool
- hasTransientDefaultDependencies bool
-)
-
-func newProp(name string, units interface{}) systemdDbus.Property {
- return systemdDbus.Property{
- Name: name,
- Value: dbus.MakeVariant(units),
- }
-}
-
-func UseSystemd() bool {
- if !systemdUtil.IsRunningSystemd() {
- return false
- }
-
- connLock.Lock()
- defer connLock.Unlock()
-
- if theConn == nil {
- var err error
- theConn, err = systemdDbus.New()
- if err != nil {
- return false
- }
-
- // Assume we have StartTransientUnit
- hasStartTransientUnit = true
-
- // But if we get UnknownMethod error we don't
- if _, err := theConn.StartTransientUnit("test.scope", "invalid", nil, nil); err != nil {
- if dbusError, ok := err.(dbus.Error); ok {
- if dbusError.Name == "org.freedesktop.DBus.Error.UnknownMethod" {
- hasStartTransientUnit = false
- return hasStartTransientUnit
- }
- }
- }
-
- // Ensure the scope name we use doesn't exist. Use the Pid to
- // avoid collisions between multiple libcontainer users on a
- // single host.
- scope := fmt.Sprintf("libcontainer-%d-systemd-test-default-dependencies.scope", os.Getpid())
- testScopeExists := true
- for i := 0; i <= testScopeWait; i++ {
- if _, err := theConn.StopUnit(scope, "replace", nil); err != nil {
- if dbusError, ok := err.(dbus.Error); ok {
- if strings.Contains(dbusError.Name, "org.freedesktop.systemd1.NoSuchUnit") {
- testScopeExists = false
- break
- }
- }
- }
- time.Sleep(time.Millisecond)
- }
-
- // Bail out if we can't kill this scope without testing for DefaultDependencies
- if testScopeExists {
- return hasStartTransientUnit
- }
-
- // Assume StartTransientUnit on a scope allows DefaultDependencies
- hasTransientDefaultDependencies = true
- ddf := newProp("DefaultDependencies", false)
- if _, err := theConn.StartTransientUnit(scope, "replace", []systemdDbus.Property{ddf}, nil); err != nil {
- if dbusError, ok := err.(dbus.Error); ok {
- if strings.Contains(dbusError.Name, "org.freedesktop.DBus.Error.PropertyReadOnly") {
- hasTransientDefaultDependencies = false
- }
- }
- }
-
- // Not critical because of the stop unit logic above.
- theConn.StopUnit(scope, "replace", nil)
- }
- return hasStartTransientUnit
-}
-
-func getIfaceForUnit(unitName string) string {
- if strings.HasSuffix(unitName, ".scope") {
- return "Scope"
- }
- if strings.HasSuffix(unitName, ".service") {
- return "Service"
- }
- return "Unit"
-}
-
-func (m *Manager) Apply(pid int) error {
- var (
- c = m.Cgroups
- unitName = getUnitName(c)
- slice = "system.slice"
- properties []systemdDbus.Property
- )
-
- if c.Slice != "" {
- slice = c.Slice
- }
-
- properties = append(properties,
- systemdDbus.PropSlice(slice),
- systemdDbus.PropDescription("docker container "+c.Name),
- newProp("PIDs", []uint32{uint32(pid)}),
- )
-
- // Always enable accounting, this gets us the same behaviour as the fs implementation,
- // plus the kernel has some problems with joining the memory cgroup at a later time.
- properties = append(properties,
- newProp("MemoryAccounting", true),
- newProp("CPUAccounting", true),
- newProp("BlockIOAccounting", true))
-
- if hasTransientDefaultDependencies {
- properties = append(properties,
- newProp("DefaultDependencies", false))
- }
-
- if c.Memory != 0 {
- properties = append(properties,
- newProp("MemoryLimit", uint64(c.Memory)))
- }
-
- if c.CpuShares != 0 {
- properties = append(properties,
- newProp("CPUShares", uint64(c.CpuShares)))
- }
-
- if c.BlkioWeight != 0 {
- properties = append(properties,
- newProp("BlockIOWeight", uint64(c.BlkioWeight)))
- }
-
- // We need to set kernel memory before processes join cgroup because
- // kmem.limit_in_bytes can only be set when the cgroup is empty.
- // And swap memory limit needs to be set after memory limit, only
- // memory limit is handled by systemd, so it's kind of ugly here.
- if c.KernelMemory > 0 {
- if err := setKernelMemory(c); err != nil {
- return err
- }
- }
-
- if _, err := theConn.StartTransientUnit(unitName, "replace", properties, nil); err != nil {
- return err
- }
-
- if err := joinDevices(c, pid); err != nil {
- return err
- }
-
- // TODO: CpuQuota and CpuPeriod not available in systemd
- // we need to manually join the cpu.cfs_quota_us and cpu.cfs_period_us
- if err := joinCpu(c, pid); err != nil {
- return err
- }
-
- // TODO: MemoryReservation and MemorySwap not available in systemd
- if err := joinMemory(c, pid); err != nil {
- return err
- }
-
- // we need to manually join the freezer, net_cls, net_prio and cpuset cgroup in systemd
- // because it does not currently support it via the dbus api.
- if err := joinFreezer(c, pid); err != nil {
- return err
- }
-
- if err := joinNetPrio(c, pid); err != nil {
- return err
- }
- if err := joinNetCls(c, pid); err != nil {
- return err
- }
-
- if err := joinCpuset(c, pid); err != nil {
- return err
- }
-
- if err := joinHugetlb(c, pid); err != nil {
- return err
- }
-
- if err := joinPerfEvent(c, pid); err != nil {
- return err
- }
- // FIXME: Systemd does have `BlockIODeviceWeight` property, but we got problem
- // using that (at least on systemd 208, see https://github.com/opencontainers/runc/libcontainer/pull/354),
- // so use fs work around for now.
- if err := joinBlkio(c, pid); err != nil {
- return err
- }
-
- paths := make(map[string]string)
- for _, s := range subsystems {
- subsystemPath, err := getSubsystemPath(m.Cgroups, s.Name())
- if err != nil {
- // Don't fail if a cgroup hierarchy was not found, just skip this subsystem
- if cgroups.IsNotFound(err) {
- continue
- }
- return err
- }
- paths[s.Name()] = subsystemPath
- }
- m.Paths = paths
-
- if paths["cpu"] != "" {
- if err := fs.CheckCpushares(paths["cpu"], c.CpuShares); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (m *Manager) Destroy() error {
- m.mu.Lock()
- defer m.mu.Unlock()
- theConn.StopUnit(getUnitName(m.Cgroups), "replace", nil)
- if err := cgroups.RemovePaths(m.Paths); err != nil {
- return err
- }
- m.Paths = make(map[string]string)
- return nil
-}
-
-func (m *Manager) GetPaths() map[string]string {
- m.mu.Lock()
- paths := m.Paths
- m.mu.Unlock()
- return paths
-}
-
-func writeFile(dir, file, data string) error {
- // Normally dir should not be empty, one case is that cgroup subsystem
- // is not mounted, we will get empty dir, and we want it fail here.
- if dir == "" {
- return fmt.Errorf("no such directory for %s.", file)
- }
- return ioutil.WriteFile(filepath.Join(dir, file), []byte(data), 0700)
-}
-
-func join(c *configs.Cgroup, subsystem string, pid int) (string, error) {
- path, err := getSubsystemPath(c, subsystem)
- if err != nil {
- return "", err
- }
- if err := os.MkdirAll(path, 0755); err != nil {
- return "", err
- }
- if err := writeFile(path, "cgroup.procs", strconv.Itoa(pid)); err != nil {
- return "", err
- }
-
- return path, nil
-}
-
-func joinCpu(c *configs.Cgroup, pid int) error {
- path, err := getSubsystemPath(c, "cpu")
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
- if c.CpuQuota != 0 {
- if err = writeFile(path, "cpu.cfs_quota_us", strconv.FormatInt(c.CpuQuota, 10)); err != nil {
- return err
- }
- }
- if c.CpuPeriod != 0 {
- if err = writeFile(path, "cpu.cfs_period_us", strconv.FormatInt(c.CpuPeriod, 10)); err != nil {
- return err
- }
- }
- if c.CpuRtPeriod != 0 {
- if err = writeFile(path, "cpu.rt_period_us", strconv.FormatInt(c.CpuRtPeriod, 10)); err != nil {
- return err
- }
- }
- if c.CpuRtRuntime != 0 {
- if err = writeFile(path, "cpu.rt_runtime_us", strconv.FormatInt(c.CpuRtRuntime, 10)); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func joinFreezer(c *configs.Cgroup, pid int) error {
- path, err := join(c, "freezer", pid)
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
- freezer, err := subsystems.Get("freezer")
- if err != nil {
- return err
- }
- return freezer.Set(path, c)
-}
-
-func joinNetPrio(c *configs.Cgroup, pid int) error {
- path, err := join(c, "net_prio", pid)
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
- netPrio, err := subsystems.Get("net_prio")
- if err != nil {
- return err
- }
- return netPrio.Set(path, c)
-}
-
-func joinNetCls(c *configs.Cgroup, pid int) error {
- path, err := join(c, "net_cls", pid)
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
- netcls, err := subsystems.Get("net_cls")
- if err != nil {
- return err
- }
- return netcls.Set(path, c)
-}
-
-func getSubsystemPath(c *configs.Cgroup, subsystem string) (string, error) {
- mountpoint, err := cgroups.FindCgroupMountpoint(subsystem)
- if err != nil {
- return "", err
- }
-
- initPath, err := cgroups.GetInitCgroupDir(subsystem)
- if err != nil {
- return "", err
- }
-
- slice := "system.slice"
- if c.Slice != "" {
- slice = c.Slice
- }
-
- return filepath.Join(mountpoint, initPath, slice, getUnitName(c)), nil
-}
-
-func (m *Manager) Freeze(state configs.FreezerState) error {
- path, err := getSubsystemPath(m.Cgroups, "freezer")
- if err != nil {
- return err
- }
- prevState := m.Cgroups.Freezer
- m.Cgroups.Freezer = state
- freezer, err := subsystems.Get("freezer")
- if err != nil {
- return err
- }
- err = freezer.Set(path, m.Cgroups)
- if err != nil {
- m.Cgroups.Freezer = prevState
- return err
- }
- return nil
-}
-
-func (m *Manager) GetPids() ([]int, error) {
- path, err := getSubsystemPath(m.Cgroups, "devices")
- if err != nil {
- return nil, err
- }
- return cgroups.GetPids(path)
-}
-
-func (m *Manager) GetStats() (*cgroups.Stats, error) {
- m.mu.Lock()
- defer m.mu.Unlock()
- stats := cgroups.NewStats()
- for name, path := range m.Paths {
- sys, err := subsystems.Get(name)
- if err == errSubsystemDoesNotExist || !cgroups.PathExists(path) {
- continue
- }
- if err := sys.GetStats(path, stats); err != nil {
- return nil, err
- }
- }
-
- return stats, nil
-}
-
-func (m *Manager) Set(container *configs.Config) error {
- for name, path := range m.Paths {
- sys, err := subsystems.Get(name)
- if err == errSubsystemDoesNotExist || !cgroups.PathExists(path) {
- continue
- }
- if err := sys.Set(path, container.Cgroups); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func getUnitName(c *configs.Cgroup) string {
- return fmt.Sprintf("%s-%s.scope", c.Parent, c.Name)
-}
-
-// Atm we can't use the systemd device support because of two missing things:
-// * Support for wildcards to allow mknod on any device
-// * Support for wildcards to allow /dev/pts support
-//
-// The second is available in more recent systemd as "char-pts", but not in e.g. v208 which is
-// in wide use. When both these are available we will be able to switch, but need to keep the old
-// implementation for backwards compat.
-//
-// Note: we can't use systemd to set up the initial limits, and then change the cgroup
-// because systemd will re-write the device settings if it needs to re-apply the cgroup context.
-// This happens at least for v208 when any sibling unit is started.
-func joinDevices(c *configs.Cgroup, pid int) error {
- path, err := join(c, "devices", pid)
- // Even if it's `not found` error, we'll return err because devices cgroup
- // is hard requirement for container security.
- if err != nil {
- return err
- }
- devices, err := subsystems.Get("devices")
- if err != nil {
- return err
- }
- return devices.Set(path, c)
-}
-
-func setKernelMemory(c *configs.Cgroup) error {
- path, err := getSubsystemPath(c, "memory")
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
-
- if err := os.MkdirAll(path, 0755); err != nil {
- return err
- }
-
- if c.KernelMemory > 0 {
- err = writeFile(path, "memory.kmem.limit_in_bytes", strconv.FormatInt(c.KernelMemory, 10))
- if err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func joinMemory(c *configs.Cgroup, pid int) error {
- path, err := getSubsystemPath(c, "memory")
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
-
- // -1 disables memoryswap
- if c.MemorySwap > 0 {
- err = writeFile(path, "memory.memsw.limit_in_bytes", strconv.FormatInt(c.MemorySwap, 10))
- if err != nil {
- return err
- }
- }
- if c.MemoryReservation > 0 {
- err = writeFile(path, "memory.soft_limit_in_bytes", strconv.FormatInt(c.MemoryReservation, 10))
- if err != nil {
- return err
- }
- }
- if c.OomKillDisable {
- if err := writeFile(path, "memory.oom_control", "1"); err != nil {
- return err
- }
- }
-
- if c.MemorySwappiness >= 0 && c.MemorySwappiness <= 100 {
- err = writeFile(path, "memory.swappiness", strconv.FormatInt(c.MemorySwappiness, 10))
- if err != nil {
- return err
- }
- } else if c.MemorySwappiness == -1 {
- return nil
- } else {
- return fmt.Errorf("invalid value:%d. valid memory swappiness range is 0-100", c.MemorySwappiness)
- }
-
- return nil
-}
-
-// systemd does not atm set up the cpuset controller, so we must manually
-// join it. Additionally that is a very finicky controller where each
-// level must have a full setup as the default for a new directory is "no cpus"
-func joinCpuset(c *configs.Cgroup, pid int) error {
- path, err := getSubsystemPath(c, "cpuset")
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
-
- s := &fs.CpusetGroup{}
-
- return s.ApplyDir(path, c, pid)
-}
-
-// `BlockIODeviceWeight` property of systemd does not work properly, and systemd
-// expects device path instead of major minor numbers, which is also confusing
-// for users. So we use fs work around for now.
-func joinBlkio(c *configs.Cgroup, pid int) error {
- path, err := getSubsystemPath(c, "blkio")
- if err != nil {
- return err
- }
- // systemd doesn't directly support this in the dbus properties
- if c.BlkioLeafWeight != 0 {
- if err := writeFile(path, "blkio.leaf_weight", strconv.FormatUint(uint64(c.BlkioLeafWeight), 10)); err != nil {
- return err
- }
- }
- for _, wd := range c.BlkioWeightDevice {
- if err := writeFile(path, "blkio.weight_device", wd.WeightString()); err != nil {
- return err
- }
- if err := writeFile(path, "blkio.leaf_weight_device", wd.LeafWeightString()); err != nil {
- return err
- }
- }
- for _, td := range c.BlkioThrottleReadBpsDevice {
- if err := writeFile(path, "blkio.throttle.read_bps_device", td.String()); err != nil {
- return err
- }
- }
- for _, td := range c.BlkioThrottleWriteBpsDevice {
- if err := writeFile(path, "blkio.throttle.write_bps_device", td.String()); err != nil {
- return err
- }
- }
- for _, td := range c.BlkioThrottleReadIOPSDevice {
- if err := writeFile(path, "blkio.throttle.read_iops_device", td.String()); err != nil {
- return err
- }
- }
- for _, td := range c.BlkioThrottleWriteIOPSDevice {
- if err := writeFile(path, "blkio.throttle.write_iops_device", td.String()); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func joinHugetlb(c *configs.Cgroup, pid int) error {
- path, err := join(c, "hugetlb", pid)
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
- hugetlb, err := subsystems.Get("hugetlb")
- if err != nil {
- return err
- }
- return hugetlb.Set(path, c)
-}
-
-func joinPerfEvent(c *configs.Cgroup, pid int) error {
- path, err := join(c, "perf_event", pid)
- if err != nil && !cgroups.IsNotFound(err) {
- return err
- }
- perfEvent, err := subsystems.Get("perf_event")
- if err != nil {
- return err
- }
- return perfEvent.Set(path, c)
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/utils.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/utils.go
deleted file mode 100644
index d00e0e2..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/cgroups/utils.go
+++ /dev/null
@@ -1,347 +0,0 @@
-// +build linux
-
-package cgroups
-
-import (
- "bufio"
- "fmt"
- "io/ioutil"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "time"
-
- "github.com/docker/docker/pkg/mount"
- "github.com/docker/docker/pkg/units"
-)
-
-const cgroupNamePrefix = "name="
-
-// https://www.kernel.org/doc/Documentation/cgroups/cgroups.txt
-func FindCgroupMountpoint(subsystem string) (string, error) {
- // We are not using mount.GetMounts() because it's super-inefficient,
- // parsing it directly sped up x10 times because of not using Sscanf.
- // It was one of two major performance drawbacks in container start.
- f, err := os.Open("/proc/self/mountinfo")
- if err != nil {
- return "", err
- }
- defer f.Close()
-
- scanner := bufio.NewScanner(f)
- for scanner.Scan() {
- txt := scanner.Text()
- fields := strings.Split(txt, " ")
- for _, opt := range strings.Split(fields[len(fields)-1], ",") {
- if opt == subsystem {
- return fields[4], nil
- }
- }
- }
- if err := scanner.Err(); err != nil {
- return "", err
- }
-
- return "", NewNotFoundError(subsystem)
-}
-
-func FindCgroupMountpointAndRoot(subsystem string) (string, string, error) {
- f, err := os.Open("/proc/self/mountinfo")
- if err != nil {
- return "", "", err
- }
- defer f.Close()
-
- scanner := bufio.NewScanner(f)
- for scanner.Scan() {
- txt := scanner.Text()
- fields := strings.Split(txt, " ")
- for _, opt := range strings.Split(fields[len(fields)-1], ",") {
- if opt == subsystem {
- return fields[4], fields[3], nil
- }
- }
- }
- if err := scanner.Err(); err != nil {
- return "", "", err
- }
-
- return "", "", NewNotFoundError(subsystem)
-}
-
-func FindCgroupMountpointDir() (string, error) {
- f, err := os.Open("/proc/self/mountinfo")
- if err != nil {
- return "", err
- }
- defer f.Close()
-
- scanner := bufio.NewScanner(f)
- for scanner.Scan() {
- text := scanner.Text()
- fields := strings.Split(text, " ")
- // Safe as mountinfo encodes mountpoints with spaces as \040.
- index := strings.Index(text, " - ")
- postSeparatorFields := strings.Fields(text[index+3:])
- if len(postSeparatorFields) < 3 {
- return "", fmt.Errorf("Error found less than 3 fields post '-' in %q", text)
- }
- if postSeparatorFields[0] == "cgroup" {
- return filepath.Dir(fields[4]), nil
- }
- }
- if err := scanner.Err(); err != nil {
- return "", err
- }
-
- return "", NewNotFoundError("cgroup")
-}
-
-type Mount struct {
- Mountpoint string
- Root string
- Subsystems []string
-}
-
-func (m Mount) GetThisCgroupDir(cgroups map[string]string) (string, error) {
- if len(m.Subsystems) == 0 {
- return "", fmt.Errorf("no subsystem for mount")
- }
-
- return getControllerPath(m.Subsystems[0], cgroups)
-}
-
-func GetCgroupMounts() ([]Mount, error) {
- mounts, err := mount.GetMounts()
- if err != nil {
- return nil, err
- }
-
- all, err := GetAllSubsystems()
- if err != nil {
- return nil, err
- }
-
- allMap := make(map[string]bool)
- for _, s := range all {
- allMap[s] = true
- }
-
- res := []Mount{}
- for _, mount := range mounts {
- if mount.Fstype == "cgroup" {
- m := Mount{Mountpoint: mount.Mountpoint, Root: mount.Root}
-
- for _, opt := range strings.Split(mount.VfsOpts, ",") {
- if strings.HasPrefix(opt, cgroupNamePrefix) {
- m.Subsystems = append(m.Subsystems, opt[len(cgroupNamePrefix):])
- }
- if allMap[opt] {
- m.Subsystems = append(m.Subsystems, opt)
- }
- }
- res = append(res, m)
- }
- }
- return res, nil
-}
-
-// Returns all the cgroup subsystems supported by the kernel
-func GetAllSubsystems() ([]string, error) {
- f, err := os.Open("/proc/cgroups")
- if err != nil {
- return nil, err
- }
- defer f.Close()
-
- subsystems := []string{}
-
- s := bufio.NewScanner(f)
- for s.Scan() {
- if err := s.Err(); err != nil {
- return nil, err
- }
- text := s.Text()
- if text[0] != '#' {
- parts := strings.Fields(text)
- if len(parts) >= 4 && parts[3] != "0" {
- subsystems = append(subsystems, parts[0])
- }
- }
- }
- return subsystems, nil
-}
-
-// Returns the relative path to the cgroup docker is running in.
-func GetThisCgroupDir(subsystem string) (string, error) {
- cgroups, err := ParseCgroupFile("/proc/self/cgroup")
- if err != nil {
- return "", err
- }
-
- return getControllerPath(subsystem, cgroups)
-}
-
-func GetInitCgroupDir(subsystem string) (string, error) {
-
- cgroups, err := ParseCgroupFile("/proc/1/cgroup")
- if err != nil {
- return "", err
- }
-
- return getControllerPath(subsystem, cgroups)
-}
-
-func readProcsFile(dir string) ([]int, error) {
- f, err := os.Open(filepath.Join(dir, "cgroup.procs"))
- if err != nil {
- return nil, err
- }
- defer f.Close()
-
- var (
- s = bufio.NewScanner(f)
- out = []int{}
- )
-
- for s.Scan() {
- if t := s.Text(); t != "" {
- pid, err := strconv.Atoi(t)
- if err != nil {
- return nil, err
- }
- out = append(out, pid)
- }
- }
- return out, nil
-}
-
-func ParseCgroupFile(path string) (map[string]string, error) {
- f, err := os.Open(path)
- if err != nil {
- return nil, err
- }
- defer f.Close()
-
- s := bufio.NewScanner(f)
- cgroups := make(map[string]string)
-
- for s.Scan() {
- if err := s.Err(); err != nil {
- return nil, err
- }
-
- text := s.Text()
- parts := strings.Split(text, ":")
-
- for _, subs := range strings.Split(parts[1], ",") {
- cgroups[subs] = parts[2]
- }
- }
- return cgroups, nil
-}
-
-func getControllerPath(subsystem string, cgroups map[string]string) (string, error) {
-
- if p, ok := cgroups[subsystem]; ok {
- return p, nil
- }
-
- if p, ok := cgroups[cgroupNamePrefix+subsystem]; ok {
- return p, nil
- }
-
- return "", NewNotFoundError(subsystem)
-}
-
-func PathExists(path string) bool {
- if _, err := os.Stat(path); err != nil {
- return false
- }
- return true
-}
-
-func EnterPid(cgroupPaths map[string]string, pid int) error {
- for _, path := range cgroupPaths {
- if PathExists(path) {
- if err := ioutil.WriteFile(filepath.Join(path, "cgroup.procs"),
- []byte(strconv.Itoa(pid)), 0700); err != nil {
- return err
- }
- }
- }
- return nil
-}
-
-// RemovePaths iterates over the provided paths removing them.
-// We trying to remove all paths five times with increasing delay between tries.
-// If after all there are not removed cgroups - appropriate error will be
-// returned.
-func RemovePaths(paths map[string]string) (err error) {
- delay := 10 * time.Millisecond
- for i := 0; i < 5; i++ {
- if i != 0 {
- time.Sleep(delay)
- delay *= 2
- }
- for s, p := range paths {
- os.RemoveAll(p)
- // TODO: here probably should be logging
- _, err := os.Stat(p)
- // We need this strange way of checking cgroups existence because
- // RemoveAll almost always returns error, even on already removed
- // cgroups
- if os.IsNotExist(err) {
- delete(paths, s)
- }
- }
- if len(paths) == 0 {
- return nil
- }
- }
- return fmt.Errorf("Failed to remove paths: %s", paths)
-}
-
-func GetHugePageSize() ([]string, error) {
- var pageSizes []string
- sizeList := []string{"B", "kB", "MB", "GB", "TB", "PB"}
- files, err := ioutil.ReadDir("/sys/kernel/mm/hugepages")
- if err != nil {
- return pageSizes, err
- }
- for _, st := range files {
- nameArray := strings.Split(st.Name(), "-")
- pageSize, err := units.RAMInBytes(nameArray[1])
- if err != nil {
- return []string{}, err
- }
- sizeString := units.CustomSize("%g%s", float64(pageSize), 1024.0, sizeList)
- pageSizes = append(pageSizes, sizeString)
- }
-
- return pageSizes, nil
-}
-
-// GetPids returns all pids, that were added to cgroup at path and to all its
-// subcgroups.
-func GetPids(path string) ([]int, error) {
- var pids []int
- // collect pids from all sub-cgroups
- err := filepath.Walk(path, func(p string, info os.FileInfo, iErr error) error {
- dir, file := filepath.Split(p)
- if file != "cgroup.procs" {
- return nil
- }
- if iErr != nil {
- return iErr
- }
- cPids, err := readProcsFile(dir)
- if err != nil {
- return err
- }
- pids = append(pids, cPids...)
- return nil
- })
- return pids, err
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/compat_1.5_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/compat_1.5_linux.go
deleted file mode 100644
index c7bdf1f..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/compat_1.5_linux.go
+++ /dev/null
@@ -1,10 +0,0 @@
-// +build linux,!go1.5
-
-package libcontainer
-
-import "syscall"
-
-// GidMappingsEnableSetgroups was added in Go 1.5, so do nothing when building
-// with earlier versions
-func enableSetgroups(sys *syscall.SysProcAttr) {
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/blkio_device.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/blkio_device.go
deleted file mode 100644
index e0f3ca1..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/blkio_device.go
+++ /dev/null
@@ -1,61 +0,0 @@
-package configs
-
-import "fmt"
-
-// blockIODevice holds major:minor format supported in blkio cgroup
-type blockIODevice struct {
- // Major is the device's major number
- Major int64 `json:"major"`
- // Minor is the device's minor number
- Minor int64 `json:"minor"`
-}
-
-// WeightDevice struct holds a `major:minor weight`|`major:minor leaf_weight` pair
-type WeightDevice struct {
- blockIODevice
- // Weight is the bandwidth rate for the device, range is from 10 to 1000
- Weight uint16 `json:"weight"`
- // LeafWeight is the bandwidth rate for the device while competing with the cgroup's child cgroups, range is from 10 to 1000, cfq scheduler only
- LeafWeight uint16 `json:"leafWeight"`
-}
-
-// NewWeightDevice returns a configured WeightDevice pointer
-func NewWeightDevice(major, minor int64, weight, leafWeight uint16) *WeightDevice {
- wd := &WeightDevice{}
- wd.Major = major
- wd.Minor = minor
- wd.Weight = weight
- wd.LeafWeight = leafWeight
- return wd
-}
-
-// WeightString formats the struct to be writable to the cgroup specific file
-func (wd *WeightDevice) WeightString() string {
- return fmt.Sprintf("%d:%d %d", wd.Major, wd.Minor, wd.Weight)
-}
-
-// LeafWeightString formats the struct to be writable to the cgroup specific file
-func (wd *WeightDevice) LeafWeightString() string {
- return fmt.Sprintf("%d:%d %d", wd.Major, wd.Minor, wd.LeafWeight)
-}
-
-// ThrottleDevice struct holds a `major:minor rate_per_second` pair
-type ThrottleDevice struct {
- blockIODevice
- // Rate is the IO rate limit per cgroup per device
- Rate uint64 `json:"rate"`
-}
-
-// NewThrottleDevice returns a configured ThrottleDevice pointer
-func NewThrottleDevice(major, minor int64, rate uint64) *ThrottleDevice {
- td := &ThrottleDevice{}
- td.Major = major
- td.Minor = minor
- td.Rate = rate
- return td
-}
-
-// String formats the struct to be writable to the cgroup specific file
-func (td *ThrottleDevice) String() string {
- return fmt.Sprintf("%d:%d %d", td.Major, td.Minor, td.Rate)
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_unix.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_unix.go
deleted file mode 100644
index 24f93c1..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_unix.go
+++ /dev/null
@@ -1,100 +0,0 @@
-// +build linux freebsd
-
-package configs
-
-type FreezerState string
-
-const (
- Undefined FreezerState = ""
- Frozen FreezerState = "FROZEN"
- Thawed FreezerState = "THAWED"
-)
-
-type Cgroup struct {
- Name string `json:"name"`
-
- // name of parent cgroup or slice
- Parent string `json:"parent"`
-
- // If this is true allow access to any kind of device within the container. If false, allow access only to devices explicitly listed in the allowed_devices list.
- AllowAllDevices bool `json:"allow_all_devices"`
-
- AllowedDevices []*Device `json:"allowed_devices"`
-
- DeniedDevices []*Device `json:"denied_devices"`
-
- // Memory limit (in bytes)
- Memory int64 `json:"memory"`
-
- // Memory reservation or soft_limit (in bytes)
- MemoryReservation int64 `json:"memory_reservation"`
-
- // Total memory usage (memory + swap); set `-1' to disable swap
- MemorySwap int64 `json:"memory_swap"`
-
- // Kernel memory limit (in bytes)
- KernelMemory int64 `json:"kernel_memory"`
-
- // CPU shares (relative weight vs. other containers)
- CpuShares int64 `json:"cpu_shares"`
-
- // CPU hardcap limit (in usecs). Allowed cpu time in a given period.
- CpuQuota int64 `json:"cpu_quota"`
-
- // CPU period to be used for hardcapping (in usecs). 0 to use system default.
- CpuPeriod int64 `json:"cpu_period"`
-
- // How many time CPU will use in realtime scheduling (in usecs).
- CpuRtRuntime int64 `json:"cpu_quota"`
-
- // CPU period to be used for realtime scheduling (in usecs).
- CpuRtPeriod int64 `json:"cpu_period"`
-
- // CPU to use
- CpusetCpus string `json:"cpuset_cpus"`
-
- // MEM to use
- CpusetMems string `json:"cpuset_mems"`
-
- // Specifies per cgroup weight, range is from 10 to 1000.
- BlkioWeight uint16 `json:"blkio_weight"`
-
- // Specifies tasks' weight in the given cgroup while competing with the cgroup's child cgroups, range is from 10 to 1000, cfq scheduler only
- BlkioLeafWeight uint16 `json:"blkio_leaf_weight"`
-
- // Weight per cgroup per device, can override BlkioWeight.
- BlkioWeightDevice []*WeightDevice `json:"blkio_weight_device"`
-
- // IO read rate limit per cgroup per device, bytes per second.
- BlkioThrottleReadBpsDevice []*ThrottleDevice `json:"blkio_throttle_read_bps_device"`
-
- // IO write rate limit per cgroup per divice, bytes per second.
- BlkioThrottleWriteBpsDevice []*ThrottleDevice `json:"blkio_throttle_write_bps_device"`
-
- // IO read rate limit per cgroup per device, IO per second.
- BlkioThrottleReadIOPSDevice []*ThrottleDevice `json:"blkio_throttle_read_iops_device"`
-
- // IO write rate limit per cgroup per device, IO per second.
- BlkioThrottleWriteIOPSDevice []*ThrottleDevice `json:"blkio_throttle_write_iops_device"`
-
- // set the freeze value for the process
- Freezer FreezerState `json:"freezer"`
-
- // Hugetlb limit (in bytes)
- HugetlbLimit []*HugepageLimit `json:"hugetlb_limit"`
-
- // Parent slice to use for systemd TODO: remove in favor or parent
- Slice string `json:"slice"`
-
- // Whether to disable OOM Killer
- OomKillDisable bool `json:"oom_kill_disable"`
-
- // Tuning swappiness behaviour per cgroup
- MemorySwappiness int64 `json:"memory_swappiness"`
-
- // Set priority of network traffic for container
- NetPrioIfpriomap []*IfPrioMap `json:"net_prio_ifpriomap"`
-
- // Set class identifier for container's network packets
- NetClsClassid string `json:"net_cls_classid"`
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_windows.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_windows.go
deleted file mode 100644
index d74847b..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/cgroup_windows.go
+++ /dev/null
@@ -1,6 +0,0 @@
-package configs
-
-// TODO Windows: This can ultimately be entirely factored out on Windows as
-// cgroups are a Unix-specific construct.
-type Cgroup struct {
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/config.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/config.go
deleted file mode 100644
index 7fd311d..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/config.go
+++ /dev/null
@@ -1,248 +0,0 @@
-package configs
-
-import (
- "bytes"
- "encoding/json"
- "os/exec"
-)
-
-type Rlimit struct {
- Type int `json:"type"`
- Hard uint64 `json:"hard"`
- Soft uint64 `json:"soft"`
-}
-
-// IDMap represents UID/GID Mappings for User Namespaces.
-type IDMap struct {
- ContainerID int `json:"container_id"`
- HostID int `json:"host_id"`
- Size int `json:"size"`
-}
-
-// Seccomp represents syscall restrictions
-// By default, only the native architecture of the kernel is allowed to be used
-// for syscalls. Additional architectures can be added by specifying them in
-// Architectures.
-type Seccomp struct {
- DefaultAction Action `json:"default_action"`
- Architectures []string `json:"architectures"`
- Syscalls []*Syscall `json:"syscalls"`
-}
-
-// An action to be taken upon rule match in Seccomp
-type Action int
-
-const (
- Kill Action = iota - 4
- Errno
- Trap
- Allow
-)
-
-// A comparison operator to be used when matching syscall arguments in Seccomp
-type Operator int
-
-const (
- EqualTo Operator = iota
- NotEqualTo
- GreaterThan
- GreaterThanOrEqualTo
- LessThan
- LessThanOrEqualTo
- MaskEqualTo
-)
-
-// A rule to match a specific syscall argument in Seccomp
-type Arg struct {
- Index uint `json:"index"`
- Value uint64 `json:"value"`
- ValueTwo uint64 `json:"value_two"`
- Op Operator `json:"op"`
-}
-
-// An rule to match a syscall in Seccomp
-type Syscall struct {
- Name string `json:"name"`
- Action Action `json:"action"`
- Args []*Arg `json:"args"`
-}
-
-// TODO Windows. Many of these fields should be factored out into those parts
-// which are common across platforms, and those which are platform specific.
-
-// Config defines configuration options for executing a process inside a contained environment.
-type Config struct {
- // NoPivotRoot will use MS_MOVE and a chroot to jail the process into the container's rootfs
- // This is a common option when the container is running in ramdisk
- NoPivotRoot bool `json:"no_pivot_root"`
-
- // ParentDeathSignal specifies the signal that is sent to the container's process in the case
- // that the parent process dies.
- ParentDeathSignal int `json:"parent_death_signal"`
-
- // PivotDir allows a custom directory inside the container's root filesystem to be used as pivot, when NoPivotRoot is not set.
- // When a custom PivotDir not set, a temporary dir inside the root filesystem will be used. The pivot dir needs to be writeable.
- // This is required when using read only root filesystems. In these cases, a read/writeable path can be (bind) mounted somewhere inside the root filesystem to act as pivot.
- PivotDir string `json:"pivot_dir"`
-
- // Path to a directory containing the container's root filesystem.
- Rootfs string `json:"rootfs"`
-
- // Readonlyfs will remount the container's rootfs as readonly where only externally mounted
- // bind mounts are writtable.
- Readonlyfs bool `json:"readonlyfs"`
-
- // Specifies the mount propagation flags to be applied to /.
- RootPropagation int `json:"rootPropagation"`
-
- // Mounts specify additional source and destination paths that will be mounted inside the container's
- // rootfs and mount namespace if specified
- Mounts []*Mount `json:"mounts"`
-
- // The device nodes that should be automatically created within the container upon container start. Note, make sure that the node is marked as allowed in the cgroup as well!
- Devices []*Device `json:"devices"`
-
- MountLabel string `json:"mount_label"`
-
- // Hostname optionally sets the container's hostname if provided
- Hostname string `json:"hostname"`
-
- // Namespaces specifies the container's namespaces that it should setup when cloning the init process
- // If a namespace is not provided that namespace is shared from the container's parent process
- Namespaces Namespaces `json:"namespaces"`
-
- // Capabilities specify the capabilities to keep when executing the process inside the container
- // All capbilities not specified will be dropped from the processes capability mask
- Capabilities []string `json:"capabilities"`
-
- // Networks specifies the container's network setup to be created
- Networks []*Network `json:"networks"`
-
- // Routes can be specified to create entries in the route table as the container is started
- Routes []*Route `json:"routes"`
-
- // Cgroups specifies specific cgroup settings for the various subsystems that the container is
- // placed into to limit the resources the container has available
- Cgroups *Cgroup `json:"cgroups"`
-
- // AppArmorProfile specifies the profile to apply to the process running in the container and is
- // change at the time the process is execed
- AppArmorProfile string `json:"apparmor_profile"`
-
- // ProcessLabel specifies the label to apply to the process running in the container. It is
- // commonly used by selinux
- ProcessLabel string `json:"process_label"`
-
- // Rlimits specifies the resource limits, such as max open files, to set in the container
- // If Rlimits are not set, the container will inherit rlimits from the parent process
- Rlimits []Rlimit `json:"rlimits"`
-
- // OomScoreAdj specifies the adjustment to be made by the kernel when calculating oom scores
- // for a process. Valid values are between the range [-1000, '1000'], where processes with
- // higher scores are preferred for being killed.
- // More information about kernel oom score calculation here: https://lwn.net/Articles/317814/
- OomScoreAdj int `json:"oom_score_adj"`
-
- // AdditionalGroups specifies the gids that should be added to supplementary groups
- // in addition to those that the user belongs to.
- AdditionalGroups []string `json:"additional_groups"`
-
- // UidMappings is an array of User ID mappings for User Namespaces
- UidMappings []IDMap `json:"uid_mappings"`
-
- // GidMappings is an array of Group ID mappings for User Namespaces
- GidMappings []IDMap `json:"gid_mappings"`
-
- // MaskPaths specifies paths within the container's rootfs to mask over with a bind
- // mount pointing to /dev/null as to prevent reads of the file.
- MaskPaths []string `json:"mask_paths"`
-
- // ReadonlyPaths specifies paths within the container's rootfs to remount as read-only
- // so that these files prevent any writes.
- ReadonlyPaths []string `json:"readonly_paths"`
-
- // Sysctl is a map of properties and their values. It is the equivalent of using
- // sysctl -w my.property.name value in Linux.
- Sysctl map[string]string `json:"sysctl"`
-
- // Seccomp allows actions to be taken whenever a syscall is made within the container.
- // A number of rules are given, each having an action to be taken if a syscall matches it.
- // A default action to be taken if no rules match is also given.
- Seccomp *Seccomp `json:"seccomp"`
-
- // Hooks are a collection of actions to perform at various container lifecycle events.
- // Hooks are not able to be marshaled to json but they are also not needed to.
- Hooks *Hooks `json:"-"`
-
- // Version is the version of opencontainer specification that is supported.
- Version string `json:"version"`
-}
-
-type Hooks struct {
- // Prestart commands are executed after the container namespaces are created,
- // but before the user supplied command is executed from init.
- Prestart []Hook
-
- // Poststop commands are executed after the container init process exits.
- Poststop []Hook
-}
-
-// HookState is the payload provided to a hook on execution.
-type HookState struct {
- Version string `json:"version"`
- ID string `json:"id"`
- Pid int `json:"pid"`
- Root string `json:"root"`
-}
-
-type Hook interface {
- // Run executes the hook with the provided state.
- Run(HookState) error
-}
-
-// NewFunctionHooks will call the provided function when the hook is run.
-func NewFunctionHook(f func(HookState) error) FuncHook {
- return FuncHook{
- run: f,
- }
-}
-
-type FuncHook struct {
- run func(HookState) error
-}
-
-func (f FuncHook) Run(s HookState) error {
- return f.run(s)
-}
-
-type Command struct {
- Path string `json:"path"`
- Args []string `json:"args"`
- Env []string `json:"env"`
- Dir string `json:"dir"`
-}
-
-// NewCommandHooks will execute the provided command when the hook is run.
-func NewCommandHook(cmd Command) CommandHook {
- return CommandHook{
- Command: cmd,
- }
-}
-
-type CommandHook struct {
- Command
-}
-
-func (c Command) Run(s HookState) error {
- b, err := json.Marshal(s)
- if err != nil {
- return err
- }
- cmd := exec.Cmd{
- Path: c.Path,
- Args: c.Args,
- Env: c.Env,
- Stdin: bytes.NewReader(b),
- }
- return cmd.Run()
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/config_unix.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/config_unix.go
deleted file mode 100644
index c447f3e..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/config_unix.go
+++ /dev/null
@@ -1,51 +0,0 @@
-// +build freebsd linux
-
-package configs
-
-import "fmt"
-
-// Gets the root uid for the process on host which could be non-zero
-// when user namespaces are enabled.
-func (c Config) HostUID() (int, error) {
- if c.Namespaces.Contains(NEWUSER) {
- if c.UidMappings == nil {
- return -1, fmt.Errorf("User namespaces enabled, but no user mappings found.")
- }
- id, found := c.hostIDFromMapping(0, c.UidMappings)
- if !found {
- return -1, fmt.Errorf("User namespaces enabled, but no root user mapping found.")
- }
- return id, nil
- }
- // Return default root uid 0
- return 0, nil
-}
-
-// Gets the root gid for the process on host which could be non-zero
-// when user namespaces are enabled.
-func (c Config) HostGID() (int, error) {
- if c.Namespaces.Contains(NEWUSER) {
- if c.GidMappings == nil {
- return -1, fmt.Errorf("User namespaces enabled, but no gid mappings found.")
- }
- id, found := c.hostIDFromMapping(0, c.GidMappings)
- if !found {
- return -1, fmt.Errorf("User namespaces enabled, but no root group mapping found.")
- }
- return id, nil
- }
- // Return default root gid 0
- return 0, nil
-}
-
-// Utility function that gets a host ID for a container ID from user namespace map
-// if that ID is present in the map.
-func (c Config) hostIDFromMapping(containerID int, uMap []IDMap) (int, bool) {
- for _, m := range uMap {
- if (containerID >= m.ContainerID) && (containerID <= (m.ContainerID + m.Size - 1)) {
- hostID := m.HostID + (containerID - m.ContainerID)
- return hostID, true
- }
- }
- return -1, false
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/device.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/device.go
deleted file mode 100644
index a52a024..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/device.go
+++ /dev/null
@@ -1,54 +0,0 @@
-package configs
-
-import (
- "fmt"
- "os"
-)
-
-const (
- Wildcard = -1
-)
-
-// TODO Windows: This can be factored out in the future
-
-type Device struct {
- // Device type, block, char, etc.
- Type rune `json:"type"`
-
- // Path to the device.
- Path string `json:"path"`
-
- // Major is the device's major number.
- Major int64 `json:"major"`
-
- // Minor is the device's minor number.
- Minor int64 `json:"minor"`
-
- // Cgroup permissions format, rwm.
- Permissions string `json:"permissions"`
-
- // FileMode permission bits for the device.
- FileMode os.FileMode `json:"file_mode"`
-
- // Uid of the device.
- Uid uint32 `json:"uid"`
-
- // Gid of the device.
- Gid uint32 `json:"gid"`
-}
-
-func (d *Device) CgroupString() string {
- return fmt.Sprintf("%c %s:%s %s", d.Type, deviceNumberString(d.Major), deviceNumberString(d.Minor), d.Permissions)
-}
-
-func (d *Device) Mkdev() int {
- return int((d.Major << 8) | (d.Minor & 0xff) | ((d.Minor & 0xfff00) << 12))
-}
-
-// deviceNumberString converts the device number to a string return result.
-func deviceNumberString(number int64) string {
- if number == Wildcard {
- return "*"
- }
- return fmt.Sprint(number)
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/device_defaults.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/device_defaults.go
deleted file mode 100644
index 0ce040f..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/device_defaults.go
+++ /dev/null
@@ -1,139 +0,0 @@
-// +build linux freebsd
-
-package configs
-
-var (
- // These are devices that are to be both allowed and created.
- DefaultSimpleDevices = []*Device{
- // /dev/null and zero
- {
- Path: "/dev/null",
- Type: 'c',
- Major: 1,
- Minor: 3,
- Permissions: "rwm",
- FileMode: 0666,
- },
- {
- Path: "/dev/zero",
- Type: 'c',
- Major: 1,
- Minor: 5,
- Permissions: "rwm",
- FileMode: 0666,
- },
-
- {
- Path: "/dev/full",
- Type: 'c',
- Major: 1,
- Minor: 7,
- Permissions: "rwm",
- FileMode: 0666,
- },
-
- // consoles and ttys
- {
- Path: "/dev/tty",
- Type: 'c',
- Major: 5,
- Minor: 0,
- Permissions: "rwm",
- FileMode: 0666,
- },
-
- // /dev/urandom,/dev/random
- {
- Path: "/dev/urandom",
- Type: 'c',
- Major: 1,
- Minor: 9,
- Permissions: "rwm",
- FileMode: 0666,
- },
- {
- Path: "/dev/random",
- Type: 'c',
- Major: 1,
- Minor: 8,
- Permissions: "rwm",
- FileMode: 0666,
- },
- }
- DefaultAllowedDevices = append([]*Device{
- // allow mknod for any device
- {
- Type: 'c',
- Major: Wildcard,
- Minor: Wildcard,
- Permissions: "m",
- },
- {
- Type: 'b',
- Major: Wildcard,
- Minor: Wildcard,
- Permissions: "m",
- },
-
- {
- Path: "/dev/console",
- Type: 'c',
- Major: 5,
- Minor: 1,
- Permissions: "rwm",
- },
- {
- Path: "/dev/tty0",
- Type: 'c',
- Major: 4,
- Minor: 0,
- Permissions: "rwm",
- },
- {
- Path: "/dev/tty1",
- Type: 'c',
- Major: 4,
- Minor: 1,
- Permissions: "rwm",
- },
- // /dev/pts/ - pts namespaces are "coming soon"
- {
- Path: "",
- Type: 'c',
- Major: 136,
- Minor: Wildcard,
- Permissions: "rwm",
- },
- {
- Path: "",
- Type: 'c',
- Major: 5,
- Minor: 2,
- Permissions: "rwm",
- },
-
- // tuntap
- {
- Path: "",
- Type: 'c',
- Major: 10,
- Minor: 200,
- Permissions: "rwm",
- },
- }, DefaultSimpleDevices...)
- DefaultAutoCreatedDevices = append([]*Device{
- {
- // /dev/fuse is created but not allowed.
- // This is to allow java to work. Because java
- // Insists on there being a /dev/fuse
- // https://github.com/docker/docker/issues/514
- // https://github.com/docker/docker/issues/2393
- //
- Path: "/dev/fuse",
- Type: 'c',
- Major: 10,
- Minor: 229,
- Permissions: "rwm",
- },
- }, DefaultSimpleDevices...)
-)
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/hugepage_limit.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/hugepage_limit.go
deleted file mode 100644
index d302163..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/hugepage_limit.go
+++ /dev/null
@@ -1,9 +0,0 @@
-package configs
-
-type HugepageLimit struct {
- // which type of hugepage to limit.
- Pagesize string `json:"page_size"`
-
- // usage limit for hugepage.
- Limit uint64 `json:"limit"`
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/interface_priority_map.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/interface_priority_map.go
deleted file mode 100644
index 9a0395e..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/interface_priority_map.go
+++ /dev/null
@@ -1,14 +0,0 @@
-package configs
-
-import (
- "fmt"
-)
-
-type IfPrioMap struct {
- Interface string `json:"interface"`
- Priority int64 `json:"priority"`
-}
-
-func (i *IfPrioMap) CgroupString() string {
- return fmt.Sprintf("%s %d", i.Interface, i.Priority)
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/mount.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/mount.go
deleted file mode 100644
index cc770c9..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/mount.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package configs
-
-type Mount struct {
- // Source path for the mount.
- Source string `json:"source"`
-
- // Destination path for the mount inside the container.
- Destination string `json:"destination"`
-
- // Device the mount is for.
- Device string `json:"device"`
-
- // Mount flags.
- Flags int `json:"flags"`
-
- // Propagation Flags
- PropagationFlags []int `json:"propagation_flags"`
-
- // Mount data applied to the mount.
- Data string `json:"data"`
-
- // Relabel source if set, "z" indicates shared, "Z" indicates unshared.
- Relabel string `json:"relabel"`
-
- // Optional Command to be run before Source is mounted.
- PremountCmds []Command `json:"premount_cmds"`
-
- // Optional Command to be run after Source is mounted.
- PostmountCmds []Command `json:"postmount_cmds"`
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces.go
deleted file mode 100644
index a3329a3..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces.go
+++ /dev/null
@@ -1,5 +0,0 @@
-package configs
-
-type NamespaceType string
-
-type Namespaces []Namespace
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall.go
deleted file mode 100644
index c962999..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall.go
+++ /dev/null
@@ -1,31 +0,0 @@
-// +build linux
-
-package configs
-
-import "syscall"
-
-func (n *Namespace) Syscall() int {
- return namespaceInfo[n.Type]
-}
-
-var namespaceInfo = map[NamespaceType]int{
- NEWNET: syscall.CLONE_NEWNET,
- NEWNS: syscall.CLONE_NEWNS,
- NEWUSER: syscall.CLONE_NEWUSER,
- NEWIPC: syscall.CLONE_NEWIPC,
- NEWUTS: syscall.CLONE_NEWUTS,
- NEWPID: syscall.CLONE_NEWPID,
-}
-
-// CloneFlags parses the container's Namespaces options to set the correct
-// flags on clone, unshare. This functions returns flags only for new namespaces.
-func (n *Namespaces) CloneFlags() uintptr {
- var flag int
- for _, v := range *n {
- if v.Path != "" {
- continue
- }
- flag |= namespaceInfo[v.Type]
- }
- return uintptr(flag)
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall_unsupported.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall_unsupported.go
deleted file mode 100644
index 1644588..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_syscall_unsupported.go
+++ /dev/null
@@ -1,15 +0,0 @@
-// +build !linux,!windows
-
-package configs
-
-func (n *Namespace) Syscall() int {
- panic("No namespace syscall support")
- return 0
-}
-
-// CloneFlags parses the container's Namespaces options to set the correct
-// flags on clone, unshare. This functions returns flags only for new namespaces.
-func (n *Namespaces) CloneFlags() uintptr {
- panic("No namespace syscall support")
- return uintptr(0)
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_unix.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_unix.go
deleted file mode 100644
index 7bc9085..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_unix.go
+++ /dev/null
@@ -1,89 +0,0 @@
-// +build linux freebsd
-
-package configs
-
-import "fmt"
-
-const (
- NEWNET NamespaceType = "NEWNET"
- NEWPID NamespaceType = "NEWPID"
- NEWNS NamespaceType = "NEWNS"
- NEWUTS NamespaceType = "NEWUTS"
- NEWIPC NamespaceType = "NEWIPC"
- NEWUSER NamespaceType = "NEWUSER"
-)
-
-func NamespaceTypes() []NamespaceType {
- return []NamespaceType{
- NEWNET,
- NEWPID,
- NEWNS,
- NEWUTS,
- NEWIPC,
- NEWUSER,
- }
-}
-
-// Namespace defines configuration for each namespace. It specifies an
-// alternate path that is able to be joined via setns.
-type Namespace struct {
- Type NamespaceType `json:"type"`
- Path string `json:"path"`
-}
-
-func (n *Namespace) GetPath(pid int) string {
- if n.Path != "" {
- return n.Path
- }
- return fmt.Sprintf("/proc/%d/ns/%s", pid, n.file())
-}
-
-func (n *Namespace) file() string {
- file := ""
- switch n.Type {
- case NEWNET:
- file = "net"
- case NEWNS:
- file = "mnt"
- case NEWPID:
- file = "pid"
- case NEWIPC:
- file = "ipc"
- case NEWUSER:
- file = "user"
- case NEWUTS:
- file = "uts"
- }
- return file
-}
-
-func (n *Namespaces) Remove(t NamespaceType) bool {
- i := n.index(t)
- if i == -1 {
- return false
- }
- *n = append((*n)[:i], (*n)[i+1:]...)
- return true
-}
-
-func (n *Namespaces) Add(t NamespaceType, path string) {
- i := n.index(t)
- if i == -1 {
- *n = append(*n, Namespace{Type: t, Path: path})
- return
- }
- (*n)[i].Path = path
-}
-
-func (n *Namespaces) index(t NamespaceType) int {
- for i, ns := range *n {
- if ns.Type == t {
- return i
- }
- }
- return -1
-}
-
-func (n *Namespaces) Contains(t NamespaceType) bool {
- return n.index(t) != -1
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_windows.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_windows.go
deleted file mode 100644
index f8fe47a..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/namespaces_windows.go
+++ /dev/null
@@ -1,6 +0,0 @@
-package configs
-
-// Namespace defines configuration for each namespace. It specifies an
-// alternate path that is able to be joined via setns.
-type Namespace struct {
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/network.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/network.go
deleted file mode 100644
index ccdb228..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/network.go
+++ /dev/null
@@ -1,72 +0,0 @@
-package configs
-
-// Network defines configuration for a container's networking stack
-//
-// The network configuration can be omitted from a container causing the
-// container to be setup with the host's networking stack
-type Network struct {
- // Type sets the networks type, commonly veth and loopback
- Type string `json:"type"`
-
- // Name of the network interface
- Name string `json:"name"`
-
- // The bridge to use.
- Bridge string `json:"bridge"`
-
- // MacAddress contains the MAC address to set on the network interface
- MacAddress string `json:"mac_address"`
-
- // Address contains the IPv4 and mask to set on the network interface
- Address string `json:"address"`
-
- // Gateway sets the gateway address that is used as the default for the interface
- Gateway string `json:"gateway"`
-
- // IPv6Address contains the IPv6 and mask to set on the network interface
- IPv6Address string `json:"ipv6_address"`
-
- // IPv6Gateway sets the ipv6 gateway address that is used as the default for the interface
- IPv6Gateway string `json:"ipv6_gateway"`
-
- // Mtu sets the mtu value for the interface and will be mirrored on both the host and
- // container's interfaces if a pair is created, specifically in the case of type veth
- // Note: This does not apply to loopback interfaces.
- Mtu int `json:"mtu"`
-
- // TxQueueLen sets the tx_queuelen value for the interface and will be mirrored on both the host and
- // container's interfaces if a pair is created, specifically in the case of type veth
- // Note: This does not apply to loopback interfaces.
- TxQueueLen int `json:"txqueuelen"`
-
- // HostInterfaceName is a unique name of a veth pair that resides on in the host interface of the
- // container.
- HostInterfaceName string `json:"host_interface_name"`
-
- // HairpinMode specifies if hairpin NAT should be enabled on the virtual interface
- // bridge port in the case of type veth
- // Note: This is unsupported on some systems.
- // Note: This does not apply to loopback interfaces.
- HairpinMode bool `json:"hairpin_mode"`
-}
-
-// Routes can be specified to create entries in the route table as the container is started
-//
-// All of destination, source, and gateway should be either IPv4 or IPv6.
-// One of the three options must be present, and omitted entries will use their
-// IP family default for the route table. For IPv4 for example, setting the
-// gateway to 1.2.3.4 and the interface to eth0 will set up a standard
-// destination of 0.0.0.0(or *) when viewed in the route table.
-type Route struct {
- // Sets the destination and mask, should be a CIDR. Accepts IPv4 and IPv6
- Destination string `json:"destination"`
-
- // Sets the source and mask, should be a CIDR. Accepts IPv4 and IPv6
- Source string `json:"source"`
-
- // Sets the gateway. Accepts IPv4 and IPv6
- Gateway string `json:"gateway"`
-
- // The device to set this route up for, for example: eth0
- InterfaceName string `json:"interface_name"`
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/validate/config.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/validate/config.go
deleted file mode 100644
index 848a67c..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/configs/validate/config.go
+++ /dev/null
@@ -1,93 +0,0 @@
-package validate
-
-import (
- "fmt"
- "os"
- "path/filepath"
-
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-type Validator interface {
- Validate(*configs.Config) error
-}
-
-func New() Validator {
- return &ConfigValidator{}
-}
-
-type ConfigValidator struct {
-}
-
-func (v *ConfigValidator) Validate(config *configs.Config) error {
- if err := v.rootfs(config); err != nil {
- return err
- }
- if err := v.network(config); err != nil {
- return err
- }
- if err := v.hostname(config); err != nil {
- return err
- }
- if err := v.security(config); err != nil {
- return err
- }
- if err := v.usernamespace(config); err != nil {
- return err
- }
- return nil
-}
-
-// rootfs validates the the rootfs is an absolute path and is not a symlink
-// to the container's root filesystem.
-func (v *ConfigValidator) rootfs(config *configs.Config) error {
- cleaned, err := filepath.Abs(config.Rootfs)
- if err != nil {
- return err
- }
- if cleaned, err = filepath.EvalSymlinks(cleaned); err != nil {
- return err
- }
- if config.Rootfs != cleaned {
- return fmt.Errorf("%s is not an absolute path or is a symlink", config.Rootfs)
- }
- return nil
-}
-
-func (v *ConfigValidator) network(config *configs.Config) error {
- if !config.Namespaces.Contains(configs.NEWNET) {
- if len(config.Networks) > 0 || len(config.Routes) > 0 {
- return fmt.Errorf("unable to apply network settings without a private NET namespace")
- }
- }
- return nil
-}
-
-func (v *ConfigValidator) hostname(config *configs.Config) error {
- if config.Hostname != "" && !config.Namespaces.Contains(configs.NEWUTS) {
- return fmt.Errorf("unable to set hostname without a private UTS namespace")
- }
- return nil
-}
-
-func (v *ConfigValidator) security(config *configs.Config) error {
- // restrict sys without mount namespace
- if (len(config.MaskPaths) > 0 || len(config.ReadonlyPaths) > 0) &&
- !config.Namespaces.Contains(configs.NEWNS) {
- return fmt.Errorf("unable to restrict sys entries without a private MNT namespace")
- }
- return nil
-}
-
-func (v *ConfigValidator) usernamespace(config *configs.Config) error {
- if config.Namespaces.Contains(configs.NEWUSER) {
- if _, err := os.Stat("/proc/self/ns/user"); os.IsNotExist(err) {
- return fmt.Errorf("USER namespaces aren't enabled in the kernel")
- }
- } else {
- if config.UidMappings != nil || config.GidMappings != nil {
- return fmt.Errorf("User namespace mappings specified, but USER namespace isn't enabled in the config")
- }
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/console.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/console.go
deleted file mode 100644
index 042a2a2..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/console.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package libcontainer
-
-import "io"
-
-// Console represents a pseudo TTY.
-type Console interface {
- io.ReadWriter
- io.Closer
-
- // Path returns the filesystem path to the slave side of the pty.
- Path() string
-
- // Fd returns the fd for the master of the pty.
- Fd() uintptr
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/console_freebsd.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/console_freebsd.go
deleted file mode 100644
index 4d20b8d..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/console_freebsd.go
+++ /dev/null
@@ -1,13 +0,0 @@
-// +build freebsd
-
-package libcontainer
-
-import (
- "errors"
-)
-
-// newConsole returns an initalized console that can be used within a container by copying bytes
-// from the master side to the slave that is attached as the tty for the container's init process.
-func newConsole(uid, gid int) (Console, error) {
- return nil, errors.New("libcontainer console is not supported on FreeBSD")
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/console_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/console_linux.go
deleted file mode 100644
index f345f57..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/console_linux.go
+++ /dev/null
@@ -1,145 +0,0 @@
-package libcontainer
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "syscall"
- "unsafe"
-
- "github.com/opencontainers/runc/libcontainer/label"
-)
-
-// newConsole returns an initalized console that can be used within a container by copying bytes
-// from the master side to the slave that is attached as the tty for the container's init process.
-func newConsole(uid, gid int) (Console, error) {
- master, err := os.OpenFile("/dev/ptmx", syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_CLOEXEC, 0)
- if err != nil {
- return nil, err
- }
- console, err := ptsname(master)
- if err != nil {
- return nil, err
- }
- if err := unlockpt(master); err != nil {
- return nil, err
- }
- if err := os.Chmod(console, 0600); err != nil {
- return nil, err
- }
- if err := os.Chown(console, uid, gid); err != nil {
- return nil, err
- }
- return &linuxConsole{
- slavePath: console,
- master: master,
- }, nil
-}
-
-// newConsoleFromPath is an internal function returning an initialized console for use inside
-// a container's MNT namespace.
-func newConsoleFromPath(slavePath string) *linuxConsole {
- return &linuxConsole{
- slavePath: slavePath,
- }
-}
-
-// linuxConsole is a linux psuedo TTY for use within a container.
-type linuxConsole struct {
- master *os.File
- slavePath string
-}
-
-func (c *linuxConsole) Fd() uintptr {
- return c.master.Fd()
-}
-
-func (c *linuxConsole) Path() string {
- return c.slavePath
-}
-
-func (c *linuxConsole) Read(b []byte) (int, error) {
- return c.master.Read(b)
-}
-
-func (c *linuxConsole) Write(b []byte) (int, error) {
- return c.master.Write(b)
-}
-
-func (c *linuxConsole) Close() error {
- if m := c.master; m != nil {
- return m.Close()
- }
- return nil
-}
-
-// mount initializes the console inside the rootfs mounting with the specified mount label
-// and applying the correct ownership of the console.
-func (c *linuxConsole) mount(rootfs, mountLabel string) error {
- oldMask := syscall.Umask(0000)
- defer syscall.Umask(oldMask)
- if err := label.SetFileLabel(c.slavePath, mountLabel); err != nil {
- return err
- }
- dest := filepath.Join(rootfs, "/dev/console")
- f, err := os.Create(dest)
- if err != nil && !os.IsExist(err) {
- return err
- }
- if f != nil {
- f.Close()
- }
- return syscall.Mount(c.slavePath, dest, "bind", syscall.MS_BIND, "")
-}
-
-// dupStdio opens the slavePath for the console and dups the fds to the current
-// processes stdio, fd 0,1,2.
-func (c *linuxConsole) dupStdio() error {
- slave, err := c.open(syscall.O_RDWR)
- if err != nil {
- return err
- }
- fd := int(slave.Fd())
- for _, i := range []int{0, 1, 2} {
- if err := syscall.Dup3(fd, i, 0); err != nil {
- return err
- }
- }
- return nil
-}
-
-// open is a clone of os.OpenFile without the O_CLOEXEC used to open the pty slave.
-func (c *linuxConsole) open(flag int) (*os.File, error) {
- r, e := syscall.Open(c.slavePath, flag, 0)
- if e != nil {
- return nil, &os.PathError{
- Op: "open",
- Path: c.slavePath,
- Err: e,
- }
- }
- return os.NewFile(uintptr(r), c.slavePath), nil
-}
-
-func ioctl(fd uintptr, flag, data uintptr) error {
- if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, flag, data); err != 0 {
- return err
- }
- return nil
-}
-
-// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f.
-// unlockpt should be called before opening the slave side of a pty.
-func unlockpt(f *os.File) error {
- var u int32
- return ioctl(f.Fd(), syscall.TIOCSPTLCK, uintptr(unsafe.Pointer(&u)))
-}
-
-// ptsname retrieves the name of the first available pts for the given master.
-func ptsname(f *os.File) (string, error) {
- var n int32
- if err := ioctl(f.Fd(), syscall.TIOCGPTN, uintptr(unsafe.Pointer(&n))); err != nil {
- return "", err
- }
- return fmt.Sprintf("/dev/pts/%d", n), nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/console_windows.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/console_windows.go
deleted file mode 100644
index 80c7463..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/console_windows.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package libcontainer
-
-// newConsole returns an initalized console that can be used within a container
-func newConsole(uid, gid int) (Console, error) {
- return &windowsConsole{}, nil
-}
-
-// windowsConsole is a Windows psuedo TTY for use within a container.
-type windowsConsole struct {
-}
-
-func (c *windowsConsole) Fd() uintptr {
- return 0
-}
-
-func (c *windowsConsole) Path() string {
- return ""
-}
-
-func (c *windowsConsole) Read(b []byte) (int, error) {
- return 0, nil
-}
-
-func (c *windowsConsole) Write(b []byte) (int, error) {
- return 0, nil
-}
-
-func (c *windowsConsole) Close() error {
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/container.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/container.go
deleted file mode 100644
index 6292fd1..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/container.go
+++ /dev/null
@@ -1,123 +0,0 @@
-// 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.
-package libcontainer
-
-import (
- "os"
-
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-// The status of a container.
-type Status int
-
-const (
- // The container exists and is running.
- Running Status = iota + 1
-
- // The container exists, it is in the process of being paused.
- Pausing
-
- // The container exists, but all its processes are paused.
- Paused
-
- // The container exists, but its state is saved on disk
- Checkpointed
-
- // The container does not exist.
- Destroyed
-)
-
-// BaseState represents the platform agnostic pieces relating to a
-// running container's state
-type BaseState struct {
- // ID is the container ID.
- ID string `json:"id"`
-
- // InitProcessPid is the init process id in the parent namespace.
- InitProcessPid int `json:"init_process_pid"`
-
- // InitProcessStartTime is the init process start time.
- InitProcessStartTime string `json:"init_process_start"`
-
- // Config is the container's configuration.
- Config configs.Config `json:"config"`
-}
-
-// A libcontainer container object.
-//
-// Each container is thread-safe within the same process. Since a container can
-// be destroyed by a separate process, any function may return that the container
-// was not found. BaseContainer includes methods that are platform agnostic.
-type BaseContainer interface {
- // Returns the ID of the container
- ID() string
-
- // Returns the current status of the container.
- //
- // errors:
- // ContainerDestroyed - Container no longer exists,
- // Systemerror - System error.
- Status() (Status, error)
-
- // State returns the current container's state information.
- //
- // errors:
- // Systemerror - System error.
- State() (*State, error)
-
- // Returns the current config of the container.
- Config() configs.Config
-
- // Returns the PIDs inside this container. The PIDs are in the namespace of the calling process.
- //
- // errors:
- // ContainerDestroyed - Container no longer exists,
- // Systemerror - System error.
- //
- // Some of the returned PIDs may no longer refer to processes in the Container, unless
- // the Container state is PAUSED in which case every PID in the slice is valid.
- Processes() ([]int, error)
-
- // Returns statistics for the container.
- //
- // errors:
- // ContainerDestroyed - Container no longer exists,
- // Systemerror - System error.
- Stats() (*Stats, error)
-
- // Set resources of container as configured
- //
- // We can use this to change resources when containers are running.
- //
- // errors:
- // Systemerror - System error.
- Set(config configs.Config) error
-
- // Start a process inside the container. Returns error if process fails to
- // start. You can track process lifecycle with passed Process structure.
- //
- // errors:
- // ContainerDestroyed - Container no longer exists,
- // ConfigInvalid - config is invalid,
- // ContainerPaused - Container is paused,
- // Systemerror - System error.
- Start(process *Process) (err error)
-
- // Destroys the container after killing all running processes.
- //
- // Any event registrations are removed before the container is destroyed.
- // No error is returned if the container is already destroyed.
- //
- // errors:
- // Systemerror - System error.
- Destroy() error
-
- // Signal sends the provided signal code to the container's initial process.
- //
- // errors:
- // Systemerror - System error.
- Signal(s os.Signal) error
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/container_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/container_linux.go
deleted file mode 100644
index 578def6..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/container_linux.go
+++ /dev/null
@@ -1,1007 +0,0 @@
-// +build linux
-
-package libcontainer
-
-import (
- "encoding/json"
- "fmt"
- "io/ioutil"
- "os"
- "os/exec"
- "path/filepath"
- "reflect"
- "strings"
- "sync"
- "syscall"
-
- "github.com/Sirupsen/logrus"
- "github.com/golang/protobuf/proto"
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
- "github.com/opencontainers/runc/libcontainer/criurpc"
-)
-
-const stdioFdCount = 3
-
-type linuxContainer struct {
- id string
- root string
- config *configs.Config
- cgroupManager cgroups.Manager
- initPath string
- initArgs []string
- initProcess parentProcess
- criuPath string
- m sync.Mutex
- criuVersion int
-}
-
-// State represents a running container's state
-type State struct {
- BaseState
-
- // Platform specific fields below here
-
- // Path to all the cgroups setup for a container. Key is cgroup subsystem name
- // with the value as the path.
- CgroupPaths map[string]string `json:"cgroup_paths"`
-
- // NamespacePaths are filepaths to the container's namespaces. Key is the namespace type
- // with the value as the path.
- NamespacePaths map[configs.NamespaceType]string `json:"namespace_paths"`
-
- // Container's standard descriptors (std{in,out,err}), needed for checkpoint and restore
- ExternalDescriptors []string `json:"external_descriptors,omitempty"`
-}
-
-// A libcontainer container object.
-//
-// Each container is thread-safe within the same process. Since a container can
-// be destroyed by a separate process, any function may return that the container
-// was not found.
-type Container interface {
- BaseContainer
-
- // Methods below here are platform specific
-
- // Checkpoint checkpoints the running container's state to disk using the criu(8) utility.
- //
- // errors:
- // Systemerror - System error.
- Checkpoint(criuOpts *CriuOpts) error
-
- // Restore restores the checkpointed container to a running state using the criu(8) utiity.
- //
- // errors:
- // Systemerror - System error.
- Restore(process *Process, criuOpts *CriuOpts) error
-
- // If the Container state is RUNNING or PAUSING, sets the Container state to PAUSING and pauses
- // the execution of any user processes. Asynchronously, when the container finished being paused the
- // state is changed to PAUSED.
- // If the Container state is PAUSED, do nothing.
- //
- // errors:
- // ContainerDestroyed - Container no longer exists,
- // Systemerror - System error.
- Pause() error
-
- // If the Container state is PAUSED, resumes the execution of any user processes in the
- // Container before setting the Container state to RUNNING.
- // If the Container state is RUNNING, do nothing.
- //
- // errors:
- // ContainerDestroyed - Container no longer exists,
- // Systemerror - System error.
- Resume() error
-
- // NotifyOOM returns a read-only channel signaling when the container receives an OOM notification.
- //
- // errors:
- // Systemerror - System error.
- NotifyOOM() (<-chan struct{}, error)
-}
-
-// ID returns the container's unique ID
-func (c *linuxContainer) ID() string {
- return c.id
-}
-
-// Config returns the container's configuration
-func (c *linuxContainer) Config() configs.Config {
- return *c.config
-}
-
-func (c *linuxContainer) Status() (Status, error) {
- c.m.Lock()
- defer c.m.Unlock()
- return c.currentStatus()
-}
-
-func (c *linuxContainer) State() (*State, error) {
- c.m.Lock()
- defer c.m.Unlock()
- return c.currentState()
-}
-
-func (c *linuxContainer) Processes() ([]int, error) {
- pids, err := c.cgroupManager.GetPids()
- if err != nil {
- return nil, newSystemError(err)
- }
- return pids, nil
-}
-
-func (c *linuxContainer) Stats() (*Stats, error) {
- var (
- err error
- stats = &Stats{}
- )
- if stats.CgroupStats, err = c.cgroupManager.GetStats(); err != nil {
- return stats, newSystemError(err)
- }
- for _, iface := range c.config.Networks {
- switch iface.Type {
- case "veth":
- istats, err := getNetworkInterfaceStats(iface.HostInterfaceName)
- if err != nil {
- return stats, newSystemError(err)
- }
- stats.Interfaces = append(stats.Interfaces, istats)
- }
- }
- return stats, nil
-}
-
-func (c *linuxContainer) Set(config configs.Config) error {
- c.m.Lock()
- defer c.m.Unlock()
- c.config = &config
- return c.cgroupManager.Set(c.config)
-}
-
-func (c *linuxContainer) Start(process *Process) error {
- c.m.Lock()
- defer c.m.Unlock()
- status, err := c.currentStatus()
- if err != nil {
- return err
- }
- doInit := status == Destroyed
- parent, err := c.newParentProcess(process, doInit)
- if err != nil {
- return newSystemError(err)
- }
- if err := parent.start(); err != nil {
- // terminate the process to ensure that it properly is reaped.
- if err := parent.terminate(); err != nil {
- logrus.Warn(err)
- }
- return newSystemError(err)
- }
- if doInit {
- c.updateState(parent)
- }
- return nil
-}
-
-func (c *linuxContainer) Signal(s os.Signal) error {
- if err := c.initProcess.signal(s); err != nil {
- return newSystemError(err)
- }
- return nil
-}
-
-func (c *linuxContainer) newParentProcess(p *Process, doInit bool) (parentProcess, error) {
- parentPipe, childPipe, err := newPipe()
- if err != nil {
- return nil, newSystemError(err)
- }
- cmd, err := c.commandTemplate(p, childPipe)
- if err != nil {
- return nil, newSystemError(err)
- }
- if !doInit {
- return c.newSetnsProcess(p, cmd, parentPipe, childPipe), nil
- }
- return c.newInitProcess(p, cmd, parentPipe, childPipe)
-}
-
-func (c *linuxContainer) commandTemplate(p *Process, childPipe *os.File) (*exec.Cmd, error) {
- cmd := &exec.Cmd{
- Path: c.initPath,
- Args: c.initArgs,
- }
- cmd.Stdin = p.Stdin
- cmd.Stdout = p.Stdout
- cmd.Stderr = p.Stderr
- cmd.Dir = c.config.Rootfs
- if cmd.SysProcAttr == nil {
- cmd.SysProcAttr = &syscall.SysProcAttr{}
- }
- cmd.ExtraFiles = append(p.ExtraFiles, childPipe)
- cmd.Env = append(cmd.Env, fmt.Sprintf("_LIBCONTAINER_INITPIPE=%d", stdioFdCount+len(cmd.ExtraFiles)-1))
- // NOTE: when running a container with no PID namespace and the parent process spawning the container is
- // PID1 the pdeathsig is being delivered to the container's init process by the kernel for some reason
- // even with the parent still running.
- if c.config.ParentDeathSignal > 0 {
- cmd.SysProcAttr.Pdeathsig = syscall.Signal(c.config.ParentDeathSignal)
- }
- return cmd, nil
-}
-
-func (c *linuxContainer) newInitProcess(p *Process, cmd *exec.Cmd, parentPipe, childPipe *os.File) (*initProcess, error) {
- t := "_LIBCONTAINER_INITTYPE=standard"
- cloneFlags := c.config.Namespaces.CloneFlags()
- if cloneFlags&syscall.CLONE_NEWUSER != 0 {
- if err := c.addUidGidMappings(cmd.SysProcAttr); err != nil {
- // user mappings are not supported
- return nil, err
- }
- enableSetgroups(cmd.SysProcAttr)
- // Default to root user when user namespaces are enabled.
- if cmd.SysProcAttr.Credential == nil {
- cmd.SysProcAttr.Credential = &syscall.Credential{}
- }
- }
- cmd.Env = append(cmd.Env, t)
- cmd.SysProcAttr.Cloneflags = cloneFlags
- return &initProcess{
- cmd: cmd,
- childPipe: childPipe,
- parentPipe: parentPipe,
- manager: c.cgroupManager,
- config: c.newInitConfig(p),
- container: c,
- process: p,
- }, nil
-}
-
-func (c *linuxContainer) newSetnsProcess(p *Process, cmd *exec.Cmd, parentPipe, childPipe *os.File) *setnsProcess {
- cmd.Env = append(cmd.Env,
- fmt.Sprintf("_LIBCONTAINER_INITPID=%d", c.initProcess.pid()),
- "_LIBCONTAINER_INITTYPE=setns",
- )
- if p.consolePath != "" {
- cmd.Env = append(cmd.Env, "_LIBCONTAINER_CONSOLE_PATH="+p.consolePath)
- }
- // TODO: set on container for process management
- return &setnsProcess{
- cmd: cmd,
- cgroupPaths: c.cgroupManager.GetPaths(),
- childPipe: childPipe,
- parentPipe: parentPipe,
- config: c.newInitConfig(p),
- process: p,
- }
-}
-
-func (c *linuxContainer) newInitConfig(process *Process) *initConfig {
- return &initConfig{
- Config: c.config,
- Args: process.Args,
- Env: process.Env,
- User: process.User,
- Cwd: process.Cwd,
- Console: process.consolePath,
- Capabilities: process.Capabilities,
- PassedFilesCount: len(process.ExtraFiles),
- }
-}
-
-func newPipe() (parent *os.File, child *os.File, err error) {
- fds, err := syscall.Socketpair(syscall.AF_LOCAL, syscall.SOCK_STREAM|syscall.SOCK_CLOEXEC, 0)
- if err != nil {
- return nil, nil, err
- }
- return os.NewFile(uintptr(fds[1]), "parent"), os.NewFile(uintptr(fds[0]), "child"), nil
-}
-
-func (c *linuxContainer) Destroy() error {
- c.m.Lock()
- defer c.m.Unlock()
- status, err := c.currentStatus()
- if err != nil {
- return err
- }
- if status != Destroyed {
- return newGenericError(fmt.Errorf("container is not destroyed"), ContainerNotStopped)
- }
- if !c.config.Namespaces.Contains(configs.NEWPID) {
- if err := killCgroupProcesses(c.cgroupManager); err != nil {
- logrus.Warn(err)
- }
- }
- err = c.cgroupManager.Destroy()
- if rerr := os.RemoveAll(c.root); err == nil {
- err = rerr
- }
- c.initProcess = nil
- if c.config.Hooks != nil {
- s := configs.HookState{
- Version: c.config.Version,
- ID: c.id,
- Root: c.config.Rootfs,
- }
- for _, hook := range c.config.Hooks.Poststop {
- if err := hook.Run(s); err != nil {
- return err
- }
- }
- }
- return err
-}
-
-func (c *linuxContainer) Pause() error {
- c.m.Lock()
- defer c.m.Unlock()
- return c.cgroupManager.Freeze(configs.Frozen)
-}
-
-func (c *linuxContainer) Resume() error {
- c.m.Lock()
- defer c.m.Unlock()
- return c.cgroupManager.Freeze(configs.Thawed)
-}
-
-func (c *linuxContainer) NotifyOOM() (<-chan struct{}, error) {
- return notifyOnOOM(c.cgroupManager.GetPaths())
-}
-
-// XXX debug support, remove when debugging done.
-func addArgsFromEnv(evar string, args *[]string) {
- if e := os.Getenv(evar); e != "" {
- for _, f := range strings.Fields(e) {
- *args = append(*args, f)
- }
- }
- fmt.Printf(">>> criu %v\n", *args)
-}
-
-// check Criu version greater than or equal to min_version
-func (c *linuxContainer) checkCriuVersion(min_version string) error {
- var x, y, z, versionReq int
-
- _, err := fmt.Sscanf(min_version, "%d.%d.%d\n", &x, &y, &z) // 1.5.2
- if err != nil {
- _, err = fmt.Sscanf(min_version, "Version: %d.%d\n", &x, &y) // 1.6
- }
- versionReq = x*10000 + y*100 + z
-
- out, err := exec.Command(c.criuPath, "-V").Output()
- if err != nil {
- return fmt.Errorf("Unable to execute CRIU command: %s", c.criuPath)
- }
-
- x = 0
- y = 0
- z = 0
- if ep := strings.Index(string(out), "-"); ep >= 0 {
- // criu Git version format
- var version string
- if sp := strings.Index(string(out), "GitID"); sp > 0 {
- version = string(out)[sp:ep]
- } else {
- return fmt.Errorf("Unable to parse the CRIU version: %s", c.criuPath)
- }
-
- n, err := fmt.Sscanf(string(version), "GitID: v%d.%d.%d", &x, &y, &z) // 1.5.2
- if err != nil {
- n, err = fmt.Sscanf(string(version), "GitID: v%d.%d", &x, &y) // 1.6
- y++
- } else {
- z++
- }
- if n < 2 || err != nil {
- return fmt.Errorf("Unable to parse the CRIU version: %s %d %s", version, n, err)
- }
- } else {
- // criu release version format
- n, err := fmt.Sscanf(string(out), "Version: %d.%d.%d\n", &x, &y, &z) // 1.5.2
- if err != nil {
- n, err = fmt.Sscanf(string(out), "Version: %d.%d\n", &x, &y) // 1.6
- }
- if n < 2 || err != nil {
- return fmt.Errorf("Unable to parse the CRIU version: %s %d %s", out, n, err)
- }
- }
-
- c.criuVersion = x*10000 + y*100 + z
-
- if c.criuVersion < versionReq {
- return fmt.Errorf("CRIU version must be %s or higher", min_version)
- }
-
- return nil
-}
-
-const descriptorsFilename = "descriptors.json"
-
-func (c *linuxContainer) addCriuDumpMount(req *criurpc.CriuReq, m *configs.Mount) {
- mountDest := m.Destination
- if strings.HasPrefix(mountDest, c.config.Rootfs) {
- mountDest = mountDest[len(c.config.Rootfs):]
- }
-
- extMnt := &criurpc.ExtMountMap{
- Key: proto.String(mountDest),
- Val: proto.String(mountDest),
- }
- req.Opts.ExtMnt = append(req.Opts.ExtMnt, extMnt)
-}
-
-func (c *linuxContainer) Checkpoint(criuOpts *CriuOpts) error {
- c.m.Lock()
- defer c.m.Unlock()
-
- if err := c.checkCriuVersion("1.5.2"); err != nil {
- return err
- }
-
- if criuOpts.ImagesDirectory == "" {
- criuOpts.ImagesDirectory = filepath.Join(c.root, "criu.image")
- }
-
- // Since a container can be C/R'ed multiple times,
- // the checkpoint directory may already exist.
- if err := os.Mkdir(criuOpts.ImagesDirectory, 0755); err != nil && !os.IsExist(err) {
- return err
- }
-
- if criuOpts.WorkDirectory == "" {
- criuOpts.WorkDirectory = filepath.Join(c.root, "criu.work")
- }
-
- if err := os.Mkdir(criuOpts.WorkDirectory, 0755); err != nil && !os.IsExist(err) {
- return err
- }
-
- workDir, err := os.Open(criuOpts.WorkDirectory)
- if err != nil {
- return err
- }
- defer workDir.Close()
-
- imageDir, err := os.Open(criuOpts.ImagesDirectory)
- if err != nil {
- return err
- }
- defer imageDir.Close()
-
- rpcOpts := criurpc.CriuOpts{
- ImagesDirFd: proto.Int32(int32(imageDir.Fd())),
- WorkDirFd: proto.Int32(int32(workDir.Fd())),
- LogLevel: proto.Int32(4),
- LogFile: proto.String("dump.log"),
- Root: proto.String(c.config.Rootfs),
- ManageCgroups: proto.Bool(true),
- NotifyScripts: proto.Bool(true),
- Pid: proto.Int32(int32(c.initProcess.pid())),
- ShellJob: proto.Bool(criuOpts.ShellJob),
- LeaveRunning: proto.Bool(criuOpts.LeaveRunning),
- TcpEstablished: proto.Bool(criuOpts.TcpEstablished),
- ExtUnixSk: proto.Bool(criuOpts.ExternalUnixConnections),
- FileLocks: proto.Bool(criuOpts.FileLocks),
- }
-
- // append optional criu opts, e.g., page-server and port
- if criuOpts.PageServer.Address != "" && criuOpts.PageServer.Port != 0 {
- rpcOpts.Ps = &criurpc.CriuPageServerInfo{
- Address: proto.String(criuOpts.PageServer.Address),
- Port: proto.Int32(criuOpts.PageServer.Port),
- }
- }
-
- // append optional manage cgroups mode
- if criuOpts.ManageCgroupsMode != 0 {
- if err := c.checkCriuVersion("1.7"); err != nil {
- return err
- }
- rpcOpts.ManageCgroupsMode = proto.Uint32(uint32(criuOpts.ManageCgroupsMode))
- }
-
- t := criurpc.CriuReqType_DUMP
- req := &criurpc.CriuReq{
- Type: &t,
- Opts: &rpcOpts,
- }
-
- for _, m := range c.config.Mounts {
- switch m.Device {
- case "bind":
- c.addCriuDumpMount(req, m)
- break
- case "cgroup":
- binds, err := getCgroupMounts(m)
- if err != nil {
- return err
- }
- for _, b := range binds {
- c.addCriuDumpMount(req, b)
- }
- break
- }
- }
-
- // Write the FD info to a file in the image directory
-
- fdsJSON, err := json.Marshal(c.initProcess.externalDescriptors())
- if err != nil {
- return err
- }
-
- err = ioutil.WriteFile(filepath.Join(criuOpts.ImagesDirectory, descriptorsFilename), fdsJSON, 0655)
- if err != nil {
- return err
- }
-
- err = c.criuSwrk(nil, req, criuOpts, false)
- if err != nil {
- return err
- }
- return nil
-}
-
-func (c *linuxContainer) addCriuRestoreMount(req *criurpc.CriuReq, m *configs.Mount) {
- mountDest := m.Destination
- if strings.HasPrefix(mountDest, c.config.Rootfs) {
- mountDest = mountDest[len(c.config.Rootfs):]
- }
-
- extMnt := &criurpc.ExtMountMap{
- Key: proto.String(mountDest),
- Val: proto.String(m.Source),
- }
- req.Opts.ExtMnt = append(req.Opts.ExtMnt, extMnt)
-}
-
-func (c *linuxContainer) Restore(process *Process, criuOpts *CriuOpts) error {
- c.m.Lock()
- defer c.m.Unlock()
-
- if err := c.checkCriuVersion("1.5.2"); err != nil {
- return err
- }
-
- if criuOpts.WorkDirectory == "" {
- criuOpts.WorkDirectory = filepath.Join(c.root, "criu.work")
- }
- // Since a container can be C/R'ed multiple times,
- // the work directory may already exist.
- if err := os.Mkdir(criuOpts.WorkDirectory, 0655); err != nil && !os.IsExist(err) {
- return err
- }
-
- workDir, err := os.Open(criuOpts.WorkDirectory)
- if err != nil {
- return err
- }
- defer workDir.Close()
-
- if criuOpts.ImagesDirectory == "" {
- criuOpts.ImagesDirectory = filepath.Join(c.root, "criu.image")
- }
- imageDir, err := os.Open(criuOpts.ImagesDirectory)
- if err != nil {
- return err
- }
- defer imageDir.Close()
-
- // CRIU has a few requirements for a root directory:
- // * it must be a mount point
- // * its parent must not be overmounted
- // c.config.Rootfs is bind-mounted to a temporary directory
- // to satisfy these requirements.
- root := filepath.Join(c.root, "criu-root")
- if err := os.Mkdir(root, 0755); err != nil {
- return err
- }
- defer os.Remove(root)
-
- root, err = filepath.EvalSymlinks(root)
- if err != nil {
- return err
- }
-
- err = syscall.Mount(c.config.Rootfs, root, "", syscall.MS_BIND|syscall.MS_REC, "")
- if err != nil {
- return err
- }
- defer syscall.Unmount(root, syscall.MNT_DETACH)
-
- t := criurpc.CriuReqType_RESTORE
- req := &criurpc.CriuReq{
- Type: &t,
- Opts: &criurpc.CriuOpts{
- ImagesDirFd: proto.Int32(int32(imageDir.Fd())),
- WorkDirFd: proto.Int32(int32(workDir.Fd())),
- EvasiveDevices: proto.Bool(true),
- LogLevel: proto.Int32(4),
- LogFile: proto.String("restore.log"),
- RstSibling: proto.Bool(true),
- Root: proto.String(root),
- ManageCgroups: proto.Bool(true),
- NotifyScripts: proto.Bool(true),
- ShellJob: proto.Bool(criuOpts.ShellJob),
- ExtUnixSk: proto.Bool(criuOpts.ExternalUnixConnections),
- TcpEstablished: proto.Bool(criuOpts.TcpEstablished),
- FileLocks: proto.Bool(criuOpts.FileLocks),
- },
- }
-
- for _, m := range c.config.Mounts {
- switch m.Device {
- case "bind":
- c.addCriuRestoreMount(req, m)
- break
- case "cgroup":
- binds, err := getCgroupMounts(m)
- if err != nil {
- return err
- }
- for _, b := range binds {
- c.addCriuRestoreMount(req, b)
- }
- break
- }
- }
- for _, iface := range c.config.Networks {
- switch iface.Type {
- case "veth":
- veth := new(criurpc.CriuVethPair)
- veth.IfOut = proto.String(iface.HostInterfaceName)
- veth.IfIn = proto.String(iface.Name)
- req.Opts.Veths = append(req.Opts.Veths, veth)
- break
- case "loopback":
- break
- }
- }
- for _, i := range criuOpts.VethPairs {
- veth := new(criurpc.CriuVethPair)
- veth.IfOut = proto.String(i.HostInterfaceName)
- veth.IfIn = proto.String(i.ContainerInterfaceName)
- req.Opts.Veths = append(req.Opts.Veths, veth)
- }
-
- // append optional manage cgroups mode
- if criuOpts.ManageCgroupsMode != 0 {
- if err := c.checkCriuVersion("1.7"); err != nil {
- return err
- }
- req.Opts.ManageCgroupsMode = proto.Uint32(uint32(criuOpts.ManageCgroupsMode))
- }
-
- var (
- fds []string
- fdJSON []byte
- )
-
- if fdJSON, err = ioutil.ReadFile(filepath.Join(criuOpts.ImagesDirectory, descriptorsFilename)); err != nil {
- return err
- }
-
- if err = json.Unmarshal(fdJSON, &fds); err != nil {
- return err
- }
-
- for i := range fds {
- if s := fds[i]; strings.Contains(s, "pipe:") {
- inheritFd := new(criurpc.InheritFd)
- inheritFd.Key = proto.String(s)
- inheritFd.Fd = proto.Int32(int32(i))
- req.Opts.InheritFd = append(req.Opts.InheritFd, inheritFd)
- }
- }
-
- err = c.criuSwrk(process, req, criuOpts, true)
- if err != nil {
- return err
- }
- return nil
-}
-
-func (c *linuxContainer) criuApplyCgroups(pid int, req *criurpc.CriuReq) error {
- if err := c.cgroupManager.Apply(pid); err != nil {
- return err
- }
-
- path := fmt.Sprintf("/proc/%d/cgroup", pid)
- cgroupsPaths, err := cgroups.ParseCgroupFile(path)
- if err != nil {
- return err
- }
-
- for c, p := range cgroupsPaths {
- cgroupRoot := &criurpc.CgroupRoot{
- Ctrl: proto.String(c),
- Path: proto.String(p),
- }
- req.Opts.CgRoot = append(req.Opts.CgRoot, cgroupRoot)
- }
-
- return nil
-}
-
-func (c *linuxContainer) criuSwrk(process *Process, req *criurpc.CriuReq, opts *CriuOpts, applyCgroups bool) error {
- fds, err := syscall.Socketpair(syscall.AF_LOCAL, syscall.SOCK_SEQPACKET|syscall.SOCK_CLOEXEC, 0)
- if err != nil {
- return err
- }
-
- logPath := filepath.Join(opts.WorkDirectory, req.GetOpts().GetLogFile())
- criuClient := os.NewFile(uintptr(fds[0]), "criu-transport-client")
- criuServer := os.NewFile(uintptr(fds[1]), "criu-transport-server")
- defer criuClient.Close()
- defer criuServer.Close()
-
- args := []string{"swrk", "3"}
- logrus.Debugf("Using CRIU %d at: %s", c.criuVersion, c.criuPath)
- logrus.Debugf("Using CRIU with following args: %s", args)
- cmd := exec.Command(c.criuPath, args...)
- if process != nil {
- cmd.Stdin = process.Stdin
- cmd.Stdout = process.Stdout
- cmd.Stderr = process.Stderr
- }
- cmd.ExtraFiles = append(cmd.ExtraFiles, criuServer)
-
- if err := cmd.Start(); err != nil {
- return err
- }
- criuServer.Close()
-
- defer func() {
- criuClient.Close()
- _, err := cmd.Process.Wait()
- if err != nil {
- return
- }
- }()
-
- if applyCgroups {
- err := c.criuApplyCgroups(cmd.Process.Pid, req)
- if err != nil {
- return err
- }
- }
-
- var extFds []string
- if process != nil {
- extFds, err = getPipeFds(cmd.Process.Pid)
- if err != nil {
- return err
- }
- }
-
- logrus.Debugf("Using CRIU in %s mode", req.GetType().String())
- val := reflect.ValueOf(req.GetOpts())
- v := reflect.Indirect(val)
- for i := 0; i < v.NumField(); i++ {
- st := v.Type()
- name := st.Field(i).Name
- if strings.HasPrefix(name, "XXX_") {
- continue
- }
- value := val.MethodByName("Get" + name).Call([]reflect.Value{})
- logrus.Debugf("CRIU option %s with value %v", name, value[0])
- }
- data, err := proto.Marshal(req)
- if err != nil {
- return err
- }
- _, err = criuClient.Write(data)
- if err != nil {
- return err
- }
-
- buf := make([]byte, 10*4096)
- for true {
- n, err := criuClient.Read(buf)
- if err != nil {
- return err
- }
- if n == 0 {
- return fmt.Errorf("unexpected EOF")
- }
- if n == len(buf) {
- return fmt.Errorf("buffer is too small")
- }
-
- resp := new(criurpc.CriuResp)
- err = proto.Unmarshal(buf[:n], resp)
- if err != nil {
- return err
- }
- if !resp.GetSuccess() {
- typeString := req.GetType().String()
- return fmt.Errorf("criu failed: type %s errno %d\nlog file: %s", typeString, resp.GetCrErrno(), logPath)
- }
-
- t := resp.GetType()
- switch {
- case t == criurpc.CriuReqType_NOTIFY:
- if err := c.criuNotifications(resp, process, opts, extFds); err != nil {
- return err
- }
- t = criurpc.CriuReqType_NOTIFY
- req = &criurpc.CriuReq{
- Type: &t,
- NotifySuccess: proto.Bool(true),
- }
- data, err = proto.Marshal(req)
- if err != nil {
- return err
- }
- n, err = criuClient.Write(data)
- if err != nil {
- return err
- }
- continue
- case t == criurpc.CriuReqType_RESTORE:
- case t == criurpc.CriuReqType_DUMP:
- break
- default:
- return fmt.Errorf("unable to parse the response %s", resp.String())
- }
-
- break
- }
-
- // cmd.Wait() waits cmd.goroutines which are used for proxying file descriptors.
- // Here we want to wait only the CRIU process.
- st, err := cmd.Process.Wait()
- if err != nil {
- return err
- }
- if !st.Success() {
- return fmt.Errorf("criu failed: %s\nlog file: %s", st.String(), logPath)
- }
- return nil
-}
-
-// block any external network activity
-func lockNetwork(config *configs.Config) error {
- for _, config := range config.Networks {
- strategy, err := getStrategy(config.Type)
- if err != nil {
- return err
- }
-
- if err := strategy.detach(config); err != nil {
- return err
- }
- }
- return nil
-}
-
-func unlockNetwork(config *configs.Config) error {
- for _, config := range config.Networks {
- strategy, err := getStrategy(config.Type)
- if err != nil {
- return err
- }
- if err = strategy.attach(config); err != nil {
- return err
- }
- }
- return nil
-}
-
-func (c *linuxContainer) criuNotifications(resp *criurpc.CriuResp, process *Process, opts *CriuOpts, fds []string) error {
- notify := resp.GetNotify()
- if notify == nil {
- return fmt.Errorf("invalid response: %s", resp.String())
- }
-
- switch {
- case notify.GetScript() == "post-dump":
- if !opts.LeaveRunning {
- f, err := os.Create(filepath.Join(c.root, "checkpoint"))
- if err != nil {
- return err
- }
- f.Close()
- }
- break
-
- case notify.GetScript() == "network-unlock":
- if err := unlockNetwork(c.config); err != nil {
- return err
- }
- break
-
- case notify.GetScript() == "network-lock":
- if err := lockNetwork(c.config); err != nil {
- return err
- }
- break
-
- case notify.GetScript() == "post-restore":
- pid := notify.GetPid()
- r, err := newRestoredProcess(int(pid), fds)
- if err != nil {
- return err
- }
-
- // TODO: crosbymichael restore previous process information by saving the init process information in
- // the container's state file or separate process state files.
- if err := c.updateState(r); err != nil {
- return err
- }
- process.ops = r
- break
- }
-
- return nil
-}
-
-func (c *linuxContainer) updateState(process parentProcess) error {
- c.initProcess = process
- state, err := c.currentState()
- if err != nil {
- return err
- }
- f, err := os.Create(filepath.Join(c.root, stateFilename))
- if err != nil {
- return err
- }
- defer f.Close()
- os.Remove(filepath.Join(c.root, "checkpoint"))
- return json.NewEncoder(f).Encode(state)
-}
-
-func (c *linuxContainer) currentStatus() (Status, error) {
- if _, err := os.Stat(filepath.Join(c.root, "checkpoint")); err == nil {
- return Checkpointed, nil
- }
- if c.initProcess == nil {
- return Destroyed, nil
- }
- // return Running if the init process is alive
- if err := syscall.Kill(c.initProcess.pid(), 0); err != nil {
- if err == syscall.ESRCH {
- return Destroyed, nil
- }
- return 0, newSystemError(err)
- }
- if c.config.Cgroups != nil && c.config.Cgroups.Freezer == configs.Frozen {
- return Paused, nil
- }
- return Running, nil
-}
-
-func (c *linuxContainer) currentState() (*State, error) {
- status, err := c.currentStatus()
- if err != nil {
- return nil, err
- }
- if status == Destroyed {
- return nil, newGenericError(fmt.Errorf("container destroyed"), ContainerNotExists)
- }
- startTime, err := c.initProcess.startTime()
- if err != nil {
- return nil, newSystemError(err)
- }
- state := &State{
- BaseState: BaseState{
- ID: c.ID(),
- Config: *c.config,
- InitProcessPid: c.initProcess.pid(),
- InitProcessStartTime: startTime,
- },
- CgroupPaths: c.cgroupManager.GetPaths(),
- NamespacePaths: make(map[configs.NamespaceType]string),
- ExternalDescriptors: c.initProcess.externalDescriptors(),
- }
- for _, ns := range c.config.Namespaces {
- state.NamespacePaths[ns.Type] = ns.GetPath(c.initProcess.pid())
- }
- for _, nsType := range configs.NamespaceTypes() {
- if _, ok := state.NamespacePaths[nsType]; !ok {
- ns := configs.Namespace{Type: nsType}
- state.NamespacePaths[ns.Type] = ns.GetPath(c.initProcess.pid())
- }
- }
- return state, nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/container_nouserns_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/container_nouserns_linux.go
deleted file mode 100644
index 3b75d59..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/container_nouserns_linux.go
+++ /dev/null
@@ -1,13 +0,0 @@
-// +build !go1.4
-
-package libcontainer
-
-import (
- "fmt"
- "syscall"
-)
-
-// not available before go 1.4
-func (c *linuxContainer) addUidGidMappings(sys *syscall.SysProcAttr) error {
- return fmt.Errorf("User namespace is not supported in golang < 1.4")
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/container_userns_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/container_userns_linux.go
deleted file mode 100644
index 5f4cf3c..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/container_userns_linux.go
+++ /dev/null
@@ -1,26 +0,0 @@
-// +build go1.4
-
-package libcontainer
-
-import "syscall"
-
-// Converts IDMap to SysProcIDMap array and adds it to SysProcAttr.
-func (c *linuxContainer) addUidGidMappings(sys *syscall.SysProcAttr) error {
- if c.config.UidMappings != nil {
- sys.UidMappings = make([]syscall.SysProcIDMap, len(c.config.UidMappings))
- for i, um := range c.config.UidMappings {
- sys.UidMappings[i].ContainerID = um.ContainerID
- sys.UidMappings[i].HostID = um.HostID
- sys.UidMappings[i].Size = um.Size
- }
- }
- if c.config.GidMappings != nil {
- sys.GidMappings = make([]syscall.SysProcIDMap, len(c.config.GidMappings))
- for i, gm := range c.config.GidMappings {
- sys.GidMappings[i].ContainerID = gm.ContainerID
- sys.GidMappings[i].HostID = gm.HostID
- sys.GidMappings[i].Size = gm.Size
- }
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/container_windows.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/container_windows.go
deleted file mode 100644
index bb84ff7..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/container_windows.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package libcontainer
-
-// State represents a running container's state
-type State struct {
- BaseState
-
- // Platform specific fields below here
-}
-
-// A libcontainer container object.
-//
-// Each container is thread-safe within the same process. Since a container can
-// be destroyed by a separate process, any function may return that the container
-// was not found.
-type Container interface {
- BaseContainer
-
- // Methods below here are platform specific
-
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/criu_opts_unix.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/criu_opts_unix.go
deleted file mode 100644
index a2a816b..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/criu_opts_unix.go
+++ /dev/null
@@ -1,36 +0,0 @@
-// +build linux freebsd
-
-package libcontainer
-
-// cgroup restoring strategy provided by criu
-type cg_mode uint32
-
-const (
- CRIU_CG_MODE_SOFT cg_mode = 3 + iota // restore cgroup properties if only dir created by criu
- CRIU_CG_MODE_FULL // always restore all cgroups and their properties
- CRIU_CG_MODE_STRICT // restore all, requiring them to not present in the system
- CRIU_CG_MODE_DEFAULT // the same as CRIU_CG_MODE_SOFT
-)
-
-type CriuPageServerInfo struct {
- Address string // IP address of CRIU page server
- Port int32 // port number of CRIU page server
-}
-
-type VethPairName struct {
- ContainerInterfaceName string
- HostInterfaceName string
-}
-
-type CriuOpts struct {
- ImagesDirectory string // directory for storing image files
- WorkDirectory string // directory to cd and write logs/pidfiles/stats to
- LeaveRunning bool // leave container in running state after checkpoint
- TcpEstablished bool // checkpoint/restore established TCP connections
- ExternalUnixConnections bool // allow external unix connections
- ShellJob bool // allow to dump and restore shell jobs
- FileLocks bool // handle file locks, for safety
- PageServer CriuPageServerInfo // allow to dump to criu page server
- VethPairs []VethPairName // pass the veth to criu when restore
- ManageCgroupsMode cg_mode // dump or restore cgroup mode
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/criu_opts_windows.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/criu_opts_windows.go
deleted file mode 100644
index bc92077..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/criu_opts_windows.go
+++ /dev/null
@@ -1,6 +0,0 @@
-package libcontainer
-
-// TODO Windows: This can ultimately be entirely factored out as criu is
-// a Unix concept not relevant on Windows.
-type CriuOpts struct {
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/criurpc/Makefile b/containerd/vendor/github.com/opencontainers/runc/libcontainer/criurpc/Makefile
deleted file mode 100644
index 3e5346a..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/criurpc/Makefile
+++ /dev/null
@@ -1,2 +0,0 @@
-gen: criurpc.proto
- protoc --go_out=. criurpc.proto
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.pb.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.pb.go
deleted file mode 100644
index 193b6df..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.pb.go
+++ /dev/null
@@ -1,689 +0,0 @@
-// Code generated by protoc-gen-go.
-// source: criurpc.proto
-// DO NOT EDIT!
-
-/*
-Package criurpc is a generated protocol buffer package.
-
-It is generated from these files:
- criurpc.proto
-
-It has these top-level messages:
- CriuPageServerInfo
- CriuVethPair
- ExtMountMap
- InheritFd
- CgroupRoot
- UnixSk
- CriuOpts
- CriuDumpResp
- CriuRestoreResp
- CriuNotify
- CriuReq
- CriuResp
-*/
-package criurpc
-
-import proto "github.com/golang/protobuf/proto"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = math.Inf
-
-type CriuReqType int32
-
-const (
- CriuReqType_EMPTY CriuReqType = 0
- CriuReqType_DUMP CriuReqType = 1
- CriuReqType_RESTORE CriuReqType = 2
- CriuReqType_CHECK CriuReqType = 3
- CriuReqType_PRE_DUMP CriuReqType = 4
- CriuReqType_PAGE_SERVER CriuReqType = 5
- CriuReqType_NOTIFY CriuReqType = 6
- CriuReqType_CPUINFO_DUMP CriuReqType = 7
- CriuReqType_CPUINFO_CHECK CriuReqType = 8
-)
-
-var CriuReqType_name = map[int32]string{
- 0: "EMPTY",
- 1: "DUMP",
- 2: "RESTORE",
- 3: "CHECK",
- 4: "PRE_DUMP",
- 5: "PAGE_SERVER",
- 6: "NOTIFY",
- 7: "CPUINFO_DUMP",
- 8: "CPUINFO_CHECK",
-}
-var CriuReqType_value = map[string]int32{
- "EMPTY": 0,
- "DUMP": 1,
- "RESTORE": 2,
- "CHECK": 3,
- "PRE_DUMP": 4,
- "PAGE_SERVER": 5,
- "NOTIFY": 6,
- "CPUINFO_DUMP": 7,
- "CPUINFO_CHECK": 8,
-}
-
-func (x CriuReqType) Enum() *CriuReqType {
- p := new(CriuReqType)
- *p = x
- return p
-}
-func (x CriuReqType) String() string {
- return proto.EnumName(CriuReqType_name, int32(x))
-}
-func (x *CriuReqType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(CriuReqType_value, data, "CriuReqType")
- if err != nil {
- return err
- }
- *x = CriuReqType(value)
- return nil
-}
-
-type CriuPageServerInfo struct {
- Address *string `protobuf:"bytes,1,opt,name=address" json:"address,omitempty"`
- Port *int32 `protobuf:"varint,2,opt,name=port" json:"port,omitempty"`
- Pid *int32 `protobuf:"varint,3,opt,name=pid" json:"pid,omitempty"`
- Fd *int32 `protobuf:"varint,4,opt,name=fd" json:"fd,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *CriuPageServerInfo) Reset() { *m = CriuPageServerInfo{} }
-func (m *CriuPageServerInfo) String() string { return proto.CompactTextString(m) }
-func (*CriuPageServerInfo) ProtoMessage() {}
-
-func (m *CriuPageServerInfo) GetAddress() string {
- if m != nil && m.Address != nil {
- return *m.Address
- }
- return ""
-}
-
-func (m *CriuPageServerInfo) GetPort() int32 {
- if m != nil && m.Port != nil {
- return *m.Port
- }
- return 0
-}
-
-func (m *CriuPageServerInfo) GetPid() int32 {
- if m != nil && m.Pid != nil {
- return *m.Pid
- }
- return 0
-}
-
-func (m *CriuPageServerInfo) GetFd() int32 {
- if m != nil && m.Fd != nil {
- return *m.Fd
- }
- return 0
-}
-
-type CriuVethPair struct {
- IfIn *string `protobuf:"bytes,1,req,name=if_in" json:"if_in,omitempty"`
- IfOut *string `protobuf:"bytes,2,req,name=if_out" json:"if_out,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *CriuVethPair) Reset() { *m = CriuVethPair{} }
-func (m *CriuVethPair) String() string { return proto.CompactTextString(m) }
-func (*CriuVethPair) ProtoMessage() {}
-
-func (m *CriuVethPair) GetIfIn() string {
- if m != nil && m.IfIn != nil {
- return *m.IfIn
- }
- return ""
-}
-
-func (m *CriuVethPair) GetIfOut() string {
- if m != nil && m.IfOut != nil {
- return *m.IfOut
- }
- return ""
-}
-
-type ExtMountMap struct {
- Key *string `protobuf:"bytes,1,req,name=key" json:"key,omitempty"`
- Val *string `protobuf:"bytes,2,req,name=val" json:"val,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *ExtMountMap) Reset() { *m = ExtMountMap{} }
-func (m *ExtMountMap) String() string { return proto.CompactTextString(m) }
-func (*ExtMountMap) ProtoMessage() {}
-
-func (m *ExtMountMap) GetKey() string {
- if m != nil && m.Key != nil {
- return *m.Key
- }
- return ""
-}
-
-func (m *ExtMountMap) GetVal() string {
- if m != nil && m.Val != nil {
- return *m.Val
- }
- return ""
-}
-
-type InheritFd struct {
- Key *string `protobuf:"bytes,1,req,name=key" json:"key,omitempty"`
- Fd *int32 `protobuf:"varint,2,req,name=fd" json:"fd,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *InheritFd) Reset() { *m = InheritFd{} }
-func (m *InheritFd) String() string { return proto.CompactTextString(m) }
-func (*InheritFd) ProtoMessage() {}
-
-func (m *InheritFd) GetKey() string {
- if m != nil && m.Key != nil {
- return *m.Key
- }
- return ""
-}
-
-func (m *InheritFd) GetFd() int32 {
- if m != nil && m.Fd != nil {
- return *m.Fd
- }
- return 0
-}
-
-type CgroupRoot struct {
- Ctrl *string `protobuf:"bytes,1,opt,name=ctrl" json:"ctrl,omitempty"`
- Path *string `protobuf:"bytes,2,req,name=path" json:"path,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *CgroupRoot) Reset() { *m = CgroupRoot{} }
-func (m *CgroupRoot) String() string { return proto.CompactTextString(m) }
-func (*CgroupRoot) ProtoMessage() {}
-
-func (m *CgroupRoot) GetCtrl() string {
- if m != nil && m.Ctrl != nil {
- return *m.Ctrl
- }
- return ""
-}
-
-func (m *CgroupRoot) GetPath() string {
- if m != nil && m.Path != nil {
- return *m.Path
- }
- return ""
-}
-
-type UnixSk struct {
- Inode *uint32 `protobuf:"varint,1,req,name=inode" json:"inode,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *UnixSk) Reset() { *m = UnixSk{} }
-func (m *UnixSk) String() string { return proto.CompactTextString(m) }
-func (*UnixSk) ProtoMessage() {}
-
-func (m *UnixSk) GetInode() uint32 {
- if m != nil && m.Inode != nil {
- return *m.Inode
- }
- return 0
-}
-
-type CriuOpts struct {
- ImagesDirFd *int32 `protobuf:"varint,1,req,name=images_dir_fd" json:"images_dir_fd,omitempty"`
- Pid *int32 `protobuf:"varint,2,opt,name=pid" json:"pid,omitempty"`
- LeaveRunning *bool `protobuf:"varint,3,opt,name=leave_running" json:"leave_running,omitempty"`
- ExtUnixSk *bool `protobuf:"varint,4,opt,name=ext_unix_sk" json:"ext_unix_sk,omitempty"`
- TcpEstablished *bool `protobuf:"varint,5,opt,name=tcp_established" json:"tcp_established,omitempty"`
- EvasiveDevices *bool `protobuf:"varint,6,opt,name=evasive_devices" json:"evasive_devices,omitempty"`
- ShellJob *bool `protobuf:"varint,7,opt,name=shell_job" json:"shell_job,omitempty"`
- FileLocks *bool `protobuf:"varint,8,opt,name=file_locks" json:"file_locks,omitempty"`
- LogLevel *int32 `protobuf:"varint,9,opt,name=log_level,def=2" json:"log_level,omitempty"`
- LogFile *string `protobuf:"bytes,10,opt,name=log_file" json:"log_file,omitempty"`
- Ps *CriuPageServerInfo `protobuf:"bytes,11,opt,name=ps" json:"ps,omitempty"`
- NotifyScripts *bool `protobuf:"varint,12,opt,name=notify_scripts" json:"notify_scripts,omitempty"`
- Root *string `protobuf:"bytes,13,opt,name=root" json:"root,omitempty"`
- ParentImg *string `protobuf:"bytes,14,opt,name=parent_img" json:"parent_img,omitempty"`
- TrackMem *bool `protobuf:"varint,15,opt,name=track_mem" json:"track_mem,omitempty"`
- AutoDedup *bool `protobuf:"varint,16,opt,name=auto_dedup" json:"auto_dedup,omitempty"`
- WorkDirFd *int32 `protobuf:"varint,17,opt,name=work_dir_fd" json:"work_dir_fd,omitempty"`
- LinkRemap *bool `protobuf:"varint,18,opt,name=link_remap" json:"link_remap,omitempty"`
- Veths []*CriuVethPair `protobuf:"bytes,19,rep,name=veths" json:"veths,omitempty"`
- CpuCap *uint32 `protobuf:"varint,20,opt,name=cpu_cap,def=4294967295" json:"cpu_cap,omitempty"`
- ForceIrmap *bool `protobuf:"varint,21,opt,name=force_irmap" json:"force_irmap,omitempty"`
- ExecCmd []string `protobuf:"bytes,22,rep,name=exec_cmd" json:"exec_cmd,omitempty"`
- ExtMnt []*ExtMountMap `protobuf:"bytes,23,rep,name=ext_mnt" json:"ext_mnt,omitempty"`
- ManageCgroups *bool `protobuf:"varint,24,opt,name=manage_cgroups" json:"manage_cgroups,omitempty"`
- CgRoot []*CgroupRoot `protobuf:"bytes,25,rep,name=cg_root" json:"cg_root,omitempty"`
- RstSibling *bool `protobuf:"varint,26,opt,name=rst_sibling" json:"rst_sibling,omitempty"`
- InheritFd []*InheritFd `protobuf:"bytes,27,rep,name=inherit_fd" json:"inherit_fd,omitempty"`
- AutoExtMnt *bool `protobuf:"varint,28,opt,name=auto_ext_mnt" json:"auto_ext_mnt,omitempty"`
- ExtSharing *bool `protobuf:"varint,29,opt,name=ext_sharing" json:"ext_sharing,omitempty"`
- ExtMasters *bool `protobuf:"varint,30,opt,name=ext_masters" json:"ext_masters,omitempty"`
- SkipMnt []string `protobuf:"bytes,31,rep,name=skip_mnt" json:"skip_mnt,omitempty"`
- EnableFs []string `protobuf:"bytes,32,rep,name=enable_fs" json:"enable_fs,omitempty"`
- UnixSkIno []*UnixSk `protobuf:"bytes,33,rep,name=unix_sk_ino" json:"unix_sk_ino,omitempty"`
- ManageCgroupsMode *uint32 `protobuf:"varint,34,opt,name=manage_cgroups_mode" json:"manage_cgroups_mode,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *CriuOpts) Reset() { *m = CriuOpts{} }
-func (m *CriuOpts) String() string { return proto.CompactTextString(m) }
-func (*CriuOpts) ProtoMessage() {}
-
-const Default_CriuOpts_LogLevel int32 = 2
-const Default_CriuOpts_CpuCap uint32 = 4294967295
-
-func (m *CriuOpts) GetImagesDirFd() int32 {
- if m != nil && m.ImagesDirFd != nil {
- return *m.ImagesDirFd
- }
- return 0
-}
-
-func (m *CriuOpts) GetPid() int32 {
- if m != nil && m.Pid != nil {
- return *m.Pid
- }
- return 0
-}
-
-func (m *CriuOpts) GetLeaveRunning() bool {
- if m != nil && m.LeaveRunning != nil {
- return *m.LeaveRunning
- }
- return false
-}
-
-func (m *CriuOpts) GetExtUnixSk() bool {
- if m != nil && m.ExtUnixSk != nil {
- return *m.ExtUnixSk
- }
- return false
-}
-
-func (m *CriuOpts) GetTcpEstablished() bool {
- if m != nil && m.TcpEstablished != nil {
- return *m.TcpEstablished
- }
- return false
-}
-
-func (m *CriuOpts) GetEvasiveDevices() bool {
- if m != nil && m.EvasiveDevices != nil {
- return *m.EvasiveDevices
- }
- return false
-}
-
-func (m *CriuOpts) GetShellJob() bool {
- if m != nil && m.ShellJob != nil {
- return *m.ShellJob
- }
- return false
-}
-
-func (m *CriuOpts) GetFileLocks() bool {
- if m != nil && m.FileLocks != nil {
- return *m.FileLocks
- }
- return false
-}
-
-func (m *CriuOpts) GetLogLevel() int32 {
- if m != nil && m.LogLevel != nil {
- return *m.LogLevel
- }
- return Default_CriuOpts_LogLevel
-}
-
-func (m *CriuOpts) GetLogFile() string {
- if m != nil && m.LogFile != nil {
- return *m.LogFile
- }
- return ""
-}
-
-func (m *CriuOpts) GetPs() *CriuPageServerInfo {
- if m != nil {
- return m.Ps
- }
- return nil
-}
-
-func (m *CriuOpts) GetNotifyScripts() bool {
- if m != nil && m.NotifyScripts != nil {
- return *m.NotifyScripts
- }
- return false
-}
-
-func (m *CriuOpts) GetRoot() string {
- if m != nil && m.Root != nil {
- return *m.Root
- }
- return ""
-}
-
-func (m *CriuOpts) GetParentImg() string {
- if m != nil && m.ParentImg != nil {
- return *m.ParentImg
- }
- return ""
-}
-
-func (m *CriuOpts) GetTrackMem() bool {
- if m != nil && m.TrackMem != nil {
- return *m.TrackMem
- }
- return false
-}
-
-func (m *CriuOpts) GetAutoDedup() bool {
- if m != nil && m.AutoDedup != nil {
- return *m.AutoDedup
- }
- return false
-}
-
-func (m *CriuOpts) GetWorkDirFd() int32 {
- if m != nil && m.WorkDirFd != nil {
- return *m.WorkDirFd
- }
- return 0
-}
-
-func (m *CriuOpts) GetLinkRemap() bool {
- if m != nil && m.LinkRemap != nil {
- return *m.LinkRemap
- }
- return false
-}
-
-func (m *CriuOpts) GetVeths() []*CriuVethPair {
- if m != nil {
- return m.Veths
- }
- return nil
-}
-
-func (m *CriuOpts) GetCpuCap() uint32 {
- if m != nil && m.CpuCap != nil {
- return *m.CpuCap
- }
- return Default_CriuOpts_CpuCap
-}
-
-func (m *CriuOpts) GetForceIrmap() bool {
- if m != nil && m.ForceIrmap != nil {
- return *m.ForceIrmap
- }
- return false
-}
-
-func (m *CriuOpts) GetExecCmd() []string {
- if m != nil {
- return m.ExecCmd
- }
- return nil
-}
-
-func (m *CriuOpts) GetExtMnt() []*ExtMountMap {
- if m != nil {
- return m.ExtMnt
- }
- return nil
-}
-
-func (m *CriuOpts) GetManageCgroups() bool {
- if m != nil && m.ManageCgroups != nil {
- return *m.ManageCgroups
- }
- return false
-}
-
-func (m *CriuOpts) GetCgRoot() []*CgroupRoot {
- if m != nil {
- return m.CgRoot
- }
- return nil
-}
-
-func (m *CriuOpts) GetRstSibling() bool {
- if m != nil && m.RstSibling != nil {
- return *m.RstSibling
- }
- return false
-}
-
-func (m *CriuOpts) GetInheritFd() []*InheritFd {
- if m != nil {
- return m.InheritFd
- }
- return nil
-}
-
-func (m *CriuOpts) GetAutoExtMnt() bool {
- if m != nil && m.AutoExtMnt != nil {
- return *m.AutoExtMnt
- }
- return false
-}
-
-func (m *CriuOpts) GetExtSharing() bool {
- if m != nil && m.ExtSharing != nil {
- return *m.ExtSharing
- }
- return false
-}
-
-func (m *CriuOpts) GetExtMasters() bool {
- if m != nil && m.ExtMasters != nil {
- return *m.ExtMasters
- }
- return false
-}
-
-func (m *CriuOpts) GetSkipMnt() []string {
- if m != nil {
- return m.SkipMnt
- }
- return nil
-}
-
-func (m *CriuOpts) GetEnableFs() []string {
- if m != nil {
- return m.EnableFs
- }
- return nil
-}
-
-func (m *CriuOpts) GetUnixSkIno() []*UnixSk {
- if m != nil {
- return m.UnixSkIno
- }
- return nil
-}
-
-func (m *CriuOpts) GetManageCgroupsMode() uint32 {
- if m != nil && m.ManageCgroupsMode != nil {
- return *m.ManageCgroupsMode
- }
- return 0
-}
-
-type CriuDumpResp struct {
- Restored *bool `protobuf:"varint,1,opt,name=restored" json:"restored,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *CriuDumpResp) Reset() { *m = CriuDumpResp{} }
-func (m *CriuDumpResp) String() string { return proto.CompactTextString(m) }
-func (*CriuDumpResp) ProtoMessage() {}
-
-func (m *CriuDumpResp) GetRestored() bool {
- if m != nil && m.Restored != nil {
- return *m.Restored
- }
- return false
-}
-
-type CriuRestoreResp struct {
- Pid *int32 `protobuf:"varint,1,req,name=pid" json:"pid,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *CriuRestoreResp) Reset() { *m = CriuRestoreResp{} }
-func (m *CriuRestoreResp) String() string { return proto.CompactTextString(m) }
-func (*CriuRestoreResp) ProtoMessage() {}
-
-func (m *CriuRestoreResp) GetPid() int32 {
- if m != nil && m.Pid != nil {
- return *m.Pid
- }
- return 0
-}
-
-type CriuNotify struct {
- Script *string `protobuf:"bytes,1,opt,name=script" json:"script,omitempty"`
- Pid *int32 `protobuf:"varint,2,opt,name=pid" json:"pid,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *CriuNotify) Reset() { *m = CriuNotify{} }
-func (m *CriuNotify) String() string { return proto.CompactTextString(m) }
-func (*CriuNotify) ProtoMessage() {}
-
-func (m *CriuNotify) GetScript() string {
- if m != nil && m.Script != nil {
- return *m.Script
- }
- return ""
-}
-
-func (m *CriuNotify) GetPid() int32 {
- if m != nil && m.Pid != nil {
- return *m.Pid
- }
- return 0
-}
-
-type CriuReq struct {
- Type *CriuReqType `protobuf:"varint,1,req,name=type,enum=CriuReqType" json:"type,omitempty"`
- Opts *CriuOpts `protobuf:"bytes,2,opt,name=opts" json:"opts,omitempty"`
- NotifySuccess *bool `protobuf:"varint,3,opt,name=notify_success" json:"notify_success,omitempty"`
- //
- // When set service won't close the connection but
- // will wait for more req-s to appear. Works not
- // for all request types.
- KeepOpen *bool `protobuf:"varint,4,opt,name=keep_open" json:"keep_open,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *CriuReq) Reset() { *m = CriuReq{} }
-func (m *CriuReq) String() string { return proto.CompactTextString(m) }
-func (*CriuReq) ProtoMessage() {}
-
-func (m *CriuReq) GetType() CriuReqType {
- if m != nil && m.Type != nil {
- return *m.Type
- }
- return CriuReqType_EMPTY
-}
-
-func (m *CriuReq) GetOpts() *CriuOpts {
- if m != nil {
- return m.Opts
- }
- return nil
-}
-
-func (m *CriuReq) GetNotifySuccess() bool {
- if m != nil && m.NotifySuccess != nil {
- return *m.NotifySuccess
- }
- return false
-}
-
-func (m *CriuReq) GetKeepOpen() bool {
- if m != nil && m.KeepOpen != nil {
- return *m.KeepOpen
- }
- return false
-}
-
-type CriuResp struct {
- Type *CriuReqType `protobuf:"varint,1,req,name=type,enum=CriuReqType" json:"type,omitempty"`
- Success *bool `protobuf:"varint,2,req,name=success" json:"success,omitempty"`
- Dump *CriuDumpResp `protobuf:"bytes,3,opt,name=dump" json:"dump,omitempty"`
- Restore *CriuRestoreResp `protobuf:"bytes,4,opt,name=restore" json:"restore,omitempty"`
- Notify *CriuNotify `protobuf:"bytes,5,opt,name=notify" json:"notify,omitempty"`
- Ps *CriuPageServerInfo `protobuf:"bytes,6,opt,name=ps" json:"ps,omitempty"`
- CrErrno *int32 `protobuf:"varint,7,opt,name=cr_errno" json:"cr_errno,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *CriuResp) Reset() { *m = CriuResp{} }
-func (m *CriuResp) String() string { return proto.CompactTextString(m) }
-func (*CriuResp) ProtoMessage() {}
-
-func (m *CriuResp) GetType() CriuReqType {
- if m != nil && m.Type != nil {
- return *m.Type
- }
- return CriuReqType_EMPTY
-}
-
-func (m *CriuResp) GetSuccess() bool {
- if m != nil && m.Success != nil {
- return *m.Success
- }
- return false
-}
-
-func (m *CriuResp) GetDump() *CriuDumpResp {
- if m != nil {
- return m.Dump
- }
- return nil
-}
-
-func (m *CriuResp) GetRestore() *CriuRestoreResp {
- if m != nil {
- return m.Restore
- }
- return nil
-}
-
-func (m *CriuResp) GetNotify() *CriuNotify {
- if m != nil {
- return m.Notify
- }
- return nil
-}
-
-func (m *CriuResp) GetPs() *CriuPageServerInfo {
- if m != nil {
- return m.Ps
- }
- return nil
-}
-
-func (m *CriuResp) GetCrErrno() int32 {
- if m != nil && m.CrErrno != nil {
- return *m.CrErrno
- }
- return 0
-}
-
-func init() {
- proto.RegisterEnum("CriuReqType", CriuReqType_name, CriuReqType_value)
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.proto b/containerd/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.proto
deleted file mode 100644
index f49325e..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/criurpc/criurpc.proto
+++ /dev/null
@@ -1,142 +0,0 @@
-message criu_page_server_info {
- optional string address = 1;
- optional int32 port = 2;
- optional int32 pid = 3;
- optional int32 fd = 4;
-}
-
-message criu_veth_pair {
- required string if_in = 1;
- required string if_out = 2;
-};
-
-message ext_mount_map {
- required string key = 1;
- required string val = 2;
-};
-
-message inherit_fd {
- required string key = 1;
- required int32 fd = 2;
-};
-
-message cgroup_root {
- optional string ctrl = 1;
- required string path = 2;
-};
-
-message unix_sk {
- required uint32 inode = 1;
-};
-
-message criu_opts {
- required int32 images_dir_fd = 1;
- optional int32 pid = 2; /* if not set on dump, will dump requesting process */
-
- optional bool leave_running = 3;
- optional bool ext_unix_sk = 4;
- optional bool tcp_established = 5;
- optional bool evasive_devices = 6;
- optional bool shell_job = 7;
- optional bool file_locks = 8;
- optional int32 log_level = 9 [default = 2];
- optional string log_file = 10; /* No subdirs are allowed. Consider using work-dir */
-
- optional criu_page_server_info ps = 11;
-
- optional bool notify_scripts = 12;
-
- optional string root = 13;
- optional string parent_img = 14;
- optional bool track_mem = 15;
- optional bool auto_dedup = 16;
-
- optional int32 work_dir_fd = 17;
- optional bool link_remap = 18;
- repeated criu_veth_pair veths = 19;
-
- optional uint32 cpu_cap = 20 [default = 0xffffffff];
- optional bool force_irmap = 21;
- repeated string exec_cmd = 22;
-
- repeated ext_mount_map ext_mnt = 23;
- optional bool manage_cgroups = 24; /* backward compatibility */
- repeated cgroup_root cg_root = 25;
-
- optional bool rst_sibling = 26; /* swrk only */
- repeated inherit_fd inherit_fd = 27; /* swrk only */
-
- optional bool auto_ext_mnt = 28;
- optional bool ext_sharing = 29;
- optional bool ext_masters = 30;
-
- repeated string skip_mnt = 31;
- repeated string enable_fs = 32;
-
- repeated unix_sk unix_sk_ino = 33;
-
- optional uint32 manage_cgroups_mode = 34;
-}
-
-message criu_dump_resp {
- optional bool restored = 1;
-}
-
-message criu_restore_resp {
- required int32 pid = 1;
-}
-
-message criu_notify {
- optional string script = 1;
- optional int32 pid = 2;
-}
-
-enum criu_req_type {
- EMPTY = 0;
- DUMP = 1;
- RESTORE = 2;
- CHECK = 3;
- PRE_DUMP = 4;
- PAGE_SERVER = 5;
-
- NOTIFY = 6;
-
- CPUINFO_DUMP = 7;
- CPUINFO_CHECK = 8;
-}
-
-/*
- * Request -- each type corresponds to must-be-there
- * request arguments of respective type
- */
-
-message criu_req {
- required criu_req_type type = 1;
-
- optional criu_opts opts = 2;
- optional bool notify_success = 3;
-
- /*
- * When set service won't close the connection but
- * will wait for more req-s to appear. Works not
- * for all request types.
- */
- optional bool keep_open = 4;
-}
-
-/*
- * Responce -- it states whether the request was served
- * and additional request-specific informarion
- */
-
-message criu_resp {
- required criu_req_type type = 1;
- required bool success = 2;
-
- optional criu_dump_resp dump = 3;
- optional criu_restore_resp restore = 4;
- optional criu_notify notify = 5;
- optional criu_page_server_info ps = 6;
-
- optional int32 cr_errno = 7;
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_unix.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_unix.go
deleted file mode 100644
index c02b73e..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_unix.go
+++ /dev/null
@@ -1,102 +0,0 @@
-// +build linux freebsd
-
-package devices
-
-import (
- "errors"
- "fmt"
- "io/ioutil"
- "os"
- "path/filepath"
- "syscall"
-
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-var (
- ErrNotADevice = errors.New("not a device node")
-)
-
-// Testing dependencies
-var (
- osLstat = os.Lstat
- ioutilReadDir = ioutil.ReadDir
-)
-
-// Given the path to a device and it's cgroup_permissions(which cannot be easily queried) look up the information about a linux device and return that information as a Device struct.
-func DeviceFromPath(path, permissions string) (*configs.Device, error) {
- fileInfo, err := osLstat(path)
- if err != nil {
- return nil, err
- }
- var (
- devType rune
- mode = fileInfo.Mode()
- fileModePermissionBits = os.FileMode.Perm(mode)
- )
- switch {
- case mode&os.ModeDevice == 0:
- return nil, ErrNotADevice
- case mode&os.ModeCharDevice != 0:
- fileModePermissionBits |= syscall.S_IFCHR
- devType = 'c'
- default:
- fileModePermissionBits |= syscall.S_IFBLK
- devType = 'b'
- }
- stat_t, ok := fileInfo.Sys().(*syscall.Stat_t)
- if !ok {
- return nil, fmt.Errorf("cannot determine the device number for device %s", path)
- }
- devNumber := int(stat_t.Rdev)
- return &configs.Device{
- Type: devType,
- Path: path,
- Major: Major(devNumber),
- Minor: Minor(devNumber),
- Permissions: permissions,
- FileMode: fileModePermissionBits,
- Uid: stat_t.Uid,
- Gid: stat_t.Gid,
- }, nil
-}
-
-func HostDevices() ([]*configs.Device, error) {
- return getDevices("/dev")
-}
-
-func getDevices(path string) ([]*configs.Device, error) {
- files, err := ioutilReadDir(path)
- if err != nil {
- return nil, err
- }
- out := []*configs.Device{}
- for _, f := range files {
- switch {
- case f.IsDir():
- switch f.Name() {
- case "pts", "shm", "fd", "mqueue":
- continue
- default:
- sub, err := getDevices(filepath.Join(path, f.Name()))
- if err != nil {
- return nil, err
- }
-
- out = append(out, sub...)
- continue
- }
- case f.Name() == "console":
- continue
- }
- device, err := DeviceFromPath(filepath.Join(path, f.Name()), "rwm")
- if err != nil {
- if err == ErrNotADevice {
- continue
- }
- return nil, err
- }
- out = append(out, device)
- }
- return out, nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_unsupported.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_unsupported.go
deleted file mode 100644
index 1e84033..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/devices/devices_unsupported.go
+++ /dev/null
@@ -1,3 +0,0 @@
-// +build windows
-
-package devices
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/devices/number.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/devices/number.go
deleted file mode 100644
index 885b6e5..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/devices/number.go
+++ /dev/null
@@ -1,24 +0,0 @@
-// +build linux freebsd
-
-package devices
-
-/*
-
-This code provides support for manipulating linux device numbers. It should be replaced by normal syscall functions once http://code.google.com/p/go/issues/detail?id=8106 is solved.
-
-You can read what they are here:
-
- - http://www.makelinux.net/ldd3/chp-3-sect-2
- - http://www.linux-tutorial.info/modules.php?name=MContent&pageid=94
-
-Note! These are NOT the same as the MAJOR(dev_t device);, MINOR(dev_t device); and MKDEV(int major, int minor); functions as defined in as the representation of device numbers used by go is different than the one used internally to the kernel! - https://github.com/torvalds/linux/blob/master/include/linux/kdev_t.h#L9
-
-*/
-
-func Major(devNumber int) int64 {
- return int64((devNumber >> 8) & 0xfff)
-}
-
-func Minor(devNumber int) int64 {
- return int64((devNumber & 0xff) | ((devNumber >> 12) & 0xfff00))
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/error.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/error.go
deleted file mode 100644
index 6c26662..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/error.go
+++ /dev/null
@@ -1,62 +0,0 @@
-package libcontainer
-
-import "io"
-
-// API error code type.
-type ErrorCode int
-
-// API error codes.
-const (
- // Factory errors
- IdInUse ErrorCode = iota
- InvalidIdFormat
-
- // Container errors
- ContainerNotExists
- ContainerPaused
- ContainerNotStopped
- ContainerNotRunning
-
- // Process errors
- ProcessNotExecuted
-
- // Common errors
- ConfigInvalid
- SystemError
-)
-
-func (c ErrorCode) String() string {
- switch c {
- case IdInUse:
- return "Id already in use"
- case InvalidIdFormat:
- return "Invalid format"
- case ContainerPaused:
- return "Container paused"
- case ConfigInvalid:
- return "Invalid configuration"
- case SystemError:
- return "System error"
- case ContainerNotExists:
- return "Container does not exist"
- case ContainerNotStopped:
- return "Container is not stopped"
- case ContainerNotRunning:
- return "Container is not running"
- default:
- return "Unknown error"
- }
-}
-
-// API Error type.
-type Error interface {
- error
-
- // Returns a verbose string including the error message
- // and a representation of the stack trace suitable for
- // printing.
- Detail(w io.Writer) error
-
- // Returns the error code for this error.
- Code() ErrorCode
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/factory.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/factory.go
deleted file mode 100644
index f0ccb52..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/factory.go
+++ /dev/null
@@ -1,45 +0,0 @@
-package libcontainer
-
-import (
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-type Factory interface {
- // Creates a new container with the given id and starts the initial process inside it.
- // id must be a string containing only letters, digits and underscores and must contain
- // between 1 and 1024 characters, inclusive.
- //
- // The id must not already be in use by an existing container. Containers created using
- // a factory with the same path (and file system) must have distinct ids.
- //
- // Returns the new container with a running process.
- //
- // errors:
- // IdInUse - id is already in use by a container
- // InvalidIdFormat - id has incorrect format
- // ConfigInvalid - config is invalid
- // Systemerror - System error
- //
- // On error, any partially created container parts are cleaned up (the operation is atomic).
- Create(id string, config *configs.Config) (Container, error)
-
- // Load takes an ID for an existing container and returns the container information
- // from the state. This presents a read only view of the container.
- //
- // errors:
- // Path does not exist
- // Container is stopped
- // System error
- Load(id string) (Container, error)
-
- // StartInitialization is an internal API to libcontainer used during the reexec of the
- // container.
- //
- // Errors:
- // Pipe connection error
- // System error
- StartInitialization() error
-
- // Type returns info string about factory type (e.g. lxc, libcontainer...)
- Type() string
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/factory_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/factory_linux.go
deleted file mode 100644
index 70513f7..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/factory_linux.go
+++ /dev/null
@@ -1,270 +0,0 @@
-// +build linux
-
-package libcontainer
-
-import (
- "encoding/json"
- "fmt"
- "io/ioutil"
- "os"
- "os/exec"
- "path/filepath"
- "regexp"
- "strconv"
- "syscall"
-
- "github.com/docker/docker/pkg/mount"
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/cgroups/fs"
- "github.com/opencontainers/runc/libcontainer/cgroups/systemd"
- "github.com/opencontainers/runc/libcontainer/configs"
- "github.com/opencontainers/runc/libcontainer/configs/validate"
-)
-
-const (
- stateFilename = "state.json"
-)
-
-var (
- idRegex = regexp.MustCompile(`^[\w_-]+$`)
- maxIdLen = 1024
-)
-
-// InitArgs returns an options func to configure a LinuxFactory with the
-// provided init arguments.
-func InitArgs(args ...string) func(*LinuxFactory) error {
- return func(l *LinuxFactory) error {
- name := args[0]
- if filepath.Base(name) == name {
- if lp, err := exec.LookPath(name); err == nil {
- name = lp
- }
- } else {
- abs, err := filepath.Abs(name)
- if err != nil {
- return err
- }
- name = abs
- }
- l.InitPath = "/proc/self/exe"
- l.InitArgs = append([]string{name}, args[1:]...)
- return nil
- }
-}
-
-// InitPath returns an options func to configure a LinuxFactory with the
-// provided absolute path to the init binary and arguements.
-func InitPath(path string, args ...string) func(*LinuxFactory) error {
- return func(l *LinuxFactory) error {
- l.InitPath = path
- l.InitArgs = args
- return nil
- }
-}
-
-// SystemdCgroups is an options func to configure a LinuxFactory to return
-// containers that use systemd to create and manage cgroups.
-func SystemdCgroups(l *LinuxFactory) error {
- l.NewCgroupsManager = func(config *configs.Cgroup, paths map[string]string) cgroups.Manager {
- return &systemd.Manager{
- Cgroups: config,
- Paths: paths,
- }
- }
- return nil
-}
-
-// Cgroupfs is an options func to configure a LinuxFactory to return
-// containers that use the native cgroups filesystem implementation to
-// create and manage cgroups.
-func Cgroupfs(l *LinuxFactory) error {
- l.NewCgroupsManager = func(config *configs.Cgroup, paths map[string]string) cgroups.Manager {
- return &fs.Manager{
- Cgroups: config,
- Paths: paths,
- }
- }
- return nil
-}
-
-// TmpfsRoot is an option func to mount LinuxFactory.Root to tmpfs.
-func TmpfsRoot(l *LinuxFactory) error {
- mounted, err := mount.Mounted(l.Root)
- if err != nil {
- return err
- }
- if !mounted {
- if err := syscall.Mount("tmpfs", l.Root, "tmpfs", 0, ""); err != nil {
- return err
- }
- }
- return nil
-}
-
-// New returns a linux based container factory based in the root directory and
-// configures the factory with the provided option funcs.
-func New(root string, options ...func(*LinuxFactory) error) (Factory, error) {
- if root != "" {
- if err := os.MkdirAll(root, 0700); err != nil {
- return nil, newGenericError(err, SystemError)
- }
- }
- l := &LinuxFactory{
- Root: root,
- Validator: validate.New(),
- CriuPath: "criu",
- }
- InitArgs(os.Args[0], "init")(l)
- Cgroupfs(l)
- for _, opt := range options {
- if err := opt(l); err != nil {
- return nil, err
- }
- }
- return l, nil
-}
-
-// LinuxFactory implements the default factory interface for linux based systems.
-type LinuxFactory struct {
- // Root directory for the factory to store state.
- Root string
-
- // InitPath is the absolute path to the init binary.
- InitPath string
-
- // InitArgs are arguments for calling the init responsibilities for spawning
- // a container.
- InitArgs []string
-
- // CriuPath is the path to the criu binary used for checkpoint and restore of
- // containers.
- CriuPath string
-
- // Validator provides validation to container configurations.
- Validator validate.Validator
-
- // NewCgroupsManager returns an initialized cgroups manager for a single container.
- NewCgroupsManager func(config *configs.Cgroup, paths map[string]string) cgroups.Manager
-}
-
-func (l *LinuxFactory) Create(id string, config *configs.Config) (Container, error) {
- if l.Root == "" {
- return nil, newGenericError(fmt.Errorf("invalid root"), ConfigInvalid)
- }
- if err := l.validateID(id); err != nil {
- return nil, err
- }
- if err := l.Validator.Validate(config); err != nil {
- return nil, newGenericError(err, ConfigInvalid)
- }
- containerRoot := filepath.Join(l.Root, id)
- if _, err := os.Stat(containerRoot); err == nil {
- return nil, newGenericError(fmt.Errorf("container with id exists: %v", id), IdInUse)
- } else if !os.IsNotExist(err) {
- return nil, newGenericError(err, SystemError)
- }
- if err := os.MkdirAll(containerRoot, 0700); err != nil {
- return nil, newGenericError(err, SystemError)
- }
- return &linuxContainer{
- id: id,
- root: containerRoot,
- config: config,
- initPath: l.InitPath,
- initArgs: l.InitArgs,
- criuPath: l.CriuPath,
- cgroupManager: l.NewCgroupsManager(config.Cgroups, nil),
- }, nil
-}
-
-func (l *LinuxFactory) Load(id string) (Container, error) {
- if l.Root == "" {
- return nil, newGenericError(fmt.Errorf("invalid root"), ConfigInvalid)
- }
- containerRoot := filepath.Join(l.Root, id)
- state, err := l.loadState(containerRoot)
- if err != nil {
- return nil, err
- }
- r := &nonChildProcess{
- processPid: state.InitProcessPid,
- processStartTime: state.InitProcessStartTime,
- fds: state.ExternalDescriptors,
- }
- return &linuxContainer{
- initProcess: r,
- id: id,
- config: &state.Config,
- initPath: l.InitPath,
- initArgs: l.InitArgs,
- criuPath: l.CriuPath,
- cgroupManager: l.NewCgroupsManager(state.Config.Cgroups, state.CgroupPaths),
- root: containerRoot,
- }, nil
-}
-
-func (l *LinuxFactory) Type() string {
- return "libcontainer"
-}
-
-// StartInitialization loads a container by opening the pipe fd from the parent to read the configuration and state
-// This is a low level implementation detail of the reexec and should not be consumed externally
-func (l *LinuxFactory) StartInitialization() (err error) {
- fdStr := os.Getenv("_LIBCONTAINER_INITPIPE")
- pipefd, err := strconv.Atoi(fdStr)
- if err != nil {
- return fmt.Errorf("error converting env var _LIBCONTAINER_INITPIPE(%q) to an int: %s", fdStr, err)
- }
- var (
- pipe = os.NewFile(uintptr(pipefd), "pipe")
- it = initType(os.Getenv("_LIBCONTAINER_INITTYPE"))
- )
- // clear the current process's environment to clean any libcontainer
- // specific env vars.
- os.Clearenv()
- defer func() {
- // if we have an error during the initialization of the container's init then send it back to the
- // parent process in the form of an initError.
- if err != nil {
- // ensure that any data sent from the parent is consumed so it doesn't
- // receive ECONNRESET when the child writes to the pipe.
- ioutil.ReadAll(pipe)
- if err := json.NewEncoder(pipe).Encode(newSystemError(err)); err != nil {
- panic(err)
- }
- }
- // ensure that this pipe is always closed
- pipe.Close()
- }()
- i, err := newContainerInit(it, pipe)
- if err != nil {
- return err
- }
- return i.Init()
-}
-
-func (l *LinuxFactory) loadState(root string) (*State, error) {
- f, err := os.Open(filepath.Join(root, stateFilename))
- if err != nil {
- if os.IsNotExist(err) {
- return nil, newGenericError(err, ContainerNotExists)
- }
- return nil, newGenericError(err, SystemError)
- }
- defer f.Close()
- var state *State
- if err := json.NewDecoder(f).Decode(&state); err != nil {
- return nil, newGenericError(err, SystemError)
- }
- return state, nil
-}
-
-func (l *LinuxFactory) validateID(id string) error {
- if !idRegex.MatchString(id) {
- return newGenericError(fmt.Errorf("invalid id format: %v", id), InvalidIdFormat)
- }
- if len(id) > maxIdLen {
- return newGenericError(fmt.Errorf("invalid id format: %v", id), InvalidIdFormat)
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/generic_error.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/generic_error.go
deleted file mode 100644
index 6fbc2d7..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/generic_error.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package libcontainer
-
-import (
- "fmt"
- "io"
- "text/template"
- "time"
-
- "github.com/opencontainers/runc/libcontainer/stacktrace"
-)
-
-var errorTemplate = template.Must(template.New("error").Parse(`Timestamp: {{.Timestamp}}
-Code: {{.ECode}}
-{{if .Message }}
-Message: {{.Message}}
-{{end}}
-Frames:{{range $i, $frame := .Stack.Frames}}
----
-{{$i}}: {{$frame.Function}}
-Package: {{$frame.Package}}
-File: {{$frame.File}}@{{$frame.Line}}{{end}}
-`))
-
-func newGenericError(err error, c ErrorCode) Error {
- if le, ok := err.(Error); ok {
- return le
- }
- gerr := &genericError{
- Timestamp: time.Now(),
- Err: err,
- ECode: c,
- Stack: stacktrace.Capture(1),
- }
- if err != nil {
- gerr.Message = err.Error()
- }
- return gerr
-}
-
-func newSystemError(err error) Error {
- if le, ok := err.(Error); ok {
- return le
- }
- gerr := &genericError{
- Timestamp: time.Now(),
- Err: err,
- ECode: SystemError,
- Stack: stacktrace.Capture(1),
- }
- if err != nil {
- gerr.Message = err.Error()
- }
- return gerr
-}
-
-type genericError struct {
- Timestamp time.Time
- ECode ErrorCode
- Err error `json:"-"`
- Message string
- Stack stacktrace.Stacktrace
-}
-
-func (e *genericError) Error() string {
- return fmt.Sprintf("[%d] %s: %s", e.ECode, e.ECode, e.Message)
-}
-
-func (e *genericError) Code() ErrorCode {
- return e.ECode
-}
-
-func (e *genericError) Detail(w io.Writer) error {
- return errorTemplate.Execute(w, e)
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/hack/validate.sh b/containerd/vendor/github.com/opencontainers/runc/libcontainer/hack/validate.sh
deleted file mode 100644
index 0bf1541..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/hack/validate.sh
+++ /dev/null
@@ -1,16 +0,0 @@
-#!/usr/bin/env bash
-set -e
-
-# This script runs all validations
-
-validate() {
- export MAKEDIR=/go/src/github.com/docker/docker/hack/make
- sed -i 's!docker/docker!opencontainers/runc/libcontainer!' /go/src/github.com/docker/docker/hack/make/.validate
- bash /go/src/github.com/docker/docker/hack/make/validate-dco
- bash /go/src/github.com/docker/docker/hack/make/validate-gofmt
- go get golang.org/x/tools/cmd/vet
- bash /go/src/github.com/docker/docker/hack/make/validate-vet
-}
-
-# run validations
-validate
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/init_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/init_linux.go
deleted file mode 100644
index ddb1186..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/init_linux.go
+++ /dev/null
@@ -1,334 +0,0 @@
-// +build linux
-
-package libcontainer
-
-import (
- "encoding/json"
- "fmt"
- "io/ioutil"
- "net"
- "os"
- "strconv"
- "strings"
- "syscall"
-
- "github.com/Sirupsen/logrus"
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
- "github.com/opencontainers/runc/libcontainer/system"
- "github.com/opencontainers/runc/libcontainer/user"
- "github.com/opencontainers/runc/libcontainer/utils"
- "github.com/vishvananda/netlink"
-)
-
-type initType string
-
-const (
- initSetns initType = "setns"
- initStandard initType = "standard"
-)
-
-type pid struct {
- Pid int `json:"pid"`
-}
-
-// network is an internal struct used to setup container networks.
-type network struct {
- configs.Network
-
- // TempVethPeerName is a unique temporary veth peer name that was placed into
- // the container's namespace.
- TempVethPeerName string `json:"temp_veth_peer_name"`
-}
-
-// initConfig is used for transferring parameters from Exec() to Init()
-type initConfig struct {
- Args []string `json:"args"`
- Env []string `json:"env"`
- Cwd string `json:"cwd"`
- Capabilities []string `json:"capabilities"`
- User string `json:"user"`
- Config *configs.Config `json:"config"`
- Console string `json:"console"`
- Networks []*network `json:"network"`
- PassedFilesCount int `json:"passed_files_count"`
-}
-
-type initer interface {
- Init() error
-}
-
-func newContainerInit(t initType, pipe *os.File) (initer, error) {
- var config *initConfig
- if err := json.NewDecoder(pipe).Decode(&config); err != nil {
- return nil, err
- }
- if err := populateProcessEnvironment(config.Env); err != nil {
- return nil, err
- }
- switch t {
- case initSetns:
- return &linuxSetnsInit{
- config: config,
- }, nil
- case initStandard:
- return &linuxStandardInit{
- parentPid: syscall.Getppid(),
- config: config,
- }, nil
- }
- return nil, fmt.Errorf("unknown init type %q", t)
-}
-
-// populateProcessEnvironment loads the provided environment variables into the
-// current processes's environment.
-func populateProcessEnvironment(env []string) error {
- for _, pair := range env {
- p := strings.SplitN(pair, "=", 2)
- if len(p) < 2 {
- return fmt.Errorf("invalid environment '%v'", pair)
- }
- if err := os.Setenv(p[0], p[1]); err != nil {
- return err
- }
- }
- return nil
-}
-
-// finalizeNamespace drops the caps, sets the correct user
-// and working dir, and closes any leaked file descriptors
-// before executing the command inside the namespace
-func finalizeNamespace(config *initConfig) error {
- // Ensure that all unwanted fds we may have accidentally
- // inherited are marked close-on-exec so they stay out of the
- // container
- if err := utils.CloseExecFrom(config.PassedFilesCount + 3); err != nil {
- return err
- }
-
- capabilities := config.Config.Capabilities
- if config.Capabilities != nil {
- capabilities = config.Capabilities
- }
- w, err := newCapWhitelist(capabilities)
- if err != nil {
- return err
- }
- // drop capabilities in bounding set before changing user
- if err := w.dropBoundingSet(); err != nil {
- return err
- }
- // preserve existing capabilities while we change users
- if err := system.SetKeepCaps(); err != nil {
- return err
- }
- if err := setupUser(config); err != nil {
- return err
- }
- if err := system.ClearKeepCaps(); err != nil {
- return err
- }
- // drop all other capabilities
- if err := w.drop(); err != nil {
- return err
- }
- if config.Cwd != "" {
- if err := syscall.Chdir(config.Cwd); err != nil {
- return err
- }
- }
- return nil
-}
-
-// joinExistingNamespaces gets all the namespace paths specified for the container and
-// does a setns on the namespace fd so that the current process joins the namespace.
-func joinExistingNamespaces(namespaces []configs.Namespace) error {
- for _, ns := range namespaces {
- if ns.Path != "" {
- f, err := os.OpenFile(ns.Path, os.O_RDONLY, 0)
- if err != nil {
- return err
- }
- err = system.Setns(f.Fd(), uintptr(ns.Syscall()))
- f.Close()
- if err != nil {
- return err
- }
- }
- }
- return nil
-}
-
-// setupUser changes the groups, gid, and uid for the user inside the container
-func setupUser(config *initConfig) error {
- // Set up defaults.
- defaultExecUser := user.ExecUser{
- Uid: syscall.Getuid(),
- Gid: syscall.Getgid(),
- Home: "/",
- }
- passwdPath, err := user.GetPasswdPath()
- if err != nil {
- return err
- }
- groupPath, err := user.GetGroupPath()
- if err != nil {
- return err
- }
- execUser, err := user.GetExecUserPath(config.User, &defaultExecUser, passwdPath, groupPath)
- if err != nil {
- return err
- }
-
- var addGroups []int
- if len(config.Config.AdditionalGroups) > 0 {
- addGroups, err = user.GetAdditionalGroupsPath(config.Config.AdditionalGroups, groupPath)
- if err != nil {
- return err
- }
- }
- // before we change to the container's user make sure that the processes STDIO
- // is correctly owned by the user that we are switching to.
- if err := fixStdioPermissions(execUser); err != nil {
- return err
- }
- suppGroups := append(execUser.Sgids, addGroups...)
- if err := syscall.Setgroups(suppGroups); err != nil {
- return err
- }
-
- if err := system.Setgid(execUser.Gid); err != nil {
- return err
- }
- if err := system.Setuid(execUser.Uid); err != nil {
- return err
- }
- // if we didn't get HOME already, set it based on the user's HOME
- if envHome := os.Getenv("HOME"); envHome == "" {
- if err := os.Setenv("HOME", execUser.Home); err != nil {
- return err
- }
- }
- return nil
-}
-
-// fixStdioPermissions fixes the permissions of PID 1's STDIO within the container to the specified user.
-// The ownership needs to match because it is created outside of the container and needs to be
-// localized.
-func fixStdioPermissions(u *user.ExecUser) error {
- var null syscall.Stat_t
- if err := syscall.Stat("/dev/null", &null); err != nil {
- return err
- }
- for _, fd := range []uintptr{
- os.Stdin.Fd(),
- os.Stderr.Fd(),
- os.Stdout.Fd(),
- } {
- var s syscall.Stat_t
- if err := syscall.Fstat(int(fd), &s); err != nil {
- return err
- }
- // skip chown of /dev/null if it was used as one of the STDIO fds.
- if s.Rdev == null.Rdev {
- continue
- }
- if err := syscall.Fchown(int(fd), u.Uid, u.Gid); err != nil {
- return err
- }
- }
- return nil
-}
-
-// setupNetwork sets up and initializes any network interface inside the container.
-func setupNetwork(config *initConfig) error {
- for _, config := range config.Networks {
- strategy, err := getStrategy(config.Type)
- if err != nil {
- return err
- }
- if err := strategy.initialize(config); err != nil {
- return err
- }
- }
- return nil
-}
-
-func setupRoute(config *configs.Config) error {
- for _, config := range config.Routes {
- _, dst, err := net.ParseCIDR(config.Destination)
- if err != nil {
- return err
- }
- src := net.ParseIP(config.Source)
- if src == nil {
- return fmt.Errorf("Invalid source for route: %s", config.Source)
- }
- gw := net.ParseIP(config.Gateway)
- if gw == nil {
- return fmt.Errorf("Invalid gateway for route: %s", config.Gateway)
- }
- l, err := netlink.LinkByName(config.InterfaceName)
- if err != nil {
- return err
- }
- route := &netlink.Route{
- Scope: netlink.SCOPE_UNIVERSE,
- Dst: dst,
- Src: src,
- Gw: gw,
- LinkIndex: l.Attrs().Index,
- }
- if err := netlink.RouteAdd(route); err != nil {
- return err
- }
- }
- return nil
-}
-
-func setupRlimits(config *configs.Config) error {
- for _, rlimit := range config.Rlimits {
- l := &syscall.Rlimit{Max: rlimit.Hard, Cur: rlimit.Soft}
- if err := syscall.Setrlimit(rlimit.Type, l); err != nil {
- return fmt.Errorf("error setting rlimit type %v: %v", rlimit.Type, err)
- }
- }
- return nil
-}
-
-func setOomScoreAdj(oomScoreAdj int) error {
- path := "/proc/self/oom_score_adj"
- return ioutil.WriteFile(path, []byte(strconv.Itoa(oomScoreAdj)), 0700)
-}
-
-// killCgroupProcesses freezes then iterates over all the processes inside the
-// manager's cgroups sending a SIGKILL to each process then waiting for them to
-// exit.
-func killCgroupProcesses(m cgroups.Manager) error {
- var procs []*os.Process
- if err := m.Freeze(configs.Frozen); err != nil {
- logrus.Warn(err)
- }
- pids, err := m.GetPids()
- if err != nil {
- m.Freeze(configs.Thawed)
- return err
- }
- for _, pid := range pids {
- if p, err := os.FindProcess(pid); err == nil {
- procs = append(procs, p)
- if err := p.Kill(); err != nil {
- logrus.Warn(err)
- }
- }
- }
- if err := m.Freeze(configs.Thawed); err != nil {
- logrus.Warn(err)
- }
- for _, p := range procs {
- if _, err := p.Wait(); err != nil {
- logrus.Warn(err)
- }
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/integration/doc.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/integration/doc.go
deleted file mode 100644
index 87545bc..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/integration/doc.go
+++ /dev/null
@@ -1,2 +0,0 @@
-// integration is used for integration testing of libcontainer
-package integration
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/label/label.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/label/label.go
deleted file mode 100644
index 97dc6ba..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/label/label.go
+++ /dev/null
@@ -1,76 +0,0 @@
-// +build !selinux !linux
-
-package label
-
-// InitLabels returns the process label and file labels to be used within
-// the container. A list of options can be passed into this function to alter
-// the labels.
-func InitLabels(options []string) (string, string, error) {
- return "", "", nil
-}
-
-func GenLabels(options string) (string, string, error) {
- return "", "", nil
-}
-
-func FormatMountLabel(src string, mountLabel string) string {
- return src
-}
-
-func SetProcessLabel(processLabel string) error {
- return nil
-}
-
-func SetFileLabel(path string, fileLabel string) error {
- return nil
-}
-
-func SetFileCreateLabel(fileLabel string) error {
- return nil
-}
-
-func Relabel(path string, fileLabel string, shared bool) error {
- return nil
-}
-
-func GetPidLabel(pid int) (string, error) {
- return "", nil
-}
-
-func Init() {
-}
-
-func ReserveLabel(label string) error {
- return nil
-}
-
-func UnreserveLabel(label string) error {
- return nil
-}
-
-// DupSecOpt takes an process label and returns security options that
-// can be used to set duplicate labels on future container processes
-func DupSecOpt(src string) []string {
- return nil
-}
-
-// DisableSecOpt returns a security opt that can disable labeling
-// support for future container processes
-func DisableSecOpt() []string {
- return nil
-}
-
-// Validate checks that the label does not include unexpected options
-func Validate(label string) error {
- return nil
-}
-
-// RelabelNeeded checks whether the user requested a relabel
-func RelabelNeeded(label string) bool {
- return false
-}
-
-// IsShared checks that the label includes a "shared" mark
-func IsShared(label string) bool {
- return false
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/label/label_selinux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/label/label_selinux.go
deleted file mode 100644
index e561cbf..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/label/label_selinux.go
+++ /dev/null
@@ -1,192 +0,0 @@
-// +build selinux,linux
-
-package label
-
-import (
- "fmt"
- "strings"
-
- "github.com/opencontainers/runc/libcontainer/selinux"
-)
-
-// Valid Label Options
-var validOptions = map[string]bool{
- "disable": true,
- "type": true,
- "user": true,
- "role": true,
- "level": true,
-}
-
-var ErrIncompatibleLabel = fmt.Errorf("Bad SELinux option z and Z can not be used together")
-
-// InitLabels returns the process label and file labels to be used within
-// the container. A list of options can be passed into this function to alter
-// the labels. The labels returned will include a random MCS String, that is
-// guaranteed to be unique.
-func InitLabels(options []string) (string, string, error) {
- if !selinux.SelinuxEnabled() {
- return "", "", nil
- }
- processLabel, mountLabel := selinux.GetLxcContexts()
- if processLabel != "" {
- pcon := selinux.NewContext(processLabel)
- mcon := selinux.NewContext(mountLabel)
- for _, opt := range options {
- if opt == "disable" {
- return "", "", nil
- }
- if i := strings.Index(opt, ":"); i == -1 {
- return "", "", fmt.Errorf("Bad label option %q, valid options 'disable' or \n'user, role, level, type' followed by ':' and a value", opt)
- }
- con := strings.SplitN(opt, ":", 2)
- if !validOptions[con[0]] {
- return "", "", fmt.Errorf("Bad label option %q, valid options 'disable, user, role, level, type'", con[0])
-
- }
- pcon[con[0]] = con[1]
- if con[0] == "level" || con[0] == "user" {
- mcon[con[0]] = con[1]
- }
- }
- processLabel = pcon.Get()
- mountLabel = mcon.Get()
- }
- return processLabel, mountLabel, nil
-}
-
-// DEPRECATED: The GenLabels function is only to be used during the transition to the official API.
-func GenLabels(options string) (string, string, error) {
- return InitLabels(strings.Fields(options))
-}
-
-// FormatMountLabel returns a string to be used by the mount command.
-// The format of this string will be used to alter the labeling of the mountpoint.
-// The string returned is suitable to be used as the options field of the mount command.
-// If you need to have additional mount point options, you can pass them in as
-// the first parameter. Second parameter is the label that you wish to apply
-// to all content in the mount point.
-func FormatMountLabel(src, mountLabel string) string {
- if mountLabel != "" {
- switch src {
- case "":
- src = fmt.Sprintf("context=%q", mountLabel)
- default:
- src = fmt.Sprintf("%s,context=%q", src, mountLabel)
- }
- }
- return src
-}
-
-// SetProcessLabel takes a process label and tells the kernel to assign the
-// label to the next program executed by the current process.
-func SetProcessLabel(processLabel string) error {
- if processLabel == "" {
- return nil
- }
- return selinux.Setexeccon(processLabel)
-}
-
-// GetProcessLabel returns the process label that the kernel will assign
-// to the next program executed by the current process. If "" is returned
-// this indicates that the default labeling will happen for the process.
-func GetProcessLabel() (string, error) {
- return selinux.Getexeccon()
-}
-
-// SetFileLabel modifies the "path" label to the specified file label
-func SetFileLabel(path string, fileLabel string) error {
- if selinux.SelinuxEnabled() && fileLabel != "" {
- return selinux.Setfilecon(path, fileLabel)
- }
- return nil
-}
-
-// Tell the kernel the label for all files to be created
-func SetFileCreateLabel(fileLabel string) error {
- if selinux.SelinuxEnabled() {
- return selinux.Setfscreatecon(fileLabel)
- }
- return nil
-}
-
-// Change the label of path to the filelabel string.
-// It changes the MCS label to s0 if shared is true.
-// This will allow all containers to share the content.
-func Relabel(path string, fileLabel string, shared bool) error {
- if !selinux.SelinuxEnabled() {
- return nil
- }
-
- if fileLabel == "" {
- return nil
- }
-
- exclude_paths := map[string]bool{"/": true, "/usr": true, "/etc": true}
- if exclude_paths[path] {
- return fmt.Errorf("Relabeling of %s is not allowed", path)
- }
-
- if shared {
- c := selinux.NewContext(fileLabel)
- c["level"] = "s0"
- fileLabel = c.Get()
- }
- return selinux.Chcon(path, fileLabel, true)
-}
-
-// GetPidLabel will return the label of the process running with the specified pid
-func GetPidLabel(pid int) (string, error) {
- return selinux.Getpidcon(pid)
-}
-
-// Init initialises the labeling system
-func Init() {
- selinux.SelinuxEnabled()
-}
-
-// ReserveLabel will record the fact that the MCS label has already been used.
-// This will prevent InitLabels from using the MCS label in a newly created
-// container
-func ReserveLabel(label string) error {
- selinux.ReserveLabel(label)
- return nil
-}
-
-// UnreserveLabel will remove the reservation of the MCS label.
-// This will allow InitLabels to use the MCS label in a newly created
-// containers
-func UnreserveLabel(label string) error {
- selinux.FreeLxcContexts(label)
- return nil
-}
-
-// DupSecOpt takes an process label and returns security options that
-// can be used to set duplicate labels on future container processes
-func DupSecOpt(src string) []string {
- return selinux.DupSecOpt(src)
-}
-
-// DisableSecOpt returns a security opt that can disable labeling
-// support for future container processes
-func DisableSecOpt() []string {
- return selinux.DisableSecOpt()
-}
-
-// Validate checks that the label does not include unexpected options
-func Validate(label string) error {
- if strings.Contains(label, "z") && strings.Contains(label, "Z") {
- return ErrIncompatibleLabel
- }
- return nil
-}
-
-// RelabelNeeded checks whether the user requested a relabel
-func RelabelNeeded(label string) bool {
- return strings.Contains(label, "z") || strings.Contains(label, "Z")
-}
-
-// IsShared checks that the label includes a "shared" mark
-func IsShared(label string) bool {
- return strings.Contains(label, "z")
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/network_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/network_linux.go
deleted file mode 100644
index ce93277..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/network_linux.go
+++ /dev/null
@@ -1,259 +0,0 @@
-// +build linux
-
-package libcontainer
-
-import (
- "fmt"
- "io/ioutil"
- "net"
- "path/filepath"
- "strconv"
- "strings"
-
- "github.com/opencontainers/runc/libcontainer/configs"
- "github.com/opencontainers/runc/libcontainer/utils"
- "github.com/vishvananda/netlink"
-)
-
-var strategies = map[string]networkStrategy{
- "veth": &veth{},
- "loopback": &loopback{},
-}
-
-// networkStrategy represents a specific network configuration for
-// a container's networking stack
-type networkStrategy interface {
- create(*network, int) error
- initialize(*network) error
- detach(*configs.Network) error
- attach(*configs.Network) error
-}
-
-// getStrategy returns the specific network strategy for the
-// provided type.
-func getStrategy(tpe string) (networkStrategy, error) {
- s, exists := strategies[tpe]
- if !exists {
- return nil, fmt.Errorf("unknown strategy type %q", tpe)
- }
- return s, nil
-}
-
-// Returns the network statistics for the network interfaces represented by the NetworkRuntimeInfo.
-func getNetworkInterfaceStats(interfaceName string) (*NetworkInterface, error) {
- out := &NetworkInterface{Name: interfaceName}
- // This can happen if the network runtime information is missing - possible if the
- // container was created by an old version of libcontainer.
- if interfaceName == "" {
- return out, nil
- }
- type netStatsPair struct {
- // Where to write the output.
- Out *uint64
- // The network stats file to read.
- File string
- }
- // Ingress for host veth is from the container. Hence tx_bytes stat on the host veth is actually number of bytes received by the container.
- netStats := []netStatsPair{
- {Out: &out.RxBytes, File: "tx_bytes"},
- {Out: &out.RxPackets, File: "tx_packets"},
- {Out: &out.RxErrors, File: "tx_errors"},
- {Out: &out.RxDropped, File: "tx_dropped"},
-
- {Out: &out.TxBytes, File: "rx_bytes"},
- {Out: &out.TxPackets, File: "rx_packets"},
- {Out: &out.TxErrors, File: "rx_errors"},
- {Out: &out.TxDropped, File: "rx_dropped"},
- }
- for _, netStat := range netStats {
- data, err := readSysfsNetworkStats(interfaceName, netStat.File)
- if err != nil {
- return nil, err
- }
- *(netStat.Out) = data
- }
- return out, nil
-}
-
-// Reads the specified statistics available under /sys/class/net//statistics
-func readSysfsNetworkStats(ethInterface, statsFile string) (uint64, error) {
- data, err := ioutil.ReadFile(filepath.Join("/sys/class/net", ethInterface, "statistics", statsFile))
- if err != nil {
- return 0, err
- }
- return strconv.ParseUint(strings.TrimSpace(string(data)), 10, 64)
-}
-
-// loopback is a network strategy that provides a basic loopback device
-type loopback struct {
-}
-
-func (l *loopback) create(n *network, nspid int) error {
- return nil
-}
-
-func (l *loopback) initialize(config *network) error {
- return netlink.LinkSetUp(&netlink.Device{netlink.LinkAttrs{Name: "lo"}})
-}
-
-func (l *loopback) attach(n *configs.Network) (err error) {
- return nil
-}
-
-func (l *loopback) detach(n *configs.Network) (err error) {
- return nil
-}
-
-// veth is a network strategy that uses a bridge and creates
-// a veth pair, one that is attached to the bridge on the host and the other
-// is placed inside the container's namespace
-type veth struct {
-}
-
-func (v *veth) detach(n *configs.Network) (err error) {
- return netlink.LinkSetMaster(&netlink.Device{netlink.LinkAttrs{Name: n.HostInterfaceName}}, nil)
-}
-
-// attach a container network interface to an external network
-func (v *veth) attach(n *configs.Network) (err error) {
- brl, err := netlink.LinkByName(n.Bridge)
- if err != nil {
- return err
- }
- br, ok := brl.(*netlink.Bridge)
- if !ok {
- return fmt.Errorf("Wrong device type %T", brl)
- }
- host, err := netlink.LinkByName(n.HostInterfaceName)
- if err != nil {
- return err
- }
-
- if err := netlink.LinkSetMaster(host, br); err != nil {
- return err
- }
- if err := netlink.LinkSetMTU(host, n.Mtu); err != nil {
- return err
- }
- if n.HairpinMode {
- if err := netlink.LinkSetHairpin(host, true); err != nil {
- return err
- }
- }
- if err := netlink.LinkSetUp(host); err != nil {
- return err
- }
-
- return nil
-}
-
-func (v *veth) create(n *network, nspid int) (err error) {
- tmpName, err := v.generateTempPeerName()
- if err != nil {
- return err
- }
- n.TempVethPeerName = tmpName
- if n.Bridge == "" {
- return fmt.Errorf("bridge is not specified")
- }
- veth := &netlink.Veth{
- LinkAttrs: netlink.LinkAttrs{
- Name: n.HostInterfaceName,
- TxQLen: n.TxQueueLen,
- },
- PeerName: n.TempVethPeerName,
- }
- if err := netlink.LinkAdd(veth); err != nil {
- return err
- }
- defer func() {
- if err != nil {
- netlink.LinkDel(veth)
- }
- }()
- if err := v.attach(&n.Network); err != nil {
- return err
- }
- child, err := netlink.LinkByName(n.TempVethPeerName)
- if err != nil {
- return err
- }
- return netlink.LinkSetNsPid(child, nspid)
-}
-
-func (v *veth) generateTempPeerName() (string, error) {
- return utils.GenerateRandomName("veth", 7)
-}
-
-func (v *veth) initialize(config *network) error {
- peer := config.TempVethPeerName
- if peer == "" {
- return fmt.Errorf("peer is not specified")
- }
- child, err := netlink.LinkByName(peer)
- if err != nil {
- return err
- }
- if err := netlink.LinkSetDown(child); err != nil {
- return err
- }
- if err := netlink.LinkSetName(child, config.Name); err != nil {
- return err
- }
- // get the interface again after we changed the name as the index also changes.
- if child, err = netlink.LinkByName(config.Name); err != nil {
- return err
- }
- if config.MacAddress != "" {
- mac, err := net.ParseMAC(config.MacAddress)
- if err != nil {
- return err
- }
- if err := netlink.LinkSetHardwareAddr(child, mac); err != nil {
- return err
- }
- }
- ip, err := netlink.ParseAddr(config.Address)
- if err != nil {
- return err
- }
- if err := netlink.AddrAdd(child, ip); err != nil {
- return err
- }
- if config.IPv6Address != "" {
- ip6, err := netlink.ParseAddr(config.IPv6Address)
- if err != nil {
- return err
- }
- if err := netlink.AddrAdd(child, ip6); err != nil {
- return err
- }
- }
- if err := netlink.LinkSetMTU(child, config.Mtu); err != nil {
- return err
- }
- if err := netlink.LinkSetUp(child); err != nil {
- return err
- }
- if config.Gateway != "" {
- gw := net.ParseIP(config.Gateway)
- if err := netlink.RouteAdd(&netlink.Route{
- Scope: netlink.SCOPE_UNIVERSE,
- LinkIndex: child.Attrs().Index,
- Gw: gw,
- }); err != nil {
- return err
- }
- }
- if config.IPv6Gateway != "" {
- gw := net.ParseIP(config.IPv6Gateway)
- if err := netlink.RouteAdd(&netlink.Route{
- Scope: netlink.SCOPE_UNIVERSE,
- LinkIndex: child.Attrs().Index,
- Gw: gw,
- }); err != nil {
- return err
- }
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/notify_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/notify_linux.go
deleted file mode 100644
index cf81e24..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/notify_linux.go
+++ /dev/null
@@ -1,63 +0,0 @@
-// +build linux
-
-package libcontainer
-
-import (
- "fmt"
- "io/ioutil"
- "os"
- "path/filepath"
- "syscall"
-)
-
-const oomCgroupName = "memory"
-
-// notifyOnOOM returns channel on which you can expect event about OOM,
-// if process died without OOM this channel will be closed.
-// s is current *libcontainer.State for container.
-func notifyOnOOM(paths map[string]string) (<-chan struct{}, error) {
- dir := paths[oomCgroupName]
- if dir == "" {
- return nil, fmt.Errorf("There is no path for %q in state", oomCgroupName)
- }
- oomControl, err := os.Open(filepath.Join(dir, "memory.oom_control"))
- if err != nil {
- return nil, err
- }
- fd, _, syserr := syscall.RawSyscall(syscall.SYS_EVENTFD2, 0, syscall.FD_CLOEXEC, 0)
- if syserr != 0 {
- oomControl.Close()
- return nil, syserr
- }
-
- eventfd := os.NewFile(fd, "eventfd")
-
- eventControlPath := filepath.Join(dir, "cgroup.event_control")
- data := fmt.Sprintf("%d %d", eventfd.Fd(), oomControl.Fd())
- if err := ioutil.WriteFile(eventControlPath, []byte(data), 0700); err != nil {
- eventfd.Close()
- oomControl.Close()
- return nil, err
- }
- ch := make(chan struct{})
- go func() {
- defer func() {
- close(ch)
- eventfd.Close()
- oomControl.Close()
- }()
- buf := make([]byte, 8)
- for {
- if _, err := eventfd.Read(buf); err != nil {
- return
- }
- // When a cgroup is destroyed, an event is sent to eventfd.
- // So if the control path is gone, return instead of notifying.
- if _, err := os.Lstat(eventControlPath); os.IsNotExist(err) {
- return
- }
- ch <- struct{}{}
- }
- }()
- return ch, nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/nsenter/README.md b/containerd/vendor/github.com/opencontainers/runc/libcontainer/nsenter/README.md
deleted file mode 100644
index d1a60ef..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/nsenter/README.md
+++ /dev/null
@@ -1,25 +0,0 @@
-## 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 Docker execdriver, so every time
-before we call `execdriver.Exec()`, that C code would run.
-
-`nsexec()` will first check the environment variable `_LIBCONTAINER_INITPID`
-which will give the process of the container that should be joined. Namespaces fd will
-be found from `/proc/[pid]/ns` and set by `setns` syscall.
-
-And then get the pipe number from `_LIBCONTAINER_INITPIPE`, error message could
-be transfered through it. If tty is added, `_LIBCONTAINER_CONSOLE_PATH` will
-have value and start a console for output.
-
-Finally, `nsexec()` will clone a child process , exit the parent process and let
-the Go runtime take over.
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter.go
deleted file mode 100644
index 07f4d63..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter.go
+++ /dev/null
@@ -1,12 +0,0 @@
-// +build linux,!gccgo
-
-package nsenter
-
-/*
-#cgo CFLAGS: -Wall
-extern void nsexec();
-void __attribute__((constructor)) init(void) {
- nsexec();
-}
-*/
-import "C"
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter_gccgo.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter_gccgo.go
deleted file mode 100644
index 63c7a3e..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter_gccgo.go
+++ /dev/null
@@ -1,25 +0,0 @@
-// +build linux,gccgo
-
-package nsenter
-
-/*
-#cgo CFLAGS: -Wall
-extern void nsexec();
-void __attribute__((constructor)) init(void) {
- nsexec();
-}
-*/
-import "C"
-
-// AlwaysFalse is here to stay false
-// (and be exported so the compiler doesn't optimize out its reference)
-var AlwaysFalse bool
-
-func init() {
- if AlwaysFalse {
- // by referencing this C init() in a noop test, it will ensure the compiler
- // links in the C function.
- // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=65134
- C.init()
- }
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter_unsupported.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter_unsupported.go
deleted file mode 100644
index ac701ca..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsenter_unsupported.go
+++ /dev/null
@@ -1,5 +0,0 @@
-// +build !linux !cgo
-
-package nsenter
-
-import "C"
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsexec.c b/containerd/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsexec.c
deleted file mode 100644
index 01450a9..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/nsenter/nsexec.c
+++ /dev/null
@@ -1,206 +0,0 @@
-#define _GNU_SOURCE
-#include
-#include
-#include
-#include
-#include
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-/* All arguments should be above stack, because it grows down */
-struct clone_arg {
- /*
- * Reserve some space for clone() to locate arguments
- * and retcode in this place
- */
- char stack[4096] __attribute__ ((aligned(16)));
- char stack_ptr[0];
- jmp_buf *env;
-};
-
-#define pr_perror(fmt, ...) fprintf(stderr, "nsenter: " fmt ": %m\n", ##__VA_ARGS__)
-
-static int child_func(void *_arg)
-{
- struct clone_arg *arg = (struct clone_arg *)_arg;
- longjmp(*arg->env, 1);
-}
-
-// Use raw setns syscall for versions of glibc that don't include it (namely glibc-2.12)
-#if __GLIBC__ == 2 && __GLIBC_MINOR__ < 14
-#define _GNU_SOURCE
-#include "syscall.h"
-#if defined(__NR_setns) && !defined(SYS_setns)
-#define SYS_setns __NR_setns
-#endif
-#ifdef SYS_setns
-int setns(int fd, int nstype)
-{
- return syscall(SYS_setns, fd, nstype);
-}
-#endif
-#endif
-
-static int clone_parent(jmp_buf * env) __attribute__ ((noinline));
-static int clone_parent(jmp_buf * env)
-{
- struct clone_arg ca;
- int child;
-
- ca.env = env;
- child = clone(child_func, ca.stack_ptr, CLONE_PARENT | SIGCHLD, &ca);
-
- return child;
-}
-
-void nsexec()
-{
- char *namespaces[] = { "ipc", "uts", "net", "pid", "mnt", "user" };
- const int num = sizeof(namespaces) / sizeof(char *);
- jmp_buf env;
- char buf[PATH_MAX], *val;
- int i, tfd, self_tfd, child, len, pipenum, consolefd = -1;
- pid_t pid;
- char *console;
-
- val = getenv("_LIBCONTAINER_INITPID");
- if (val == NULL)
- return;
-
- pid = atoi(val);
- snprintf(buf, sizeof(buf), "%d", pid);
- if (strcmp(val, buf)) {
- pr_perror("Unable to parse _LIBCONTAINER_INITPID");
- exit(1);
- }
-
- val = getenv("_LIBCONTAINER_INITPIPE");
- if (val == NULL) {
- pr_perror("Child pipe not found");
- exit(1);
- }
-
- pipenum = atoi(val);
- snprintf(buf, sizeof(buf), "%d", pipenum);
- if (strcmp(val, buf)) {
- pr_perror("Unable to parse _LIBCONTAINER_INITPIPE");
- exit(1);
- }
-
- console = getenv("_LIBCONTAINER_CONSOLE_PATH");
- if (console != NULL) {
- consolefd = open(console, O_RDWR);
- if (consolefd < 0) {
- pr_perror("Failed to open console %s", console);
- exit(1);
- }
- }
-
- /* Check that the specified process exists */
- snprintf(buf, PATH_MAX - 1, "/proc/%d/ns", pid);
- tfd = open(buf, O_DIRECTORY | O_RDONLY);
- if (tfd == -1) {
- pr_perror("Failed to open \"%s\"", buf);
- exit(1);
- }
-
- self_tfd = open("/proc/self/ns", O_DIRECTORY | O_RDONLY);
- if (self_tfd == -1) {
- pr_perror("Failed to open /proc/self/ns");
- exit(1);
- }
-
- for (i = 0; i < num; i++) {
- struct stat st;
- struct stat self_st;
- int fd;
-
- /* Symlinks on all namespaces exist for dead processes, but they can't be opened */
- if (fstatat(tfd, namespaces[i], &st, 0) == -1) {
- // Ignore nonexistent namespaces.
- if (errno == ENOENT)
- continue;
- }
-
- /* Skip namespaces we're already part of */
- if (fstatat(self_tfd, namespaces[i], &self_st, 0) != -1 &&
- st.st_ino == self_st.st_ino) {
- continue;
- }
-
- fd = openat(tfd, namespaces[i], O_RDONLY);
- if (fd == -1) {
- pr_perror("Failed to open ns file %s for ns %s", buf,
- namespaces[i]);
- exit(1);
- }
- // Set the namespace.
- if (setns(fd, 0) == -1) {
- pr_perror("Failed to setns for %s", namespaces[i]);
- exit(1);
- }
- close(fd);
- }
-
- close(self_tfd);
- close(tfd);
-
- if (setjmp(env) == 1) {
- // Child
-
- if (setsid() == -1) {
- pr_perror("setsid failed");
- exit(1);
- }
- if (consolefd != -1) {
- if (ioctl(consolefd, TIOCSCTTY, 0) == -1) {
- pr_perror("ioctl TIOCSCTTY failed");
- exit(1);
- }
- if (dup3(consolefd, STDIN_FILENO, 0) != STDIN_FILENO) {
- pr_perror("Failed to dup 0");
- exit(1);
- }
- if (dup3(consolefd, STDOUT_FILENO, 0) != STDOUT_FILENO) {
- pr_perror("Failed to dup 1");
- exit(1);
- }
- if (dup3(consolefd, STDERR_FILENO, 0) != STDERR_FILENO) {
- pr_perror("Failed to dup 2");
- exit(1);
- }
- }
- // Finish executing, let the Go runtime take over.
- return;
- }
- // Parent
-
- // We must fork to actually enter the PID namespace, use CLONE_PARENT
- // so the child can have the right parent, and we don't need to forward
- // the child's exit code or resend its death signal.
- child = clone_parent(&env);
- if (child < 0) {
- pr_perror("Unable to fork");
- exit(1);
- }
-
- len = snprintf(buf, sizeof(buf), "{ \"pid\" : %d }\n", child);
-
- if (write(pipenum, buf, len) != len) {
- pr_perror("Unable to send a child pid");
- kill(child, SIGKILL);
- exit(1);
- }
-
- exit(0);
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/process.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/process.go
deleted file mode 100644
index 7902d08..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/process.go
+++ /dev/null
@@ -1,89 +0,0 @@
-package libcontainer
-
-import (
- "fmt"
- "io"
- "math"
- "os"
-)
-
-type processOperations interface {
- wait() (*os.ProcessState, error)
- signal(sig os.Signal) error
- pid() int
-}
-
-// Process specifies the configuration and IO for a process inside
-// a container.
-type Process struct {
- // The command to be run followed by any arguments.
- Args []string
-
- // Env specifies the environment variables for the process.
- Env []string
-
- // User will set the uid and gid of the executing process running inside the container
- // local to the container's user and group configuration.
- User string
-
- // Cwd will change the processes current working directory inside the container's rootfs.
- Cwd string
-
- // Stdin is a pointer to a reader which provides the standard input stream.
- Stdin io.Reader
-
- // Stdout is a pointer to a writer which receives the standard output stream.
- Stdout io.Writer
-
- // Stderr is a pointer to a writer which receives the standard error stream.
- Stderr io.Writer
-
- // ExtraFiles specifies additional open files to be inherited by the container
- ExtraFiles []*os.File
-
- // consolePath is the path to the console allocated to the container.
- consolePath string
-
- // Capabilities specify the capabilities to keep when executing the process inside the container
- // All capabilities not specified will be dropped from the processes capability mask
- Capabilities []string
-
- ops processOperations
-}
-
-// Wait waits for the process to exit.
-// Wait releases any resources associated with the Process
-func (p Process) Wait() (*os.ProcessState, error) {
- if p.ops == nil {
- return nil, newGenericError(fmt.Errorf("invalid process"), ProcessNotExecuted)
- }
- return p.ops.wait()
-}
-
-// Pid returns the process ID
-func (p Process) Pid() (int, error) {
- // math.MinInt32 is returned here, because it's invalid value
- // for the kill() system call.
- if p.ops == nil {
- return math.MinInt32, newGenericError(fmt.Errorf("invalid process"), ProcessNotExecuted)
- }
- return p.ops.pid(), nil
-}
-
-// Signal sends a signal to the Process.
-func (p Process) Signal(sig os.Signal) error {
- if p.ops == nil {
- return newGenericError(fmt.Errorf("invalid process"), ProcessNotExecuted)
- }
- return p.ops.signal(sig)
-}
-
-// NewConsole creates new console for process and returns it
-func (p *Process) NewConsole(rootuid int) (Console, error) {
- console, err := newConsole(rootuid, rootuid)
- if err != nil {
- return nil, err
- }
- p.consolePath = console.Path()
- return console, nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/process_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/process_linux.go
deleted file mode 100644
index 4d17cbc..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/process_linux.go
+++ /dev/null
@@ -1,316 +0,0 @@
-// +build linux
-
-package libcontainer
-
-import (
- "encoding/json"
- "errors"
- "io"
- "os"
- "os/exec"
- "path/filepath"
- "strconv"
- "syscall"
-
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
- "github.com/opencontainers/runc/libcontainer/system"
-)
-
-type parentProcess interface {
- // pid returns the pid for the running process.
- pid() int
-
- // start starts the process execution.
- start() error
-
- // send a SIGKILL to the process and wait for the exit.
- terminate() error
-
- // wait waits on the process returning the process state.
- wait() (*os.ProcessState, error)
-
- // startTime return's the process start time.
- startTime() (string, error)
-
- signal(os.Signal) error
-
- externalDescriptors() []string
-
- setExternalDescriptors(fds []string)
-}
-
-type setnsProcess struct {
- cmd *exec.Cmd
- parentPipe *os.File
- childPipe *os.File
- cgroupPaths map[string]string
- config *initConfig
- fds []string
- process *Process
-}
-
-func (p *setnsProcess) startTime() (string, error) {
- return system.GetProcessStartTime(p.pid())
-}
-
-func (p *setnsProcess) signal(sig os.Signal) error {
- s, ok := sig.(syscall.Signal)
- if !ok {
- return errors.New("os: unsupported signal type")
- }
- return syscall.Kill(p.pid(), s)
-}
-
-func (p *setnsProcess) start() (err error) {
- defer p.parentPipe.Close()
- if err = p.execSetns(); err != nil {
- return newSystemError(err)
- }
- if len(p.cgroupPaths) > 0 {
- if err := cgroups.EnterPid(p.cgroupPaths, p.pid()); err != nil {
- return newSystemError(err)
- }
- }
- if err := json.NewEncoder(p.parentPipe).Encode(p.config); err != nil {
- return newSystemError(err)
- }
- if err := syscall.Shutdown(int(p.parentPipe.Fd()), syscall.SHUT_WR); err != nil {
- return newSystemError(err)
- }
- // wait for the child process to fully complete and receive an error message
- // if one was encoutered
- var ierr *genericError
- if err := json.NewDecoder(p.parentPipe).Decode(&ierr); err != nil && err != io.EOF {
- return newSystemError(err)
- }
- if ierr != nil {
- p.wait()
- return newSystemError(ierr)
- }
- return nil
-}
-
-// execSetns runs the process that executes C code to perform the setns calls
-// because setns support requires the C process to fork off a child and perform the setns
-// before the go runtime boots, we wait on the process to die and receive the child's pid
-// over the provided pipe.
-func (p *setnsProcess) execSetns() error {
- err := p.cmd.Start()
- p.childPipe.Close()
- if err != nil {
- return newSystemError(err)
- }
- status, err := p.cmd.Process.Wait()
- if err != nil {
- p.cmd.Wait()
- return newSystemError(err)
- }
- if !status.Success() {
- p.cmd.Wait()
- return newSystemError(&exec.ExitError{ProcessState: status})
- }
- var pid *pid
- if err := json.NewDecoder(p.parentPipe).Decode(&pid); err != nil {
- p.cmd.Wait()
- return newSystemError(err)
- }
- process, err := os.FindProcess(pid.Pid)
- if err != nil {
- return err
- }
- p.cmd.Process = process
- p.process.ops = p
- return nil
-}
-
-// terminate sends a SIGKILL to the forked process for the setns routine then waits to
-// avoid the process becomming a zombie.
-func (p *setnsProcess) terminate() error {
- if p.cmd.Process == nil {
- return nil
- }
- err := p.cmd.Process.Kill()
- if _, werr := p.wait(); err == nil {
- err = werr
- }
- return err
-}
-
-func (p *setnsProcess) wait() (*os.ProcessState, error) {
- err := p.cmd.Wait()
-
- // Return actual ProcessState even on Wait error
- return p.cmd.ProcessState, err
-}
-
-func (p *setnsProcess) pid() int {
- return p.cmd.Process.Pid
-}
-
-func (p *setnsProcess) externalDescriptors() []string {
- return p.fds
-}
-
-func (p *setnsProcess) setExternalDescriptors(newFds []string) {
- p.fds = newFds
-}
-
-type initProcess struct {
- cmd *exec.Cmd
- parentPipe *os.File
- childPipe *os.File
- config *initConfig
- manager cgroups.Manager
- container *linuxContainer
- fds []string
- process *Process
-}
-
-func (p *initProcess) pid() int {
- return p.cmd.Process.Pid
-}
-
-func (p *initProcess) externalDescriptors() []string {
- return p.fds
-}
-
-func (p *initProcess) start() (err error) {
- defer p.parentPipe.Close()
- err = p.cmd.Start()
- p.process.ops = p
- p.childPipe.Close()
- if err != nil {
- p.process.ops = nil
- return newSystemError(err)
- }
- // Save the standard descriptor names before the container process
- // can potentially move them (e.g., via dup2()). If we don't do this now,
- // we won't know at checkpoint time which file descriptor to look up.
- fds, err := getPipeFds(p.pid())
- if err != nil {
- return newSystemError(err)
- }
- p.setExternalDescriptors(fds)
-
- // Do this before syncing with child so that no children
- // can escape the cgroup
- if err := p.manager.Apply(p.pid()); err != nil {
- return newSystemError(err)
- }
- defer func() {
- if err != nil {
- // TODO: should not be the responsibility to call here
- p.manager.Destroy()
- }
- }()
- if p.config.Config.Hooks != nil {
- s := configs.HookState{
- Version: p.container.config.Version,
- ID: p.container.id,
- Pid: p.pid(),
- Root: p.config.Config.Rootfs,
- }
- for _, hook := range p.config.Config.Hooks.Prestart {
- if err := hook.Run(s); err != nil {
- return newSystemError(err)
- }
- }
- }
- if err := p.createNetworkInterfaces(); err != nil {
- return newSystemError(err)
- }
- if err := p.sendConfig(); err != nil {
- return newSystemError(err)
- }
- // wait for the child process to fully complete and receive an error message
- // if one was encoutered
- var ierr *genericError
- if err := json.NewDecoder(p.parentPipe).Decode(&ierr); err != nil && err != io.EOF {
- return newSystemError(err)
- }
- if ierr != nil {
- return newSystemError(ierr)
- }
- return nil
-}
-
-func (p *initProcess) wait() (*os.ProcessState, error) {
- err := p.cmd.Wait()
- if err != nil {
- return p.cmd.ProcessState, err
- }
- // we should kill all processes in cgroup when init is died if we use host PID namespace
- if p.cmd.SysProcAttr.Cloneflags&syscall.CLONE_NEWPID == 0 {
- killCgroupProcesses(p.manager)
- }
- return p.cmd.ProcessState, nil
-}
-
-func (p *initProcess) terminate() error {
- if p.cmd.Process == nil {
- return nil
- }
- err := p.cmd.Process.Kill()
- if _, werr := p.wait(); err == nil {
- err = werr
- }
- return err
-}
-
-func (p *initProcess) startTime() (string, error) {
- return system.GetProcessStartTime(p.pid())
-}
-
-func (p *initProcess) sendConfig() error {
- // send the state to the container's init process then shutdown writes for the parent
- if err := json.NewEncoder(p.parentPipe).Encode(p.config); err != nil {
- return err
- }
- // shutdown writes for the parent side of the pipe
- return syscall.Shutdown(int(p.parentPipe.Fd()), syscall.SHUT_WR)
-}
-
-func (p *initProcess) createNetworkInterfaces() error {
- for _, config := range p.config.Config.Networks {
- strategy, err := getStrategy(config.Type)
- if err != nil {
- return err
- }
- n := &network{
- Network: *config,
- }
- if err := strategy.create(n, p.pid()); err != nil {
- return err
- }
- p.config.Networks = append(p.config.Networks, n)
- }
- return nil
-}
-
-func (p *initProcess) signal(sig os.Signal) error {
- s, ok := sig.(syscall.Signal)
- if !ok {
- return errors.New("os: unsupported signal type")
- }
- return syscall.Kill(p.pid(), s)
-}
-
-func (p *initProcess) setExternalDescriptors(newFds []string) {
- p.fds = newFds
-}
-
-func getPipeFds(pid int) ([]string, error) {
- fds := make([]string, 3)
-
- dirPath := filepath.Join("/proc", strconv.Itoa(pid), "/fd")
- for i := 0; i < 3; i++ {
- f := filepath.Join(dirPath, strconv.Itoa(i))
- target, err := os.Readlink(f)
- if err != nil {
- return fds, err
- }
- fds[i] = target
- }
- return fds, nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/restored_process.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/restored_process.go
deleted file mode 100644
index a96f4ca..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/restored_process.go
+++ /dev/null
@@ -1,122 +0,0 @@
-// +build linux
-
-package libcontainer
-
-import (
- "fmt"
- "os"
-
- "github.com/opencontainers/runc/libcontainer/system"
-)
-
-func newRestoredProcess(pid int, fds []string) (*restoredProcess, error) {
- var (
- err error
- )
- proc, err := os.FindProcess(pid)
- if err != nil {
- return nil, err
- }
- started, err := system.GetProcessStartTime(pid)
- if err != nil {
- return nil, err
- }
- return &restoredProcess{
- proc: proc,
- processStartTime: started,
- fds: fds,
- }, nil
-}
-
-type restoredProcess struct {
- proc *os.Process
- processStartTime string
- fds []string
-}
-
-func (p *restoredProcess) start() error {
- return newGenericError(fmt.Errorf("restored process cannot be started"), SystemError)
-}
-
-func (p *restoredProcess) pid() int {
- return p.proc.Pid
-}
-
-func (p *restoredProcess) terminate() error {
- err := p.proc.Kill()
- if _, werr := p.wait(); err == nil {
- err = werr
- }
- return err
-}
-
-func (p *restoredProcess) wait() (*os.ProcessState, error) {
- // TODO: how do we wait on the actual process?
- // maybe use --exec-cmd in criu
- st, err := p.proc.Wait()
- if err != nil {
- return nil, err
- }
- return st, nil
-}
-
-func (p *restoredProcess) startTime() (string, error) {
- return p.processStartTime, nil
-}
-
-func (p *restoredProcess) signal(s os.Signal) error {
- return p.proc.Signal(s)
-}
-
-func (p *restoredProcess) externalDescriptors() []string {
- return p.fds
-}
-
-func (p *restoredProcess) setExternalDescriptors(newFds []string) {
- p.fds = newFds
-}
-
-// nonChildProcess represents a process where the calling process is not
-// the parent process. This process is created when a factory loads a container from
-// a persisted state.
-type nonChildProcess struct {
- processPid int
- processStartTime string
- fds []string
-}
-
-func (p *nonChildProcess) start() error {
- return newGenericError(fmt.Errorf("restored process cannot be started"), SystemError)
-}
-
-func (p *nonChildProcess) pid() int {
- return p.processPid
-}
-
-func (p *nonChildProcess) terminate() error {
- return newGenericError(fmt.Errorf("restored process cannot be terminated"), SystemError)
-}
-
-func (p *nonChildProcess) wait() (*os.ProcessState, error) {
- return nil, newGenericError(fmt.Errorf("restored process cannot be waited on"), SystemError)
-}
-
-func (p *nonChildProcess) startTime() (string, error) {
- return p.processStartTime, nil
-}
-
-func (p *nonChildProcess) signal(s os.Signal) error {
- proc, err := os.FindProcess(p.processPid)
- if err != nil {
- return err
- }
- return proc.Signal(s)
-}
-
-func (p *nonChildProcess) externalDescriptors() []string {
- return p.fds
-}
-
-func (p *nonChildProcess) setExternalDescriptors(newFds []string) {
- p.fds = newFds
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/rootfs_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/rootfs_linux.go
deleted file mode 100644
index 78beb03..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/rootfs_linux.go
+++ /dev/null
@@ -1,665 +0,0 @@
-// +build linux
-
-package libcontainer
-
-import (
- "fmt"
- "io/ioutil"
- "os"
- "os/exec"
- "path"
- "path/filepath"
- "strings"
- "syscall"
- "time"
-
- "github.com/docker/docker/pkg/mount"
- "github.com/docker/docker/pkg/symlink"
- "github.com/opencontainers/runc/libcontainer/cgroups"
- "github.com/opencontainers/runc/libcontainer/configs"
- "github.com/opencontainers/runc/libcontainer/label"
-)
-
-const defaultMountFlags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NODEV
-
-// setupRootfs sets up the devices, mount points, and filesystems for use inside a
-// new mount namespace.
-func setupRootfs(config *configs.Config, console *linuxConsole) (err error) {
- if err := prepareRoot(config); err != nil {
- return newSystemError(err)
- }
-
- setupDev := len(config.Devices) != 0
- for _, m := range config.Mounts {
- for _, precmd := range m.PremountCmds {
- if err := mountCmd(precmd); err != nil {
- return newSystemError(err)
- }
- }
- if err := mountToRootfs(m, config.Rootfs, config.MountLabel); err != nil {
- return newSystemError(err)
- }
-
- for _, postcmd := range m.PostmountCmds {
- if err := mountCmd(postcmd); err != nil {
- return newSystemError(err)
- }
- }
- }
- if setupDev {
- if err := createDevices(config); err != nil {
- return newSystemError(err)
- }
- if err := setupPtmx(config, console); err != nil {
- return newSystemError(err)
- }
- if err := setupDevSymlinks(config.Rootfs); err != nil {
- return newSystemError(err)
- }
- }
- if err := syscall.Chdir(config.Rootfs); err != nil {
- return newSystemError(err)
- }
- if config.NoPivotRoot {
- err = msMoveRoot(config.Rootfs)
- } else {
- err = pivotRoot(config.Rootfs, config.PivotDir)
- }
- if err != nil {
- return newSystemError(err)
- }
- if setupDev {
- if err := reOpenDevNull(); err != nil {
- return newSystemError(err)
- }
- }
- if config.Readonlyfs {
- if err := setReadonly(); err != nil {
- return newSystemError(err)
- }
- }
- syscall.Umask(0022)
- return nil
-}
-
-func mountCmd(cmd configs.Command) error {
-
- command := exec.Command(cmd.Path, cmd.Args[:]...)
- command.Env = cmd.Env
- command.Dir = cmd.Dir
- if out, err := command.CombinedOutput(); err != nil {
- return fmt.Errorf("%#v failed: %s: %v", cmd, string(out), err)
- }
-
- return nil
-}
-
-func mountToRootfs(m *configs.Mount, rootfs, mountLabel string) error {
- var (
- dest = m.Destination
- )
- if !strings.HasPrefix(dest, rootfs) {
- dest = filepath.Join(rootfs, dest)
- }
-
- switch m.Device {
- case "proc", "sysfs":
- if err := os.MkdirAll(dest, 0755); err != nil {
- return err
- }
- // Selinux kernels do not support labeling of /proc or /sys
- return mountPropagate(m, rootfs, "")
- case "mqueue":
- if err := os.MkdirAll(dest, 0755); err != nil {
- return err
- }
- if err := mountPropagate(m, rootfs, mountLabel); err != nil {
- // older kernels do not support labeling of /dev/mqueue
- if err := mountPropagate(m, rootfs, ""); err != nil {
- return err
- }
- }
- return label.SetFileLabel(dest, mountLabel)
- case "tmpfs":
- stat, err := os.Stat(dest)
- if err != nil {
- if err := os.MkdirAll(dest, 0755); err != nil {
- return err
- }
- }
- if err := mountPropagate(m, rootfs, mountLabel); err != nil {
- return err
- }
- if stat != nil {
- if err = os.Chmod(dest, stat.Mode()); err != nil {
- return err
- }
- }
- return nil
- case "devpts":
- if err := os.MkdirAll(dest, 0755); err != nil {
- return err
- }
- return mountPropagate(m, rootfs, mountLabel)
- case "securityfs":
- if err := os.MkdirAll(dest, 0755); err != nil {
- return err
- }
- return mountPropagate(m, rootfs, mountLabel)
- case "bind":
- stat, err := os.Stat(m.Source)
- if err != nil {
- // error out if the source of a bind mount does not exist as we will be
- // unable to bind anything to it.
- return err
- }
- // ensure that the destination of the bind mount is resolved of symlinks at mount time because
- // any previous mounts can invalidate the next mount's destination.
- // this can happen when a user specifies mounts within other mounts to cause breakouts or other
- // evil stuff to try to escape the container's rootfs.
- if dest, err = symlink.FollowSymlinkInScope(filepath.Join(rootfs, m.Destination), rootfs); err != nil {
- return err
- }
- if err := checkMountDestination(rootfs, dest); err != nil {
- return err
- }
- // update the mount with the correct dest after symlinks are resolved.
- m.Destination = dest
- if err := createIfNotExists(dest, stat.IsDir()); err != nil {
- return err
- }
- if err := mountPropagate(m, rootfs, mountLabel); err != nil {
- return err
- }
- // bind mount won't change mount options, we need remount to make mount options effective.
- // first check that we have non-default options required before attempting a remount
- if m.Flags&^(syscall.MS_REC|syscall.MS_REMOUNT|syscall.MS_BIND) != 0 {
- // only remount if unique mount options are set
- if err := remount(m, rootfs); err != nil {
- return err
- }
- }
-
- if m.Relabel != "" {
- if err := label.Validate(m.Relabel); err != nil {
- return err
- }
- shared := label.IsShared(m.Relabel)
- if err := label.Relabel(m.Source, mountLabel, shared); err != nil {
- return err
- }
- }
- case "cgroup":
- binds, err := getCgroupMounts(m)
- if err != nil {
- return err
- }
- var merged []string
- for _, b := range binds {
- ss := filepath.Base(b.Destination)
- if strings.Contains(ss, ",") {
- merged = append(merged, ss)
- }
- }
- tmpfs := &configs.Mount{
- Source: "tmpfs",
- Device: "tmpfs",
- Destination: m.Destination,
- Flags: defaultMountFlags,
- Data: "mode=755",
- PropagationFlags: m.PropagationFlags,
- }
- if err := mountToRootfs(tmpfs, rootfs, mountLabel); err != nil {
- return err
- }
- for _, b := range binds {
- if err := mountToRootfs(b, rootfs, mountLabel); err != nil {
- return err
- }
- }
- // create symlinks for merged cgroups
- cwd, err := os.Getwd()
- if err != nil {
- return err
- }
- if err := os.Chdir(filepath.Join(rootfs, m.Destination)); err != nil {
- return err
- }
- for _, mc := range merged {
- for _, ss := range strings.Split(mc, ",") {
- if err := os.Symlink(mc, ss); err != nil {
- // if cgroup already exists, then okay(it could have been created before)
- if os.IsExist(err) {
- continue
- }
- os.Chdir(cwd)
- return err
- }
- }
- }
- if err := os.Chdir(cwd); err != nil {
- return err
- }
- if m.Flags&syscall.MS_RDONLY != 0 {
- // remount cgroup root as readonly
- mcgrouproot := &configs.Mount{
- Destination: m.Destination,
- Flags: defaultMountFlags | syscall.MS_RDONLY,
- }
- if err := remount(mcgrouproot, rootfs); err != nil {
- return err
- }
- }
- default:
- return fmt.Errorf("unknown mount device %q to %q", m.Device, m.Destination)
- }
- return nil
-}
-
-func getCgroupMounts(m *configs.Mount) ([]*configs.Mount, error) {
- mounts, err := cgroups.GetCgroupMounts()
- if err != nil {
- return nil, err
- }
-
- cgroupPaths, err := cgroups.ParseCgroupFile("/proc/self/cgroup")
- if err != nil {
- return nil, err
- }
-
- var binds []*configs.Mount
-
- for _, mm := range mounts {
- dir, err := mm.GetThisCgroupDir(cgroupPaths)
- if err != nil {
- return nil, err
- }
- relDir, err := filepath.Rel(mm.Root, dir)
- if err != nil {
- return nil, err
- }
- binds = append(binds, &configs.Mount{
- Device: "bind",
- Source: filepath.Join(mm.Mountpoint, relDir),
- Destination: filepath.Join(m.Destination, strings.Join(mm.Subsystems, ",")),
- Flags: syscall.MS_BIND | syscall.MS_REC | m.Flags,
- PropagationFlags: m.PropagationFlags,
- })
- }
-
- return binds, nil
-}
-
-// checkMountDestination checks to ensure that the mount destination is not over the
-// top of /proc or /sys.
-// dest is required to be an abs path and have any symlinks resolved before calling this function.
-func checkMountDestination(rootfs, dest string) error {
- if filepath.Clean(rootfs) == filepath.Clean(dest) {
- return fmt.Errorf("mounting into / is prohibited")
- }
- invalidDestinations := []string{
- "/proc",
- }
- for _, invalid := range invalidDestinations {
- path, err := filepath.Rel(filepath.Join(rootfs, invalid), dest)
- if err != nil {
- return err
- }
- if path == "." || !strings.HasPrefix(path, "..") {
- return fmt.Errorf("%q cannot be mounted because it is located inside %q", dest, invalid)
- }
- }
- return nil
-}
-
-func setupDevSymlinks(rootfs string) error {
- var links = [][2]string{
- {"/proc/self/fd", "/dev/fd"},
- {"/proc/self/fd/0", "/dev/stdin"},
- {"/proc/self/fd/1", "/dev/stdout"},
- {"/proc/self/fd/2", "/dev/stderr"},
- }
- // kcore support can be toggled with CONFIG_PROC_KCORE; only create a symlink
- // in /dev if it exists in /proc.
- if _, err := os.Stat("/proc/kcore"); err == nil {
- links = append(links, [2]string{"/proc/kcore", "/dev/kcore"})
- }
- for _, link := range links {
- var (
- src = link[0]
- dst = filepath.Join(rootfs, link[1])
- )
- if err := os.Symlink(src, dst); err != nil && !os.IsExist(err) {
- return fmt.Errorf("symlink %s %s %s", src, dst, err)
- }
- }
- return nil
-}
-
-// If stdin, stdout, and/or stderr are pointing to `/dev/null` in the parent's rootfs
-// this method will make them point to `/dev/null` in this container's rootfs. This
-// needs to be called after we chroot/pivot into the container's rootfs so that any
-// symlinks are resolved locally.
-func reOpenDevNull() error {
- var stat, devNullStat syscall.Stat_t
- file, err := os.OpenFile("/dev/null", os.O_RDWR, 0)
- if err != nil {
- return fmt.Errorf("Failed to open /dev/null - %s", err)
- }
- defer file.Close()
- if err := syscall.Fstat(int(file.Fd()), &devNullStat); err != nil {
- return err
- }
- for fd := 0; fd < 3; fd++ {
- if err := syscall.Fstat(fd, &stat); err != nil {
- return err
- }
- if stat.Rdev == devNullStat.Rdev {
- // Close and re-open the fd.
- if err := syscall.Dup3(int(file.Fd()), fd, 0); err != nil {
- return err
- }
- }
- }
- return nil
-}
-
-// Create the device nodes in the container.
-func createDevices(config *configs.Config) error {
- oldMask := syscall.Umask(0000)
- for _, node := range config.Devices {
- // containers running in a user namespace are not allowed to mknod
- // devices so we can just bind mount it from the host.
- if err := createDeviceNode(config.Rootfs, node, config.Namespaces.Contains(configs.NEWUSER)); err != nil {
- syscall.Umask(oldMask)
- return err
- }
- }
- syscall.Umask(oldMask)
- return nil
-}
-
-// Creates the device node in the rootfs of the container.
-func createDeviceNode(rootfs string, node *configs.Device, bind bool) error {
- dest := filepath.Join(rootfs, node.Path)
- if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
- return err
- }
-
- if bind {
- f, err := os.Create(dest)
- if err != nil && !os.IsExist(err) {
- return err
- }
- if f != nil {
- f.Close()
- }
- return syscall.Mount(node.Path, dest, "bind", syscall.MS_BIND, "")
- }
- if err := mknodDevice(dest, node); err != nil {
- if os.IsExist(err) {
- return nil
- }
- return err
- }
- return nil
-}
-
-func mknodDevice(dest string, node *configs.Device) error {
- fileMode := node.FileMode
- switch node.Type {
- case 'c':
- fileMode |= syscall.S_IFCHR
- case 'b':
- fileMode |= syscall.S_IFBLK
- default:
- return fmt.Errorf("%c is not a valid device type for device %s", node.Type, node.Path)
- }
- if err := syscall.Mknod(dest, uint32(fileMode), node.Mkdev()); err != nil {
- return err
- }
- return syscall.Chown(dest, int(node.Uid), int(node.Gid))
-}
-
-func getMountInfo(mountinfo []*mount.Info, dir string) *mount.Info {
- for _, m := range mountinfo {
- if m.Mountpoint == dir {
- return m
- }
- }
- return nil
-}
-
-// Get the parent mount point of directory passed in as argument. Also return
-// optional fields.
-func getParentMount(rootfs string) (string, string, error) {
- var path string
-
- mountinfos, err := mount.GetMounts()
- if err != nil {
- return "", "", err
- }
-
- mountinfo := getMountInfo(mountinfos, rootfs)
- if mountinfo != nil {
- return rootfs, mountinfo.Optional, nil
- }
-
- path = rootfs
- for {
- path = filepath.Dir(path)
-
- mountinfo = getMountInfo(mountinfos, path)
- if mountinfo != nil {
- return path, mountinfo.Optional, nil
- }
-
- if path == "/" {
- break
- }
- }
-
- // If we are here, we did not find parent mount. Something is wrong.
- return "", "", fmt.Errorf("Could not find parent mount of %s", rootfs)
-}
-
-// Make parent mount private if it was shared
-func rootfsParentMountPrivate(config *configs.Config) error {
- sharedMount := false
-
- parentMount, optionalOpts, err := getParentMount(config.Rootfs)
- if err != nil {
- return err
- }
-
- optsSplit := strings.Split(optionalOpts, " ")
- for _, opt := range optsSplit {
- if strings.HasPrefix(opt, "shared:") {
- sharedMount = true
- break
- }
- }
-
- // Make parent mount PRIVATE if it was shared. It is needed for two
- // reasons. First of all pivot_root() will fail if parent mount is
- // shared. Secondly when we bind mount rootfs it will propagate to
- // parent namespace and we don't want that to happen.
- if sharedMount {
- return syscall.Mount("", parentMount, "", syscall.MS_PRIVATE, "")
- }
-
- return nil
-}
-
-func prepareRoot(config *configs.Config) error {
- flag := syscall.MS_SLAVE | syscall.MS_REC
- if config.RootPropagation != 0 {
- flag = config.RootPropagation
- }
- if err := syscall.Mount("", "/", "", uintptr(flag), ""); err != nil {
- return err
- }
-
- if err := rootfsParentMountPrivate(config); err != nil {
- return err
- }
-
- return syscall.Mount(config.Rootfs, config.Rootfs, "bind", syscall.MS_BIND|syscall.MS_REC, "")
-}
-
-func setReadonly() error {
- return syscall.Mount("/", "/", "bind", syscall.MS_BIND|syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_REC, "")
-}
-
-func setupPtmx(config *configs.Config, console *linuxConsole) error {
- ptmx := filepath.Join(config.Rootfs, "dev/ptmx")
- if err := os.Remove(ptmx); err != nil && !os.IsNotExist(err) {
- return err
- }
- if err := os.Symlink("pts/ptmx", ptmx); err != nil {
- return fmt.Errorf("symlink dev ptmx %s", err)
- }
- if console != nil {
- return console.mount(config.Rootfs, config.MountLabel)
- }
- return nil
-}
-
-func pivotRoot(rootfs, pivotBaseDir string) error {
- if pivotBaseDir == "" {
- pivotBaseDir = "/"
- }
- tmpDir := filepath.Join(rootfs, pivotBaseDir)
- if err := os.MkdirAll(tmpDir, 0755); err != nil {
- return fmt.Errorf("can't create tmp dir %s, error %v", tmpDir, err)
- }
- pivotDir, err := ioutil.TempDir(tmpDir, ".pivot_root")
- if err != nil {
- return fmt.Errorf("can't create pivot_root dir %s, error %v", pivotDir, err)
- }
- if err := syscall.PivotRoot(rootfs, pivotDir); err != nil {
- return fmt.Errorf("pivot_root %s", err)
- }
- if err := syscall.Chdir("/"); err != nil {
- return fmt.Errorf("chdir / %s", err)
- }
- // path to pivot dir now changed, update
- pivotDir = filepath.Join(pivotBaseDir, filepath.Base(pivotDir))
-
- // Make pivotDir rprivate to make sure any of the unmounts don't
- // propagate to parent.
- if err := syscall.Mount("", pivotDir, "", syscall.MS_PRIVATE|syscall.MS_REC, ""); err != nil {
- return err
- }
-
- if err := syscall.Unmount(pivotDir, syscall.MNT_DETACH); err != nil {
- return fmt.Errorf("unmount pivot_root dir %s", err)
- }
- return os.Remove(pivotDir)
-}
-
-func msMoveRoot(rootfs string) error {
- if err := syscall.Mount(rootfs, "/", "", syscall.MS_MOVE, ""); err != nil {
- return err
- }
- if err := syscall.Chroot("."); err != nil {
- return err
- }
- return syscall.Chdir("/")
-}
-
-// createIfNotExists creates a file or a directory only if it does not already exist.
-func createIfNotExists(path string, isDir bool) error {
- if _, err := os.Stat(path); err != nil {
- if os.IsNotExist(err) {
- if isDir {
- return os.MkdirAll(path, 0755)
- }
- if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
- return err
- }
- f, err := os.OpenFile(path, os.O_CREATE, 0755)
- if err != nil {
- return err
- }
- f.Close()
- }
- }
- return nil
-}
-
-// remountReadonly will bind over the top of an existing path and ensure that it is read-only.
-func remountReadonly(path string) error {
- for i := 0; i < 5; i++ {
- if err := syscall.Mount("", path, "", syscall.MS_REMOUNT|syscall.MS_RDONLY, ""); err != nil && !os.IsNotExist(err) {
- switch err {
- case syscall.EINVAL:
- // Probably not a mountpoint, use bind-mount
- if err := syscall.Mount(path, path, "", syscall.MS_BIND, ""); err != nil {
- return err
- }
- return syscall.Mount(path, path, "", syscall.MS_BIND|syscall.MS_REMOUNT|syscall.MS_RDONLY|syscall.MS_REC|defaultMountFlags, "")
- case syscall.EBUSY:
- time.Sleep(100 * time.Millisecond)
- continue
- default:
- return err
- }
- }
- return nil
- }
- return fmt.Errorf("unable to mount %s as readonly max retries reached", path)
-}
-
-// maskFile bind mounts /dev/null over the top of the specified path inside a container
-// to avoid security issues from processes reading information from non-namespace aware mounts ( proc/kcore ).
-func maskFile(path string) error {
- if err := syscall.Mount("/dev/null", path, "", syscall.MS_BIND, ""); err != nil && !os.IsNotExist(err) {
- return err
- }
- return nil
-}
-
-// writeSystemProperty writes the value to a path under /proc/sys as determined from the key.
-// For e.g. net.ipv4.ip_forward translated to /proc/sys/net/ipv4/ip_forward.
-func writeSystemProperty(key, value string) error {
- keyPath := strings.Replace(key, ".", "/", -1)
- return ioutil.WriteFile(path.Join("/proc/sys", keyPath), []byte(value), 0644)
-}
-
-func remount(m *configs.Mount, rootfs string) error {
- var (
- dest = m.Destination
- )
- if !strings.HasPrefix(dest, rootfs) {
- dest = filepath.Join(rootfs, dest)
- }
-
- if err := syscall.Mount(m.Source, dest, m.Device, uintptr(m.Flags|syscall.MS_REMOUNT), ""); err != nil {
- return err
- }
- return nil
-}
-
-// Do the mount operation followed by additional mounts required to take care
-// of propagation flags.
-func mountPropagate(m *configs.Mount, rootfs string, mountLabel string) error {
- var (
- dest = m.Destination
- data = label.FormatMountLabel(m.Data, mountLabel)
- )
- if !strings.HasPrefix(dest, rootfs) {
- dest = filepath.Join(rootfs, dest)
- }
-
- if err := syscall.Mount(m.Source, dest, m.Device, uintptr(m.Flags), data); err != nil {
- return err
- }
-
- for _, pflag := range m.PropagationFlags {
- if err := syscall.Mount("", dest, "", uintptr(pflag), ""); err != nil {
- return err
- }
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/seccomp/config.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/seccomp/config.go
deleted file mode 100644
index 5a3d016..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/seccomp/config.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package seccomp
-
-import (
- "fmt"
-
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-var operators = map[string]configs.Operator{
- "SCMP_CMP_NE": configs.NotEqualTo,
- "SCMP_CMP_LT": configs.LessThan,
- "SCMP_CMP_LE": configs.LessThanOrEqualTo,
- "SCMP_CMP_EQ": configs.EqualTo,
- "SCMP_CMP_GE": configs.GreaterThanOrEqualTo,
- "SCMP_CMP_GT": configs.GreaterThan,
- "SCMP_CMP_MASKED_EQ": configs.MaskEqualTo,
-}
-
-var actions = map[string]configs.Action{
- "SCMP_ACT_KILL": configs.Kill,
- "SCMP_ACT_ERRNO": configs.Errno,
- "SCMP_ACT_TRAP": configs.Trap,
- "SCMP_ACT_ALLOW": configs.Allow,
-}
-
-var archs = map[string]string{
- "SCMP_ARCH_X86": "x86",
- "SCMP_ARCH_X86_64": "amd64",
- "SCMP_ARCH_X32": "x32",
- "SCMP_ARCH_ARM": "arm",
- "SCMP_ARCH_AARCH64": "arm64",
- "SCMP_ARCH_MIPS": "mips",
- "SCMP_ARCH_MIPS64": "mips64",
- "SCMP_ARCH_MIPS64N32": "mips64n32",
- "SCMP_ARCH_MIPSEL": "mipsel",
- "SCMP_ARCH_MIPSEL64": "mipsel64",
- "SCMP_ARCH_MIPSEL64N32": "mipsel64n32",
-}
-
-// ConvertStringToOperator converts a string into a Seccomp comparison operator.
-// Comparison operators use the names they are assigned by Libseccomp's header.
-// Attempting to convert a string that is not a valid operator results in an
-// error.
-func ConvertStringToOperator(in string) (configs.Operator, error) {
- if op, ok := operators[in]; ok == true {
- return op, nil
- }
- return 0, fmt.Errorf("string %s is not a valid operator for seccomp", in)
-}
-
-// ConvertStringToAction converts a string into a Seccomp rule match action.
-// Actions use the names they are assigned in Libseccomp's header, though some
-// (notable, SCMP_ACT_TRACE) are not available in this implementation and will
-// return errors.
-// Attempting to convert a string that is not a valid action results in an
-// error.
-func ConvertStringToAction(in string) (configs.Action, error) {
- if act, ok := actions[in]; ok == true {
- return act, nil
- }
- return 0, fmt.Errorf("string %s is not a valid action for seccomp", in)
-}
-
-// ConvertStringToArch converts a string into a Seccomp comparison arch.
-func ConvertStringToArch(in string) (string, error) {
- if arch, ok := archs[in]; ok == true {
- return arch, nil
- }
- return "", fmt.Errorf("string %s is not a valid arch for seccomp", in)
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_linux.go
deleted file mode 100644
index 1e9ccf8..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_linux.go
+++ /dev/null
@@ -1,177 +0,0 @@
-// +build linux,cgo,seccomp
-
-package seccomp
-
-import (
- "fmt"
- "log"
- "syscall"
-
- "github.com/opencontainers/runc/libcontainer/configs"
- libseccomp "github.com/seccomp/libseccomp-golang"
-)
-
-var (
- actAllow = libseccomp.ActAllow
- actTrap = libseccomp.ActTrap
- actKill = libseccomp.ActKill
- actErrno = libseccomp.ActErrno.SetReturnCode(int16(syscall.EPERM))
-)
-
-// Filters given syscalls in a container, preventing them from being used
-// Started in the container init process, and carried over to all child processes
-// Setns calls, however, require a separate invocation, as they are not children
-// of the init until they join the namespace
-func InitSeccomp(config *configs.Seccomp) error {
- if config == nil {
- return fmt.Errorf("cannot initialize Seccomp - nil config passed")
- }
-
- defaultAction, err := getAction(config.DefaultAction)
- if err != nil {
- return fmt.Errorf("error initializing seccomp - invalid default action")
- }
-
- filter, err := libseccomp.NewFilter(defaultAction)
- if err != nil {
- return fmt.Errorf("error creating filter: %s", err)
- }
-
- // Add extra architectures
- for _, arch := range config.Architectures {
- scmpArch, err := libseccomp.GetArchFromString(arch)
- if err != nil {
- return err
- }
-
- if err := filter.AddArch(scmpArch); err != nil {
- return err
- }
- }
-
- // Unset no new privs bit
- if err := filter.SetNoNewPrivsBit(false); err != nil {
- return fmt.Errorf("error setting no new privileges: %s", err)
- }
-
- // Add a rule for each syscall
- for _, call := range config.Syscalls {
- if call == nil {
- return fmt.Errorf("encountered nil syscall while initializing Seccomp")
- }
-
- if err = matchCall(filter, call); err != nil {
- return err
- }
- }
-
- if err = filter.Load(); err != nil {
- return fmt.Errorf("error loading seccomp filter into kernel: %s", err)
- }
-
- return nil
-}
-
-// Convert Libcontainer Action to Libseccomp ScmpAction
-func getAction(act configs.Action) (libseccomp.ScmpAction, error) {
- switch act {
- case configs.Kill:
- return actKill, nil
- case configs.Errno:
- return actErrno, nil
- case configs.Trap:
- return actTrap, nil
- case configs.Allow:
- return actAllow, nil
- default:
- return libseccomp.ActInvalid, fmt.Errorf("invalid action, cannot use in rule")
- }
-}
-
-// Convert Libcontainer Operator to Libseccomp ScmpCompareOp
-func getOperator(op configs.Operator) (libseccomp.ScmpCompareOp, error) {
- switch op {
- case configs.EqualTo:
- return libseccomp.CompareEqual, nil
- case configs.NotEqualTo:
- return libseccomp.CompareNotEqual, nil
- case configs.GreaterThan:
- return libseccomp.CompareGreater, nil
- case configs.GreaterThanOrEqualTo:
- return libseccomp.CompareGreaterEqual, nil
- case configs.LessThan:
- return libseccomp.CompareLess, nil
- case configs.LessThanOrEqualTo:
- return libseccomp.CompareLessOrEqual, nil
- case configs.MaskEqualTo:
- return libseccomp.CompareMaskedEqual, nil
- default:
- return libseccomp.CompareInvalid, fmt.Errorf("invalid operator, cannot use in rule")
- }
-}
-
-// Convert Libcontainer Arg to Libseccomp ScmpCondition
-func getCondition(arg *configs.Arg) (libseccomp.ScmpCondition, error) {
- cond := libseccomp.ScmpCondition{}
-
- if arg == nil {
- return cond, fmt.Errorf("cannot convert nil to syscall condition")
- }
-
- op, err := getOperator(arg.Op)
- if err != nil {
- return cond, err
- }
-
- return libseccomp.MakeCondition(arg.Index, op, arg.Value, arg.ValueTwo)
-}
-
-// Add a rule to match a single syscall
-func matchCall(filter *libseccomp.ScmpFilter, call *configs.Syscall) error {
- if call == nil || filter == nil {
- return fmt.Errorf("cannot use nil as syscall to block")
- }
-
- if len(call.Name) == 0 {
- return fmt.Errorf("empty string is not a valid syscall")
- }
-
- // If we can't resolve the syscall, assume it's not supported on this kernel
- // Ignore it, don't error out
- callNum, err := libseccomp.GetSyscallFromName(call.Name)
- if err != nil {
- log.Printf("Error resolving syscall name %s: %s - ignoring syscall.", call.Name, err)
- return nil
- }
-
- // Convert the call's action to the libseccomp equivalent
- callAct, err := getAction(call.Action)
- if err != nil {
- return err
- }
-
- // Unconditional match - just add the rule
- if len(call.Args) == 0 {
- if err = filter.AddRule(callNum, callAct); err != nil {
- return err
- }
- } else {
- // Conditional match - convert the per-arg rules into library format
- conditions := []libseccomp.ScmpCondition{}
-
- for _, cond := range call.Args {
- newCond, err := getCondition(cond)
- if err != nil {
- return err
- }
-
- conditions = append(conditions, newCond)
- }
-
- if err = filter.AddRuleConditional(callNum, callAct, conditions); err != nil {
- return err
- }
- }
-
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_unsupported.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_unsupported.go
deleted file mode 100644
index 87d3abb..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/seccomp/seccomp_unsupported.go
+++ /dev/null
@@ -1,19 +0,0 @@
-// +build !linux !cgo !seccomp
-
-package seccomp
-
-import (
- "errors"
-
- "github.com/opencontainers/runc/libcontainer/configs"
-)
-
-var ErrSeccompNotEnabled = errors.New("seccomp: config provided but seccomp not supported")
-
-// Seccomp not supported, do nothing
-func InitSeccomp(config *configs.Seccomp) error {
- if config != nil {
- return ErrSeccompNotEnabled
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/selinux/selinux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/selinux/selinux.go
deleted file mode 100644
index 2771bb5..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/selinux/selinux.go
+++ /dev/null
@@ -1,469 +0,0 @@
-// +build linux
-
-package selinux
-
-import (
- "bufio"
- "crypto/rand"
- "encoding/binary"
- "fmt"
- "io"
- "os"
- "path/filepath"
- "regexp"
- "strconv"
- "strings"
- "syscall"
-
- "github.com/docker/docker/pkg/mount"
- "github.com/opencontainers/runc/libcontainer/system"
-)
-
-const (
- Enforcing = 1
- Permissive = 0
- Disabled = -1
- selinuxDir = "/etc/selinux/"
- selinuxConfig = selinuxDir + "config"
- selinuxTypeTag = "SELINUXTYPE"
- selinuxTag = "SELINUX"
- selinuxPath = "/sys/fs/selinux"
- xattrNameSelinux = "security.selinux"
- stRdOnly = 0x01
-)
-
-var (
- assignRegex = regexp.MustCompile(`^([^=]+)=(.*)$`)
- mcsList = make(map[string]bool)
- selinuxfs = "unknown"
- selinuxEnabled = false // Stores whether selinux is currently enabled
- selinuxEnabledChecked = false // Stores whether selinux enablement has been checked or established yet
-)
-
-type SELinuxContext map[string]string
-
-// SetDisabled disables selinux support for the package
-func SetDisabled() {
- selinuxEnabled, selinuxEnabledChecked = false, true
-}
-
-// getSelinuxMountPoint returns the path to the mountpoint of an selinuxfs
-// filesystem or an empty string if no mountpoint is found. Selinuxfs is
-// a proc-like pseudo-filesystem that exposes the selinux policy API to
-// processes. The existence of an selinuxfs mount is used to determine
-// whether selinux is currently enabled or not.
-func getSelinuxMountPoint() string {
- if selinuxfs != "unknown" {
- return selinuxfs
- }
- selinuxfs = ""
-
- mounts, err := mount.GetMounts()
- if err != nil {
- return selinuxfs
- }
- for _, mount := range mounts {
- if mount.Fstype == "selinuxfs" {
- selinuxfs = mount.Mountpoint
- break
- }
- }
- if selinuxfs != "" {
- var buf syscall.Statfs_t
- syscall.Statfs(selinuxfs, &buf)
- if (buf.Flags & stRdOnly) == 1 {
- selinuxfs = ""
- }
- }
- return selinuxfs
-}
-
-// SelinuxEnabled returns whether selinux is currently enabled.
-func SelinuxEnabled() bool {
- if selinuxEnabledChecked {
- return selinuxEnabled
- }
- selinuxEnabledChecked = true
- if fs := getSelinuxMountPoint(); fs != "" {
- if con, _ := Getcon(); con != "kernel" {
- selinuxEnabled = true
- }
- }
- return selinuxEnabled
-}
-
-func readConfig(target string) (value string) {
- var (
- val, key string
- bufin *bufio.Reader
- )
-
- in, err := os.Open(selinuxConfig)
- if err != nil {
- return ""
- }
- defer in.Close()
-
- bufin = bufio.NewReader(in)
-
- for done := false; !done; {
- var line string
- if line, err = bufin.ReadString('\n'); err != nil {
- if err != io.EOF {
- return ""
- }
- done = true
- }
- line = strings.TrimSpace(line)
- if len(line) == 0 {
- // Skip blank lines
- continue
- }
- if line[0] == ';' || line[0] == '#' {
- // Skip comments
- continue
- }
- if groups := assignRegex.FindStringSubmatch(line); groups != nil {
- key, val = strings.TrimSpace(groups[1]), strings.TrimSpace(groups[2])
- if key == target {
- return strings.Trim(val, "\"")
- }
- }
- }
- return ""
-}
-
-func getSELinuxPolicyRoot() string {
- return selinuxDir + readConfig(selinuxTypeTag)
-}
-
-func readCon(name string) (string, error) {
- var val string
-
- in, err := os.Open(name)
- if err != nil {
- return "", err
- }
- defer in.Close()
-
- _, err = fmt.Fscanf(in, "%s", &val)
- return val, err
-}
-
-// Setfilecon sets the SELinux label for this path or returns an error.
-func Setfilecon(path string, scon string) error {
- return system.Lsetxattr(path, xattrNameSelinux, []byte(scon), 0)
-}
-
-// Getfilecon returns the SELinux label for this path or returns an error.
-func Getfilecon(path string) (string, error) {
- con, err := system.Lgetxattr(path, xattrNameSelinux)
-
- // Trim the NUL byte at the end of the byte buffer, if present.
- if con[len(con)-1] == '\x00' {
- con = con[:len(con)-1]
- }
- return string(con), err
-}
-
-func Setfscreatecon(scon string) error {
- return writeCon(fmt.Sprintf("/proc/self/task/%d/attr/fscreate", syscall.Gettid()), scon)
-}
-
-func Getfscreatecon() (string, error) {
- return readCon(fmt.Sprintf("/proc/self/task/%d/attr/fscreate", syscall.Gettid()))
-}
-
-// Getcon returns the SELinux label of the current process thread, or an error.
-func Getcon() (string, error) {
- return readCon(fmt.Sprintf("/proc/self/task/%d/attr/current", syscall.Gettid()))
-}
-
-// Getpidcon returns the SELinux label of the given pid, or an error.
-func Getpidcon(pid int) (string, error) {
- return readCon(fmt.Sprintf("/proc/%d/attr/current", pid))
-}
-
-func Getexeccon() (string, error) {
- return readCon(fmt.Sprintf("/proc/self/task/%d/attr/exec", syscall.Gettid()))
-}
-
-func writeCon(name string, val string) error {
- out, err := os.OpenFile(name, os.O_WRONLY, 0)
- if err != nil {
- return err
- }
- defer out.Close()
-
- if val != "" {
- _, err = out.Write([]byte(val))
- } else {
- _, err = out.Write(nil)
- }
- return err
-}
-
-func Setexeccon(scon string) error {
- return writeCon(fmt.Sprintf("/proc/self/task/%d/attr/exec", syscall.Gettid()), scon)
-}
-
-func (c SELinuxContext) Get() string {
- return fmt.Sprintf("%s:%s:%s:%s", c["user"], c["role"], c["type"], c["level"])
-}
-
-func NewContext(scon string) SELinuxContext {
- c := make(SELinuxContext)
-
- if len(scon) != 0 {
- con := strings.SplitN(scon, ":", 4)
- c["user"] = con[0]
- c["role"] = con[1]
- c["type"] = con[2]
- c["level"] = con[3]
- }
- return c
-}
-
-func ReserveLabel(scon string) {
- if len(scon) != 0 {
- con := strings.SplitN(scon, ":", 4)
- mcsAdd(con[3])
- }
-}
-
-func SelinuxGetEnforce() int {
- var enforce int
-
- enforceS, err := readCon(fmt.Sprintf("%s/enforce", selinuxPath))
- if err != nil {
- return -1
- }
-
- enforce, err = strconv.Atoi(string(enforceS))
- if err != nil {
- return -1
- }
- return enforce
-}
-
-func SelinuxGetEnforceMode() int {
- switch readConfig(selinuxTag) {
- case "enforcing":
- return Enforcing
- case "permissive":
- return Permissive
- }
- return Disabled
-}
-
-func mcsAdd(mcs string) error {
- if mcsList[mcs] {
- return fmt.Errorf("MCS Label already exists")
- }
- mcsList[mcs] = true
- return nil
-}
-
-func mcsDelete(mcs string) {
- mcsList[mcs] = false
-}
-
-func IntToMcs(id int, catRange uint32) string {
- var (
- SETSIZE = int(catRange)
- TIER = SETSIZE
- ORD = id
- )
-
- if id < 1 || id > 523776 {
- return ""
- }
-
- for ORD > TIER {
- ORD = ORD - TIER
- TIER -= 1
- }
- TIER = SETSIZE - TIER
- ORD = ORD + TIER
- return fmt.Sprintf("s0:c%d,c%d", TIER, ORD)
-}
-
-func uniqMcs(catRange uint32) string {
- var (
- n uint32
- c1, c2 uint32
- mcs string
- )
-
- for {
- binary.Read(rand.Reader, binary.LittleEndian, &n)
- c1 = n % catRange
- binary.Read(rand.Reader, binary.LittleEndian, &n)
- c2 = n % catRange
- if c1 == c2 {
- continue
- } else {
- if c1 > c2 {
- t := c1
- c1 = c2
- c2 = t
- }
- }
- mcs = fmt.Sprintf("s0:c%d,c%d", c1, c2)
- if err := mcsAdd(mcs); err != nil {
- continue
- }
- break
- }
- return mcs
-}
-
-func FreeLxcContexts(scon string) {
- if len(scon) != 0 {
- con := strings.SplitN(scon, ":", 4)
- mcsDelete(con[3])
- }
-}
-
-func GetLxcContexts() (processLabel string, fileLabel string) {
- var (
- val, key string
- bufin *bufio.Reader
- )
-
- if !SelinuxEnabled() {
- return "", ""
- }
- lxcPath := fmt.Sprintf("%s/contexts/lxc_contexts", getSELinuxPolicyRoot())
- in, err := os.Open(lxcPath)
- if err != nil {
- return "", ""
- }
- defer in.Close()
-
- bufin = bufio.NewReader(in)
-
- for done := false; !done; {
- var line string
- if line, err = bufin.ReadString('\n'); err != nil {
- if err == io.EOF {
- done = true
- } else {
- goto exit
- }
- }
- line = strings.TrimSpace(line)
- if len(line) == 0 {
- // Skip blank lines
- continue
- }
- if line[0] == ';' || line[0] == '#' {
- // Skip comments
- continue
- }
- if groups := assignRegex.FindStringSubmatch(line); groups != nil {
- key, val = strings.TrimSpace(groups[1]), strings.TrimSpace(groups[2])
- if key == "process" {
- processLabel = strings.Trim(val, "\"")
- }
- if key == "file" {
- fileLabel = strings.Trim(val, "\"")
- }
- }
- }
-
- if processLabel == "" || fileLabel == "" {
- return "", ""
- }
-
-exit:
- // mcs := IntToMcs(os.Getpid(), 1024)
- mcs := uniqMcs(1024)
- scon := NewContext(processLabel)
- scon["level"] = mcs
- processLabel = scon.Get()
- scon = NewContext(fileLabel)
- scon["level"] = mcs
- fileLabel = scon.Get()
- return processLabel, fileLabel
-}
-
-func SecurityCheckContext(val string) error {
- return writeCon(fmt.Sprintf("%s.context", selinuxPath), val)
-}
-
-func CopyLevel(src, dest string) (string, error) {
- if src == "" {
- return "", nil
- }
- if err := SecurityCheckContext(src); err != nil {
- return "", err
- }
- if err := SecurityCheckContext(dest); err != nil {
- return "", err
- }
- scon := NewContext(src)
- tcon := NewContext(dest)
- mcsDelete(tcon["level"])
- mcsAdd(scon["level"])
- tcon["level"] = scon["level"]
- return tcon.Get(), nil
-}
-
-// Prevent users from relabing system files
-func badPrefix(fpath string) error {
- var badprefixes = []string{"/usr"}
-
- for _, prefix := range badprefixes {
- if fpath == prefix || strings.HasPrefix(fpath, fmt.Sprintf("%s/", prefix)) {
- return fmt.Errorf("Relabeling content in %s is not allowed.", prefix)
- }
- }
- return nil
-}
-
-// Change the fpath file object to the SELinux label scon.
-// If the fpath is a directory and recurse is true Chcon will walk the
-// directory tree setting the label
-func Chcon(fpath string, scon string, recurse bool) error {
- if scon == "" {
- return nil
- }
- if err := badPrefix(fpath); err != nil {
- return err
- }
- callback := func(p string, info os.FileInfo, err error) error {
- return Setfilecon(p, scon)
- }
-
- if recurse {
- return filepath.Walk(fpath, callback)
- }
-
- return Setfilecon(fpath, scon)
-}
-
-// DupSecOpt takes an SELinux process label and returns security options that
-// can will set the SELinux Type and Level for future container processes
-func DupSecOpt(src string) []string {
- if src == "" {
- return nil
- }
- con := NewContext(src)
- if con["user"] == "" ||
- con["role"] == "" ||
- con["type"] == "" ||
- con["level"] == "" {
- return nil
- }
- return []string{"label:user:" + con["user"],
- "label:role:" + con["role"],
- "label:type:" + con["type"],
- "label:level:" + con["level"]}
-}
-
-// DisableSecOpt returns a security opt that can be used to disabling SELinux
-// labeling support for future container processes
-func DisableSecOpt() []string {
- return []string{"label:disable"}
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/setgroups_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/setgroups_linux.go
deleted file mode 100644
index c7bdb60..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/setgroups_linux.go
+++ /dev/null
@@ -1,11 +0,0 @@
-// +build linux,go1.5
-
-package libcontainer
-
-import "syscall"
-
-// Set the GidMappingsEnableSetgroups member to true, so the process's
-// setgroups proc entry wont be set to 'deny' if GidMappings are set
-func enableSetgroups(sys *syscall.SysProcAttr) {
- sys.GidMappingsEnableSetgroups = true
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/setns_init_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/setns_init_linux.go
deleted file mode 100644
index 2bde44f..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/setns_init_linux.go
+++ /dev/null
@@ -1,44 +0,0 @@
-// +build linux
-
-package libcontainer
-
-import (
- "os"
-
- "github.com/opencontainers/runc/libcontainer/apparmor"
- "github.com/opencontainers/runc/libcontainer/label"
- "github.com/opencontainers/runc/libcontainer/seccomp"
- "github.com/opencontainers/runc/libcontainer/system"
-)
-
-// linuxSetnsInit performs the container's initialization for running a new process
-// inside an existing container.
-type linuxSetnsInit struct {
- config *initConfig
-}
-
-func (l *linuxSetnsInit) Init() error {
- if err := setupRlimits(l.config.Config); err != nil {
- return err
- }
- if err := setOomScoreAdj(l.config.Config.OomScoreAdj); err != nil {
- return err
- }
- if l.config.Config.Seccomp != nil {
- if err := seccomp.InitSeccomp(l.config.Config.Seccomp); err != nil {
- return err
- }
- }
- if err := finalizeNamespace(l.config); err != nil {
- return err
- }
- if err := apparmor.ApplyProfile(l.config.Config.AppArmorProfile); err != nil {
- return err
- }
- if l.config.Config.ProcessLabel != "" {
- if err := label.SetProcessLabel(l.config.Config.ProcessLabel); err != nil {
- return err
- }
- }
- return system.Execv(l.config.Args[0], l.config.Args[0:], os.Environ())
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/capture.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/capture.go
deleted file mode 100644
index 5ee6e37..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/capture.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package stacktrace
-
-import "runtime"
-
-// Caputure captures a stacktrace for the current calling go program
-//
-// skip is the number of frames to skip
-func Capture(userSkip int) Stacktrace {
- var (
- skip = userSkip + 1 // add one for our own function
- frames []Frame
- prevPc uintptr = 0
- )
- for i := skip; ; i++ {
- pc, file, line, ok := runtime.Caller(i)
- //detect if caller is repeated to avoid loop, gccgo
- //currently runs into a loop without this check
- if !ok || pc == prevPc {
- break
- }
- frames = append(frames, NewFrame(pc, file, line))
- prevPc = pc
- }
- return Stacktrace{
- Frames: frames,
- }
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/frame.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/frame.go
deleted file mode 100644
index 0d590d9..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/frame.go
+++ /dev/null
@@ -1,38 +0,0 @@
-package stacktrace
-
-import (
- "path/filepath"
- "runtime"
- "strings"
-)
-
-// NewFrame returns a new stack frame for the provided information
-func NewFrame(pc uintptr, file string, line int) Frame {
- fn := runtime.FuncForPC(pc)
- if fn == nil {
- return Frame{}
- }
- pack, name := parseFunctionName(fn.Name())
- return Frame{
- Line: line,
- File: filepath.Base(file),
- Package: pack,
- Function: name,
- }
-}
-
-func parseFunctionName(name string) (string, string) {
- i := strings.LastIndex(name, ".")
- if i == -1 {
- return "", name
- }
- return name[:i], name[i+1:]
-}
-
-// Frame contains all the information for a stack frame within a go program
-type Frame struct {
- File string
- Function string
- Package string
- Line int
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/stacktrace.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/stacktrace.go
deleted file mode 100644
index 5e8b58d..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/stacktrace/stacktrace.go
+++ /dev/null
@@ -1,5 +0,0 @@
-package stacktrace
-
-type Stacktrace struct {
- Frames []Frame
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/standard_init_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/standard_init_linux.go
deleted file mode 100644
index ec10057..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/standard_init_linux.go
+++ /dev/null
@@ -1,113 +0,0 @@
-// +build linux
-
-package libcontainer
-
-import (
- "os"
- "syscall"
-
- "github.com/opencontainers/runc/libcontainer/apparmor"
- "github.com/opencontainers/runc/libcontainer/configs"
- "github.com/opencontainers/runc/libcontainer/label"
- "github.com/opencontainers/runc/libcontainer/seccomp"
- "github.com/opencontainers/runc/libcontainer/system"
-)
-
-type linuxStandardInit struct {
- parentPid int
- config *initConfig
-}
-
-func (l *linuxStandardInit) Init() error {
- // join any namespaces via a path to the namespace fd if provided
- if err := joinExistingNamespaces(l.config.Config.Namespaces); err != nil {
- return err
- }
- var console *linuxConsole
- if l.config.Console != "" {
- console = newConsoleFromPath(l.config.Console)
- if err := console.dupStdio(); err != nil {
- return err
- }
- }
- if _, err := syscall.Setsid(); err != nil {
- return err
- }
- if console != nil {
- if err := system.Setctty(); err != nil {
- return err
- }
- }
- if err := setupNetwork(l.config); err != nil {
- return err
- }
- if err := setupRoute(l.config.Config); err != nil {
- return err
- }
- if err := setupRlimits(l.config.Config); err != nil {
- return err
- }
- if err := setOomScoreAdj(l.config.Config.OomScoreAdj); err != nil {
- return err
- }
-
- label.Init()
- // InitializeMountNamespace() can be executed only for a new mount namespace
- if l.config.Config.Namespaces.Contains(configs.NEWNS) {
- if err := setupRootfs(l.config.Config, console); err != nil {
- return err
- }
- }
- if hostname := l.config.Config.Hostname; hostname != "" {
- if err := syscall.Sethostname([]byte(hostname)); err != nil {
- return err
- }
- }
- if err := apparmor.ApplyProfile(l.config.Config.AppArmorProfile); err != nil {
- return err
- }
- if err := label.SetProcessLabel(l.config.Config.ProcessLabel); err != nil {
- return err
- }
-
- for key, value := range l.config.Config.Sysctl {
- if err := writeSystemProperty(key, value); err != nil {
- return err
- }
- }
-
- for _, path := range l.config.Config.ReadonlyPaths {
- if err := remountReadonly(path); err != nil {
- return err
- }
- }
- for _, path := range l.config.Config.MaskPaths {
- if err := maskFile(path); err != nil {
- return err
- }
- }
- pdeath, err := system.GetParentDeathSignal()
- if err != nil {
- return err
- }
- if l.config.Config.Seccomp != nil {
- if err := seccomp.InitSeccomp(l.config.Config.Seccomp); err != nil {
- return err
- }
- }
- if err := finalizeNamespace(l.config); err != nil {
- return err
- }
- // finalizeNamespace can change user/group which clears the parent death
- // signal, so we restore it here.
- if err := pdeath.Restore(); err != nil {
- return err
- }
- // compare the parent from the inital start of the init process and make sure that it did not change.
- // if the parent changes that means it died and we were reparened to something else so we should
- // just kill ourself and not cause problems for someone else.
- if syscall.Getppid() != l.parentPid {
- return syscall.Kill(syscall.Getpid(), syscall.SIGKILL)
- }
- return system.Execv(l.config.Args[0], l.config.Args[0:], os.Environ())
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/stats.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/stats.go
deleted file mode 100644
index 303e4b9..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/stats.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package libcontainer
-
-type NetworkInterface struct {
- // Name is the name of the network interface.
- Name string
-
- RxBytes uint64
- RxPackets uint64
- RxErrors uint64
- RxDropped uint64
- TxBytes uint64
- TxPackets uint64
- TxErrors uint64
- TxDropped uint64
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/stats_freebsd.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/stats_freebsd.go
deleted file mode 100644
index f8d1d68..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/stats_freebsd.go
+++ /dev/null
@@ -1,5 +0,0 @@
-package libcontainer
-
-type Stats struct {
- Interfaces []*NetworkInterface
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/stats_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/stats_linux.go
deleted file mode 100644
index c629dc6..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/stats_linux.go
+++ /dev/null
@@ -1,8 +0,0 @@
-package libcontainer
-
-import "github.com/opencontainers/runc/libcontainer/cgroups"
-
-type Stats struct {
- Interfaces []*NetworkInterface
- CgroupStats *cgroups.Stats
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/stats_windows.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/stats_windows.go
deleted file mode 100644
index f8d1d68..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/stats_windows.go
+++ /dev/null
@@ -1,5 +0,0 @@
-package libcontainer
-
-type Stats struct {
- Interfaces []*NetworkInterface
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/linux.go
deleted file mode 100644
index 2cc3ef8..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/linux.go
+++ /dev/null
@@ -1,77 +0,0 @@
-// +build linux
-
-package system
-
-import (
- "os/exec"
- "syscall"
- "unsafe"
-)
-
-type ParentDeathSignal int
-
-func (p ParentDeathSignal) Restore() error {
- if p == 0 {
- return nil
- }
- current, err := GetParentDeathSignal()
- if err != nil {
- return err
- }
- if p == current {
- return nil
- }
- return p.Set()
-}
-
-func (p ParentDeathSignal) Set() error {
- return SetParentDeathSignal(uintptr(p))
-}
-
-func Execv(cmd string, args []string, env []string) error {
- name, err := exec.LookPath(cmd)
- if err != nil {
- return err
- }
-
- return syscall.Exec(name, args, env)
-}
-
-func SetParentDeathSignal(sig uintptr) error {
- if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_SET_PDEATHSIG, sig, 0); err != 0 {
- return err
- }
- return nil
-}
-
-func GetParentDeathSignal() (ParentDeathSignal, error) {
- var sig int
- _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_GET_PDEATHSIG, uintptr(unsafe.Pointer(&sig)), 0)
- if err != 0 {
- return -1, err
- }
- return ParentDeathSignal(sig), nil
-}
-
-func SetKeepCaps() error {
- if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_SET_KEEPCAPS, 1, 0); err != 0 {
- return err
- }
-
- return nil
-}
-
-func ClearKeepCaps() error {
- if _, _, err := syscall.RawSyscall(syscall.SYS_PRCTL, syscall.PR_SET_KEEPCAPS, 0, 0); err != 0 {
- return err
- }
-
- return nil
-}
-
-func Setctty() error {
- if _, _, err := syscall.RawSyscall(syscall.SYS_IOCTL, 0, uintptr(syscall.TIOCSCTTY), 0); err != 0 {
- return err
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/proc.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/proc.go
deleted file mode 100644
index 37808a2..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/proc.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package system
-
-import (
- "io/ioutil"
- "path/filepath"
- "strconv"
- "strings"
-)
-
-// look in /proc to find the process start time so that we can verify
-// that this pid has started after ourself
-func GetProcessStartTime(pid int) (string, error) {
- data, err := ioutil.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat"))
- if err != nil {
- return "", err
- }
-
- parts := strings.Split(string(data), " ")
- // the starttime is located at pos 22
- // from the man page
- //
- // starttime %llu (was %lu before Linux 2.6)
- // (22) The time the process started after system boot. In kernels before Linux 2.6, this
- // value was expressed in jiffies. Since Linux 2.6, the value is expressed in clock ticks
- // (divide by sysconf(_SC_CLK_TCK)).
- return parts[22-1], nil // starts at 1
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/setns_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/setns_linux.go
deleted file mode 100644
index 615ff4c..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/setns_linux.go
+++ /dev/null
@@ -1,40 +0,0 @@
-package system
-
-import (
- "fmt"
- "runtime"
- "syscall"
-)
-
-// Via http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=7b21fddd087678a70ad64afc0f632e0f1071b092
-//
-// We need different setns values for the different platforms and arch
-// We are declaring the macro here because the SETNS syscall does not exist in th stdlib
-var setNsMap = map[string]uintptr{
- "linux/386": 346,
- "linux/arm64": 268,
- "linux/amd64": 308,
- "linux/arm": 375,
- "linux/ppc": 350,
- "linux/ppc64": 350,
- "linux/ppc64le": 350,
- "linux/s390x": 339,
-}
-
-var sysSetns = setNsMap[fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)]
-
-func SysSetns() uint32 {
- return uint32(sysSetns)
-}
-
-func Setns(fd uintptr, flags uintptr) error {
- ns, exists := setNsMap[fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)]
- if !exists {
- return fmt.Errorf("unsupported platform %s/%s", runtime.GOOS, runtime.GOARCH)
- }
- _, _, err := syscall.RawSyscall(ns, fd, flags, 0)
- if err != 0 {
- return err
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_386.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_386.go
deleted file mode 100644
index c990065..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_386.go
+++ /dev/null
@@ -1,25 +0,0 @@
-// +build linux,386
-
-package system
-
-import (
- "syscall"
-)
-
-// Setuid sets the uid of the calling thread to the specified uid.
-func Setuid(uid int) (err error) {
- _, _, e1 := syscall.RawSyscall(syscall.SYS_SETUID, uintptr(uid), 0, 0)
- if e1 != 0 {
- err = e1
- }
- return
-}
-
-// Setgid sets the gid of the calling thread to the specified gid.
-func Setgid(gid int) (err error) {
- _, _, e1 := syscall.RawSyscall(syscall.SYS_SETGID32, uintptr(gid), 0, 0)
- if e1 != 0 {
- err = e1
- }
- return
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_64.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_64.go
deleted file mode 100644
index 0816bf8..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_64.go
+++ /dev/null
@@ -1,25 +0,0 @@
-// +build linux,arm64 linux,amd64 linux,ppc linux,ppc64 linux,ppc64le linux,s390x
-
-package system
-
-import (
- "syscall"
-)
-
-// Setuid sets the uid of the calling thread to the specified uid.
-func Setuid(uid int) (err error) {
- _, _, e1 := syscall.RawSyscall(syscall.SYS_SETUID, uintptr(uid), 0, 0)
- if e1 != 0 {
- err = e1
- }
- return
-}
-
-// Setgid sets the gid of the calling thread to the specified gid.
-func Setgid(gid int) (err error) {
- _, _, e1 := syscall.RawSyscall(syscall.SYS_SETGID, uintptr(gid), 0, 0)
- if e1 != 0 {
- err = e1
- }
- return
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_arm.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_arm.go
deleted file mode 100644
index 3f780f3..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/syscall_linux_arm.go
+++ /dev/null
@@ -1,25 +0,0 @@
-// +build linux,arm
-
-package system
-
-import (
- "syscall"
-)
-
-// Setuid sets the uid of the calling thread to the specified uid.
-func Setuid(uid int) (err error) {
- _, _, e1 := syscall.RawSyscall(syscall.SYS_SETUID32, uintptr(uid), 0, 0)
- if e1 != 0 {
- err = e1
- }
- return
-}
-
-// Setgid sets the gid of the calling thread to the specified gid.
-func Setgid(gid int) (err error) {
- _, _, e1 := syscall.RawSyscall(syscall.SYS_SETGID32, uintptr(gid), 0, 0)
- if e1 != 0 {
- err = e1
- }
- return
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/sysconfig.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/sysconfig.go
deleted file mode 100644
index b3a07cb..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/sysconfig.go
+++ /dev/null
@@ -1,12 +0,0 @@
-// +build cgo,linux cgo,freebsd
-
-package system
-
-/*
-#include
-*/
-import "C"
-
-func GetClockTicks() int {
- return int(C.sysconf(C._SC_CLK_TCK))
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/sysconfig_notcgo.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/sysconfig_notcgo.go
deleted file mode 100644
index d93b5d5..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/sysconfig_notcgo.go
+++ /dev/null
@@ -1,15 +0,0 @@
-// +build !cgo windows
-
-package system
-
-func GetClockTicks() int {
- // TODO figure out a better alternative for platforms where we're missing cgo
- //
- // TODO Windows. This could be implemented using Win32 QueryPerformanceFrequency().
- // https://msdn.microsoft.com/en-us/library/windows/desktop/ms644905(v=vs.85).aspx
- //
- // An example of its usage can be found here.
- // https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx
-
- return 100
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/xattrs_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/xattrs_linux.go
deleted file mode 100644
index 30f74df..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/system/xattrs_linux.go
+++ /dev/null
@@ -1,99 +0,0 @@
-package system
-
-import (
- "syscall"
- "unsafe"
-)
-
-var _zero uintptr
-
-// Returns the size of xattrs and nil error
-// Requires path, takes allocated []byte or nil as last argument
-func Llistxattr(path string, dest []byte) (size int, err error) {
- pathBytes, err := syscall.BytePtrFromString(path)
- if err != nil {
- return -1, err
- }
- var newpathBytes unsafe.Pointer
- if len(dest) > 0 {
- newpathBytes = unsafe.Pointer(&dest[0])
- } else {
- newpathBytes = unsafe.Pointer(&_zero)
- }
-
- _size, _, errno := syscall.Syscall6(syscall.SYS_LLISTXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(newpathBytes), uintptr(len(dest)), 0, 0, 0)
- size = int(_size)
- if errno != 0 {
- return -1, errno
- }
-
- return size, nil
-}
-
-// Returns a []byte slice if the xattr is set and nil otherwise
-// Requires path and its attribute as arguments
-func Lgetxattr(path string, attr string) ([]byte, error) {
- var sz int
- pathBytes, err := syscall.BytePtrFromString(path)
- if err != nil {
- return nil, err
- }
- attrBytes, err := syscall.BytePtrFromString(attr)
- if err != nil {
- return nil, err
- }
-
- // Start with a 128 length byte array
- sz = 128
- dest := make([]byte, sz)
- destBytes := unsafe.Pointer(&dest[0])
- _sz, _, errno := syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0)
-
- switch {
- case errno == syscall.ENODATA:
- return nil, errno
- case errno == syscall.ENOTSUP:
- return nil, errno
- case errno == syscall.ERANGE:
- // 128 byte array might just not be good enough,
- // A dummy buffer is used ``uintptr(0)`` to get real size
- // of the xattrs on disk
- _sz, _, errno = syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(unsafe.Pointer(nil)), uintptr(0), 0, 0)
- sz = int(_sz)
- if sz < 0 {
- return nil, errno
- }
- dest = make([]byte, sz)
- destBytes := unsafe.Pointer(&dest[0])
- _sz, _, errno = syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0)
- if errno != 0 {
- return nil, errno
- }
- case errno != 0:
- return nil, errno
- }
- sz = int(_sz)
- return dest[:sz], nil
-}
-
-func Lsetxattr(path string, attr string, data []byte, flags int) error {
- pathBytes, err := syscall.BytePtrFromString(path)
- if err != nil {
- return err
- }
- attrBytes, err := syscall.BytePtrFromString(attr)
- if err != nil {
- return err
- }
- var dataBytes unsafe.Pointer
- if len(data) > 0 {
- dataBytes = unsafe.Pointer(&data[0])
- } else {
- dataBytes = unsafe.Pointer(&_zero)
- }
- _, _, errno := syscall.Syscall6(syscall.SYS_LSETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(dataBytes), uintptr(len(data)), uintptr(flags), 0)
- if errno != 0 {
- return errno
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/user/MAINTAINERS b/containerd/vendor/github.com/opencontainers/runc/libcontainer/user/MAINTAINERS
deleted file mode 100644
index edbe200..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/user/MAINTAINERS
+++ /dev/null
@@ -1,2 +0,0 @@
-Tianon Gravi (@tianon)
-Aleksa Sarai (@cyphar)
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/user/lookup.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/user/lookup.go
deleted file mode 100644
index 6f8a982..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/user/lookup.go
+++ /dev/null
@@ -1,108 +0,0 @@
-package user
-
-import (
- "errors"
- "fmt"
- "syscall"
-)
-
-var (
- // The current operating system does not provide the required data for user lookups.
- ErrUnsupported = errors.New("user lookup: operating system does not provide passwd-formatted data")
-)
-
-func lookupUser(filter func(u User) bool) (User, error) {
- // Get operating system-specific passwd reader-closer.
- passwd, err := GetPasswd()
- if err != nil {
- return User{}, err
- }
- defer passwd.Close()
-
- // Get the users.
- users, err := ParsePasswdFilter(passwd, filter)
- if err != nil {
- return User{}, err
- }
-
- // No user entries found.
- if len(users) == 0 {
- return User{}, fmt.Errorf("no matching entries in passwd file")
- }
-
- // Assume the first entry is the "correct" one.
- return users[0], nil
-}
-
-// CurrentUser looks up the current user by their user id in /etc/passwd. If the
-// user cannot be found (or there is no /etc/passwd file on the filesystem),
-// then CurrentUser returns an error.
-func CurrentUser() (User, error) {
- return LookupUid(syscall.Getuid())
-}
-
-// LookupUser looks up a user by their username in /etc/passwd. If the user
-// cannot be found (or there is no /etc/passwd file on the filesystem), then
-// LookupUser returns an error.
-func LookupUser(username string) (User, error) {
- return lookupUser(func(u User) bool {
- return u.Name == username
- })
-}
-
-// LookupUid looks up a user by their user id in /etc/passwd. If the user cannot
-// be found (or there is no /etc/passwd file on the filesystem), then LookupId
-// returns an error.
-func LookupUid(uid int) (User, error) {
- return lookupUser(func(u User) bool {
- return u.Uid == uid
- })
-}
-
-func lookupGroup(filter func(g Group) bool) (Group, error) {
- // Get operating system-specific group reader-closer.
- group, err := GetGroup()
- if err != nil {
- return Group{}, err
- }
- defer group.Close()
-
- // Get the users.
- groups, err := ParseGroupFilter(group, filter)
- if err != nil {
- return Group{}, err
- }
-
- // No user entries found.
- if len(groups) == 0 {
- return Group{}, fmt.Errorf("no matching entries in group file")
- }
-
- // Assume the first entry is the "correct" one.
- return groups[0], nil
-}
-
-// CurrentGroup looks up the current user's group by their primary group id's
-// entry in /etc/passwd. If the group cannot be found (or there is no
-// /etc/group file on the filesystem), then CurrentGroup returns an error.
-func CurrentGroup() (Group, error) {
- return LookupGid(syscall.Getgid())
-}
-
-// LookupGroup looks up a group by its name in /etc/group. If the group cannot
-// be found (or there is no /etc/group file on the filesystem), then LookupGroup
-// returns an error.
-func LookupGroup(groupname string) (Group, error) {
- return lookupGroup(func(g Group) bool {
- return g.Name == groupname
- })
-}
-
-// LookupGid looks up a group by its group id in /etc/group. If the group cannot
-// be found (or there is no /etc/group file on the filesystem), then LookupGid
-// returns an error.
-func LookupGid(gid int) (Group, error) {
- return lookupGroup(func(g Group) bool {
- return g.Gid == gid
- })
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/user/lookup_unix.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/user/lookup_unix.go
deleted file mode 100644
index 758b734..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/user/lookup_unix.go
+++ /dev/null
@@ -1,30 +0,0 @@
-// +build darwin dragonfly freebsd linux netbsd openbsd solaris
-
-package user
-
-import (
- "io"
- "os"
-)
-
-// Unix-specific path to the passwd and group formatted files.
-const (
- unixPasswdPath = "/etc/passwd"
- unixGroupPath = "/etc/group"
-)
-
-func GetPasswdPath() (string, error) {
- return unixPasswdPath, nil
-}
-
-func GetPasswd() (io.ReadCloser, error) {
- return os.Open(unixPasswdPath)
-}
-
-func GetGroupPath() (string, error) {
- return unixGroupPath, nil
-}
-
-func GetGroup() (io.ReadCloser, error) {
- return os.Open(unixGroupPath)
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/user/lookup_unsupported.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/user/lookup_unsupported.go
deleted file mode 100644
index 7217948..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/user/lookup_unsupported.go
+++ /dev/null
@@ -1,21 +0,0 @@
-// +build !darwin,!dragonfly,!freebsd,!linux,!netbsd,!openbsd,!solaris
-
-package user
-
-import "io"
-
-func GetPasswdPath() (string, error) {
- return "", ErrUnsupported
-}
-
-func GetPasswd() (io.ReadCloser, error) {
- return nil, ErrUnsupported
-}
-
-func GetGroupPath() (string, error) {
- return "", ErrUnsupported
-}
-
-func GetGroup() (io.ReadCloser, error) {
- return nil, ErrUnsupported
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/user/user.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/user/user.go
deleted file mode 100644
index e6375ea..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/user/user.go
+++ /dev/null
@@ -1,418 +0,0 @@
-package user
-
-import (
- "bufio"
- "fmt"
- "io"
- "os"
- "strconv"
- "strings"
-)
-
-const (
- minId = 0
- maxId = 1<<31 - 1 //for 32-bit systems compatibility
-)
-
-var (
- ErrRange = fmt.Errorf("Uids and gids must be in range %d-%d", minId, maxId)
-)
-
-type User struct {
- Name string
- Pass string
- Uid int
- Gid int
- Gecos string
- Home string
- Shell string
-}
-
-type Group struct {
- Name string
- Pass string
- Gid int
- List []string
-}
-
-func parseLine(line string, v ...interface{}) {
- if line == "" {
- return
- }
-
- parts := strings.Split(line, ":")
- for i, p := range parts {
- if len(v) <= i {
- // if we have more "parts" than we have places to put them, bail for great "tolerance" of naughty configuration files
- break
- }
-
- switch e := v[i].(type) {
- case *string:
- // "root", "adm", "/bin/bash"
- *e = p
- case *int:
- // "0", "4", "1000"
- // ignore string to int conversion errors, for great "tolerance" of naughty configuration files
- *e, _ = strconv.Atoi(p)
- case *[]string:
- // "", "root", "root,adm,daemon"
- if p != "" {
- *e = strings.Split(p, ",")
- } else {
- *e = []string{}
- }
- default:
- // panic, because this is a programming/logic error, not a runtime one
- panic("parseLine expects only pointers! argument " + strconv.Itoa(i) + " is not a pointer!")
- }
- }
-}
-
-func ParsePasswdFile(path string) ([]User, error) {
- passwd, err := os.Open(path)
- if err != nil {
- return nil, err
- }
- defer passwd.Close()
- return ParsePasswd(passwd)
-}
-
-func ParsePasswd(passwd io.Reader) ([]User, error) {
- return ParsePasswdFilter(passwd, nil)
-}
-
-func ParsePasswdFileFilter(path string, filter func(User) bool) ([]User, error) {
- passwd, err := os.Open(path)
- if err != nil {
- return nil, err
- }
- defer passwd.Close()
- return ParsePasswdFilter(passwd, filter)
-}
-
-func ParsePasswdFilter(r io.Reader, filter func(User) bool) ([]User, error) {
- if r == nil {
- return nil, fmt.Errorf("nil source for passwd-formatted data")
- }
-
- var (
- s = bufio.NewScanner(r)
- out = []User{}
- )
-
- for s.Scan() {
- if err := s.Err(); err != nil {
- return nil, err
- }
-
- text := strings.TrimSpace(s.Text())
- if text == "" {
- continue
- }
-
- // see: man 5 passwd
- // name:password:UID:GID:GECOS:directory:shell
- // Name:Pass:Uid:Gid:Gecos:Home:Shell
- // root:x:0:0:root:/root:/bin/bash
- // adm:x:3:4:adm:/var/adm:/bin/false
- p := User{}
- parseLine(
- text,
- &p.Name, &p.Pass, &p.Uid, &p.Gid, &p.Gecos, &p.Home, &p.Shell,
- )
-
- if filter == nil || filter(p) {
- out = append(out, p)
- }
- }
-
- return out, nil
-}
-
-func ParseGroupFile(path string) ([]Group, error) {
- group, err := os.Open(path)
- if err != nil {
- return nil, err
- }
- defer group.Close()
- return ParseGroup(group)
-}
-
-func ParseGroup(group io.Reader) ([]Group, error) {
- return ParseGroupFilter(group, nil)
-}
-
-func ParseGroupFileFilter(path string, filter func(Group) bool) ([]Group, error) {
- group, err := os.Open(path)
- if err != nil {
- return nil, err
- }
- defer group.Close()
- return ParseGroupFilter(group, filter)
-}
-
-func ParseGroupFilter(r io.Reader, filter func(Group) bool) ([]Group, error) {
- if r == nil {
- return nil, fmt.Errorf("nil source for group-formatted data")
- }
-
- var (
- s = bufio.NewScanner(r)
- out = []Group{}
- )
-
- for s.Scan() {
- if err := s.Err(); err != nil {
- return nil, err
- }
-
- text := s.Text()
- if text == "" {
- continue
- }
-
- // see: man 5 group
- // group_name:password:GID:user_list
- // Name:Pass:Gid:List
- // root:x:0:root
- // adm:x:4:root,adm,daemon
- p := Group{}
- parseLine(
- text,
- &p.Name, &p.Pass, &p.Gid, &p.List,
- )
-
- if filter == nil || filter(p) {
- out = append(out, p)
- }
- }
-
- return out, nil
-}
-
-type ExecUser struct {
- Uid, Gid int
- Sgids []int
- Home string
-}
-
-// GetExecUserPath is a wrapper for GetExecUser. It reads data from each of the
-// given file paths and uses that data as the arguments to GetExecUser. If the
-// files cannot be opened for any reason, the error is ignored and a nil
-// io.Reader is passed instead.
-func GetExecUserPath(userSpec string, defaults *ExecUser, passwdPath, groupPath string) (*ExecUser, error) {
- passwd, err := os.Open(passwdPath)
- if err != nil {
- passwd = nil
- } else {
- defer passwd.Close()
- }
-
- group, err := os.Open(groupPath)
- if err != nil {
- group = nil
- } else {
- defer group.Close()
- }
-
- return GetExecUser(userSpec, defaults, passwd, group)
-}
-
-// GetExecUser parses a user specification string (using the passwd and group
-// readers as sources for /etc/passwd and /etc/group data, respectively). In
-// the case of blank fields or missing data from the sources, the values in
-// defaults is used.
-//
-// GetExecUser will return an error if a user or group literal could not be
-// found in any entry in passwd and group respectively.
-//
-// Examples of valid user specifications are:
-// * ""
-// * "user"
-// * "uid"
-// * "user:group"
-// * "uid:gid
-// * "user:gid"
-// * "uid:group"
-func GetExecUser(userSpec string, defaults *ExecUser, passwd, group io.Reader) (*ExecUser, error) {
- var (
- userArg, groupArg string
- name string
- )
-
- if defaults == nil {
- defaults = new(ExecUser)
- }
-
- // Copy over defaults.
- user := &ExecUser{
- Uid: defaults.Uid,
- Gid: defaults.Gid,
- Sgids: defaults.Sgids,
- Home: defaults.Home,
- }
-
- // Sgids slice *cannot* be nil.
- if user.Sgids == nil {
- user.Sgids = []int{}
- }
-
- // allow for userArg to have either "user" syntax, or optionally "user:group" syntax
- parseLine(userSpec, &userArg, &groupArg)
-
- users, err := ParsePasswdFilter(passwd, func(u User) bool {
- if userArg == "" {
- return u.Uid == user.Uid
- }
- return u.Name == userArg || strconv.Itoa(u.Uid) == userArg
- })
- if err != nil && passwd != nil {
- if userArg == "" {
- userArg = strconv.Itoa(user.Uid)
- }
- return nil, fmt.Errorf("Unable to find user %v: %v", userArg, err)
- }
-
- haveUser := users != nil && len(users) > 0
- if haveUser {
- // if we found any user entries that matched our filter, let's take the first one as "correct"
- name = users[0].Name
- user.Uid = users[0].Uid
- user.Gid = users[0].Gid
- user.Home = users[0].Home
- } else if userArg != "" {
- // we asked for a user but didn't find them... let's check to see if we wanted a numeric user
- user.Uid, err = strconv.Atoi(userArg)
- if err != nil {
- // not numeric - we have to bail
- return nil, fmt.Errorf("Unable to find user %v", userArg)
- }
-
- // Must be inside valid uid range.
- if user.Uid < minId || user.Uid > maxId {
- return nil, ErrRange
- }
-
- // if userArg couldn't be found in /etc/passwd but is numeric, just roll with it - this is legit
- }
-
- if groupArg != "" || name != "" {
- groups, err := ParseGroupFilter(group, func(g Group) bool {
- // Explicit group format takes precedence.
- if groupArg != "" {
- return g.Name == groupArg || strconv.Itoa(g.Gid) == groupArg
- }
-
- // Check if user is a member.
- for _, u := range g.List {
- if u == name {
- return true
- }
- }
-
- return false
- })
- if err != nil && group != nil {
- return nil, fmt.Errorf("Unable to find groups for user %v: %v", users[0].Name, err)
- }
-
- haveGroup := groups != nil && len(groups) > 0
- if groupArg != "" {
- if haveGroup {
- // if we found any group entries that matched our filter, let's take the first one as "correct"
- user.Gid = groups[0].Gid
- } else {
- // we asked for a group but didn't find id... let's check to see if we wanted a numeric group
- user.Gid, err = strconv.Atoi(groupArg)
- if err != nil {
- // not numeric - we have to bail
- return nil, fmt.Errorf("Unable to find group %v", groupArg)
- }
-
- // Ensure gid is inside gid range.
- if user.Gid < minId || user.Gid > maxId {
- return nil, ErrRange
- }
-
- // if groupArg couldn't be found in /etc/group but is numeric, just roll with it - this is legit
- }
- } else if haveGroup {
- // If implicit group format, fill supplementary gids.
- user.Sgids = make([]int, len(groups))
- for i, group := range groups {
- user.Sgids[i] = group.Gid
- }
- }
- }
-
- return user, nil
-}
-
-// GetAdditionalGroups looks up a list of groups by name or group id
-// against the given /etc/group formatted data. If a group name cannot
-// be found, an error will be returned. If a group id cannot be found,
-// or the given group data is nil, the id will be returned as-is
-// provided it is in the legal range.
-func GetAdditionalGroups(additionalGroups []string, group io.Reader) ([]int, error) {
- var groups = []Group{}
- if group != nil {
- var err error
- groups, err = ParseGroupFilter(group, func(g Group) bool {
- for _, ag := range additionalGroups {
- if g.Name == ag || strconv.Itoa(g.Gid) == ag {
- return true
- }
- }
- return false
- })
- if err != nil {
- return nil, fmt.Errorf("Unable to find additional groups %v: %v", additionalGroups, err)
- }
- }
-
- gidMap := make(map[int]struct{})
- for _, ag := range additionalGroups {
- var found bool
- for _, g := range groups {
- // if we found a matched group either by name or gid, take the
- // first matched as correct
- if g.Name == ag || strconv.Itoa(g.Gid) == ag {
- if _, ok := gidMap[g.Gid]; !ok {
- gidMap[g.Gid] = struct{}{}
- found = true
- break
- }
- }
- }
- // we asked for a group but didn't find it. let's check to see
- // if we wanted a numeric group
- if !found {
- gid, err := strconv.Atoi(ag)
- if err != nil {
- return nil, fmt.Errorf("Unable to find group %s", ag)
- }
- // Ensure gid is inside gid range.
- if gid < minId || gid > maxId {
- return nil, ErrRange
- }
- gidMap[gid] = struct{}{}
- }
- }
- gids := []int{}
- for gid := range gidMap {
- gids = append(gids, gid)
- }
- return gids, nil
-}
-
-// GetAdditionalGroupsPath is a wrapper around GetAdditionalGroups
-// that opens the groupPath given and gives it as an argument to
-// GetAdditionalGroups.
-func GetAdditionalGroupsPath(additionalGroups []string, groupPath string) ([]int, error) {
- group, err := os.Open(groupPath)
- if err == nil {
- defer group.Close()
- }
- return GetAdditionalGroups(additionalGroups, group)
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/utils/utils.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/utils/utils.go
deleted file mode 100644
index 86cf1d6..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/utils/utils.go
+++ /dev/null
@@ -1,45 +0,0 @@
-package utils
-
-import (
- "crypto/rand"
- "encoding/hex"
- "io"
- "path/filepath"
- "syscall"
-)
-
-const (
- exitSignalOffset = 128
-)
-
-// GenerateRandomName returns a new name joined with a prefix. This size
-// specified is used to truncate the randomly generated value
-func GenerateRandomName(prefix string, size int) (string, error) {
- id := make([]byte, 32)
- if _, err := io.ReadFull(rand.Reader, id); err != nil {
- return "", err
- }
- if size > 64 {
- size = 64
- }
- return prefix + hex.EncodeToString(id)[:size], nil
-}
-
-// ResolveRootfs ensures that the current working directory is
-// not a symlink and returns the absolute path to the rootfs
-func ResolveRootfs(uncleanRootfs string) (string, error) {
- rootfs, err := filepath.Abs(uncleanRootfs)
- if err != nil {
- return "", err
- }
- return filepath.EvalSymlinks(rootfs)
-}
-
-// ExitStatus returns the correct exit status for a process based on if it
-// was signaled or exited cleanly.
-func ExitStatus(status syscall.WaitStatus) int {
- if status.Signaled() {
- return exitSignalOffset + int(status.Signal())
- }
- return status.ExitStatus()
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/utils/utils_unix.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/utils/utils_unix.go
deleted file mode 100644
index 408918f..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/utils/utils_unix.go
+++ /dev/null
@@ -1,33 +0,0 @@
-// +build !windows
-
-package utils
-
-import (
- "io/ioutil"
- "strconv"
- "syscall"
-)
-
-func CloseExecFrom(minFd int) error {
- fdList, err := ioutil.ReadDir("/proc/self/fd")
- if err != nil {
- return err
- }
- for _, fi := range fdList {
- fd, err := strconv.Atoi(fi.Name())
- if err != nil {
- // ignore non-numeric file names
- continue
- }
-
- if fd < minFd {
- // ignore descriptors lower than our specified minimum
- continue
- }
-
- // intentionally ignore errors from syscall.CloseOnExec
- syscall.CloseOnExec(fd)
- // the cases where this might fail are basically file descriptors that have already been closed (including and especially the one that was created when ioutil.ReadDir did the "opendir" syscall)
- }
- return nil
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/xattr/errors.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/xattr/errors.go
deleted file mode 100644
index 8cd7741..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/xattr/errors.go
+++ /dev/null
@@ -1,8 +0,0 @@
-package xattr
-
-import (
- "fmt"
- "runtime"
-)
-
-var ErrNotSupportedPlatform = fmt.Errorf("platform and architecture is not supported %s %s", runtime.GOOS, runtime.GOARCH)
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/xattr/xattr_linux.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/xattr/xattr_linux.go
deleted file mode 100644
index 933a752..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/xattr/xattr_linux.go
+++ /dev/null
@@ -1,53 +0,0 @@
-// +build linux
-
-package xattr
-
-import (
- "syscall"
-
- "github.com/opencontainers/runc/libcontainer/system"
-)
-
-func XattrEnabled(path string) bool {
- if Setxattr(path, "user.test", "") == syscall.ENOTSUP {
- return false
- }
- return true
-}
-
-func stringsfromByte(buf []byte) (result []string) {
- offset := 0
- for index, b := range buf {
- if b == 0 {
- result = append(result, string(buf[offset:index]))
- offset = index + 1
- }
- }
- return
-}
-
-func Listxattr(path string) ([]string, error) {
- size, err := system.Llistxattr(path, nil)
- if err != nil {
- return nil, err
- }
- buf := make([]byte, size)
- read, err := system.Llistxattr(path, buf)
- if err != nil {
- return nil, err
- }
- names := stringsfromByte(buf[:read])
- return names, nil
-}
-
-func Getxattr(path, attr string) (string, error) {
- value, err := system.Lgetxattr(path, attr)
- if err != nil {
- return "", err
- }
- return string(value), nil
-}
-
-func Setxattr(path, xattr, value string) error {
- return system.Lsetxattr(path, xattr, []byte(value), 0)
-}
diff --git a/containerd/vendor/github.com/opencontainers/runc/libcontainer/xattr/xattr_unsupported.go b/containerd/vendor/github.com/opencontainers/runc/libcontainer/xattr/xattr_unsupported.go
deleted file mode 100644
index 821dea3..0000000
--- a/containerd/vendor/github.com/opencontainers/runc/libcontainer/xattr/xattr_unsupported.go
+++ /dev/null
@@ -1,15 +0,0 @@
-// +build !linux
-
-package xattr
-
-func Listxattr(path string) ([]string, error) {
- return nil, ErrNotSupportedPlatform
-}
-
-func Getxattr(path, attr string) (string, error) {
- return "", ErrNotSupportedPlatform
-}
-
-func Setxattr(path, xattr, value string) error {
- return ErrNotSupportedPlatform
-}
diff --git a/containerd/vendor/github.com/opencontainers/specs/.travis.yml b/containerd/vendor/github.com/opencontainers/specs/.travis.yml
deleted file mode 100644
index 64b57bf..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/.travis.yml
+++ /dev/null
@@ -1,20 +0,0 @@
-language: go
-go:
- - 1.5.1
- - 1.4.3
- - 1.3.3
-
-sudo: false
-
-before_install:
- - go get golang.org/x/tools/cmd/vet
- - go get github.com/golang/lint/golint
- - go get github.com/vbatts/git-validation
-
-install: true
-
-script:
- - go vet -x ./...
- - $HOME/gopath/bin/golint ./...
- - $HOME/gopath/bin/git-validation -run DCO,short-subject -v -range ${TRAVIS_COMMIT_RANGE}
-
diff --git a/containerd/vendor/github.com/opencontainers/specs/LICENSE b/containerd/vendor/github.com/opencontainers/specs/LICENSE
deleted file mode 100644
index bdc4036..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/LICENSE
+++ /dev/null
@@ -1,191 +0,0 @@
-
- Apache License
- Version 2.0, January 2004
- http://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 2015 The Linux Foundation.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
diff --git a/containerd/vendor/github.com/opencontainers/specs/MAINTAINERS b/containerd/vendor/github.com/opencontainers/specs/MAINTAINERS
deleted file mode 100644
index 286dbe3..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/MAINTAINERS
+++ /dev/null
@@ -1,8 +0,0 @@
-Michael Crosby (@crosbymichael)
-Alexander Morozov (@LK4D4)
-Vishnu Kannan (@vishnuk)
-Mrunal Patel (@mrunalp)
-Vincent Batts (@vbatts)
-Daniel, Dao Quang Minh (@dqminh)
-Brandon Philips (@philips)
-Tianon Gravi (@tianon)
diff --git a/containerd/vendor/github.com/opencontainers/specs/README.md b/containerd/vendor/github.com/opencontainers/specs/README.md
deleted file mode 100644
index cfe73fa..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/README.md
+++ /dev/null
@@ -1,144 +0,0 @@
-# Open Container Specifications
-
-[Open Container Initiative](http://www.opencontainers.org/) Specifications for standards on Operating System process and application containers.
-
-
-Table of Contents
-
-- [Container Principles](principles.md)
-- [Filesystem Bundle](bundle.md)
-- Configuration
- - [Container Configuration](config.md)
- - [Container Configuration (Linux-specific)](config-linux.md)
- - [Runtime Configuration](runtime-config.md)
- - [Runtime Configuration (Linux-specific)](runtime-config-linux.md)
-- [Runtime and Lifecycle](runtime.md)
- - [Linux Specific Runtime](runtime-linux.md)
-- [Implementations](implementations.md)
-
-# Use Cases
-
-To provide context for users the following section gives example use cases for each part of the spec.
-
-## Filesystem Bundle & Configuration
-
-- A user can create a root filesystem and configuration, with low-level OS and host specific details, and launch it as a container under an Open Container runtime.
-
-# Releases
-
-There is a loose [Road Map](https://github.com/opencontainers/specs/wiki/RoadMap:) on the wiki.
-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` file of this repository.
-
-## Code of Conduct
-
-Participation in the OpenContainers community is governed by [OpenContainer's Code of Conduct](code-of-conduct.md).
-
-## 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 the project have a weekly meeting Wednesdays at 10:00 AM PST.
-Everyone is welcome to participate in the [BlueJeans call][BlueJeans].
-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/specs/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.
-
-## 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: ...")
-
-[BlueJeans]: https://bluejeans.com/1771332256/
diff --git a/containerd/vendor/github.com/opencontainers/specs/ROADMAP.md b/containerd/vendor/github.com/opencontainers/specs/ROADMAP.md
deleted file mode 100644
index 8941528..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/ROADMAP.md
+++ /dev/null
@@ -1,96 +0,0 @@
-# OCI Specs Roadmap
-
-This document serves to provide a long term roadmap on our quest to a 1.0 version of the OCI container specification.
-Its goal is to help both maintainers and contributors find meaningful tasks to focus on and create a low noise environment.
-The items in the 1.0 roadmap can be broken down into smaller milestones that are easy to accomplish.
-The topics below are broad and small working groups will be needed for each to define scope and requirements or if the feature is required at all for the OCI level.
-Topics listed in the roadmap do not mean that they will be implemented or added but are areas that need discussion to see if they fit in to the goals of the OCI.
-
-## 1.0
-
-### Digest and Hashing
-
-A bundle is designed to be moved between hosts.
-Although OCI doesn't define a transport method we should have a cryptographic digest of the on-disk bundle that can be used to verify that a bundle is not corrupted and in an expected configuration.
-
-*Owner:* philips
-
-### Review the need for runtime.json
-
-There are some discussions about having `runtime.json` being optional for containers and specifying defaults.
-Runtimes would use this standard set of defaults for containers and `runtime.json` would provide overrides for fine tuning of these extra host or platform specific settings.
-
-*Owner:*
-
-### Define Container Lifecycle
-
-Containers have a lifecycle and being able to identify and document the lifecycle of a container is very helpful for implementations of the spec.
-The lifecycle events of a container also help identify areas to implement hooks that are portable across various implementations and platforms.
-
-*Owner:* mrunalp
-
-### Define Standard Container Actions
-
-Define what type of actions a runtime can perform on a container without imposing hardships on authors of platforms that do not support advanced options.
-
-*Owner:*
-
-### Clarify rootfs requirement in base spec
-
-Is the rootfs needed or should it just be expected in the bundle without having a field in the spec?
-
-*Owner:*
-
-### Container Definition
-
-Define what a software container is and its attributes in a cross platform way.
-
-*Owner:*
-
-### Live Container Updates
-
-Should we allow dynamic container updates to runtime options?
-
-*Owner:* vishh
-
-### Protobuf Config
-
-We currently have only one language binding for the spec and that is Go.
-If we change the specs format in the respository to be something like protobuf then the generation for multiple language bindings become effortless.
-
-*Owner:* vbatts
-
-### Validation Tooling
-
-Provide validation tooling for compliance with OCI spec and runtime environment.
-
-*Owner:* mrunalp
-
-### Version Schema
-
-Decide on a robust versioning schema for the spec as it evolves.
-
-*Owner:*
-
-### Printable/Compiled Spec
-
-Reguardless of how the spec is written, ensure that it is easy to read and follow for first time users.
-
-*Owner:* vbatts
-
-### Base Config Compatibility
-
-Ensure that the base configuration format is viable for various platforms.
-
-Systems:
-
-* Solaris
-* Windows
-* Linux
-
-*Owner:*
-
-### Full Lifecycle Hooks
-Ensure that we have lifecycle hooks in the correct places with full coverage over the container lifecycle.
-
-*Owner:*
diff --git a/containerd/vendor/github.com/opencontainers/specs/bundle.md b/containerd/vendor/github.com/opencontainers/specs/bundle.md
deleted file mode 100644
index 8e25255..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/bundle.md
+++ /dev/null
@@ -1,30 +0,0 @@
-# Filesystem Bundle
-
-## Container Format
-
-This section defines a format for encoding a container as a *filesystem bundle* - a set of files organized in a certain way, and containing all the necessary data and metadata for any compliant runtime to perform all standard operations against it.
-See also [OS X application bundles](http://en.wikipedia.org/wiki/Bundle_%28OS_X%29) for a similar use of the term *bundle*.
-
-The definition of a bundle is only concerned with how a container, and its configuration data, are stored on a local file system so that it can be consumed by a compliant runtime.
-
-A Standard Container bundle contains all the information needed to load and run a container.
-This includes the following three artifacts which MUST all reside in the same directory on the local filesystem:
-
-1. `config.json` : contains host independent configuration data.
-This REQUIRED file, which MUST be named `config.json`, contains settings that are host independent and application specific such as security permissions, environment variables and arguments.
-When the bundle is packaged up for distribution, this file MUST be included.
-See [`config.json`](config.md) for more details.
-
-2. `runtime.json` : contains host-specific configuration data.
-This REQUIRED file, which MUST be named `runtime.json`, contains settings that are host specific such as mount sources and hooks.
-The goal is that the bundle can be moved as a unit to another runtime and run the same application once a host-specific `runtime.json` is defined.
-When the bundle is packaged up for distribution, this file MUST NOT be included.
-See [`runtime.json`](runtime-config.md) for more details.
-
-3. A directory representing the root filesystem of the container.
-While the name of this REQUIRED directory may be arbitrary, users should consider using a conventional name, such as `rootfs`.
-When the bundle is packaged up for distribution, this directory MUST be included.
-This directory MUST be referenced from within the `config.json` file.
-
-While these three artifacts MUST all be present in a single directory on the local filesytem, that directory itself is not part of the bundle.
-In other words, a tar archive of a *bundle* will have these artifacts at the root of the archive, not nested within a top-level directory.
diff --git a/containerd/vendor/github.com/opencontainers/specs/code-of-conduct.md b/containerd/vendor/github.com/opencontainers/specs/code-of-conduct.md
deleted file mode 100644
index 06cb2b8..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/code-of-conduct.md
+++ /dev/null
@@ -1,37 +0,0 @@
-# OpenContainers Code of Conduct
-
-Behave as a community member, follow the code of conduct.
-
-## Code of Conduct
-
-The OpenContainers community is made up of a mixture of professionals and volunteers from all over the world.
-
-When we disagree, we try to understand why.
-Disagreements, both social and technical, happen all the time and OpenContainers is no exception.
-It is important that we resolve disagreements and differing views constructively.
-
-This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community.
-Participants should be aware of these concerns.
-
-We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality.
-
-Examples of unacceptable behavior by participants include:
-
-* The use of sexualized language or imagery
-* Personal attacks
-* Trolling or insulting/derogatory comments
-* Public or private harassment
-* Publishing other's private information, such as physical or electronic addresses, without explicit permission
-* Other unethical or unprofessional conduct
-
-The OpenContainers team does not condone any statements by speakers contrary to these standards.
-The OpenContainers team reserves the right to deny participation any individual found to be engaging in discriminatory or harassing actions.
-
-Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct.
-By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project.
-
-## Thanks
-
-Thanks to the [Fedora Code of Conduct](https://getfedora.org/code-of-conduct) and [Contributor Covenant](http://contributor-covenant.org) for inspiration and ideas.
-
-Portions of this Code of Conduct are adapted from the Contributor Covenant, version 1.2.0, available at http://contributor-covenant.org/version/1/2/0/
diff --git a/containerd/vendor/github.com/opencontainers/specs/config-linux.md b/containerd/vendor/github.com/opencontainers/specs/config-linux.md
deleted file mode 100644
index 883daba..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/config-linux.md
+++ /dev/null
@@ -1,63 +0,0 @@
-# Linux-specific Container Configuration
-
-The Linux container specification uses various kernel features like namespaces, cgroups, capabilities, LSM, and file system jails to fulfill the spec.
-Additional information is needed for Linux over the [default spec configuration](config.md) in order to configure these various kernel features.
-
-## Capabilities
-
-Capabilities is an array that specifies Linux capabilities that can be provided to the process inside the container.
-Valid values are the strings for capabilities defined in [the man page](http://man7.org/linux/man-pages/man7/capabilities.7.html)
-
-```json
- "capabilities": [
- "CAP_AUDIT_WRITE",
- "CAP_KILL",
- "CAP_NET_BIND_SERVICE"
- ]
-```
-
-## User namespace mappings
-
-```json
- "uidMappings": [
- {
- "hostID": 1000,
- "containerID": 0,
- "size": 10
- }
- ],
- "gidMappings": [
- {
- "hostID": 1000,
- "containerID": 0,
- "size": 10
- }
- ]
-```
-
-uid/gid mappings describe the user namespace mappings from the host to the container.
-The mappings represent how the bundle `rootfs` expects the user namespace to be setup and the runtime SHOULD NOT modify the permissions on the rootfs to realize the mapping.
-*hostID* is the starting uid/gid on the host to be mapped to *containerID* which is the starting uid/gid in the container and *size* refers to the number of ids to be mapped.
-There is a limit of 5 mappings which is the Linux kernel hard limit.
-
-## Default Devices and File Systems
-
-The Linux ABI includes both syscalls and several special file paths.
-Applications expecting a Linux environment will very likely expect these files paths to be setup correctly.
-
-The following devices and filesystems MUST be made available in each application's filesystem
-
-| Path | Type | Notes |
-| ------------ | ------ | ------- |
-| /proc | [procfs](https://www.kernel.org/doc/Documentation/filesystems/proc.txt) | |
-| /sys | [sysfs](https://www.kernel.org/doc/Documentation/filesystems/sysfs.txt) | |
-| /dev/null | [device](http://man7.org/linux/man-pages/man4/null.4.html) | |
-| /dev/zero | [device](http://man7.org/linux/man-pages/man4/zero.4.html) | |
-| /dev/full | [device](http://man7.org/linux/man-pages/man4/full.4.html) | |
-| /dev/random | [device](http://man7.org/linux/man-pages/man4/random.4.html) | |
-| /dev/urandom | [device](http://man7.org/linux/man-pages/man4/random.4.html) | |
-| /dev/tty | [device](http://man7.org/linux/man-pages/man4/tty.4.html) | |
-| /dev/console | [device](http://man7.org/linux/man-pages/man4/console.4.html) | |
-| /dev/pts | [devpts](https://www.kernel.org/doc/Documentation/filesystems/devpts.txt) | |
-| /dev/ptmx | [device](https://www.kernel.org/doc/Documentation/filesystems/devpts.txt) | Bind-mount or symlink of /dev/pts/ptmx |
-| /dev/shm | [tmpfs](https://www.kernel.org/doc/Documentation/filesystems/tmpfs.txt) | |
diff --git a/containerd/vendor/github.com/opencontainers/specs/config.go b/containerd/vendor/github.com/opencontainers/specs/config.go
deleted file mode 100644
index de2aa5a..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/config.go
+++ /dev/null
@@ -1,59 +0,0 @@
-package specs
-
-// Spec is the base configuration for the container. It specifies platform
-// independent configuration. This information must be included when the
-// bundle is packaged for distribution.
-type Spec struct {
- // Version is the version of the specification that is supported.
- Version string `json:"version"`
- // Platform is the host information for OS and Arch.
- Platform Platform `json:"platform"`
- // Process is the container's main process.
- Process Process `json:"process"`
- // Root is the root information for the container's filesystem.
- Root Root `json:"root"`
- // Hostname is the container's host name.
- Hostname string `json:"hostname"`
- // Mounts profile configuration for adding mounts to the container's filesystem.
- Mounts []MountPoint `json:"mounts"`
-}
-
-// Process contains information to start a specific application inside the container.
-type Process struct {
- // Terminal creates an interactive terminal for the container.
- Terminal bool `json:"terminal"`
- // User specifies user information for the process.
- User User `json:"user"`
- // Args specifies the binary and arguments for the application to execute.
- Args []string `json:"args"`
- // Env populates the process environment for the process.
- Env []string `json:"env"`
- // Cwd is the current working directory for the process and must be
- // relative to the container's root.
- Cwd string `json:"cwd"`
-}
-
-// Root contains information about the container's root filesystem on the host.
-type Root struct {
- // Path is the absolute path to the container's root filesystem.
- Path string `json:"path"`
- // Readonly makes the root filesystem for the container readonly before the process is executed.
- Readonly bool `json:"readonly"`
-}
-
-// Platform specifies OS and arch information for the host system that the container
-// is created for.
-type Platform struct {
- // OS is the operating system.
- OS string `json:"os"`
- // Arch is the architecture
- Arch string `json:"arch"`
-}
-
-// MountPoint describes a directory that may be fullfilled by a mount in the runtime.json.
-type MountPoint struct {
- // Name is a unique descriptive identifier for this mount point.
- Name string `json:"name"`
- // Path specifies the path of the mount. The path and child directories MUST exist, a runtime MUST NOT create directories automatically to a mount point.
- Path string `json:"path"`
-}
diff --git a/containerd/vendor/github.com/opencontainers/specs/config.md b/containerd/vendor/github.com/opencontainers/specs/config.md
deleted file mode 100644
index 4e98d29..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/config.md
+++ /dev/null
@@ -1,128 +0,0 @@
-# Container Configuration file
-
-The container's top-level directory MUST contain a configuration file called `config.json`.
-For now the canonical schema is defined in [config.go](config.go) and [config_linux.go](config_linux.go), but this will be moved to a formal JSON schema over time.
-
-The configuration file contains metadata necessary to implement standard operations against the container.
-This includes the process to run, environment variables to inject, sandboxing features to use, etc.
-
-Below is a detailed description of each field defined in the configuration format.
-
-## Manifest version
-
-* **`version`** (string, required) must be in [SemVer v2.0.0](http://semver.org/spec/v2.0.0.html) format and specifies the version of the OCF specification with which the container bundle complies. The Open Container spec follows semantic versioning and retains forward and backward compatibility within major versions. For example, if an implementation is compliant with version 1.0.1 of the spec, it is compatible with the complete 1.x series.
-
-*Example*
-
-```json
- "version": "0.1.0"
-```
-
-## Root Configuration
-
-Each container has exactly one *root filesystem*, specified in the *root* object:
-
-* **`path`** (string, required) Specifies the path to the root filesystem for the container, relative to the path where the manifest is. A directory MUST exist at the relative path declared by the field.
-* **`readonly`** (bool, optional) If true then the root filesystem MUST be read-only inside the container. Defaults to false.
-
-*Example*
-
-```json
-"root": {
- "path": "rootfs",
- "readonly": true
-}
-```
-
-## Mount Points
-
-You can add array of mount points inside container as `mounts`.
-Each record in this array must have configuration in [runtime config](runtime-config.md#mount-configuration).
-The runtime MUST mount entries in the listed order.
-
-* **`name`** (string, required) Name of mount point. Used for config lookup.
-* **`path`** (string, required) Destination of mount point: path inside container.
-
-*Example*
-
-```json
-"mounts": [
- {
- "name": "proc",
- "path": "/proc"
- },
- {
- "name": "dev",
- "path": "/dev"
- },
- {
- "name": "devpts",
- "path": "/dev/pts"
- },
- {
- "name": "data",
- "path": "/data"
- }
-]
-```
-
-## Process configuration
-
-* **`terminal`** (bool, optional) specifies whether you want a terminal attached to that process. Defaults to false.
-* **`cwd`** (string, optional) is the working directory that will be set for the executable.
-* **`env`** (array of strings, optional) contains a list of variables that will be set in the process's environment prior to execution. Elements in the array are specified as Strings in the form "KEY=value". The left hand side must consist solely of letters, digits, and underscores `_` as outlined in [IEEE Std 1003.1-2001](http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html).
-* **`args`** (string, required) executable to launch and any flags as an array. The executable is the first element and must be available at the given path inside of the rootfs. If the executable path is not an absolute path then the search $PATH is interpreted to find the executable.
-
-The user for the process is a platform-specific structure that allows specific control over which user the process runs as.
-For Linux-based systems the user structure has the following fields:
-
-* **`uid`** (int, required) specifies the user id.
-* **`gid`** (int, required) specifies the group id.
-* **`additionalGids`** (array of ints, optional) specifies additional group ids to be added to the process.
-
-*Example (Linux)*
-
-```json
-"process": {
- "terminal": true,
- "user": {
- "uid": 1,
- "gid": 1,
- "additionalGids": [5, 6]
- },
- "env": [
- "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
- "TERM=xterm"
- ],
- "cwd": "/root",
- "args": [
- "sh"
- ]
-}
-```
-
-
-## Hostname
-
-* **`hostname`** (string, optional) as it is accessible to processes running inside.
-
-*Example*
-
-```json
-"hostname": "mrsdalloway"
-```
-
-## Platform-specific configuration
-
-* **`os`** (string, required) specifies the operating system family this image must run on. Values for os must be in the list specified by the Go Language document for [`$GOOS`](https://golang.org/doc/install/source#environment).
-* **`arch`** (string, required) specifies the instruction set for which the binaries in the image have been compiled. Values for arch must be in the list specified by the Go Language document for [`$GOARCH`](https://golang.org/doc/install/source#environment).
-
-```json
-"platform": {
- "os": "linux",
- "arch": "amd64"
-}
-```
-
-Interpretation of the platform section of the JSON file is used to find which platform-specific sections may be available in the document.
-For example, if `os` is set to `linux`, then a JSON object conforming to the [Linux-specific schema](config-linux.md) SHOULD be found at the key `linux` in the `config.json`.
diff --git a/containerd/vendor/github.com/opencontainers/specs/config_linux.go b/containerd/vendor/github.com/opencontainers/specs/config_linux.go
deleted file mode 100644
index b991553..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/config_linux.go
+++ /dev/null
@@ -1,25 +0,0 @@
-package specs
-
-// LinuxSpec is the full specification for linux containers.
-type LinuxSpec struct {
- Spec
- // Linux is platform specific configuration for linux based containers.
- Linux Linux `json:"linux"`
-}
-
-// Linux contains platform specific configuration for linux based containers.
-type Linux struct {
- // Capabilities are linux capabilities that are kept for the container.
- Capabilities []string `json:"capabilities"`
-}
-
-// User specifies linux specific user and group information for the container's
-// main process.
-type User struct {
- // UID is the user id.
- UID uint32 `json:"uid"`
- // GID is the group id.
- GID uint32 `json:"gid"`
- // AdditionalGids are additional group ids set for the container's process.
- AdditionalGids []uint32 `json:"additionalGids"`
-}
diff --git a/containerd/vendor/github.com/opencontainers/specs/implementations.md b/containerd/vendor/github.com/opencontainers/specs/implementations.md
deleted file mode 100644
index 5cd16b9..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/implementations.md
+++ /dev/null
@@ -1,21 +0,0 @@
-# Implementations
-
-The following sections link to associated projects, some of which are maintained by the OCI and some of which are maintained by external organizations.
-If you know of any associated projects that are not listed here, please file a pull request adding a link to that project.
-
-## Runtime (Container)
-
-* [opencontainers/runc](https://github.com/opencontainers/runc) - Reference implementation of OCI runtime
-
-## Runtime (Virtual Machine)
-
-* [hyperhq/runv](https://github.com/hyperhq/runv) - Hypervisor-based runtime for OCI
-
-## Bundle authoring
-
-* [kunalkushwaha/octool](https://github.com/kunalkushwaha/octool) - A config linter and validator.
-* [mrunalp/ocitools](https://github.com/mrunalp/ocitools) - A config generator.
-
-## Testing
-
-* [huawei-openlab/oct](https://github.com/huawei-openlab/oct) - Open Container Testing framework for OCI configuration and runtime
diff --git a/containerd/vendor/github.com/opencontainers/specs/principles.md b/containerd/vendor/github.com/opencontainers/specs/principles.md
deleted file mode 100644
index 5dbab16..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/principles.md
+++ /dev/null
@@ -1,46 +0,0 @@
-# The 5 principles of Standard Containers
-
-Define a unit of software delivery called a Standard Container.
-The goal of a Standard Container is to encapsulate a software component and all its dependencies in a format that is self-describing and portable, so that any compliant runtime can run it without extra dependencies, regardless of the underlying machine and the contents of the container.
-
-The specification for Standard Containers defines:
-
-1. configuration file formats
-2. a set of standard operations
-3. an execution environment.
-
-A great analogy for this is the physical shipping container used by the transportation industry.
-Shipping containers are a fundamental unit of delivery, they can be lifted, stacked, locked, loaded, unloaded and labelled.
-Irrespective of their contents, by standardizing the container itself it allowed for a consistent, more streamlined and efficient set of processes to be defined.
-For software Standard Containers offer similar functionality by being the fundamental, standardized, unit of delivery for a software package.
-
-## 1. Standard operations
-
-Standard Containers define a set of STANDARD OPERATIONS.
-They can be created, started, and stopped using standard container tools; copied and snapshotted using standard filesystem tools; and downloaded and uploaded using standard network tools.
-
-## 2. Content-agnostic
-
-Standard Containers are CONTENT-AGNOSTIC: all standard operations have the same effect regardless of the contents.
-They are started in the same way whether they contain a postgres database, a php application with its dependencies and application server, or Java build artifacts.
-
-## 3. Infrastructure-agnostic
-
-Standard Containers are INFRASTRUCTURE-AGNOSTIC: they can be run in any OCI supported infrastructure.
-For example, a standard container can be bundled on a laptop, uploaded to cloud storage, downloaded, run and snapshotted by a build server at a fiber hotel in Virginia, uploaded to 10 staging servers in a home-made private cloud cluster, then sent to 30 production instances across 3 public cloud regions.
-
-## 4. Designed for automation
-
-Standard Containers are DESIGNED FOR AUTOMATION: because they offer the same standard operations regardless of content and infrastructure, Standard Containers, are extremely well-suited for automation.
-In fact, you could say automation is their secret weapon.
-
-Many things that once required time-consuming and error-prone human effort can now be programmed.
-Before Standard Containers, by the time a software component ran in production, it had been individually built, configured, bundled, documented, patched, vendored, templated, tweaked and instrumented by 10 different people on 10 different computers.
-Builds failed, libraries conflicted, mirrors crashed, post-it notes were lost, logs were misplaced, cluster updates were half-broken.
-The process was slow, inefficient and cost a fortune - and was entirely different depending on the language and infrastructure provider.
-
-## 5. Industrial-grade delivery
-
-Standard Containers make INDUSTRIAL-GRADE DELIVERY of software a reality.
-Leveraging all of the properties listed above, Standard Containers are enabling large and small enterprises to streamline and automate their software delivery pipelines.
-Whether it is in-house devOps flows, or external customer-based software delivery mechanisms, Standard Containers are changing the way the community thinks about software packaging and delivery.
diff --git a/containerd/vendor/github.com/opencontainers/specs/runtime-config-linux.md b/containerd/vendor/github.com/opencontainers/specs/runtime-config-linux.md
deleted file mode 100644
index 1fff724..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/runtime-config-linux.md
+++ /dev/null
@@ -1,502 +0,0 @@
-# Linux-specific Runtime Configuration
-
-## Namespaces
-
-A namespace wraps a global system resource in an abstraction that makes it appear to the processes within the namespace that they have their own isolated instance of the global resource.
-Changes to the global resource are visible to other processes that are members of the namespace, but are invisible to other processes.
-For more information, see [the man page](http://man7.org/linux/man-pages/man7/namespaces.7.html).
-
-Namespaces are specified as an array of entries inside the `namespaces` root field.
-The following parameters can be specified to setup namespaces:
-
-* **`type`** *(string, required)* - namespace type. The following namespaces types are supported:
- * **`pid`** processes inside the container will only be able to see other processes inside the same container
- * **`network`** the container will have its own network stack
- * **`mount`** the container will have an isolated mount table
- * **`ipc`** processes inside the container will only be able to communicate to other processes inside the same container via system level IPC
- * **`uts`** the container will be able to have its own hostname and domain name
- * **`user`** the container will be able to remap user and group IDs from the host to local users and groups within the container
-
-* **`path`** *(string, optional)* - path to namespace file
-
-If a path is specified, that particular file is used to join that type of namespace.
-Also, when a path is specified, a runtime MUST assume that the setup for that particular namespace has already been done and error out if the config specifies anything else related to that namespace.
-
-###### Example
-
-```json
- "namespaces": [
- {
- "type": "pid",
- "path": "/proc/1234/ns/pid"
- },
- {
- "type": "network",
- "path": "/var/run/netns/neta"
- },
- {
- "type": "mount"
- },
- {
- "type": "ipc"
- },
- {
- "type": "uts"
- },
- {
- "type": "user"
- }
- ]
-```
-
-## Devices
-
-`devices` is an array specifying the list of devices to be created in the container.
-
-The following parameters can be specified:
-
-* **`type`** *(char, required)* - type of device: `c`, `b`, `u` or `p`. More info in `man mknod`.
-
-* **`path`** *(string, optional)* - full path to device inside container
-
-* **`major, minor`** *(int64, required)* - major, minor numbers for device. More info in `man mknod`. There is a special value: `-1`, which means `*` for `device` cgroup setup.
-
-* **`permissions`** *(string, optional)* - cgroup permissions for device. A composition of `r` (*read*), `w` (*write*), and `m` (*mknod*).
-
-* **`fileMode`** *(uint32, optional)* - file mode for device file
-
-* **`uid`** *(uint32, optional)* - uid of device owner
-
-* **`gid`** *(uint32, optional)* - gid of device owner
-
-**`fileMode`**, **`uid`** and **`gid`** are required if **`path`** is given and are otherwise not allowed.
-
-###### Example
-
-```json
- "devices": [
- {
- "path": "/dev/random",
- "type": "c",
- "major": 1,
- "minor": 8,
- "permissions": "rwm",
- "fileMode": 0666,
- "uid": 0,
- "gid": 0
- },
- {
- "path": "/dev/urandom",
- "type": "c",
- "major": 1,
- "minor": 9,
- "permissions": "rwm",
- "fileMode": 0666,
- "uid": 0,
- "gid": 0
- },
- {
- "path": "/dev/null",
- "type": "c",
- "major": 1,
- "minor": 3,
- "permissions": "rwm",
- "fileMode": 0666,
- "uid": 0,
- "gid": 0
- },
- {
- "path": "/dev/zero",
- "type": "c",
- "major": 1,
- "minor": 5,
- "permissions": "rwm",
- "fileMode": 0666,
- "uid": 0,
- "gid": 0
- },
- {
- "path": "/dev/tty",
- "type": "c",
- "major": 5,
- "minor": 0,
- "permissions": "rwm",
- "fileMode": 0666,
- "uid": 0,
- "gid": 0
- },
- {
- "path": "/dev/full",
- "type": "c",
- "major": 1,
- "minor": 7,
- "permissions": "rwm",
- "fileMode": 0666,
- "uid": 0,
- "gid": 0
- }
- ]
-```
-
-## Control groups
-
-Also known as cgroups, they are used to restrict resource usage for a container and handle device access.
-cgroups provide controls to restrict cpu, memory, IO, pids and network for the container.
-For more information, see the [kernel cgroups documentation](https://www.kernel.org/doc/Documentation/cgroups/cgroups.txt).
-
-The path to the cgroups can be specified in the Spec via `cgroupsPath`.
-`cgroupsPath` is expected to be relative to the cgroups mount point.
-If not specified, cgroups will be created under '/'.
-Implementations of the Spec can choose to name cgroups in any manner.
-The Spec does not include naming schema for cgroups.
-The Spec does not support [split hierarchy](https://www.kernel.org/doc/Documentation/cgroups/unified-hierarchy.txt).
-The cgroups will be created if they don't exist.
-
-```json
- "cgroupsPath": "/myRuntime/myContainer"
-```
-
-`cgroupsPath` can be used to either control the cgroups hierarchy for containers or to run a new process in an existing container.
-
-You can configure a container's cgroups via the `resources` field of the Linux configuration.
-Do not specify `resources` unless limits have to be updated.
-For example, to run a new process in an existing container without updating limits, `resources` need not be specified.
-
-#### Disable out-of-memory killer
-
-`disableOOMKiller` contains a boolean (`true` or `false`) that enables or disables the Out of Memory killer for a cgroup.
-If enabled (`false`), tasks that attempt to consume more memory than they are allowed are immediately killed by the OOM killer.
-The OOM killer is enabled by default in every cgroup using the `memory` subsystem.
-To disable it, specify a value of `true`.
-For more information, see [the memory cgroup man page](https://www.kernel.org/doc/Documentation/cgroups/memory.txt).
-
-* **`disableOOMKiller`** *(bool, optional)* - enables or disables the OOM killer
-
-###### Example
-
-```json
- "disableOOMKiller": false
-```
-
-#### Set oom_score_adj
-
-More information on `oom_score_adj` available [here](https://www.kernel.org/doc/Documentation/filesystems/proc.txt).
-
-```json
- "oomScoreAdj": 0
-```
-
-#### Memory
-
-`memory` represents the cgroup subsystem `memory` and it's used to set limits on the container's memory usage.
-For more information, see [the memory cgroup man page](https://www.kernel.org/doc/Documentation/cgroups/memory.txt).
-
-The following parameters can be specified to setup the controller:
-
-* **`limit`** *(uint64, optional)* - sets limit of memory usage
-
-* **`reservation`** *(uint64, optional)* - sets soft limit of memory usage
-
-* **`swap`** *(uint64, optional)* - sets limit of memory+Swap usage
-
-* **`kernel`** *(uint64, optional)* - sets hard limit for kernel memory
-
-* **`swappiness`** *(uint64, optional)* - sets swappiness parameter of vmscan (See sysctl's vm.swappiness)
-
-###### Example
-
-```json
- "memory": {
- "limit": 0,
- "reservation": 0,
- "swap": 0,
- "kernel": 0,
- "swappiness": -1
- }
-```
-
-#### CPU
-
-`cpu` represents the cgroup subsystems `cpu` and `cpusets`.
-For more information, see [the cpusets cgroup man page](https://www.kernel.org/doc/Documentation/cgroups/cpusets.txt).
-
-The following parameters can be specified to setup the controller:
-
-* **`shares`** *(uint64, optional)* - specifies a relative share of CPU time available to the tasks in a cgroup
-
-* **`quota`** *(uint64, optional)* - specifies the total amount of time in microseconds for which all tasks in a cgroup can run during one period (as defined by **`period`** below)
-
-* **`period`** *(uint64, optional)* - specifies a period of time in microseconds for how regularly a cgroup's access to CPU resources should be reallocated (CFS scheduler only)
-
-* **`realtimeRuntime`** *(uint64, optional)* - specifies a period of time in microseconds for the longest continuous period in which the tasks in a cgroup have access to CPU resources
-
-* **`realtimePeriod`** *(uint64, optional)* - same as **`period`** but applies to realtime scheduler only
-
-* **`cpus`** *(cpus, optional)* - list of CPUs the container will run in
-
-* **`mems`** *(mems, optional)* - list of Memory Nodes the container will run in
-
-###### Example
-
-```json
- "cpu": {
- "shares": 0,
- "quota": 0,
- "period": 0,
- "realtimeRuntime": 0,
- "realtimePeriod": 0,
- "cpus": "",
- "mems": ""
- }
-```
-
-#### Block IO Controller
-
-`blockIO` represents the cgroup subsystem `blkio` which implements the block io controller.
-For more information, see [the kernel cgroups documentation about blkio](https://www.kernel.org/doc/Documentation/cgroups/blkio-controller.txt).
-
-The following parameters can be specified to setup the controller:
-
-* **`blkioWeight`** *(uint16, optional)* - specifies per-cgroup weight. This is default weight of the group on all devices until and unless overridden by per-device rules. The range is from 10 to 1000.
-
-* **`blkioLeafWeight`** *(uint16, optional)* - equivalents of `blkioWeight` for the purpose of deciding how much weight tasks in the given cgroup has while competing with the cgroup's child cgroups. The range is from 10 to 1000.
-
-* **`blkioWeightDevice`** *(array, optional)* - specifies the list of devices which will be bandwidth rate limited. The following parameters can be specified per-device:
- * **`major, minor`** *(int64, required)* - major, minor numbers for device. More info in `man mknod`.
- * **`weight`** *(uint16, optional)* - bandwidth rate for the device, range is from 10 to 1000
- * **`leafWeight`** *(uint16, optional)* - bandwidth rate for the device while competing with the cgroup's child cgroups, range is from 10 to 1000, CFQ scheduler only
-
- You must specify at least one of `weight` or `leafWeight` in a given entry, and can specify both.
-
-* **`blkioThrottleReadBpsDevice`**, **`blkioThrottleWriteBpsDevice`**, **`blkioThrottleReadIOPSDevice`**, **`blkioThrottleWriteIOPSDevice`** *(array, optional)* - specify the list of devices which will be IO rate limited. The following parameters can be specified per-device:
- * **`major, minor`** *(int64, required)* - major, minor numbers for device. More info in `man mknod`.
- * **`rate`** *(uint64, required)* - IO rate limit for the device
-
-###### Example
-
-```json
- "blockIO": {
- "blkioWeight": 0,
- "blkioLeafWeight": 0,
- "blkioWeightDevice": [
- {
- "major": 8,
- "minor": 0,
- "weight": 500,
- "leafWeight": 300
- },
- {
- "major": 8,
- "minor": 16,
- "weight": 500
- }
- ],
- "blkioThrottleReadBpsDevice": [
- {
- "major": 8,
- "minor": 0,
- "rate": 600
- }
- ],
- "blkioThrottleWriteIOPSDevice": [
- {
- "major": 8,
- "minor": 16,
- "rate": 300
- }
- ]
- }
-```
-
-#### Huge page limits
-
-`hugepageLimits` represents the `hugetlb` controller which allows to limit the
-HugeTLB usage per control group and enforces the controller limit during page fault.
-For more information, see the [kernel cgroups documentation about HugeTLB](https://www.kernel.org/doc/Documentation/cgroups/hugetlb.txt).
-
-`hugepageLimits` is an array of entries, each having the following structure:
-
-* **`pageSize`** *(string, required)* - hugepage size
-
-* **`limit`** *(uint64, required)* - limit in bytes of *hugepagesize* HugeTLB usage
-
-###### Example
-
-```json
- "hugepageLimits": [
- {
- "pageSize": "2MB",
- "limit": 9223372036854771712
- }
- ]
-```
-
-#### Network
-
-`network` represents the cgroup subsystems `net_cls` and `net_prio`.
-For more information, see [the net\_cls cgroup man page](https://www.kernel.org/doc/Documentation/cgroups/net_cls.txt) and [the net\_prio cgroup man page](https://www.kernel.org/doc/Documentation/cgroups/net_prio.txt).
-
-The following parameters can be specified to setup these cgroup controllers:
-
-* **`classID`** *(string, optional)* - is the network class identifier the cgroup's network packets will be tagged with
-
-* **`priorities`** *(array, optional)* - specifies a list of objects of the priorities assigned to traffic originating from
-processes in the group and egressing the system on various interfaces. The following parameters can be specified per-priority:
- * **`name`** *(string, required)* - interface name
- * **`priority`** *(uint32, required)* - priority applied to the interface
-
-###### Example
-
-```json
- "network": {
- "classID": "0x100001",
- "priorities": [
- {
- "name": "eth0",
- "priority": 500
- },
- {
- "name": "eth1",
- "priority": 1000
- }
- ]
- }
-```
-
-#### PIDs
-
-`pids` represents the cgroup subsystem `pids`.
-For more information, see [the pids cgroup man page](https://www.kernel.org/doc/Documentation/cgroups/pids.txt
-).
-
-The following paramters can be specified to setup the controller:
-
-* **`limit`** *(int64, required)* - specifies the maximum number of tasks in the cgroup
-
-###### Example
-
-```json
- "pids": {
- "limit": 32771
- }
-```
-
-## Sysctl
-
-sysctl allows kernel parameters to be modified at runtime for the container.
-For more information, see [the man page](http://man7.org/linux/man-pages/man8/sysctl.8.html)
-
-###### Example
-
-```json
- "sysctl": {
- "net.ipv4.ip_forward": "1",
- "net.core.somaxconn": "256"
- }
-```
-
-## Rlimits
-
-rlimits allow setting resource limits.
-`type` is a string with a value from those defined in [the man page](http://man7.org/linux/man-pages/man2/setrlimit.2.html).
-The kernel enforces the `soft` limit for a resource while the `hard` limit acts as a ceiling for that value that could be set by an unprivileged process.
-
-###### Example
-
-```json
- "rlimits": [
- {
- "type": "RLIMIT_NPROC",
- "soft": 1024,
- "hard": 102400
- }
- ]
-```
-
-## SELinux process label
-
-SELinux process label specifies the label with which the processes in a container are run.
-For more information about SELinux, see [Selinux documentation](http://selinuxproject.org/page/Main_Page)
-
-###### Example
-
-```json
- "selinuxProcessLabel": "system_u:system_r:svirt_lxc_net_t:s0:c124,c675"
-```
-
-## Apparmor profile
-
-Apparmor profile specifies the name of the apparmor profile that will be used for the container.
-For more information about Apparmor, see [Apparmor documentation](https://wiki.ubuntu.com/AppArmor)
-
-###### Example
-
-```json
- "apparmorProfile": "acme_secure_profile"
-```
-
-## seccomp
-
-Seccomp provides application sandboxing mechanism in the Linux kernel.
-Seccomp configuration allows one to configure actions to take for matched syscalls and furthermore also allows matching on values passed as arguments to syscalls.
-For more information about Seccomp, see [Seccomp kernel documentation](https://www.kernel.org/doc/Documentation/prctl/seccomp_filter.txt)
-The actions, architectures, and operators are strings that match the definitions in seccomp.h from [libseccomp](https://github.com/seccomp/libseccomp) and are translated to corresponding values.
-A valid list of constants as of Libseccomp v2.2.3 is contained below.
-
-Architecture Constants
-* `SCMP_ARCH_X86`
-* `SCMP_ARCH_X86_64`
-* `SCMP_ARCH_X32`
-* `SCMP_ARCH_ARM`
-* `SCMP_ARCH_AARCH64`
-* `SCMP_ARCH_MIPS`
-* `SCMP_ARCH_MIPS64`
-* `SCMP_ARCH_MIPS64N32`
-* `SCMP_ARCH_MIPSEL`
-* `SCMP_ARCH_MIPSEL64`
-* `SCMP_ARCH_MIPSEL64N32`
-
-Action Constants:
-* `SCMP_ACT_KILL`
-* `SCMP_ACT_TRAP`
-* `SCMP_ACT_ERRNO`
-* `SCMP_ACT_TRACE`
-* `SCMP_ACT_ALLOW`
-
-Operator Constants:
-* `SCMP_CMP_NE`
-* `SCMP_CMP_LT`
-* `SCMP_CMP_LE`
-* `SCMP_CMP_EQ`
-* `SCMP_CMP_GE`
-* `SCMP_CMP_GT`
-* `SCMP_CMP_MASKED_EQ`
-
-###### Example
-
-```json
- "seccomp": {
- "defaultAction": "SCMP_ACT_ALLOW",
- "architectures": [
- "SCMP_ARCH_X86"
- ],
- "syscalls": [
- {
- "name": "getcwd",
- "action": "SCMP_ACT_ERRNO"
- }
- ]
- }
-```
-
-## Rootfs Mount Propagation
-
-rootfsPropagation sets the rootfs's mount propagation.
-Its value is either slave, private, or shared.
-[The kernel doc](https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt) has more information about mount propagation.
-
-###### Example
-
-```json
- "rootfsPropagation": "slave",
-```
diff --git a/containerd/vendor/github.com/opencontainers/specs/runtime-config.md b/containerd/vendor/github.com/opencontainers/specs/runtime-config.md
deleted file mode 100644
index 3313a0a..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/runtime-config.md
+++ /dev/null
@@ -1,121 +0,0 @@
-# Runtime Configuration
-
-## Hooks
-
-Lifecycle hooks allow custom events for different points in a container's runtime.
-Presently there are `Prestart`, `Poststart` and `Poststop`.
-
-* [`Prestart`](#prestart) is a list of hooks to be run before the container process is executed
-* [`Poststart`](#poststart) is a list of hooks to be run immediately after the container process is started
-* [`Poststop`](#poststop) is a list of hooks to be run after the container process exits
-
-Hooks allow one to run code before/after various lifecycle events of the container.
-Hooks MUST be called in the listed order.
-The state of the container is passed to the hooks over stdin, so the hooks could get the information they need to do their work.
-
-Hook paths are absolute and are executed from the host's filesystem.
-
-### Prestart
-
-The pre-start hooks are called after the container process is spawned, but before the user supplied command is executed.
-They are called after the container namespaces are created on Linux, so they provide an opportunity to customize the container.
-In Linux, for e.g., the network namespace could be configured in this hook.
-
-If a hook returns a non-zero exit code, then an error including the exit code and the stderr is returned to the caller and the container is torn down.
-
-### Poststart
-
-The post-start hooks are called after the user process is started.
-For example this hook can notify user that real process is spawned.
-
-If a hook returns a non-zero exit code, then an error is logged and the remaining hooks are executed.
-
-### Poststop
-
-The post-stop hooks are called after the container process is stopped.
-Cleanup or debugging could be performed in such a hook.
-If a hook returns a non-zero exit code, then an error is logged and the remaining hooks are executed.
-
-*Example*
-
-```json
- "hooks" : {
- "prestart": [
- {
- "path": "/usr/bin/fix-mounts",
- "args": ["arg1", "arg2"],
- "env": [ "key1=value1"]
- },
- {
- "path": "/usr/bin/setup-network"
- }
- ],
- "poststart": [
- {
- "path": "/usr/bin/notify-start"
- }
- ],
- "poststop": [
- {
- "path": "/usr/sbin/cleanup.sh",
- "args": ["-f"]
- }
- ]
- }
-```
-
-`path` is required for a hook.
-`args` and `env` are optional.
-
-## Mount Configuration
-
-Additional filesystems can be declared as "mounts", specified in the *mounts* object.
-Keys in this object are names of mount points from portable config.
-Values are objects with configuration of mount points.
-The parameters are similar to the ones in [the Linux mount system call](http://man7.org/linux/man-pages/man2/mount.2.html).
-Only [mounts from the portable config](config.md#mount-points) will be mounted.
-
-* **`type`** (string, required) Linux, *filesystemtype* argument supported by the kernel are listed in */proc/filesystems* (e.g., "minix", "ext2", "ext3", "jfs", "xfs", "reiserfs", "msdos", "proc", "nfs", "iso9660"). Windows: ntfs
-* **`source`** (string, required) a device name, but can also be a directory name or a dummy. Windows, the volume name that is the target of the mount point. \\?\Volume\{GUID}\ (on Windows source is called target)
-* **`options`** (list of strings, optional) in the fstab format [https://wiki.archlinux.org/index.php/Fstab](https://wiki.archlinux.org/index.php/Fstab).
-
-*Example (Linux)*
-
-```json
-"mounts": {
- "proc": {
- "type": "proc",
- "source": "proc",
- "options": []
- },
- "dev": {
- "type": "tmpfs",
- "source": "tmpfs",
- "options": ["nosuid","strictatime","mode=755","size=65536k"]
- },
- "devpts": {
- "type": "devpts",
- "source": "devpts",
- "options": ["nosuid","noexec","newinstance","ptmxmode=0666","mode=0620","gid=5"]
- },
- "data": {
- "type": "bind",
- "source": "/volumes/testing",
- "options": ["rbind","rw"]
- }
-}
-```
-
-*Example (Windows)*
-
-```json
-"mounts": {
- "myfancymountpoint": {
- "type": "ntfs",
- "source": "\\\\?\\Volume\\{2eca078d-5cbc-43d3-aff8-7e8511f60d0e}\\",
- "options": []
- }
-}
-```
-
-See links for details about [mountvol](http://ss64.com/nt/mountvol.html) and [SetVolumeMountPoint](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365561(v=vs.85).aspx) in Windows.
diff --git a/containerd/vendor/github.com/opencontainers/specs/runtime-linux.md b/containerd/vendor/github.com/opencontainers/specs/runtime-linux.md
deleted file mode 100644
index 36277a1..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/runtime-linux.md
+++ /dev/null
@@ -1,8 +0,0 @@
-# Linux Runtime
-
-## File descriptors
-By default, only the `stdin`, `stdout` and `stderr` file descriptors are kept open for the application by the runtime.
-
-The runtime may pass additional file descriptors to the application to support features such as [socket activation](http://0pointer.de/blog/projects/socket-activated-containers.html).
-
-Some of the file descriptors may be redirected to `/dev/null` even though they are open.
diff --git a/containerd/vendor/github.com/opencontainers/specs/runtime.md b/containerd/vendor/github.com/opencontainers/specs/runtime.md
deleted file mode 100644
index fdaf965..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/runtime.md
+++ /dev/null
@@ -1,56 +0,0 @@
-# Runtime and Lifecycle
-
-## State
-
-Runtime MUST store container metadata on disk so that external tools can consume and act on this information.
-It is recommended that this data be stored in a temporary filesystem so that it can be removed on a system reboot.
-On Linux/Unix based systems the metadata MUST be stored under `/run/opencontainer/containers`.
-For non-Linux/Unix based systems the location of the root metadata directory is currently undefined.
-Within that directory there MUST be one directory for each container created, where the name of the directory MUST be the ID of the container.
-For example: for a Linux container with an ID of `173975398351`, there will be a corresponding directory: `/run/opencontainer/containers/173975398351`.
-Within each container's directory, there MUST be a JSON encoded file called `state.json` that contains the runtime state of the container.
-For example: `/run/opencontainer/containers/173975398351/state.json`.
-
-The `state.json` file MUST contain all of the following properties:
-
-* **`version`**: (string) is the OCF specification version used when creating the container.
-* **`id`**: (string) is the container's ID.
-This MUST be unique across all containers on this host.
-There is no requirement that it be unique across hosts.
-The ID is provided in the state because hooks will be executed with the state as the payload.
-This allows the hooks to perform cleanup and teardown logic after the runtime destroys its own state.
-* **`pid`**: (int) is the ID of the main process within the container, as seen by the host.
-* **`bundlePath`**: (string) is the absolute path to the container's bundle directory.
-This is provided so that consumers can find the container's configuration and root filesystem on the host.
-
-*Example*
-
-```json
-{
- "id": "oc-container",
- "pid": 4422,
- "root": "/containers/redis"
-}
-```
-
-## Lifecycle
-
-### Create
-
-Creates the container: file system, namespaces, cgroups, capabilities.
-
-### Start (process)
-
-Runs a process in a container.
-Can be invoked several times.
-
-### Stop (process)
-
-Not sure we need that from runc cli.
-Process is killed from the outside.
-
-This event needs to be captured by runc to run onstop event handlers.
-
-## Hooks
-
-See [runtime configuration for hooks](./runtime-config.md)
diff --git a/containerd/vendor/github.com/opencontainers/specs/runtime_config.go b/containerd/vendor/github.com/opencontainers/specs/runtime_config.go
deleted file mode 100644
index 5665ca9..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/runtime_config.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package specs
-
-// RuntimeSpec contains host-specific configuration information for
-// a container. This information must not be included when the bundle
-// is packaged for distribution.
-type RuntimeSpec struct {
- // Mounts is a mapping of names to mount configurations.
- // Which mounts will be mounted and where should be chosen with MountPoints
- // in Spec.
- Mounts map[string]Mount `json:"mounts"`
- // Hooks are the commands run at various lifecycle events of the container.
- Hooks Hooks `json:"hooks"`
-}
-
-// Hook specifies a command that is run at a particular event in the lifecycle of a container
-type Hook struct {
- Path string `json:"path"`
- Args []string `json:"args"`
- Env []string `json:"env"`
-}
-
-// Hooks for container setup and teardown
-type Hooks struct {
- // Prestart is a list of hooks to be run before the container process is executed.
- // On Linux, they are run after the container namespaces are created.
- Prestart []Hook `json:"prestart"`
- // Poststart is a list of hooks to be run after the container process is started.
- Poststart []Hook `json:"poststart"`
- // Poststop is a list of hooks to be run after the container process exits.
- Poststop []Hook `json:"poststop"`
-}
-
-// Mount specifies a mount for a container
-type Mount struct {
- // Type specifies the mount kind.
- Type string `json:"type"`
- // Source specifies the source path of the mount. In the case of bind mounts on
- // linux based systems this would be the file on the host.
- Source string `json:"source"`
- // Options are fstab style mount options.
- Options []string `json:"options"`
-}
diff --git a/containerd/vendor/github.com/opencontainers/specs/runtime_config_linux.go b/containerd/vendor/github.com/opencontainers/specs/runtime_config_linux.go
deleted file mode 100644
index bcace7e..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/runtime_config_linux.go
+++ /dev/null
@@ -1,301 +0,0 @@
-package specs
-
-import "os"
-
-// LinuxStateDirectory holds the container's state information
-const LinuxStateDirectory = "/run/opencontainer/containers"
-
-// LinuxRuntimeSpec is the full specification for linux containers.
-type LinuxRuntimeSpec struct {
- RuntimeSpec
- // LinuxRuntime is platform specific configuration for linux based containers.
- Linux LinuxRuntime `json:"linux"`
-}
-
-// LinuxRuntime hosts the Linux-only runtime information
-type LinuxRuntime struct {
- // UIDMapping specifies user mappings for supporting user namespaces on linux.
- UIDMappings []IDMapping `json:"uidMappings"`
- // GIDMapping specifies group mappings for supporting user namespaces on linux.
- GIDMappings []IDMapping `json:"gidMappings"`
- // Rlimits specifies rlimit options to apply to the container's process.
- Rlimits []Rlimit `json:"rlimits"`
- // Sysctl are a set of key value pairs that are set for the container on start
- Sysctl map[string]string `json:"sysctl"`
- // Resources contain cgroup information for handling resource constraints
- // for the container
- Resources *Resources `json:"resources"`
- // CgroupsPath specifies the path to cgroups that are created and/or joined by the container.
- // The path is expected to be relative to the cgroups mountpoint.
- // If resources are specified, the cgroups at CgroupsPath will be updated based on resources.
- CgroupsPath string `json:"cgroupsPath"`
- // Namespaces contains the namespaces that are created and/or joined by the container
- Namespaces []Namespace `json:"namespaces"`
- // Devices are a list of device nodes that are created and enabled for the container
- Devices []Device `json:"devices"`
- // ApparmorProfile specified the apparmor profile for the container.
- ApparmorProfile string `json:"apparmorProfile"`
- // SelinuxProcessLabel specifies the selinux context that the container process is run as.
- SelinuxProcessLabel string `json:"selinuxProcessLabel"`
- // Seccomp specifies the seccomp security settings for the container.
- Seccomp Seccomp `json:"seccomp"`
- // RootfsPropagation is the rootfs mount propagation mode for the container
- RootfsPropagation string `json:"rootfsPropagation"`
-}
-
-// Namespace is the configuration for a linux namespace
-type Namespace struct {
- // Type is the type of Linux namespace
- Type NamespaceType `json:"type"`
- // Path is a path to an existing namespace persisted on disk that can be joined
- // and is of the same type
- Path string `json:"path"`
-}
-
-// NamespaceType is one of the linux namespaces
-type NamespaceType string
-
-const (
- // PIDNamespace for isolating process IDs
- PIDNamespace NamespaceType = "pid"
- // NetworkNamespace for isolating network devices, stacks, ports, etc
- NetworkNamespace = "network"
- // MountNamespace for isolating mount points
- MountNamespace = "mount"
- // IPCNamespace for isolating System V IPC, POSIX message queues
- IPCNamespace = "ipc"
- // UTSNamespace for isolating hostname and NIS domain name
- UTSNamespace = "uts"
- // UserNamespace for isolating user and group IDs
- UserNamespace = "user"
-)
-
-// IDMapping specifies UID/GID mappings
-type IDMapping struct {
- // HostID is the UID/GID of the host user or group
- HostID uint32 `json:"hostID"`
- // ContainerID is the UID/GID of the container's user or group
- ContainerID uint32 `json:"containerID"`
- // Size is the length of the range of IDs mapped between the two namespaces
- Size uint32 `json:"size"`
-}
-
-// Rlimit type and restrictions
-type Rlimit struct {
- // Type of the rlimit to set
- Type string `json:"type"`
- // Hard is the hard limit for the specified type
- Hard uint64 `json:"hard"`
- // Soft is the soft limit for the specified type
- Soft uint64 `json:"soft"`
-}
-
-// HugepageLimit structure corresponds to limiting kernel hugepages
-type HugepageLimit struct {
- // Pagesize is the hugepage size
- Pagesize string `json:"pageSize"`
- // Limit is the limit of "hugepagesize" hugetlb usage
- Limit uint64 `json:"limit"`
-}
-
-// InterfacePriority for network interfaces
-type InterfacePriority struct {
- // Name is the name of the network interface
- Name string `json:"name"`
- // Priority for the interface
- Priority uint32 `json:"priority"`
-}
-
-// blockIODevice holds major:minor format supported in blkio cgroup
-type blockIODevice struct {
- // Major is the device's major number.
- Major int64 `json:"major"`
- // Minor is the device's minor number.
- Minor int64 `json:"minor"`
-}
-
-// WeightDevice struct holds a `major:minor weight` pair for blkioWeightDevice
-type WeightDevice struct {
- blockIODevice
- // Weight is the bandwidth rate for the device, range is from 10 to 1000
- Weight uint16 `json:"weight"`
- // LeafWeight is the bandwidth rate for the device while competing with the cgroup's child cgroups, range is from 10 to 1000, CFQ scheduler only
- LeafWeight uint16 `json:"leafWeight"`
-}
-
-// ThrottleDevice struct holds a `major:minor rate_per_second` pair
-type ThrottleDevice struct {
- blockIODevice
- // Rate is the IO rate limit per cgroup per device
- Rate uint64 `json:"rate"`
-}
-
-// BlockIO for Linux cgroup 'blkio' resource management
-type BlockIO struct {
- // Specifies per cgroup weight, range is from 10 to 1000
- Weight uint16 `json:"blkioWeight"`
- // Specifies tasks' weight in the given cgroup while competing with the cgroup's child cgroups, range is from 10 to 1000, CFQ scheduler only
- LeafWeight uint16 `json:"blkioLeafWeight"`
- // Weight per cgroup per device, can override BlkioWeight
- WeightDevice []*WeightDevice `json:"blkioWeightDevice"`
- // IO read rate limit per cgroup per device, bytes per second
- ThrottleReadBpsDevice []*ThrottleDevice `json:"blkioThrottleReadBpsDevice"`
- // IO write rate limit per cgroup per device, bytes per second
- ThrottleWriteBpsDevice []*ThrottleDevice `json:"blkioThrottleWriteBpsDevice"`
- // IO read rate limit per cgroup per device, IO per second
- ThrottleReadIOPSDevice []*ThrottleDevice `json:"blkioThrottleReadIOPSDevice"`
- // IO write rate limit per cgroup per device, IO per second
- ThrottleWriteIOPSDevice []*ThrottleDevice `json:"blkioThrottleWriteIOPSDevice"`
-}
-
-// Memory for Linux cgroup 'memory' resource management
-type Memory struct {
- // Memory limit (in bytes)
- Limit uint64 `json:"limit"`
- // Memory reservation or soft_limit (in bytes)
- Reservation uint64 `json:"reservation"`
- // Total memory usage (memory + swap); set `-1' to disable swap
- Swap uint64 `json:"swap"`
- // Kernel memory limit (in bytes)
- Kernel uint64 `json:"kernel"`
- // How aggressive the kernel will swap memory pages. Range from 0 to 100. Set -1 to use system default
- Swappiness uint64 `json:"swappiness"`
-}
-
-// CPU for Linux cgroup 'cpu' resource management
-type CPU struct {
- // CPU shares (relative weight vs. other cgroups with cpu shares)
- Shares uint64 `json:"shares"`
- // CPU hardcap limit (in usecs). Allowed cpu time in a given period
- Quota uint64 `json:"quota"`
- // CPU period to be used for hardcapping (in usecs). 0 to use system default
- Period uint64 `json:"period"`
- // How many time CPU will use in realtime scheduling (in usecs)
- RealtimeRuntime uint64 `json:"realtimeRuntime"`
- // CPU period to be used for realtime scheduling (in usecs)
- RealtimePeriod uint64 `json:"realtimePeriod"`
- // CPU to use within the cpuset
- Cpus string `json:"cpus"`
- // MEM to use within the cpuset
- Mems string `json:"mems"`
-}
-
-// Pids for Linux cgroup 'pids' resource management (Linux 4.3)
-type Pids struct {
- // Maximum number of PIDs. A value <= 0 indicates "no limit".
- Limit int64 `json:"limit"`
-}
-
-// Network identification and priority configuration
-type Network struct {
- // Set class identifier for container's network packets
- // this is actually a string instead of a uint64 to overcome the json
- // limitation of specifying hex numbers
- ClassID string `json:"classID"`
- // Set priority of network traffic for container
- Priorities []InterfacePriority `json:"priorities"`
-}
-
-// Resources has container runtime resource constraints
-type Resources struct {
- // DisableOOMKiller disables the OOM killer for out of memory conditions
- DisableOOMKiller bool `json:"disableOOMKiller"`
- // Specify an oom_score_adj for the container. Optional.
- OOMScoreAdj int `json:"oomScoreAdj"`
- // Memory restriction configuration
- Memory Memory `json:"memory"`
- // CPU resource restriction configuration
- CPU CPU `json:"cpu"`
- // Task resource restriction configuration.
- Pids Pids `json:"pids"`
- // BlockIO restriction configuration
- BlockIO BlockIO `json:"blockIO"`
- // Hugetlb limit (in bytes)
- HugepageLimits []HugepageLimit `json:"hugepageLimits"`
- // Network restriction configuration
- Network Network `json:"network"`
-}
-
-// Device represents the information on a Linux special device file
-type Device struct {
- // Path to the device.
- Path string `json:"path"`
- // Device type, block, char, etc.
- Type rune `json:"type"`
- // Major is the device's major number.
- Major int64 `json:"major"`
- // Minor is the device's minor number.
- Minor int64 `json:"minor"`
- // Cgroup permissions format, rwm.
- Permissions string `json:"permissions"`
- // FileMode permission bits for the device.
- FileMode os.FileMode `json:"fileMode"`
- // UID of the device.
- UID uint32 `json:"uid"`
- // Gid of the device.
- GID uint32 `json:"gid"`
-}
-
-// Seccomp represents syscall restrictions
-type Seccomp struct {
- DefaultAction Action `json:"defaultAction"`
- Architectures []Arch `json:"architectures"`
- Syscalls []*Syscall `json:"syscalls"`
-}
-
-// Additional architectures permitted to be used for system calls
-// By default only the native architecture of the kernel is permitted
-type Arch string
-
-const (
- ArchX86 Arch = "SCMP_ARCH_X86"
- ArchX86_64 Arch = "SCMP_ARCH_X86_64"
- ArchX32 Arch = "SCMP_ARCH_X32"
- ArchARM Arch = "SCMP_ARCH_ARM"
- ArchAARCH64 Arch = "SCMP_ARCH_AARCH64"
- ArchMIPS Arch = "SCMP_ARCH_MIPS"
- ArchMIPS64 Arch = "SCMP_ARCH_MIPS64"
- ArchMIPS64N32 Arch = "SCMP_ARCH_MIPS64N32"
- ArchMIPSEL Arch = "SCMP_ARCH_MIPSEL"
- ArchMIPSEL64 Arch = "SCMP_ARCH_MIPSEL64"
- ArchMIPSEL64N32 Arch = "SCMP_ARCH_MIPSEL64N32"
-)
-
-// Action taken upon Seccomp rule match
-type Action string
-
-const (
- ActKill Action = "SCMP_ACT_KILL"
- ActTrap Action = "SCMP_ACT_TRAP"
- ActErrno Action = "SCMP_ACT_ERRNO"
- ActTrace Action = "SCMP_ACT_TRACE"
- ActAllow Action = "SCMP_ACT_ALLOW"
-)
-
-// Operator used to match syscall arguments in Seccomp
-type Operator string
-
-const (
- OpNotEqual Operator = "SCMP_CMP_NE"
- OpLessThan Operator = "SCMP_CMP_LT"
- OpLessEqual Operator = "SCMP_CMP_LE"
- OpEqualTo Operator = "SCMP_CMP_EQ"
- OpGreaterEqual Operator = "SCMP_CMP_GE"
- OpGreaterThan Operator = "SCMP_CMP_GT"
- OpMaskedEqual Operator = "SCMP_CMP_MASKED_EQ"
-)
-
-// Arg used for matching specific syscall arguments in Seccomp
-type Arg struct {
- Index uint `json:"index"`
- Value uint64 `json:"value"`
- ValueTwo uint64 `json:"valueTwo"`
- Op Operator `json:"op"`
-}
-
-// Syscall is used to match a syscall in Seccomp
-type Syscall struct {
- Name string `json:"name"`
- Action Action `json:"action"`
- Args []*Arg `json:"args"`
-}
diff --git a/containerd/vendor/github.com/opencontainers/specs/state.go b/containerd/vendor/github.com/opencontainers/specs/state.go
deleted file mode 100644
index a663381..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/state.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package specs
-
-// State holds information about the runtime state of the container.
-// This information will be stored in a file called `state.json`.
-// The location of this file will be operating system specific. On Linux
-// it will be in `/run/opencontainers/runc//state.json`
-type State struct {
- // Version is the version of the specification that is supported.
- Version string `json:"version"`
- // ID is the container ID
- ID string `json:"id"`
- // Pid is the process id for the container's main process.
- Pid int `json:"pid"`
- // BundlePath is the path to the container's bundle directory.
- BundlePath string `json:"bundlePath"`
-}
diff --git a/containerd/vendor/github.com/opencontainers/specs/version.go b/containerd/vendor/github.com/opencontainers/specs/version.go
deleted file mode 100644
index c2d1e29..0000000
--- a/containerd/vendor/github.com/opencontainers/specs/version.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package specs
-
-import "fmt"
-
-const (
- // VersionMajor is for an API incompatible changes
- VersionMajor = 0
- // VersionMinor is for functionality in a backwards-compatible manner
- VersionMinor = 2
- // VersionPatch is for backwards-compatible bug fixes
- VersionPatch = 0
-)
-
-// Version is the specification version that the package types support.
-var Version = fmt.Sprintf("%d.%d.%d", VersionMajor, VersionMinor, VersionPatch)
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/.gitignore b/containerd/vendor/github.com/rcrowley/go-metrics/.gitignore
deleted file mode 100644
index 83c8f82..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/.gitignore
+++ /dev/null
@@ -1,9 +0,0 @@
-*.[68]
-*.a
-*.out
-*.swp
-_obj
-_testmain.go
-cmd/metrics-bench/metrics-bench
-cmd/metrics-example/metrics-example
-cmd/never-read/never-read
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/.travis.yml b/containerd/vendor/github.com/rcrowley/go-metrics/.travis.yml
deleted file mode 100644
index 8fb623c..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/.travis.yml
+++ /dev/null
@@ -1,13 +0,0 @@
-language: go
-
-go:
- - 1.2
- - 1.3
- - 1.4
-
-script:
- - ./validate.sh
-
-# this should give us faster builds according to
-# http://docs.travis-ci.com/user/migrating-from-legacy/
-sudo: false
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/LICENSE b/containerd/vendor/github.com/rcrowley/go-metrics/LICENSE
deleted file mode 100644
index 363fa9e..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/LICENSE
+++ /dev/null
@@ -1,29 +0,0 @@
-Copyright 2012 Richard Crowley. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- 1. Redistributions of source code must retain the above copyright
- notice, this list of conditions and the following disclaimer.
-
- 2. 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.
-
-THIS SOFTWARE IS PROVIDED BY RICHARD CROWLEY ``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 RICHARD CROWLEY 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.
-
-The views and conclusions contained in the software and documentation
-are those of the authors and should not be interpreted as representing
-official policies, either expressed or implied, of Richard Crowley.
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/README.md b/containerd/vendor/github.com/rcrowley/go-metrics/README.md
deleted file mode 100644
index ce829a0..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/README.md
+++ /dev/null
@@ -1,126 +0,0 @@
-go-metrics
-==========
-
-![travis build status](https://travis-ci.org/rcrowley/go-metrics.svg?branch=master)
-
-Go port of Coda Hale's Metrics library: .
-
-Documentation: .
-
-Usage
------
-
-Create and update metrics:
-
-```go
-c := metrics.NewCounter()
-metrics.Register("foo", c)
-c.Inc(47)
-
-g := metrics.NewGauge()
-metrics.Register("bar", g)
-g.Update(47)
-
-s := metrics.NewExpDecaySample(1028, 0.015) // or metrics.NewUniformSample(1028)
-h := metrics.NewHistogram(s)
-metrics.Register("baz", h)
-h.Update(47)
-
-m := metrics.NewMeter()
-metrics.Register("quux", m)
-m.Mark(47)
-
-t := metrics.NewTimer()
-metrics.Register("bang", t)
-t.Time(func() {})
-t.Update(47)
-```
-
-Periodically log every metric in human-readable form to standard error:
-
-```go
-go metrics.Log(metrics.DefaultRegistry, 60e9, log.New(os.Stderr, "metrics: ", log.Lmicroseconds))
-```
-
-Periodically log every metric in slightly-more-parseable form to syslog:
-
-```go
-w, _ := syslog.Dial("unixgram", "/dev/log", syslog.LOG_INFO, "metrics")
-go metrics.Syslog(metrics.DefaultRegistry, 60e9, w)
-```
-
-Periodically emit every metric to Graphite using the [Graphite client](https://github.com/cyberdelia/go-metrics-graphite):
-
-```go
-
-import "github.com/cyberdelia/go-metrics-graphite"
-
-addr, _ := net.ResolveTCPAddr("tcp", "127.0.0.1:2003")
-go graphite.Graphite(metrics.DefaultRegistry, 10e9, "metrics", addr)
-```
-
-Periodically emit every metric into InfluxDB:
-
-**NOTE:** this has been pulled out of the library due to constant fluctuations
-in the InfluxDB API. In fact, all client libraries are on their way out. see
-issues [#121](https://github.com/rcrowley/go-metrics/issues/121) and
-[#124](https://github.com/rcrowley/go-metrics/issues/124) for progress and details.
-
-```go
-import "github.com/rcrowley/go-metrics/influxdb"
-
-go influxdb.Influxdb(metrics.DefaultRegistry, 10e9, &influxdb.Config{
- Host: "127.0.0.1:8086",
- Database: "metrics",
- Username: "test",
- Password: "test",
-})
-```
-
-Periodically upload every metric to Librato using the [Librato client](https://github.com/mihasya/go-metrics-librato):
-
-**Note**: the client included with this repository under the `librato` package
-has been deprecated and moved to the repository linked above.
-
-```go
-import "github.com/mihasya/go-metrics-librato"
-
-go librato.Librato(metrics.DefaultRegistry,
- 10e9, // interval
- "example@example.com", // account owner email address
- "token", // Librato API token
- "hostname", // source
- []float64{0.95}, // percentiles to send
- time.Millisecond, // time unit
-)
-```
-
-Periodically emit every metric to StatHat:
-
-```go
-import "github.com/rcrowley/go-metrics/stathat"
-
-go stathat.Stathat(metrics.DefaultRegistry, 10e9, "example@example.com")
-```
-
-Installation
-------------
-
-```sh
-go get github.com/rcrowley/go-metrics
-```
-
-StatHat support additionally requires their Go client:
-
-```sh
-go get github.com/stathat/go
-```
-
-Publishing Metrics
-------------------
-
-Clients are available for the following destinations:
-
-* Librato - [https://github.com/mihasya/go-metrics-librato](https://github.com/mihasya/go-metrics-librato)
-* Graphite - [https://github.com/cyberdelia/go-metrics-graphite](https://github.com/cyberdelia/go-metrics-graphite)
-* InfluxDB - [https://github.com/vrischmann/go-metrics-influxdb](https://github.com/vrischmann/go-metrics-influxdb)
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/cmd/metrics-bench/metrics-bench.go b/containerd/vendor/github.com/rcrowley/go-metrics/cmd/metrics-bench/metrics-bench.go
deleted file mode 100644
index dddaf4b..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/cmd/metrics-bench/metrics-bench.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package main
-
-import (
- "fmt"
- "github.com/rcrowley/go-metrics"
- "time"
-)
-
-func main() {
- r := metrics.NewRegistry()
- for i := 0; i < 10000; i++ {
- r.Register(fmt.Sprintf("counter-%d", i), metrics.NewCounter())
- r.Register(fmt.Sprintf("gauge-%d", i), metrics.NewGauge())
- r.Register(fmt.Sprintf("gaugefloat64-%d", i), metrics.NewGaugeFloat64())
- r.Register(fmt.Sprintf("histogram-uniform-%d", i), metrics.NewHistogram(metrics.NewUniformSample(1028)))
- r.Register(fmt.Sprintf("histogram-exp-%d", i), metrics.NewHistogram(metrics.NewExpDecaySample(1028, 0.015)))
- r.Register(fmt.Sprintf("meter-%d", i), metrics.NewMeter())
- }
- time.Sleep(600e9)
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/cmd/metrics-example/metrics-example.go b/containerd/vendor/github.com/rcrowley/go-metrics/cmd/metrics-example/metrics-example.go
deleted file mode 100644
index 66f42c0..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/cmd/metrics-example/metrics-example.go
+++ /dev/null
@@ -1,154 +0,0 @@
-package main
-
-import (
- "errors"
- "github.com/rcrowley/go-metrics"
- // "github.com/rcrowley/go-metrics/stathat"
- "log"
- "math/rand"
- "os"
- // "syslog"
- "time"
-)
-
-const fanout = 10
-
-func main() {
-
- r := metrics.NewRegistry()
-
- c := metrics.NewCounter()
- r.Register("foo", c)
- for i := 0; i < fanout; i++ {
- go func() {
- for {
- c.Dec(19)
- time.Sleep(300e6)
- }
- }()
- go func() {
- for {
- c.Inc(47)
- time.Sleep(400e6)
- }
- }()
- }
-
- g := metrics.NewGauge()
- r.Register("bar", g)
- for i := 0; i < fanout; i++ {
- go func() {
- for {
- g.Update(19)
- time.Sleep(300e6)
- }
- }()
- go func() {
- for {
- g.Update(47)
- time.Sleep(400e6)
- }
- }()
- }
-
- gf := metrics.NewGaugeFloat64()
- r.Register("barfloat64", gf)
- for i := 0; i < fanout; i++ {
- go func() {
- for {
- g.Update(19.0)
- time.Sleep(300e6)
- }
- }()
- go func() {
- for {
- g.Update(47.0)
- time.Sleep(400e6)
- }
- }()
- }
-
- hc := metrics.NewHealthcheck(func(h metrics.Healthcheck) {
- if 0 < rand.Intn(2) {
- h.Healthy()
- } else {
- h.Unhealthy(errors.New("baz"))
- }
- })
- r.Register("baz", hc)
-
- s := metrics.NewExpDecaySample(1028, 0.015)
- //s := metrics.NewUniformSample(1028)
- h := metrics.NewHistogram(s)
- r.Register("bang", h)
- for i := 0; i < fanout; i++ {
- go func() {
- for {
- h.Update(19)
- time.Sleep(300e6)
- }
- }()
- go func() {
- for {
- h.Update(47)
- time.Sleep(400e6)
- }
- }()
- }
-
- m := metrics.NewMeter()
- r.Register("quux", m)
- for i := 0; i < fanout; i++ {
- go func() {
- for {
- m.Mark(19)
- time.Sleep(300e6)
- }
- }()
- go func() {
- for {
- m.Mark(47)
- time.Sleep(400e6)
- }
- }()
- }
-
- t := metrics.NewTimer()
- r.Register("hooah", t)
- for i := 0; i < fanout; i++ {
- go func() {
- for {
- t.Time(func() { time.Sleep(300e6) })
- }
- }()
- go func() {
- for {
- t.Time(func() { time.Sleep(400e6) })
- }
- }()
- }
-
- metrics.RegisterDebugGCStats(r)
- go metrics.CaptureDebugGCStats(r, 5e9)
-
- metrics.RegisterRuntimeMemStats(r)
- go metrics.CaptureRuntimeMemStats(r, 5e9)
-
- metrics.Log(r, 60e9, log.New(os.Stderr, "metrics: ", log.Lmicroseconds))
-
- /*
- w, err := syslog.Dial("unixgram", "/dev/log", syslog.LOG_INFO, "metrics")
- if nil != err { log.Fatalln(err) }
- metrics.Syslog(r, 60e9, w)
- */
-
- /*
- addr, _ := net.ResolveTCPAddr("tcp", "127.0.0.1:2003")
- metrics.Graphite(r, 10e9, "metrics", addr)
- */
-
- /*
- stathat.Stathat(r, 10e9, "example@example.com")
- */
-
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/cmd/never-read/never-read.go b/containerd/vendor/github.com/rcrowley/go-metrics/cmd/never-read/never-read.go
deleted file mode 100644
index dc175b7..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/cmd/never-read/never-read.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package main
-
-import (
- "log"
- "net"
-)
-
-func main() {
- addr, _ := net.ResolveTCPAddr("tcp", "127.0.0.1:2003")
- l, err := net.ListenTCP("tcp", addr)
- if nil != err {
- log.Fatalln(err)
- }
- log.Println("listening", l.Addr())
- for {
- c, err := l.AcceptTCP()
- if nil != err {
- log.Fatalln(err)
- }
- log.Println("accepted", c.RemoteAddr())
- }
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/counter.go b/containerd/vendor/github.com/rcrowley/go-metrics/counter.go
deleted file mode 100644
index bb7b039..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/counter.go
+++ /dev/null
@@ -1,112 +0,0 @@
-package metrics
-
-import "sync/atomic"
-
-// Counters hold an int64 value that can be incremented and decremented.
-type Counter interface {
- Clear()
- Count() int64
- Dec(int64)
- Inc(int64)
- Snapshot() Counter
-}
-
-// GetOrRegisterCounter returns an existing Counter or constructs and registers
-// a new StandardCounter.
-func GetOrRegisterCounter(name string, r Registry) Counter {
- if nil == r {
- r = DefaultRegistry
- }
- return r.GetOrRegister(name, NewCounter).(Counter)
-}
-
-// NewCounter constructs a new StandardCounter.
-func NewCounter() Counter {
- if UseNilMetrics {
- return NilCounter{}
- }
- return &StandardCounter{0}
-}
-
-// NewRegisteredCounter constructs and registers a new StandardCounter.
-func NewRegisteredCounter(name string, r Registry) Counter {
- c := NewCounter()
- if nil == r {
- r = DefaultRegistry
- }
- r.Register(name, c)
- return c
-}
-
-// CounterSnapshot is a read-only copy of another Counter.
-type CounterSnapshot int64
-
-// Clear panics.
-func (CounterSnapshot) Clear() {
- panic("Clear called on a CounterSnapshot")
-}
-
-// Count returns the count at the time the snapshot was taken.
-func (c CounterSnapshot) Count() int64 { return int64(c) }
-
-// Dec panics.
-func (CounterSnapshot) Dec(int64) {
- panic("Dec called on a CounterSnapshot")
-}
-
-// Inc panics.
-func (CounterSnapshot) Inc(int64) {
- panic("Inc called on a CounterSnapshot")
-}
-
-// Snapshot returns the snapshot.
-func (c CounterSnapshot) Snapshot() Counter { return c }
-
-// NilCounter is a no-op Counter.
-type NilCounter struct{}
-
-// Clear is a no-op.
-func (NilCounter) Clear() {}
-
-// Count is a no-op.
-func (NilCounter) Count() int64 { return 0 }
-
-// Dec is a no-op.
-func (NilCounter) Dec(i int64) {}
-
-// Inc is a no-op.
-func (NilCounter) Inc(i int64) {}
-
-// Snapshot is a no-op.
-func (NilCounter) Snapshot() Counter { return NilCounter{} }
-
-// StandardCounter is the standard implementation of a Counter and uses the
-// sync/atomic package to manage a single int64 value.
-type StandardCounter struct {
- count int64
-}
-
-// Clear sets the counter to zero.
-func (c *StandardCounter) Clear() {
- atomic.StoreInt64(&c.count, 0)
-}
-
-// Count returns the current count.
-func (c *StandardCounter) Count() int64 {
- return atomic.LoadInt64(&c.count)
-}
-
-// Dec decrements the counter by the given amount.
-func (c *StandardCounter) Dec(i int64) {
- atomic.AddInt64(&c.count, -i)
-}
-
-// Inc increments the counter by the given amount.
-func (c *StandardCounter) Inc(i int64) {
- atomic.AddInt64(&c.count, i)
-}
-
-// Snapshot returns a read-only copy of the counter.
-func (c *StandardCounter) Snapshot() Counter {
- return CounterSnapshot(c.Count())
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/debug.go b/containerd/vendor/github.com/rcrowley/go-metrics/debug.go
deleted file mode 100644
index 043ccef..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/debug.go
+++ /dev/null
@@ -1,76 +0,0 @@
-package metrics
-
-import (
- "runtime/debug"
- "time"
-)
-
-var (
- debugMetrics struct {
- GCStats struct {
- LastGC Gauge
- NumGC Gauge
- Pause Histogram
- //PauseQuantiles Histogram
- PauseTotal Gauge
- }
- ReadGCStats Timer
- }
- gcStats debug.GCStats
-)
-
-// Capture new values for the Go garbage collector statistics exported in
-// debug.GCStats. This is designed to be called as a goroutine.
-func CaptureDebugGCStats(r Registry, d time.Duration) {
- for _ = range time.Tick(d) {
- CaptureDebugGCStatsOnce(r)
- }
-}
-
-// Capture new values for the Go garbage collector statistics exported in
-// debug.GCStats. This is designed to be called in a background goroutine.
-// Giving a registry which has not been given to RegisterDebugGCStats will
-// panic.
-//
-// Be careful (but much less so) with this because debug.ReadGCStats calls
-// the C function runtime·lock(runtime·mheap) which, while not a stop-the-world
-// operation, isn't something you want to be doing all the time.
-func CaptureDebugGCStatsOnce(r Registry) {
- lastGC := gcStats.LastGC
- t := time.Now()
- debug.ReadGCStats(&gcStats)
- debugMetrics.ReadGCStats.UpdateSince(t)
-
- debugMetrics.GCStats.LastGC.Update(int64(gcStats.LastGC.UnixNano()))
- debugMetrics.GCStats.NumGC.Update(int64(gcStats.NumGC))
- if lastGC != gcStats.LastGC && 0 < len(gcStats.Pause) {
- debugMetrics.GCStats.Pause.Update(int64(gcStats.Pause[0]))
- }
- //debugMetrics.GCStats.PauseQuantiles.Update(gcStats.PauseQuantiles)
- debugMetrics.GCStats.PauseTotal.Update(int64(gcStats.PauseTotal))
-}
-
-// Register metrics for the Go garbage collector statistics exported in
-// debug.GCStats. The metrics are named by their fully-qualified Go symbols,
-// i.e. debug.GCStats.PauseTotal.
-func RegisterDebugGCStats(r Registry) {
- debugMetrics.GCStats.LastGC = NewGauge()
- debugMetrics.GCStats.NumGC = NewGauge()
- debugMetrics.GCStats.Pause = NewHistogram(NewExpDecaySample(1028, 0.015))
- //debugMetrics.GCStats.PauseQuantiles = NewHistogram(NewExpDecaySample(1028, 0.015))
- debugMetrics.GCStats.PauseTotal = NewGauge()
- debugMetrics.ReadGCStats = NewTimer()
-
- r.Register("debug.GCStats.LastGC", debugMetrics.GCStats.LastGC)
- r.Register("debug.GCStats.NumGC", debugMetrics.GCStats.NumGC)
- r.Register("debug.GCStats.Pause", debugMetrics.GCStats.Pause)
- //r.Register("debug.GCStats.PauseQuantiles", debugMetrics.GCStats.PauseQuantiles)
- r.Register("debug.GCStats.PauseTotal", debugMetrics.GCStats.PauseTotal)
- r.Register("debug.ReadGCStats", debugMetrics.ReadGCStats)
-}
-
-// Allocate an initial slice for gcStats.Pause to avoid allocations during
-// normal operation.
-func init() {
- gcStats.Pause = make([]time.Duration, 11)
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/ewma.go b/containerd/vendor/github.com/rcrowley/go-metrics/ewma.go
deleted file mode 100644
index 694a1d0..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/ewma.go
+++ /dev/null
@@ -1,118 +0,0 @@
-package metrics
-
-import (
- "math"
- "sync"
- "sync/atomic"
-)
-
-// EWMAs continuously calculate an exponentially-weighted moving average
-// based on an outside source of clock ticks.
-type EWMA interface {
- Rate() float64
- Snapshot() EWMA
- Tick()
- Update(int64)
-}
-
-// NewEWMA constructs a new EWMA with the given alpha.
-func NewEWMA(alpha float64) EWMA {
- if UseNilMetrics {
- return NilEWMA{}
- }
- return &StandardEWMA{alpha: alpha}
-}
-
-// NewEWMA1 constructs a new EWMA for a one-minute moving average.
-func NewEWMA1() EWMA {
- return NewEWMA(1 - math.Exp(-5.0/60.0/1))
-}
-
-// NewEWMA5 constructs a new EWMA for a five-minute moving average.
-func NewEWMA5() EWMA {
- return NewEWMA(1 - math.Exp(-5.0/60.0/5))
-}
-
-// NewEWMA15 constructs a new EWMA for a fifteen-minute moving average.
-func NewEWMA15() EWMA {
- return NewEWMA(1 - math.Exp(-5.0/60.0/15))
-}
-
-// EWMASnapshot is a read-only copy of another EWMA.
-type EWMASnapshot float64
-
-// Rate returns the rate of events per second at the time the snapshot was
-// taken.
-func (a EWMASnapshot) Rate() float64 { return float64(a) }
-
-// Snapshot returns the snapshot.
-func (a EWMASnapshot) Snapshot() EWMA { return a }
-
-// Tick panics.
-func (EWMASnapshot) Tick() {
- panic("Tick called on an EWMASnapshot")
-}
-
-// Update panics.
-func (EWMASnapshot) Update(int64) {
- panic("Update called on an EWMASnapshot")
-}
-
-// NilEWMA is a no-op EWMA.
-type NilEWMA struct{}
-
-// Rate is a no-op.
-func (NilEWMA) Rate() float64 { return 0.0 }
-
-// Snapshot is a no-op.
-func (NilEWMA) Snapshot() EWMA { return NilEWMA{} }
-
-// Tick is a no-op.
-func (NilEWMA) Tick() {}
-
-// Update is a no-op.
-func (NilEWMA) Update(n int64) {}
-
-// StandardEWMA is the standard implementation of an EWMA and tracks the number
-// of uncounted events and processes them on each tick. It uses the
-// sync/atomic package to manage uncounted events.
-type StandardEWMA struct {
- uncounted int64 // /!\ this should be the first member to ensure 64-bit alignment
- alpha float64
- rate float64
- init bool
- mutex sync.Mutex
-}
-
-// Rate returns the moving average rate of events per second.
-func (a *StandardEWMA) Rate() float64 {
- a.mutex.Lock()
- defer a.mutex.Unlock()
- return a.rate * float64(1e9)
-}
-
-// Snapshot returns a read-only copy of the EWMA.
-func (a *StandardEWMA) Snapshot() EWMA {
- return EWMASnapshot(a.Rate())
-}
-
-// Tick ticks the clock to update the moving average. It assumes it is called
-// every five seconds.
-func (a *StandardEWMA) Tick() {
- count := atomic.LoadInt64(&a.uncounted)
- atomic.AddInt64(&a.uncounted, -count)
- instantRate := float64(count) / float64(5e9)
- a.mutex.Lock()
- defer a.mutex.Unlock()
- if a.init {
- a.rate += a.alpha * (instantRate - a.rate)
- } else {
- a.init = true
- a.rate = instantRate
- }
-}
-
-// Update adds n uncounted events.
-func (a *StandardEWMA) Update(n int64) {
- atomic.AddInt64(&a.uncounted, n)
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/gauge.go b/containerd/vendor/github.com/rcrowley/go-metrics/gauge.go
deleted file mode 100644
index 807638a..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/gauge.go
+++ /dev/null
@@ -1,84 +0,0 @@
-package metrics
-
-import "sync/atomic"
-
-// Gauges hold an int64 value that can be set arbitrarily.
-type Gauge interface {
- Snapshot() Gauge
- Update(int64)
- Value() int64
-}
-
-// GetOrRegisterGauge returns an existing Gauge or constructs and registers a
-// new StandardGauge.
-func GetOrRegisterGauge(name string, r Registry) Gauge {
- if nil == r {
- r = DefaultRegistry
- }
- return r.GetOrRegister(name, NewGauge).(Gauge)
-}
-
-// NewGauge constructs a new StandardGauge.
-func NewGauge() Gauge {
- if UseNilMetrics {
- return NilGauge{}
- }
- return &StandardGauge{0}
-}
-
-// NewRegisteredGauge constructs and registers a new StandardGauge.
-func NewRegisteredGauge(name string, r Registry) Gauge {
- c := NewGauge()
- if nil == r {
- r = DefaultRegistry
- }
- r.Register(name, c)
- return c
-}
-
-// GaugeSnapshot is a read-only copy of another Gauge.
-type GaugeSnapshot int64
-
-// Snapshot returns the snapshot.
-func (g GaugeSnapshot) Snapshot() Gauge { return g }
-
-// Update panics.
-func (GaugeSnapshot) Update(int64) {
- panic("Update called on a GaugeSnapshot")
-}
-
-// Value returns the value at the time the snapshot was taken.
-func (g GaugeSnapshot) Value() int64 { return int64(g) }
-
-// NilGauge is a no-op Gauge.
-type NilGauge struct{}
-
-// Snapshot is a no-op.
-func (NilGauge) Snapshot() Gauge { return NilGauge{} }
-
-// Update is a no-op.
-func (NilGauge) Update(v int64) {}
-
-// Value is a no-op.
-func (NilGauge) Value() int64 { return 0 }
-
-// StandardGauge is the standard implementation of a Gauge and uses the
-// sync/atomic package to manage a single int64 value.
-type StandardGauge struct {
- value int64
-}
-
-// Snapshot returns a read-only copy of the gauge.
-func (g *StandardGauge) Snapshot() Gauge {
- return GaugeSnapshot(g.Value())
-}
-
-// Update updates the gauge's value.
-func (g *StandardGauge) Update(v int64) {
- atomic.StoreInt64(&g.value, v)
-}
-
-// Value returns the gauge's current value.
-func (g *StandardGauge) Value() int64 {
- return atomic.LoadInt64(&g.value)
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/gauge_float64.go b/containerd/vendor/github.com/rcrowley/go-metrics/gauge_float64.go
deleted file mode 100644
index 47c3566..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/gauge_float64.go
+++ /dev/null
@@ -1,91 +0,0 @@
-package metrics
-
-import "sync"
-
-// GaugeFloat64s hold a float64 value that can be set arbitrarily.
-type GaugeFloat64 interface {
- Snapshot() GaugeFloat64
- Update(float64)
- Value() float64
-}
-
-// GetOrRegisterGaugeFloat64 returns an existing GaugeFloat64 or constructs and registers a
-// new StandardGaugeFloat64.
-func GetOrRegisterGaugeFloat64(name string, r Registry) GaugeFloat64 {
- if nil == r {
- r = DefaultRegistry
- }
- return r.GetOrRegister(name, NewGaugeFloat64()).(GaugeFloat64)
-}
-
-// NewGaugeFloat64 constructs a new StandardGaugeFloat64.
-func NewGaugeFloat64() GaugeFloat64 {
- if UseNilMetrics {
- return NilGaugeFloat64{}
- }
- return &StandardGaugeFloat64{
- value: 0.0,
- }
-}
-
-// NewRegisteredGaugeFloat64 constructs and registers a new StandardGaugeFloat64.
-func NewRegisteredGaugeFloat64(name string, r Registry) GaugeFloat64 {
- c := NewGaugeFloat64()
- if nil == r {
- r = DefaultRegistry
- }
- r.Register(name, c)
- return c
-}
-
-// GaugeFloat64Snapshot is a read-only copy of another GaugeFloat64.
-type GaugeFloat64Snapshot float64
-
-// Snapshot returns the snapshot.
-func (g GaugeFloat64Snapshot) Snapshot() GaugeFloat64 { return g }
-
-// Update panics.
-func (GaugeFloat64Snapshot) Update(float64) {
- panic("Update called on a GaugeFloat64Snapshot")
-}
-
-// Value returns the value at the time the snapshot was taken.
-func (g GaugeFloat64Snapshot) Value() float64 { return float64(g) }
-
-// NilGauge is a no-op Gauge.
-type NilGaugeFloat64 struct{}
-
-// Snapshot is a no-op.
-func (NilGaugeFloat64) Snapshot() GaugeFloat64 { return NilGaugeFloat64{} }
-
-// Update is a no-op.
-func (NilGaugeFloat64) Update(v float64) {}
-
-// Value is a no-op.
-func (NilGaugeFloat64) Value() float64 { return 0.0 }
-
-// StandardGaugeFloat64 is the standard implementation of a GaugeFloat64 and uses
-// sync.Mutex to manage a single float64 value.
-type StandardGaugeFloat64 struct {
- mutex sync.Mutex
- value float64
-}
-
-// Snapshot returns a read-only copy of the gauge.
-func (g *StandardGaugeFloat64) Snapshot() GaugeFloat64 {
- return GaugeFloat64Snapshot(g.Value())
-}
-
-// Update updates the gauge's value.
-func (g *StandardGaugeFloat64) Update(v float64) {
- g.mutex.Lock()
- defer g.mutex.Unlock()
- g.value = v
-}
-
-// Value returns the gauge's current value.
-func (g *StandardGaugeFloat64) Value() float64 {
- g.mutex.Lock()
- defer g.mutex.Unlock()
- return g.value
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/graphite.go b/containerd/vendor/github.com/rcrowley/go-metrics/graphite.go
deleted file mode 100644
index abd0a7d..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/graphite.go
+++ /dev/null
@@ -1,113 +0,0 @@
-package metrics
-
-import (
- "bufio"
- "fmt"
- "log"
- "net"
- "strconv"
- "strings"
- "time"
-)
-
-// GraphiteConfig provides a container with configuration parameters for
-// the Graphite exporter
-type GraphiteConfig struct {
- Addr *net.TCPAddr // Network address to connect to
- Registry Registry // Registry to be exported
- FlushInterval time.Duration // Flush interval
- DurationUnit time.Duration // Time conversion unit for durations
- Prefix string // Prefix to be prepended to metric names
- Percentiles []float64 // Percentiles to export from timers and histograms
-}
-
-// Graphite is a blocking exporter function which reports metrics in r
-// to a graphite server located at addr, flushing them every d duration
-// and prepending metric names with prefix.
-func Graphite(r Registry, d time.Duration, prefix string, addr *net.TCPAddr) {
- GraphiteWithConfig(GraphiteConfig{
- Addr: addr,
- Registry: r,
- FlushInterval: d,
- DurationUnit: time.Nanosecond,
- Prefix: prefix,
- Percentiles: []float64{0.5, 0.75, 0.95, 0.99, 0.999},
- })
-}
-
-// GraphiteWithConfig is a blocking exporter function just like Graphite,
-// but it takes a GraphiteConfig instead.
-func GraphiteWithConfig(c GraphiteConfig) {
- log.Printf("WARNING: This go-metrics client has been DEPRECATED! It has been moved to https://github.com/cyberdelia/go-metrics-graphite and will be removed from rcrowley/go-metrics on August 12th 2015")
- for _ = range time.Tick(c.FlushInterval) {
- if err := graphite(&c); nil != err {
- log.Println(err)
- }
- }
-}
-
-// GraphiteOnce performs a single submission to Graphite, returning a
-// non-nil error on failed connections. This can be used in a loop
-// similar to GraphiteWithConfig for custom error handling.
-func GraphiteOnce(c GraphiteConfig) error {
- log.Printf("WARNING: This go-metrics client has been DEPRECATED! It has been moved to https://github.com/cyberdelia/go-metrics-graphite and will be removed from rcrowley/go-metrics on August 12th 2015")
- return graphite(&c)
-}
-
-func graphite(c *GraphiteConfig) error {
- now := time.Now().Unix()
- du := float64(c.DurationUnit)
- conn, err := net.DialTCP("tcp", nil, c.Addr)
- if nil != err {
- return err
- }
- defer conn.Close()
- w := bufio.NewWriter(conn)
- c.Registry.Each(func(name string, i interface{}) {
- switch metric := i.(type) {
- case Counter:
- fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, metric.Count(), now)
- case Gauge:
- fmt.Fprintf(w, "%s.%s.value %d %d\n", c.Prefix, name, metric.Value(), now)
- case GaugeFloat64:
- fmt.Fprintf(w, "%s.%s.value %f %d\n", c.Prefix, name, metric.Value(), now)
- case Histogram:
- h := metric.Snapshot()
- ps := h.Percentiles(c.Percentiles)
- fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, h.Count(), now)
- fmt.Fprintf(w, "%s.%s.min %d %d\n", c.Prefix, name, h.Min(), now)
- fmt.Fprintf(w, "%s.%s.max %d %d\n", c.Prefix, name, h.Max(), now)
- fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, h.Mean(), now)
- fmt.Fprintf(w, "%s.%s.std-dev %.2f %d\n", c.Prefix, name, h.StdDev(), now)
- for psIdx, psKey := range c.Percentiles {
- key := strings.Replace(strconv.FormatFloat(psKey*100.0, 'f', -1, 64), ".", "", 1)
- fmt.Fprintf(w, "%s.%s.%s-percentile %.2f %d\n", c.Prefix, name, key, ps[psIdx], now)
- }
- case Meter:
- m := metric.Snapshot()
- fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, m.Count(), now)
- fmt.Fprintf(w, "%s.%s.one-minute %.2f %d\n", c.Prefix, name, m.Rate1(), now)
- fmt.Fprintf(w, "%s.%s.five-minute %.2f %d\n", c.Prefix, name, m.Rate5(), now)
- fmt.Fprintf(w, "%s.%s.fifteen-minute %.2f %d\n", c.Prefix, name, m.Rate15(), now)
- fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, m.RateMean(), now)
- case Timer:
- t := metric.Snapshot()
- ps := t.Percentiles(c.Percentiles)
- fmt.Fprintf(w, "%s.%s.count %d %d\n", c.Prefix, name, t.Count(), now)
- fmt.Fprintf(w, "%s.%s.min %d %d\n", c.Prefix, name, t.Min()/int64(du), now)
- fmt.Fprintf(w, "%s.%s.max %d %d\n", c.Prefix, name, t.Max()/int64(du), now)
- fmt.Fprintf(w, "%s.%s.mean %.2f %d\n", c.Prefix, name, t.Mean()/du, now)
- fmt.Fprintf(w, "%s.%s.std-dev %.2f %d\n", c.Prefix, name, t.StdDev()/du, now)
- for psIdx, psKey := range c.Percentiles {
- key := strings.Replace(strconv.FormatFloat(psKey*100.0, 'f', -1, 64), ".", "", 1)
- fmt.Fprintf(w, "%s.%s.%s-percentile %.2f %d\n", c.Prefix, name, key, ps[psIdx], now)
- }
- fmt.Fprintf(w, "%s.%s.one-minute %.2f %d\n", c.Prefix, name, t.Rate1(), now)
- fmt.Fprintf(w, "%s.%s.five-minute %.2f %d\n", c.Prefix, name, t.Rate5(), now)
- fmt.Fprintf(w, "%s.%s.fifteen-minute %.2f %d\n", c.Prefix, name, t.Rate15(), now)
- fmt.Fprintf(w, "%s.%s.mean-rate %.2f %d\n", c.Prefix, name, t.RateMean(), now)
- }
- w.Flush()
- })
- return nil
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/healthcheck.go b/containerd/vendor/github.com/rcrowley/go-metrics/healthcheck.go
deleted file mode 100644
index 445131c..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/healthcheck.go
+++ /dev/null
@@ -1,61 +0,0 @@
-package metrics
-
-// Healthchecks hold an error value describing an arbitrary up/down status.
-type Healthcheck interface {
- Check()
- Error() error
- Healthy()
- Unhealthy(error)
-}
-
-// NewHealthcheck constructs a new Healthcheck which will use the given
-// function to update its status.
-func NewHealthcheck(f func(Healthcheck)) Healthcheck {
- if UseNilMetrics {
- return NilHealthcheck{}
- }
- return &StandardHealthcheck{nil, f}
-}
-
-// NilHealthcheck is a no-op.
-type NilHealthcheck struct{}
-
-// Check is a no-op.
-func (NilHealthcheck) Check() {}
-
-// Error is a no-op.
-func (NilHealthcheck) Error() error { return nil }
-
-// Healthy is a no-op.
-func (NilHealthcheck) Healthy() {}
-
-// Unhealthy is a no-op.
-func (NilHealthcheck) Unhealthy(error) {}
-
-// StandardHealthcheck is the standard implementation of a Healthcheck and
-// stores the status and a function to call to update the status.
-type StandardHealthcheck struct {
- err error
- f func(Healthcheck)
-}
-
-// Check runs the healthcheck function to update the healthcheck's status.
-func (h *StandardHealthcheck) Check() {
- h.f(h)
-}
-
-// Error returns the healthcheck's status, which will be nil if it is healthy.
-func (h *StandardHealthcheck) Error() error {
- return h.err
-}
-
-// Healthy marks the healthcheck as healthy.
-func (h *StandardHealthcheck) Healthy() {
- h.err = nil
-}
-
-// Unhealthy marks the healthcheck as unhealthy. The error is stored and
-// may be retrieved by the Error method.
-func (h *StandardHealthcheck) Unhealthy(err error) {
- h.err = err
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/histogram.go b/containerd/vendor/github.com/rcrowley/go-metrics/histogram.go
deleted file mode 100644
index dbc837f..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/histogram.go
+++ /dev/null
@@ -1,202 +0,0 @@
-package metrics
-
-// Histograms calculate distribution statistics from a series of int64 values.
-type Histogram interface {
- Clear()
- Count() int64
- Max() int64
- Mean() float64
- Min() int64
- Percentile(float64) float64
- Percentiles([]float64) []float64
- Sample() Sample
- Snapshot() Histogram
- StdDev() float64
- Sum() int64
- Update(int64)
- Variance() float64
-}
-
-// GetOrRegisterHistogram returns an existing Histogram or constructs and
-// registers a new StandardHistogram.
-func GetOrRegisterHistogram(name string, r Registry, s Sample) Histogram {
- if nil == r {
- r = DefaultRegistry
- }
- return r.GetOrRegister(name, func() Histogram { return NewHistogram(s) }).(Histogram)
-}
-
-// NewHistogram constructs a new StandardHistogram from a Sample.
-func NewHistogram(s Sample) Histogram {
- if UseNilMetrics {
- return NilHistogram{}
- }
- return &StandardHistogram{sample: s}
-}
-
-// NewRegisteredHistogram constructs and registers a new StandardHistogram from
-// a Sample.
-func NewRegisteredHistogram(name string, r Registry, s Sample) Histogram {
- c := NewHistogram(s)
- if nil == r {
- r = DefaultRegistry
- }
- r.Register(name, c)
- return c
-}
-
-// HistogramSnapshot is a read-only copy of another Histogram.
-type HistogramSnapshot struct {
- sample *SampleSnapshot
-}
-
-// Clear panics.
-func (*HistogramSnapshot) Clear() {
- panic("Clear called on a HistogramSnapshot")
-}
-
-// Count returns the number of samples recorded at the time the snapshot was
-// taken.
-func (h *HistogramSnapshot) Count() int64 { return h.sample.Count() }
-
-// Max returns the maximum value in the sample at the time the snapshot was
-// taken.
-func (h *HistogramSnapshot) Max() int64 { return h.sample.Max() }
-
-// Mean returns the mean of the values in the sample at the time the snapshot
-// was taken.
-func (h *HistogramSnapshot) Mean() float64 { return h.sample.Mean() }
-
-// Min returns the minimum value in the sample at the time the snapshot was
-// taken.
-func (h *HistogramSnapshot) Min() int64 { return h.sample.Min() }
-
-// Percentile returns an arbitrary percentile of values in the sample at the
-// time the snapshot was taken.
-func (h *HistogramSnapshot) Percentile(p float64) float64 {
- return h.sample.Percentile(p)
-}
-
-// Percentiles returns a slice of arbitrary percentiles of values in the sample
-// at the time the snapshot was taken.
-func (h *HistogramSnapshot) Percentiles(ps []float64) []float64 {
- return h.sample.Percentiles(ps)
-}
-
-// Sample returns the Sample underlying the histogram.
-func (h *HistogramSnapshot) Sample() Sample { return h.sample }
-
-// Snapshot returns the snapshot.
-func (h *HistogramSnapshot) Snapshot() Histogram { return h }
-
-// StdDev returns the standard deviation of the values in the sample at the
-// time the snapshot was taken.
-func (h *HistogramSnapshot) StdDev() float64 { return h.sample.StdDev() }
-
-// Sum returns the sum in the sample at the time the snapshot was taken.
-func (h *HistogramSnapshot) Sum() int64 { return h.sample.Sum() }
-
-// Update panics.
-func (*HistogramSnapshot) Update(int64) {
- panic("Update called on a HistogramSnapshot")
-}
-
-// Variance returns the variance of inputs at the time the snapshot was taken.
-func (h *HistogramSnapshot) Variance() float64 { return h.sample.Variance() }
-
-// NilHistogram is a no-op Histogram.
-type NilHistogram struct{}
-
-// Clear is a no-op.
-func (NilHistogram) Clear() {}
-
-// Count is a no-op.
-func (NilHistogram) Count() int64 { return 0 }
-
-// Max is a no-op.
-func (NilHistogram) Max() int64 { return 0 }
-
-// Mean is a no-op.
-func (NilHistogram) Mean() float64 { return 0.0 }
-
-// Min is a no-op.
-func (NilHistogram) Min() int64 { return 0 }
-
-// Percentile is a no-op.
-func (NilHistogram) Percentile(p float64) float64 { return 0.0 }
-
-// Percentiles is a no-op.
-func (NilHistogram) Percentiles(ps []float64) []float64 {
- return make([]float64, len(ps))
-}
-
-// Sample is a no-op.
-func (NilHistogram) Sample() Sample { return NilSample{} }
-
-// Snapshot is a no-op.
-func (NilHistogram) Snapshot() Histogram { return NilHistogram{} }
-
-// StdDev is a no-op.
-func (NilHistogram) StdDev() float64 { return 0.0 }
-
-// Sum is a no-op.
-func (NilHistogram) Sum() int64 { return 0 }
-
-// Update is a no-op.
-func (NilHistogram) Update(v int64) {}
-
-// Variance is a no-op.
-func (NilHistogram) Variance() float64 { return 0.0 }
-
-// StandardHistogram is the standard implementation of a Histogram and uses a
-// Sample to bound its memory use.
-type StandardHistogram struct {
- sample Sample
-}
-
-// Clear clears the histogram and its sample.
-func (h *StandardHistogram) Clear() { h.sample.Clear() }
-
-// Count returns the number of samples recorded since the histogram was last
-// cleared.
-func (h *StandardHistogram) Count() int64 { return h.sample.Count() }
-
-// Max returns the maximum value in the sample.
-func (h *StandardHistogram) Max() int64 { return h.sample.Max() }
-
-// Mean returns the mean of the values in the sample.
-func (h *StandardHistogram) Mean() float64 { return h.sample.Mean() }
-
-// Min returns the minimum value in the sample.
-func (h *StandardHistogram) Min() int64 { return h.sample.Min() }
-
-// Percentile returns an arbitrary percentile of the values in the sample.
-func (h *StandardHistogram) Percentile(p float64) float64 {
- return h.sample.Percentile(p)
-}
-
-// Percentiles returns a slice of arbitrary percentiles of the values in the
-// sample.
-func (h *StandardHistogram) Percentiles(ps []float64) []float64 {
- return h.sample.Percentiles(ps)
-}
-
-// Sample returns the Sample underlying the histogram.
-func (h *StandardHistogram) Sample() Sample { return h.sample }
-
-// Snapshot returns a read-only copy of the histogram.
-func (h *StandardHistogram) Snapshot() Histogram {
- return &HistogramSnapshot{sample: h.sample.Snapshot().(*SampleSnapshot)}
-}
-
-// StdDev returns the standard deviation of the values in the sample.
-func (h *StandardHistogram) StdDev() float64 { return h.sample.StdDev() }
-
-// Sum returns the sum in the sample.
-func (h *StandardHistogram) Sum() int64 { return h.sample.Sum() }
-
-// Update samples a new value.
-func (h *StandardHistogram) Update(v int64) { h.sample.Update(v) }
-
-// Variance returns the variance of the values in the sample.
-func (h *StandardHistogram) Variance() float64 { return h.sample.Variance() }
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/json.go b/containerd/vendor/github.com/rcrowley/go-metrics/json.go
deleted file mode 100644
index 2676aee..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/json.go
+++ /dev/null
@@ -1,83 +0,0 @@
-package metrics
-
-import (
- "encoding/json"
- "io"
- "time"
-)
-
-// MarshalJSON returns a byte slice containing a JSON representation of all
-// the metrics in the Registry.
-func (r *StandardRegistry) MarshalJSON() ([]byte, error) {
- data := make(map[string]map[string]interface{})
- r.Each(func(name string, i interface{}) {
- values := make(map[string]interface{})
- switch metric := i.(type) {
- case Counter:
- values["count"] = metric.Count()
- case Gauge:
- values["value"] = metric.Value()
- case GaugeFloat64:
- values["value"] = metric.Value()
- case Healthcheck:
- values["error"] = nil
- metric.Check()
- if err := metric.Error(); nil != err {
- values["error"] = metric.Error().Error()
- }
- case Histogram:
- h := metric.Snapshot()
- ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
- values["count"] = h.Count()
- values["min"] = h.Min()
- values["max"] = h.Max()
- values["mean"] = h.Mean()
- values["stddev"] = h.StdDev()
- values["median"] = ps[0]
- values["75%"] = ps[1]
- values["95%"] = ps[2]
- values["99%"] = ps[3]
- values["99.9%"] = ps[4]
- case Meter:
- m := metric.Snapshot()
- values["count"] = m.Count()
- values["1m.rate"] = m.Rate1()
- values["5m.rate"] = m.Rate5()
- values["15m.rate"] = m.Rate15()
- values["mean.rate"] = m.RateMean()
- case Timer:
- t := metric.Snapshot()
- ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
- values["count"] = t.Count()
- values["min"] = t.Min()
- values["max"] = t.Max()
- values["mean"] = t.Mean()
- values["stddev"] = t.StdDev()
- values["median"] = ps[0]
- values["75%"] = ps[1]
- values["95%"] = ps[2]
- values["99%"] = ps[3]
- values["99.9%"] = ps[4]
- values["1m.rate"] = t.Rate1()
- values["5m.rate"] = t.Rate5()
- values["15m.rate"] = t.Rate15()
- values["mean.rate"] = t.RateMean()
- }
- data[name] = values
- })
- return json.Marshal(data)
-}
-
-// WriteJSON writes metrics from the given registry periodically to the
-// specified io.Writer as JSON.
-func WriteJSON(r Registry, d time.Duration, w io.Writer) {
- for _ = range time.Tick(d) {
- WriteJSONOnce(r, w)
- }
-}
-
-// WriteJSONOnce writes metrics from the given registry to the specified
-// io.Writer as JSON.
-func WriteJSONOnce(r Registry, w io.Writer) {
- json.NewEncoder(w).Encode(r)
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/librato/client.go b/containerd/vendor/github.com/rcrowley/go-metrics/librato/client.go
deleted file mode 100644
index 8c0c850..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/librato/client.go
+++ /dev/null
@@ -1,102 +0,0 @@
-package librato
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "io/ioutil"
- "net/http"
-)
-
-const Operations = "operations"
-const OperationsShort = "ops"
-
-type LibratoClient struct {
- Email, Token string
-}
-
-// property strings
-const (
- // display attributes
- Color = "color"
- DisplayMax = "display_max"
- DisplayMin = "display_min"
- DisplayUnitsLong = "display_units_long"
- DisplayUnitsShort = "display_units_short"
- DisplayStacked = "display_stacked"
- DisplayTransform = "display_transform"
- // special gauge display attributes
- SummarizeFunction = "summarize_function"
- Aggregate = "aggregate"
-
- // metric keys
- Name = "name"
- Period = "period"
- Description = "description"
- DisplayName = "display_name"
- Attributes = "attributes"
-
- // measurement keys
- MeasureTime = "measure_time"
- Source = "source"
- Value = "value"
-
- // special gauge keys
- Count = "count"
- Sum = "sum"
- Max = "max"
- Min = "min"
- SumSquares = "sum_squares"
-
- // batch keys
- Counters = "counters"
- Gauges = "gauges"
-
- MetricsPostUrl = "https://metrics-api.librato.com/v1/metrics"
-)
-
-type Measurement map[string]interface{}
-type Metric map[string]interface{}
-
-type Batch struct {
- Gauges []Measurement `json:"gauges,omitempty"`
- Counters []Measurement `json:"counters,omitempty"`
- MeasureTime int64 `json:"measure_time"`
- Source string `json:"source"`
-}
-
-func (self *LibratoClient) PostMetrics(batch Batch) (err error) {
- var (
- js []byte
- req *http.Request
- resp *http.Response
- )
-
- if len(batch.Counters) == 0 && len(batch.Gauges) == 0 {
- return nil
- }
-
- if js, err = json.Marshal(batch); err != nil {
- return
- }
-
- if req, err = http.NewRequest("POST", MetricsPostUrl, bytes.NewBuffer(js)); err != nil {
- return
- }
-
- req.Header.Set("Content-Type", "application/json")
- req.SetBasicAuth(self.Email, self.Token)
-
- if resp, err = http.DefaultClient.Do(req); err != nil {
- return
- }
-
- if resp.StatusCode != http.StatusOK {
- var body []byte
- if body, err = ioutil.ReadAll(resp.Body); err != nil {
- body = []byte(fmt.Sprintf("(could not fetch response body for error: %s)", err))
- }
- err = fmt.Errorf("Unable to post to Librato: %d %s %s", resp.StatusCode, resp.Status, string(body))
- }
- return
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/librato/librato.go b/containerd/vendor/github.com/rcrowley/go-metrics/librato/librato.go
deleted file mode 100644
index a3b5b91..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/librato/librato.go
+++ /dev/null
@@ -1,231 +0,0 @@
-package librato
-
-import (
- "fmt"
- "log"
- "math"
- "regexp"
- "time"
-
- "github.com/rcrowley/go-metrics"
-)
-
-// a regexp for extracting the unit from time.Duration.String
-var unitRegexp = regexp.MustCompile("[^\\d]+$")
-
-// a helper that turns a time.Duration into librato display attributes for timer metrics
-func translateTimerAttributes(d time.Duration) (attrs map[string]interface{}) {
- attrs = make(map[string]interface{})
- attrs[DisplayTransform] = fmt.Sprintf("x/%d", int64(d))
- attrs[DisplayUnitsShort] = string(unitRegexp.Find([]byte(d.String())))
- return
-}
-
-type Reporter struct {
- Email, Token string
- Source string
- Interval time.Duration
- Registry metrics.Registry
- Percentiles []float64 // percentiles to report on histogram metrics
- TimerAttributes map[string]interface{} // units in which timers will be displayed
- intervalSec int64
-}
-
-func NewReporter(r metrics.Registry, d time.Duration, e string, t string, s string, p []float64, u time.Duration) *Reporter {
- return &Reporter{e, t, s, d, r, p, translateTimerAttributes(u), int64(d / time.Second)}
-}
-
-func Librato(r metrics.Registry, d time.Duration, e string, t string, s string, p []float64, u time.Duration) {
- NewReporter(r, d, e, t, s, p, u).Run()
-}
-
-func (self *Reporter) Run() {
- log.Printf("WARNING: This client has been DEPRECATED! It has been moved to https://github.com/mihasya/go-metrics-librato and will be removed from rcrowley/go-metrics on August 5th 2015")
- ticker := time.Tick(self.Interval)
- metricsApi := &LibratoClient{self.Email, self.Token}
- for now := range ticker {
- var metrics Batch
- var err error
- if metrics, err = self.BuildRequest(now, self.Registry); err != nil {
- log.Printf("ERROR constructing librato request body %s", err)
- continue
- }
- if err := metricsApi.PostMetrics(metrics); err != nil {
- log.Printf("ERROR sending metrics to librato %s", err)
- continue
- }
- }
-}
-
-// calculate sum of squares from data provided by metrics.Histogram
-// see http://en.wikipedia.org/wiki/Standard_deviation#Rapid_calculation_methods
-func sumSquares(s metrics.Sample) float64 {
- count := float64(s.Count())
- sumSquared := math.Pow(count*s.Mean(), 2)
- sumSquares := math.Pow(count*s.StdDev(), 2) + sumSquared/count
- if math.IsNaN(sumSquares) {
- return 0.0
- }
- return sumSquares
-}
-func sumSquaresTimer(t metrics.Timer) float64 {
- count := float64(t.Count())
- sumSquared := math.Pow(count*t.Mean(), 2)
- sumSquares := math.Pow(count*t.StdDev(), 2) + sumSquared/count
- if math.IsNaN(sumSquares) {
- return 0.0
- }
- return sumSquares
-}
-
-func (self *Reporter) BuildRequest(now time.Time, r metrics.Registry) (snapshot Batch, err error) {
- snapshot = Batch{
- // coerce timestamps to a stepping fn so that they line up in Librato graphs
- MeasureTime: (now.Unix() / self.intervalSec) * self.intervalSec,
- Source: self.Source,
- }
- snapshot.Gauges = make([]Measurement, 0)
- snapshot.Counters = make([]Measurement, 0)
- histogramGaugeCount := 1 + len(self.Percentiles)
- r.Each(func(name string, metric interface{}) {
- measurement := Measurement{}
- measurement[Period] = self.Interval.Seconds()
- switch m := metric.(type) {
- case metrics.Counter:
- if m.Count() > 0 {
- measurement[Name] = fmt.Sprintf("%s.%s", name, "count")
- measurement[Value] = float64(m.Count())
- measurement[Attributes] = map[string]interface{}{
- DisplayUnitsLong: Operations,
- DisplayUnitsShort: OperationsShort,
- DisplayMin: "0",
- }
- snapshot.Counters = append(snapshot.Counters, measurement)
- }
- case metrics.Gauge:
- measurement[Name] = name
- measurement[Value] = float64(m.Value())
- snapshot.Gauges = append(snapshot.Gauges, measurement)
- case metrics.GaugeFloat64:
- measurement[Name] = name
- measurement[Value] = float64(m.Value())
- snapshot.Gauges = append(snapshot.Gauges, measurement)
- case metrics.Histogram:
- if m.Count() > 0 {
- gauges := make([]Measurement, histogramGaugeCount, histogramGaugeCount)
- s := m.Sample()
- measurement[Name] = fmt.Sprintf("%s.%s", name, "hist")
- measurement[Count] = uint64(s.Count())
- measurement[Max] = float64(s.Max())
- measurement[Min] = float64(s.Min())
- measurement[Sum] = float64(s.Sum())
- measurement[SumSquares] = sumSquares(s)
- gauges[0] = measurement
- for i, p := range self.Percentiles {
- gauges[i+1] = Measurement{
- Name: fmt.Sprintf("%s.%.2f", measurement[Name], p),
- Value: s.Percentile(p),
- Period: measurement[Period],
- }
- }
- snapshot.Gauges = append(snapshot.Gauges, gauges...)
- }
- case metrics.Meter:
- measurement[Name] = name
- measurement[Value] = float64(m.Count())
- snapshot.Counters = append(snapshot.Counters, measurement)
- snapshot.Gauges = append(snapshot.Gauges,
- Measurement{
- Name: fmt.Sprintf("%s.%s", name, "1min"),
- Value: m.Rate1(),
- Period: int64(self.Interval.Seconds()),
- Attributes: map[string]interface{}{
- DisplayUnitsLong: Operations,
- DisplayUnitsShort: OperationsShort,
- DisplayMin: "0",
- },
- },
- Measurement{
- Name: fmt.Sprintf("%s.%s", name, "5min"),
- Value: m.Rate5(),
- Period: int64(self.Interval.Seconds()),
- Attributes: map[string]interface{}{
- DisplayUnitsLong: Operations,
- DisplayUnitsShort: OperationsShort,
- DisplayMin: "0",
- },
- },
- Measurement{
- Name: fmt.Sprintf("%s.%s", name, "15min"),
- Value: m.Rate15(),
- Period: int64(self.Interval.Seconds()),
- Attributes: map[string]interface{}{
- DisplayUnitsLong: Operations,
- DisplayUnitsShort: OperationsShort,
- DisplayMin: "0",
- },
- },
- )
- case metrics.Timer:
- measurement[Name] = name
- measurement[Value] = float64(m.Count())
- snapshot.Counters = append(snapshot.Counters, measurement)
- if m.Count() > 0 {
- libratoName := fmt.Sprintf("%s.%s", name, "timer.mean")
- gauges := make([]Measurement, histogramGaugeCount, histogramGaugeCount)
- gauges[0] = Measurement{
- Name: libratoName,
- Count: uint64(m.Count()),
- Sum: m.Mean() * float64(m.Count()),
- Max: float64(m.Max()),
- Min: float64(m.Min()),
- SumSquares: sumSquaresTimer(m),
- Period: int64(self.Interval.Seconds()),
- Attributes: self.TimerAttributes,
- }
- for i, p := range self.Percentiles {
- gauges[i+1] = Measurement{
- Name: fmt.Sprintf("%s.timer.%2.0f", name, p*100),
- Value: m.Percentile(p),
- Period: int64(self.Interval.Seconds()),
- Attributes: self.TimerAttributes,
- }
- }
- snapshot.Gauges = append(snapshot.Gauges, gauges...)
- snapshot.Gauges = append(snapshot.Gauges,
- Measurement{
- Name: fmt.Sprintf("%s.%s", name, "rate.1min"),
- Value: m.Rate1(),
- Period: int64(self.Interval.Seconds()),
- Attributes: map[string]interface{}{
- DisplayUnitsLong: Operations,
- DisplayUnitsShort: OperationsShort,
- DisplayMin: "0",
- },
- },
- Measurement{
- Name: fmt.Sprintf("%s.%s", name, "rate.5min"),
- Value: m.Rate5(),
- Period: int64(self.Interval.Seconds()),
- Attributes: map[string]interface{}{
- DisplayUnitsLong: Operations,
- DisplayUnitsShort: OperationsShort,
- DisplayMin: "0",
- },
- },
- Measurement{
- Name: fmt.Sprintf("%s.%s", name, "rate.15min"),
- Value: m.Rate15(),
- Period: int64(self.Interval.Seconds()),
- Attributes: map[string]interface{}{
- DisplayUnitsLong: Operations,
- DisplayUnitsShort: OperationsShort,
- DisplayMin: "0",
- },
- },
- )
- }
- }
- })
- return
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/log.go b/containerd/vendor/github.com/rcrowley/go-metrics/log.go
deleted file mode 100644
index 278a8a4..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/log.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package metrics
-
-import (
- "log"
- "time"
-)
-
-// Output each metric in the given registry periodically using the given
-// logger.
-func Log(r Registry, d time.Duration, l *log.Logger) {
- for _ = range time.Tick(d) {
- r.Each(func(name string, i interface{}) {
- switch metric := i.(type) {
- case Counter:
- l.Printf("counter %s\n", name)
- l.Printf(" count: %9d\n", metric.Count())
- case Gauge:
- l.Printf("gauge %s\n", name)
- l.Printf(" value: %9d\n", metric.Value())
- case GaugeFloat64:
- l.Printf("gauge %s\n", name)
- l.Printf(" value: %f\n", metric.Value())
- case Healthcheck:
- metric.Check()
- l.Printf("healthcheck %s\n", name)
- l.Printf(" error: %v\n", metric.Error())
- case Histogram:
- h := metric.Snapshot()
- ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
- l.Printf("histogram %s\n", name)
- l.Printf(" count: %9d\n", h.Count())
- l.Printf(" min: %9d\n", h.Min())
- l.Printf(" max: %9d\n", h.Max())
- l.Printf(" mean: %12.2f\n", h.Mean())
- l.Printf(" stddev: %12.2f\n", h.StdDev())
- l.Printf(" median: %12.2f\n", ps[0])
- l.Printf(" 75%%: %12.2f\n", ps[1])
- l.Printf(" 95%%: %12.2f\n", ps[2])
- l.Printf(" 99%%: %12.2f\n", ps[3])
- l.Printf(" 99.9%%: %12.2f\n", ps[4])
- case Meter:
- m := metric.Snapshot()
- l.Printf("meter %s\n", name)
- l.Printf(" count: %9d\n", m.Count())
- l.Printf(" 1-min rate: %12.2f\n", m.Rate1())
- l.Printf(" 5-min rate: %12.2f\n", m.Rate5())
- l.Printf(" 15-min rate: %12.2f\n", m.Rate15())
- l.Printf(" mean rate: %12.2f\n", m.RateMean())
- case Timer:
- t := metric.Snapshot()
- ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
- l.Printf("timer %s\n", name)
- l.Printf(" count: %9d\n", t.Count())
- l.Printf(" min: %9d\n", t.Min())
- l.Printf(" max: %9d\n", t.Max())
- l.Printf(" mean: %12.2f\n", t.Mean())
- l.Printf(" stddev: %12.2f\n", t.StdDev())
- l.Printf(" median: %12.2f\n", ps[0])
- l.Printf(" 75%%: %12.2f\n", ps[1])
- l.Printf(" 95%%: %12.2f\n", ps[2])
- l.Printf(" 99%%: %12.2f\n", ps[3])
- l.Printf(" 99.9%%: %12.2f\n", ps[4])
- l.Printf(" 1-min rate: %12.2f\n", t.Rate1())
- l.Printf(" 5-min rate: %12.2f\n", t.Rate5())
- l.Printf(" 15-min rate: %12.2f\n", t.Rate15())
- l.Printf(" mean rate: %12.2f\n", t.RateMean())
- }
- })
- }
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/memory.md b/containerd/vendor/github.com/rcrowley/go-metrics/memory.md
deleted file mode 100644
index 47454f5..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/memory.md
+++ /dev/null
@@ -1,285 +0,0 @@
-Memory usage
-============
-
-(Highly unscientific.)
-
-Command used to gather static memory usage:
-
-```sh
-grep ^Vm "/proc/$(ps fax | grep [m]etrics-bench | awk '{print $1}')/status"
-```
-
-Program used to gather baseline memory usage:
-
-```go
-package main
-
-import "time"
-
-func main() {
- time.Sleep(600e9)
-}
-```
-
-Baseline
---------
-
-```
-VmPeak: 42604 kB
-VmSize: 42604 kB
-VmLck: 0 kB
-VmHWM: 1120 kB
-VmRSS: 1120 kB
-VmData: 35460 kB
-VmStk: 136 kB
-VmExe: 1020 kB
-VmLib: 1848 kB
-VmPTE: 36 kB
-VmSwap: 0 kB
-```
-
-Program used to gather metric memory usage (with other metrics being similar):
-
-```go
-package main
-
-import (
- "fmt"
- "metrics"
- "time"
-)
-
-func main() {
- fmt.Sprintf("foo")
- metrics.NewRegistry()
- time.Sleep(600e9)
-}
-```
-
-1000 counters registered
-------------------------
-
-```
-VmPeak: 44016 kB
-VmSize: 44016 kB
-VmLck: 0 kB
-VmHWM: 1928 kB
-VmRSS: 1928 kB
-VmData: 36868 kB
-VmStk: 136 kB
-VmExe: 1024 kB
-VmLib: 1848 kB
-VmPTE: 40 kB
-VmSwap: 0 kB
-```
-
-**1.412 kB virtual, TODO 0.808 kB resident per counter.**
-
-100000 counters registered
---------------------------
-
-```
-VmPeak: 55024 kB
-VmSize: 55024 kB
-VmLck: 0 kB
-VmHWM: 12440 kB
-VmRSS: 12440 kB
-VmData: 47876 kB
-VmStk: 136 kB
-VmExe: 1024 kB
-VmLib: 1848 kB
-VmPTE: 64 kB
-VmSwap: 0 kB
-```
-
-**0.1242 kB virtual, 0.1132 kB resident per counter.**
-
-1000 gauges registered
-----------------------
-
-```
-VmPeak: 44012 kB
-VmSize: 44012 kB
-VmLck: 0 kB
-VmHWM: 1928 kB
-VmRSS: 1928 kB
-VmData: 36868 kB
-VmStk: 136 kB
-VmExe: 1020 kB
-VmLib: 1848 kB
-VmPTE: 40 kB
-VmSwap: 0 kB
-```
-
-**1.408 kB virtual, 0.808 kB resident per counter.**
-
-100000 gauges registered
-------------------------
-
-```
-VmPeak: 55020 kB
-VmSize: 55020 kB
-VmLck: 0 kB
-VmHWM: 12432 kB
-VmRSS: 12432 kB
-VmData: 47876 kB
-VmStk: 136 kB
-VmExe: 1020 kB
-VmLib: 1848 kB
-VmPTE: 60 kB
-VmSwap: 0 kB
-```
-
-**0.12416 kB virtual, 0.11312 resident per gauge.**
-
-1000 histograms with a uniform sample size of 1028
---------------------------------------------------
-
-```
-VmPeak: 72272 kB
-VmSize: 72272 kB
-VmLck: 0 kB
-VmHWM: 16204 kB
-VmRSS: 16204 kB
-VmData: 65100 kB
-VmStk: 136 kB
-VmExe: 1048 kB
-VmLib: 1848 kB
-VmPTE: 80 kB
-VmSwap: 0 kB
-```
-
-**29.668 kB virtual, TODO 15.084 resident per histogram.**
-
-10000 histograms with a uniform sample size of 1028
----------------------------------------------------
-
-```
-VmPeak: 256912 kB
-VmSize: 256912 kB
-VmLck: 0 kB
-VmHWM: 146204 kB
-VmRSS: 146204 kB
-VmData: 249740 kB
-VmStk: 136 kB
-VmExe: 1048 kB
-VmLib: 1848 kB
-VmPTE: 448 kB
-VmSwap: 0 kB
-```
-
-**21.4308 kB virtual, 14.5084 kB resident per histogram.**
-
-50000 histograms with a uniform sample size of 1028
----------------------------------------------------
-
-```
-VmPeak: 908112 kB
-VmSize: 908112 kB
-VmLck: 0 kB
-VmHWM: 645832 kB
-VmRSS: 645588 kB
-VmData: 900940 kB
-VmStk: 136 kB
-VmExe: 1048 kB
-VmLib: 1848 kB
-VmPTE: 1716 kB
-VmSwap: 1544 kB
-```
-
-**17.31016 kB virtual, 12.88936 kB resident per histogram.**
-
-1000 histograms with an exponentially-decaying sample size of 1028 and alpha of 0.015
--------------------------------------------------------------------------------------
-
-```
-VmPeak: 62480 kB
-VmSize: 62480 kB
-VmLck: 0 kB
-VmHWM: 11572 kB
-VmRSS: 11572 kB
-VmData: 55308 kB
-VmStk: 136 kB
-VmExe: 1048 kB
-VmLib: 1848 kB
-VmPTE: 64 kB
-VmSwap: 0 kB
-```
-
-**19.876 kB virtual, 10.452 kB resident per histogram.**
-
-10000 histograms with an exponentially-decaying sample size of 1028 and alpha of 0.015
---------------------------------------------------------------------------------------
-
-```
-VmPeak: 153296 kB
-VmSize: 153296 kB
-VmLck: 0 kB
-VmHWM: 101176 kB
-VmRSS: 101176 kB
-VmData: 146124 kB
-VmStk: 136 kB
-VmExe: 1048 kB
-VmLib: 1848 kB
-VmPTE: 240 kB
-VmSwap: 0 kB
-```
-
-**11.0692 kB virtual, 10.0056 kB resident per histogram.**
-
-50000 histograms with an exponentially-decaying sample size of 1028 and alpha of 0.015
---------------------------------------------------------------------------------------
-
-```
-VmPeak: 557264 kB
-VmSize: 557264 kB
-VmLck: 0 kB
-VmHWM: 501056 kB
-VmRSS: 501056 kB
-VmData: 550092 kB
-VmStk: 136 kB
-VmExe: 1048 kB
-VmLib: 1848 kB
-VmPTE: 1032 kB
-VmSwap: 0 kB
-```
-
-**10.2932 kB virtual, 9.99872 kB resident per histogram.**
-
-1000 meters
------------
-
-```
-VmPeak: 74504 kB
-VmSize: 74504 kB
-VmLck: 0 kB
-VmHWM: 24124 kB
-VmRSS: 24124 kB
-VmData: 67340 kB
-VmStk: 136 kB
-VmExe: 1040 kB
-VmLib: 1848 kB
-VmPTE: 92 kB
-VmSwap: 0 kB
-```
-
-**31.9 kB virtual, 23.004 kB resident per meter.**
-
-10000 meters
-------------
-
-```
-VmPeak: 278920 kB
-VmSize: 278920 kB
-VmLck: 0 kB
-VmHWM: 227300 kB
-VmRSS: 227300 kB
-VmData: 271756 kB
-VmStk: 136 kB
-VmExe: 1040 kB
-VmLib: 1848 kB
-VmPTE: 488 kB
-VmSwap: 0 kB
-```
-
-**23.6316 kB virtual, 22.618 kB resident per meter.**
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/meter.go b/containerd/vendor/github.com/rcrowley/go-metrics/meter.go
deleted file mode 100644
index 0389ab0..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/meter.go
+++ /dev/null
@@ -1,233 +0,0 @@
-package metrics
-
-import (
- "sync"
- "time"
-)
-
-// Meters count events to produce exponentially-weighted moving average rates
-// at one-, five-, and fifteen-minutes and a mean rate.
-type Meter interface {
- Count() int64
- Mark(int64)
- Rate1() float64
- Rate5() float64
- Rate15() float64
- RateMean() float64
- Snapshot() Meter
-}
-
-// GetOrRegisterMeter returns an existing Meter or constructs and registers a
-// new StandardMeter.
-func GetOrRegisterMeter(name string, r Registry) Meter {
- if nil == r {
- r = DefaultRegistry
- }
- return r.GetOrRegister(name, NewMeter).(Meter)
-}
-
-// NewMeter constructs a new StandardMeter and launches a goroutine.
-func NewMeter() Meter {
- if UseNilMetrics {
- return NilMeter{}
- }
- m := newStandardMeter()
- arbiter.Lock()
- defer arbiter.Unlock()
- arbiter.meters = append(arbiter.meters, m)
- if !arbiter.started {
- arbiter.started = true
- go arbiter.tick()
- }
- return m
-}
-
-// NewMeter constructs and registers a new StandardMeter and launches a
-// goroutine.
-func NewRegisteredMeter(name string, r Registry) Meter {
- c := NewMeter()
- if nil == r {
- r = DefaultRegistry
- }
- r.Register(name, c)
- return c
-}
-
-// MeterSnapshot is a read-only copy of another Meter.
-type MeterSnapshot struct {
- count int64
- rate1, rate5, rate15, rateMean float64
-}
-
-// Count returns the count of events at the time the snapshot was taken.
-func (m *MeterSnapshot) Count() int64 { return m.count }
-
-// Mark panics.
-func (*MeterSnapshot) Mark(n int64) {
- panic("Mark called on a MeterSnapshot")
-}
-
-// Rate1 returns the one-minute moving average rate of events per second at the
-// time the snapshot was taken.
-func (m *MeterSnapshot) Rate1() float64 { return m.rate1 }
-
-// Rate5 returns the five-minute moving average rate of events per second at
-// the time the snapshot was taken.
-func (m *MeterSnapshot) Rate5() float64 { return m.rate5 }
-
-// Rate15 returns the fifteen-minute moving average rate of events per second
-// at the time the snapshot was taken.
-func (m *MeterSnapshot) Rate15() float64 { return m.rate15 }
-
-// RateMean returns the meter's mean rate of events per second at the time the
-// snapshot was taken.
-func (m *MeterSnapshot) RateMean() float64 { return m.rateMean }
-
-// Snapshot returns the snapshot.
-func (m *MeterSnapshot) Snapshot() Meter { return m }
-
-// NilMeter is a no-op Meter.
-type NilMeter struct{}
-
-// Count is a no-op.
-func (NilMeter) Count() int64 { return 0 }
-
-// Mark is a no-op.
-func (NilMeter) Mark(n int64) {}
-
-// Rate1 is a no-op.
-func (NilMeter) Rate1() float64 { return 0.0 }
-
-// Rate5 is a no-op.
-func (NilMeter) Rate5() float64 { return 0.0 }
-
-// Rate15is a no-op.
-func (NilMeter) Rate15() float64 { return 0.0 }
-
-// RateMean is a no-op.
-func (NilMeter) RateMean() float64 { return 0.0 }
-
-// Snapshot is a no-op.
-func (NilMeter) Snapshot() Meter { return NilMeter{} }
-
-// StandardMeter is the standard implementation of a Meter.
-type StandardMeter struct {
- lock sync.RWMutex
- snapshot *MeterSnapshot
- a1, a5, a15 EWMA
- startTime time.Time
-}
-
-func newStandardMeter() *StandardMeter {
- return &StandardMeter{
- snapshot: &MeterSnapshot{},
- a1: NewEWMA1(),
- a5: NewEWMA5(),
- a15: NewEWMA15(),
- startTime: time.Now(),
- }
-}
-
-// Count returns the number of events recorded.
-func (m *StandardMeter) Count() int64 {
- m.lock.RLock()
- count := m.snapshot.count
- m.lock.RUnlock()
- return count
-}
-
-// Mark records the occurance of n events.
-func (m *StandardMeter) Mark(n int64) {
- m.lock.Lock()
- defer m.lock.Unlock()
- m.snapshot.count += n
- m.a1.Update(n)
- m.a5.Update(n)
- m.a15.Update(n)
- m.updateSnapshot()
-}
-
-// Rate1 returns the one-minute moving average rate of events per second.
-func (m *StandardMeter) Rate1() float64 {
- m.lock.RLock()
- rate1 := m.snapshot.rate1
- m.lock.RUnlock()
- return rate1
-}
-
-// Rate5 returns the five-minute moving average rate of events per second.
-func (m *StandardMeter) Rate5() float64 {
- m.lock.RLock()
- rate5 := m.snapshot.rate5
- m.lock.RUnlock()
- return rate5
-}
-
-// Rate15 returns the fifteen-minute moving average rate of events per second.
-func (m *StandardMeter) Rate15() float64 {
- m.lock.RLock()
- rate15 := m.snapshot.rate15
- m.lock.RUnlock()
- return rate15
-}
-
-// RateMean returns the meter's mean rate of events per second.
-func (m *StandardMeter) RateMean() float64 {
- m.lock.RLock()
- rateMean := m.snapshot.rateMean
- m.lock.RUnlock()
- return rateMean
-}
-
-// Snapshot returns a read-only copy of the meter.
-func (m *StandardMeter) Snapshot() Meter {
- m.lock.RLock()
- snapshot := *m.snapshot
- m.lock.RUnlock()
- return &snapshot
-}
-
-func (m *StandardMeter) updateSnapshot() {
- // should run with write lock held on m.lock
- snapshot := m.snapshot
- snapshot.rate1 = m.a1.Rate()
- snapshot.rate5 = m.a5.Rate()
- snapshot.rate15 = m.a15.Rate()
- snapshot.rateMean = float64(snapshot.count) / time.Since(m.startTime).Seconds()
-}
-
-func (m *StandardMeter) tick() {
- m.lock.Lock()
- defer m.lock.Unlock()
- m.a1.Tick()
- m.a5.Tick()
- m.a15.Tick()
- m.updateSnapshot()
-}
-
-type meterArbiter struct {
- sync.RWMutex
- started bool
- meters []*StandardMeter
- ticker *time.Ticker
-}
-
-var arbiter = meterArbiter{ticker: time.NewTicker(5e9)}
-
-// Ticks meters on the scheduled interval
-func (ma *meterArbiter) tick() {
- for {
- select {
- case <-ma.ticker.C:
- ma.tickMeters()
- }
- }
-}
-
-func (ma *meterArbiter) tickMeters() {
- ma.RLock()
- defer ma.RUnlock()
- for _, meter := range ma.meters {
- meter.tick()
- }
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/metrics.go b/containerd/vendor/github.com/rcrowley/go-metrics/metrics.go
deleted file mode 100644
index b97a49e..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/metrics.go
+++ /dev/null
@@ -1,13 +0,0 @@
-// Go port of Coda Hale's Metrics library
-//
-//
-//
-// Coda Hale's original work:
-package metrics
-
-// UseNilMetrics is checked by the constructor functions for all of the
-// standard metrics. If it is true, the metric returned is a stub.
-//
-// This global kill-switch helps quantify the observer effect and makes
-// for less cluttered pprof profiles.
-var UseNilMetrics bool = false
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/opentsdb.go b/containerd/vendor/github.com/rcrowley/go-metrics/opentsdb.go
deleted file mode 100644
index 266b6c9..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/opentsdb.go
+++ /dev/null
@@ -1,119 +0,0 @@
-package metrics
-
-import (
- "bufio"
- "fmt"
- "log"
- "net"
- "os"
- "strings"
- "time"
-)
-
-var shortHostName string = ""
-
-// OpenTSDBConfig provides a container with configuration parameters for
-// the OpenTSDB exporter
-type OpenTSDBConfig struct {
- Addr *net.TCPAddr // Network address to connect to
- Registry Registry // Registry to be exported
- FlushInterval time.Duration // Flush interval
- DurationUnit time.Duration // Time conversion unit for durations
- Prefix string // Prefix to be prepended to metric names
-}
-
-// OpenTSDB is a blocking exporter function which reports metrics in r
-// to a TSDB server located at addr, flushing them every d duration
-// and prepending metric names with prefix.
-func OpenTSDB(r Registry, d time.Duration, prefix string, addr *net.TCPAddr) {
- OpenTSDBWithConfig(OpenTSDBConfig{
- Addr: addr,
- Registry: r,
- FlushInterval: d,
- DurationUnit: time.Nanosecond,
- Prefix: prefix,
- })
-}
-
-// OpenTSDBWithConfig is a blocking exporter function just like OpenTSDB,
-// but it takes a OpenTSDBConfig instead.
-func OpenTSDBWithConfig(c OpenTSDBConfig) {
- for _ = range time.Tick(c.FlushInterval) {
- if err := openTSDB(&c); nil != err {
- log.Println(err)
- }
- }
-}
-
-func getShortHostname() string {
- if shortHostName == "" {
- host, _ := os.Hostname()
- if index := strings.Index(host, "."); index > 0 {
- shortHostName = host[:index]
- } else {
- shortHostName = host
- }
- }
- return shortHostName
-}
-
-func openTSDB(c *OpenTSDBConfig) error {
- shortHostname := getShortHostname()
- now := time.Now().Unix()
- du := float64(c.DurationUnit)
- conn, err := net.DialTCP("tcp", nil, c.Addr)
- if nil != err {
- return err
- }
- defer conn.Close()
- w := bufio.NewWriter(conn)
- c.Registry.Each(func(name string, i interface{}) {
- switch metric := i.(type) {
- case Counter:
- fmt.Fprintf(w, "put %s.%s.count %d %d host=%s\n", c.Prefix, name, now, metric.Count(), shortHostname)
- case Gauge:
- fmt.Fprintf(w, "put %s.%s.value %d %d host=%s\n", c.Prefix, name, now, metric.Value(), shortHostname)
- case GaugeFloat64:
- fmt.Fprintf(w, "put %s.%s.value %d %f host=%s\n", c.Prefix, name, now, metric.Value(), shortHostname)
- case Histogram:
- h := metric.Snapshot()
- ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
- fmt.Fprintf(w, "put %s.%s.count %d %d host=%s\n", c.Prefix, name, now, h.Count(), shortHostname)
- fmt.Fprintf(w, "put %s.%s.min %d %d host=%s\n", c.Prefix, name, now, h.Min(), shortHostname)
- fmt.Fprintf(w, "put %s.%s.max %d %d host=%s\n", c.Prefix, name, now, h.Max(), shortHostname)
- fmt.Fprintf(w, "put %s.%s.mean %d %.2f host=%s\n", c.Prefix, name, now, h.Mean(), shortHostname)
- fmt.Fprintf(w, "put %s.%s.std-dev %d %.2f host=%s\n", c.Prefix, name, now, h.StdDev(), shortHostname)
- fmt.Fprintf(w, "put %s.%s.50-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[0], shortHostname)
- fmt.Fprintf(w, "put %s.%s.75-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[1], shortHostname)
- fmt.Fprintf(w, "put %s.%s.95-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[2], shortHostname)
- fmt.Fprintf(w, "put %s.%s.99-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[3], shortHostname)
- fmt.Fprintf(w, "put %s.%s.999-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[4], shortHostname)
- case Meter:
- m := metric.Snapshot()
- fmt.Fprintf(w, "put %s.%s.count %d %d host=%s\n", c.Prefix, name, now, m.Count(), shortHostname)
- fmt.Fprintf(w, "put %s.%s.one-minute %d %.2f host=%s\n", c.Prefix, name, now, m.Rate1(), shortHostname)
- fmt.Fprintf(w, "put %s.%s.five-minute %d %.2f host=%s\n", c.Prefix, name, now, m.Rate5(), shortHostname)
- fmt.Fprintf(w, "put %s.%s.fifteen-minute %d %.2f host=%s\n", c.Prefix, name, now, m.Rate15(), shortHostname)
- fmt.Fprintf(w, "put %s.%s.mean %d %.2f host=%s\n", c.Prefix, name, now, m.RateMean(), shortHostname)
- case Timer:
- t := metric.Snapshot()
- ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
- fmt.Fprintf(w, "put %s.%s.count %d %d host=%s\n", c.Prefix, name, now, t.Count(), shortHostname)
- fmt.Fprintf(w, "put %s.%s.min %d %d host=%s\n", c.Prefix, name, now, t.Min()/int64(du), shortHostname)
- fmt.Fprintf(w, "put %s.%s.max %d %d host=%s\n", c.Prefix, name, now, t.Max()/int64(du), shortHostname)
- fmt.Fprintf(w, "put %s.%s.mean %d %.2f host=%s\n", c.Prefix, name, now, t.Mean()/du, shortHostname)
- fmt.Fprintf(w, "put %s.%s.std-dev %d %.2f host=%s\n", c.Prefix, name, now, t.StdDev()/du, shortHostname)
- fmt.Fprintf(w, "put %s.%s.50-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[0]/du, shortHostname)
- fmt.Fprintf(w, "put %s.%s.75-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[1]/du, shortHostname)
- fmt.Fprintf(w, "put %s.%s.95-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[2]/du, shortHostname)
- fmt.Fprintf(w, "put %s.%s.99-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[3]/du, shortHostname)
- fmt.Fprintf(w, "put %s.%s.999-percentile %d %.2f host=%s\n", c.Prefix, name, now, ps[4]/du, shortHostname)
- fmt.Fprintf(w, "put %s.%s.one-minute %d %.2f host=%s\n", c.Prefix, name, now, t.Rate1(), shortHostname)
- fmt.Fprintf(w, "put %s.%s.five-minute %d %.2f host=%s\n", c.Prefix, name, now, t.Rate5(), shortHostname)
- fmt.Fprintf(w, "put %s.%s.fifteen-minute %d %.2f host=%s\n", c.Prefix, name, now, t.Rate15(), shortHostname)
- fmt.Fprintf(w, "put %s.%s.mean-rate %d %.2f host=%s\n", c.Prefix, name, now, t.RateMean(), shortHostname)
- }
- w.Flush()
- })
- return nil
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/registry.go b/containerd/vendor/github.com/rcrowley/go-metrics/registry.go
deleted file mode 100644
index a3b26eb..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/registry.go
+++ /dev/null
@@ -1,240 +0,0 @@
-package metrics
-
-import (
- "fmt"
- "reflect"
- "sync"
-)
-
-// DuplicateMetric is the error returned by Registry.Register when a metric
-// already exists. If you mean to Register that metric you must first
-// Unregister the existing metric.
-type DuplicateMetric string
-
-func (err DuplicateMetric) Error() string {
- return fmt.Sprintf("duplicate metric: %s", string(err))
-}
-
-// A Registry holds references to a set of metrics by name and can iterate
-// over them, calling callback functions provided by the user.
-//
-// This is an interface so as to encourage other structs to implement
-// the Registry API as appropriate.
-type Registry interface {
-
- // Call the given function for each registered metric.
- Each(func(string, interface{}))
-
- // Get the metric by the given name or nil if none is registered.
- Get(string) interface{}
-
- // Gets an existing metric or registers the given one.
- // The interface can be the metric to register if not found in registry,
- // or a function returning the metric for lazy instantiation.
- GetOrRegister(string, interface{}) interface{}
-
- // Register the given metric under the given name.
- Register(string, interface{}) error
-
- // Run all registered healthchecks.
- RunHealthchecks()
-
- // Unregister the metric with the given name.
- Unregister(string)
-
- // Unregister all metrics. (Mostly for testing.)
- UnregisterAll()
-}
-
-// The standard implementation of a Registry is a mutex-protected map
-// of names to metrics.
-type StandardRegistry struct {
- metrics map[string]interface{}
- mutex sync.Mutex
-}
-
-// Create a new registry.
-func NewRegistry() Registry {
- return &StandardRegistry{metrics: make(map[string]interface{})}
-}
-
-// Call the given function for each registered metric.
-func (r *StandardRegistry) Each(f func(string, interface{})) {
- for name, i := range r.registered() {
- f(name, i)
- }
-}
-
-// Get the metric by the given name or nil if none is registered.
-func (r *StandardRegistry) Get(name string) interface{} {
- r.mutex.Lock()
- defer r.mutex.Unlock()
- return r.metrics[name]
-}
-
-// Gets an existing metric or creates and registers a new one. Threadsafe
-// alternative to calling Get and Register on failure.
-// The interface can be the metric to register if not found in registry,
-// or a function returning the metric for lazy instantiation.
-func (r *StandardRegistry) GetOrRegister(name string, i interface{}) interface{} {
- r.mutex.Lock()
- defer r.mutex.Unlock()
- if metric, ok := r.metrics[name]; ok {
- return metric
- }
- if v := reflect.ValueOf(i); v.Kind() == reflect.Func {
- i = v.Call(nil)[0].Interface()
- }
- r.register(name, i)
- return i
-}
-
-// Register the given metric under the given name. Returns a DuplicateMetric
-// if a metric by the given name is already registered.
-func (r *StandardRegistry) Register(name string, i interface{}) error {
- r.mutex.Lock()
- defer r.mutex.Unlock()
- return r.register(name, i)
-}
-
-// Run all registered healthchecks.
-func (r *StandardRegistry) RunHealthchecks() {
- r.mutex.Lock()
- defer r.mutex.Unlock()
- for _, i := range r.metrics {
- if h, ok := i.(Healthcheck); ok {
- h.Check()
- }
- }
-}
-
-// Unregister the metric with the given name.
-func (r *StandardRegistry) Unregister(name string) {
- r.mutex.Lock()
- defer r.mutex.Unlock()
- delete(r.metrics, name)
-}
-
-// Unregister all metrics. (Mostly for testing.)
-func (r *StandardRegistry) UnregisterAll() {
- r.mutex.Lock()
- defer r.mutex.Unlock()
- for name, _ := range r.metrics {
- delete(r.metrics, name)
- }
-}
-
-func (r *StandardRegistry) register(name string, i interface{}) error {
- if _, ok := r.metrics[name]; ok {
- return DuplicateMetric(name)
- }
- switch i.(type) {
- case Counter, Gauge, GaugeFloat64, Healthcheck, Histogram, Meter, Timer:
- r.metrics[name] = i
- }
- return nil
-}
-
-func (r *StandardRegistry) registered() map[string]interface{} {
- r.mutex.Lock()
- defer r.mutex.Unlock()
- metrics := make(map[string]interface{}, len(r.metrics))
- for name, i := range r.metrics {
- metrics[name] = i
- }
- return metrics
-}
-
-type PrefixedRegistry struct {
- underlying Registry
- prefix string
-}
-
-func NewPrefixedRegistry(prefix string) Registry {
- return &PrefixedRegistry{
- underlying: NewRegistry(),
- prefix: prefix,
- }
-}
-
-// Call the given function for each registered metric.
-func (r *PrefixedRegistry) Each(fn func(string, interface{})) {
- r.underlying.Each(fn)
-}
-
-// Get the metric by the given name or nil if none is registered.
-func (r *PrefixedRegistry) Get(name string) interface{} {
- return r.underlying.Get(name)
-}
-
-// Gets an existing metric or registers the given one.
-// The interface can be the metric to register if not found in registry,
-// or a function returning the metric for lazy instantiation.
-func (r *PrefixedRegistry) GetOrRegister(name string, metric interface{}) interface{} {
- realName := r.prefix + name
- return r.underlying.GetOrRegister(realName, metric)
-}
-
-// Register the given metric under the given name. The name will be prefixed.
-func (r *PrefixedRegistry) Register(name string, metric interface{}) error {
- realName := r.prefix + name
- return r.underlying.Register(realName, metric)
-}
-
-// Run all registered healthchecks.
-func (r *PrefixedRegistry) RunHealthchecks() {
- r.underlying.RunHealthchecks()
-}
-
-// Unregister the metric with the given name. The name will be prefixed.
-func (r *PrefixedRegistry) Unregister(name string) {
- realName := r.prefix + name
- r.underlying.Unregister(realName)
-}
-
-// Unregister all metrics. (Mostly for testing.)
-func (r *PrefixedRegistry) UnregisterAll() {
- r.underlying.UnregisterAll()
-}
-
-var DefaultRegistry Registry = NewRegistry()
-
-// Call the given function for each registered metric.
-func Each(f func(string, interface{})) {
- DefaultRegistry.Each(f)
-}
-
-// Get the metric by the given name or nil if none is registered.
-func Get(name string) interface{} {
- return DefaultRegistry.Get(name)
-}
-
-// Gets an existing metric or creates and registers a new one. Threadsafe
-// alternative to calling Get and Register on failure.
-func GetOrRegister(name string, i interface{}) interface{} {
- return DefaultRegistry.GetOrRegister(name, i)
-}
-
-// Register the given metric under the given name. Returns a DuplicateMetric
-// if a metric by the given name is already registered.
-func Register(name string, i interface{}) error {
- return DefaultRegistry.Register(name, i)
-}
-
-// Register the given metric under the given name. Panics if a metric by the
-// given name is already registered.
-func MustRegister(name string, i interface{}) {
- if err := Register(name, i); err != nil {
- panic(err)
- }
-}
-
-// Run all registered healthchecks.
-func RunHealthchecks() {
- DefaultRegistry.RunHealthchecks()
-}
-
-// Unregister the metric with the given name.
-func Unregister(name string) {
- DefaultRegistry.Unregister(name)
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/runtime.go b/containerd/vendor/github.com/rcrowley/go-metrics/runtime.go
deleted file mode 100644
index 82574bf..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/runtime.go
+++ /dev/null
@@ -1,200 +0,0 @@
-package metrics
-
-import (
- "runtime"
- "time"
-)
-
-var (
- memStats runtime.MemStats
- runtimeMetrics struct {
- MemStats struct {
- Alloc Gauge
- BuckHashSys Gauge
- DebugGC Gauge
- EnableGC Gauge
- Frees Gauge
- HeapAlloc Gauge
- HeapIdle Gauge
- HeapInuse Gauge
- HeapObjects Gauge
- HeapReleased Gauge
- HeapSys Gauge
- LastGC Gauge
- Lookups Gauge
- Mallocs Gauge
- MCacheInuse Gauge
- MCacheSys Gauge
- MSpanInuse Gauge
- MSpanSys Gauge
- NextGC Gauge
- NumGC Gauge
- PauseNs Histogram
- PauseTotalNs Gauge
- StackInuse Gauge
- StackSys Gauge
- Sys Gauge
- TotalAlloc Gauge
- }
- NumCgoCall Gauge
- NumGoroutine Gauge
- ReadMemStats Timer
- }
- frees uint64
- lookups uint64
- mallocs uint64
- numGC uint32
- numCgoCalls int64
-)
-
-// Capture new values for the Go runtime statistics exported in
-// runtime.MemStats. This is designed to be called as a goroutine.
-func CaptureRuntimeMemStats(r Registry, d time.Duration) {
- for _ = range time.Tick(d) {
- CaptureRuntimeMemStatsOnce(r)
- }
-}
-
-// Capture new values for the Go runtime statistics exported in
-// runtime.MemStats. This is designed to be called in a background
-// goroutine. Giving a registry which has not been given to
-// RegisterRuntimeMemStats will panic.
-//
-// Be very careful with this because runtime.ReadMemStats calls the C
-// functions runtime·semacquire(&runtime·worldsema) and runtime·stoptheworld()
-// and that last one does what it says on the tin.
-func CaptureRuntimeMemStatsOnce(r Registry) {
- t := time.Now()
- runtime.ReadMemStats(&memStats) // This takes 50-200us.
- runtimeMetrics.ReadMemStats.UpdateSince(t)
-
- runtimeMetrics.MemStats.Alloc.Update(int64(memStats.Alloc))
- runtimeMetrics.MemStats.BuckHashSys.Update(int64(memStats.BuckHashSys))
- if memStats.DebugGC {
- runtimeMetrics.MemStats.DebugGC.Update(1)
- } else {
- runtimeMetrics.MemStats.DebugGC.Update(0)
- }
- if memStats.EnableGC {
- runtimeMetrics.MemStats.EnableGC.Update(1)
- } else {
- runtimeMetrics.MemStats.EnableGC.Update(0)
- }
-
- runtimeMetrics.MemStats.Frees.Update(int64(memStats.Frees - frees))
- runtimeMetrics.MemStats.HeapAlloc.Update(int64(memStats.HeapAlloc))
- runtimeMetrics.MemStats.HeapIdle.Update(int64(memStats.HeapIdle))
- runtimeMetrics.MemStats.HeapInuse.Update(int64(memStats.HeapInuse))
- runtimeMetrics.MemStats.HeapObjects.Update(int64(memStats.HeapObjects))
- runtimeMetrics.MemStats.HeapReleased.Update(int64(memStats.HeapReleased))
- runtimeMetrics.MemStats.HeapSys.Update(int64(memStats.HeapSys))
- runtimeMetrics.MemStats.LastGC.Update(int64(memStats.LastGC))
- runtimeMetrics.MemStats.Lookups.Update(int64(memStats.Lookups - lookups))
- runtimeMetrics.MemStats.Mallocs.Update(int64(memStats.Mallocs - mallocs))
- runtimeMetrics.MemStats.MCacheInuse.Update(int64(memStats.MCacheInuse))
- runtimeMetrics.MemStats.MCacheSys.Update(int64(memStats.MCacheSys))
- runtimeMetrics.MemStats.MSpanInuse.Update(int64(memStats.MSpanInuse))
- runtimeMetrics.MemStats.MSpanSys.Update(int64(memStats.MSpanSys))
- runtimeMetrics.MemStats.NextGC.Update(int64(memStats.NextGC))
- runtimeMetrics.MemStats.NumGC.Update(int64(memStats.NumGC - numGC))
-
- //
- i := numGC % uint32(len(memStats.PauseNs))
- ii := memStats.NumGC % uint32(len(memStats.PauseNs))
- if memStats.NumGC-numGC >= uint32(len(memStats.PauseNs)) {
- for i = 0; i < uint32(len(memStats.PauseNs)); i++ {
- runtimeMetrics.MemStats.PauseNs.Update(int64(memStats.PauseNs[i]))
- }
- } else {
- if i > ii {
- for ; i < uint32(len(memStats.PauseNs)); i++ {
- runtimeMetrics.MemStats.PauseNs.Update(int64(memStats.PauseNs[i]))
- }
- i = 0
- }
- for ; i < ii; i++ {
- runtimeMetrics.MemStats.PauseNs.Update(int64(memStats.PauseNs[i]))
- }
- }
- frees = memStats.Frees
- lookups = memStats.Lookups
- mallocs = memStats.Mallocs
- numGC = memStats.NumGC
-
- runtimeMetrics.MemStats.PauseTotalNs.Update(int64(memStats.PauseTotalNs))
- runtimeMetrics.MemStats.StackInuse.Update(int64(memStats.StackInuse))
- runtimeMetrics.MemStats.StackSys.Update(int64(memStats.StackSys))
- runtimeMetrics.MemStats.Sys.Update(int64(memStats.Sys))
- runtimeMetrics.MemStats.TotalAlloc.Update(int64(memStats.TotalAlloc))
-
- currentNumCgoCalls := numCgoCall()
- runtimeMetrics.NumCgoCall.Update(currentNumCgoCalls - numCgoCalls)
- numCgoCalls = currentNumCgoCalls
-
- runtimeMetrics.NumGoroutine.Update(int64(runtime.NumGoroutine()))
-}
-
-// Register runtimeMetrics for the Go runtime statistics exported in runtime and
-// specifically runtime.MemStats. The runtimeMetrics are named by their
-// fully-qualified Go symbols, i.e. runtime.MemStats.Alloc.
-func RegisterRuntimeMemStats(r Registry) {
- runtimeMetrics.MemStats.Alloc = NewGauge()
- runtimeMetrics.MemStats.BuckHashSys = NewGauge()
- runtimeMetrics.MemStats.DebugGC = NewGauge()
- runtimeMetrics.MemStats.EnableGC = NewGauge()
- runtimeMetrics.MemStats.Frees = NewGauge()
- runtimeMetrics.MemStats.HeapAlloc = NewGauge()
- runtimeMetrics.MemStats.HeapIdle = NewGauge()
- runtimeMetrics.MemStats.HeapInuse = NewGauge()
- runtimeMetrics.MemStats.HeapObjects = NewGauge()
- runtimeMetrics.MemStats.HeapReleased = NewGauge()
- runtimeMetrics.MemStats.HeapSys = NewGauge()
- runtimeMetrics.MemStats.LastGC = NewGauge()
- runtimeMetrics.MemStats.Lookups = NewGauge()
- runtimeMetrics.MemStats.Mallocs = NewGauge()
- runtimeMetrics.MemStats.MCacheInuse = NewGauge()
- runtimeMetrics.MemStats.MCacheSys = NewGauge()
- runtimeMetrics.MemStats.MSpanInuse = NewGauge()
- runtimeMetrics.MemStats.MSpanSys = NewGauge()
- runtimeMetrics.MemStats.NextGC = NewGauge()
- runtimeMetrics.MemStats.NumGC = NewGauge()
- runtimeMetrics.MemStats.PauseNs = NewHistogram(NewExpDecaySample(1028, 0.015))
- runtimeMetrics.MemStats.PauseTotalNs = NewGauge()
- runtimeMetrics.MemStats.StackInuse = NewGauge()
- runtimeMetrics.MemStats.StackSys = NewGauge()
- runtimeMetrics.MemStats.Sys = NewGauge()
- runtimeMetrics.MemStats.TotalAlloc = NewGauge()
- runtimeMetrics.NumCgoCall = NewGauge()
- runtimeMetrics.NumGoroutine = NewGauge()
- runtimeMetrics.ReadMemStats = NewTimer()
-
- r.Register("runtime.MemStats.Alloc", runtimeMetrics.MemStats.Alloc)
- r.Register("runtime.MemStats.BuckHashSys", runtimeMetrics.MemStats.BuckHashSys)
- r.Register("runtime.MemStats.DebugGC", runtimeMetrics.MemStats.DebugGC)
- r.Register("runtime.MemStats.EnableGC", runtimeMetrics.MemStats.EnableGC)
- r.Register("runtime.MemStats.Frees", runtimeMetrics.MemStats.Frees)
- r.Register("runtime.MemStats.HeapAlloc", runtimeMetrics.MemStats.HeapAlloc)
- r.Register("runtime.MemStats.HeapIdle", runtimeMetrics.MemStats.HeapIdle)
- r.Register("runtime.MemStats.HeapInuse", runtimeMetrics.MemStats.HeapInuse)
- r.Register("runtime.MemStats.HeapObjects", runtimeMetrics.MemStats.HeapObjects)
- r.Register("runtime.MemStats.HeapReleased", runtimeMetrics.MemStats.HeapReleased)
- r.Register("runtime.MemStats.HeapSys", runtimeMetrics.MemStats.HeapSys)
- r.Register("runtime.MemStats.LastGC", runtimeMetrics.MemStats.LastGC)
- r.Register("runtime.MemStats.Lookups", runtimeMetrics.MemStats.Lookups)
- r.Register("runtime.MemStats.Mallocs", runtimeMetrics.MemStats.Mallocs)
- r.Register("runtime.MemStats.MCacheInuse", runtimeMetrics.MemStats.MCacheInuse)
- r.Register("runtime.MemStats.MCacheSys", runtimeMetrics.MemStats.MCacheSys)
- r.Register("runtime.MemStats.MSpanInuse", runtimeMetrics.MemStats.MSpanInuse)
- r.Register("runtime.MemStats.MSpanSys", runtimeMetrics.MemStats.MSpanSys)
- r.Register("runtime.MemStats.NextGC", runtimeMetrics.MemStats.NextGC)
- r.Register("runtime.MemStats.NumGC", runtimeMetrics.MemStats.NumGC)
- r.Register("runtime.MemStats.PauseNs", runtimeMetrics.MemStats.PauseNs)
- r.Register("runtime.MemStats.PauseTotalNs", runtimeMetrics.MemStats.PauseTotalNs)
- r.Register("runtime.MemStats.StackInuse", runtimeMetrics.MemStats.StackInuse)
- r.Register("runtime.MemStats.StackSys", runtimeMetrics.MemStats.StackSys)
- r.Register("runtime.MemStats.Sys", runtimeMetrics.MemStats.Sys)
- r.Register("runtime.MemStats.TotalAlloc", runtimeMetrics.MemStats.TotalAlloc)
- r.Register("runtime.NumCgoCall", runtimeMetrics.NumCgoCall)
- r.Register("runtime.NumGoroutine", runtimeMetrics.NumGoroutine)
- r.Register("runtime.ReadMemStats", runtimeMetrics.ReadMemStats)
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/runtime_cgo.go b/containerd/vendor/github.com/rcrowley/go-metrics/runtime_cgo.go
deleted file mode 100644
index e3391f4..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/runtime_cgo.go
+++ /dev/null
@@ -1,10 +0,0 @@
-// +build cgo
-// +build !appengine
-
-package metrics
-
-import "runtime"
-
-func numCgoCall() int64 {
- return runtime.NumCgoCall()
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/runtime_no_cgo.go b/containerd/vendor/github.com/rcrowley/go-metrics/runtime_no_cgo.go
deleted file mode 100644
index 616a3b4..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/runtime_no_cgo.go
+++ /dev/null
@@ -1,7 +0,0 @@
-// +build !cgo appengine
-
-package metrics
-
-func numCgoCall() int64 {
- return 0
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/sample.go b/containerd/vendor/github.com/rcrowley/go-metrics/sample.go
deleted file mode 100644
index 5f6a377..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/sample.go
+++ /dev/null
@@ -1,609 +0,0 @@
-package metrics
-
-import (
- "math"
- "math/rand"
- "sort"
- "sync"
- "time"
-)
-
-const rescaleThreshold = time.Hour
-
-// Samples maintain a statistically-significant selection of values from
-// a stream.
-type Sample interface {
- Clear()
- Count() int64
- Max() int64
- Mean() float64
- Min() int64
- Percentile(float64) float64
- Percentiles([]float64) []float64
- Size() int
- Snapshot() Sample
- StdDev() float64
- Sum() int64
- Update(int64)
- Values() []int64
- Variance() float64
-}
-
-// ExpDecaySample is an exponentially-decaying sample using a forward-decaying
-// priority reservoir. See Cormode et al's "Forward Decay: A Practical Time
-// Decay Model for Streaming Systems".
-//
-//
-type ExpDecaySample struct {
- alpha float64
- count int64
- mutex sync.Mutex
- reservoirSize int
- t0, t1 time.Time
- values *expDecaySampleHeap
-}
-
-// NewExpDecaySample constructs a new exponentially-decaying sample with the
-// given reservoir size and alpha.
-func NewExpDecaySample(reservoirSize int, alpha float64) Sample {
- if UseNilMetrics {
- return NilSample{}
- }
- s := &ExpDecaySample{
- alpha: alpha,
- reservoirSize: reservoirSize,
- t0: time.Now(),
- values: newExpDecaySampleHeap(reservoirSize),
- }
- s.t1 = s.t0.Add(rescaleThreshold)
- return s
-}
-
-// Clear clears all samples.
-func (s *ExpDecaySample) Clear() {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- s.count = 0
- s.t0 = time.Now()
- s.t1 = s.t0.Add(rescaleThreshold)
- s.values.Clear()
-}
-
-// Count returns the number of samples recorded, which may exceed the
-// reservoir size.
-func (s *ExpDecaySample) Count() int64 {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- return s.count
-}
-
-// Max returns the maximum value in the sample, which may not be the maximum
-// value ever to be part of the sample.
-func (s *ExpDecaySample) Max() int64 {
- return SampleMax(s.Values())
-}
-
-// Mean returns the mean of the values in the sample.
-func (s *ExpDecaySample) Mean() float64 {
- return SampleMean(s.Values())
-}
-
-// Min returns the minimum value in the sample, which may not be the minimum
-// value ever to be part of the sample.
-func (s *ExpDecaySample) Min() int64 {
- return SampleMin(s.Values())
-}
-
-// Percentile returns an arbitrary percentile of values in the sample.
-func (s *ExpDecaySample) Percentile(p float64) float64 {
- return SamplePercentile(s.Values(), p)
-}
-
-// Percentiles returns a slice of arbitrary percentiles of values in the
-// sample.
-func (s *ExpDecaySample) Percentiles(ps []float64) []float64 {
- return SamplePercentiles(s.Values(), ps)
-}
-
-// Size returns the size of the sample, which is at most the reservoir size.
-func (s *ExpDecaySample) Size() int {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- return s.values.Size()
-}
-
-// Snapshot returns a read-only copy of the sample.
-func (s *ExpDecaySample) Snapshot() Sample {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- vals := s.values.Values()
- values := make([]int64, len(vals))
- for i, v := range vals {
- values[i] = v.v
- }
- return &SampleSnapshot{
- count: s.count,
- values: values,
- }
-}
-
-// StdDev returns the standard deviation of the values in the sample.
-func (s *ExpDecaySample) StdDev() float64 {
- return SampleStdDev(s.Values())
-}
-
-// Sum returns the sum of the values in the sample.
-func (s *ExpDecaySample) Sum() int64 {
- return SampleSum(s.Values())
-}
-
-// Update samples a new value.
-func (s *ExpDecaySample) Update(v int64) {
- s.update(time.Now(), v)
-}
-
-// Values returns a copy of the values in the sample.
-func (s *ExpDecaySample) Values() []int64 {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- vals := s.values.Values()
- values := make([]int64, len(vals))
- for i, v := range vals {
- values[i] = v.v
- }
- return values
-}
-
-// Variance returns the variance of the values in the sample.
-func (s *ExpDecaySample) Variance() float64 {
- return SampleVariance(s.Values())
-}
-
-// update samples a new value at a particular timestamp. This is a method all
-// its own to facilitate testing.
-func (s *ExpDecaySample) update(t time.Time, v int64) {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- s.count++
- if s.values.Size() == s.reservoirSize {
- s.values.Pop()
- }
- s.values.Push(expDecaySample{
- k: math.Exp(t.Sub(s.t0).Seconds()*s.alpha) / rand.Float64(),
- v: v,
- })
- if t.After(s.t1) {
- values := s.values.Values()
- t0 := s.t0
- s.values.Clear()
- s.t0 = t
- s.t1 = s.t0.Add(rescaleThreshold)
- for _, v := range values {
- v.k = v.k * math.Exp(-s.alpha*s.t0.Sub(t0).Seconds())
- s.values.Push(v)
- }
- }
-}
-
-// NilSample is a no-op Sample.
-type NilSample struct{}
-
-// Clear is a no-op.
-func (NilSample) Clear() {}
-
-// Count is a no-op.
-func (NilSample) Count() int64 { return 0 }
-
-// Max is a no-op.
-func (NilSample) Max() int64 { return 0 }
-
-// Mean is a no-op.
-func (NilSample) Mean() float64 { return 0.0 }
-
-// Min is a no-op.
-func (NilSample) Min() int64 { return 0 }
-
-// Percentile is a no-op.
-func (NilSample) Percentile(p float64) float64 { return 0.0 }
-
-// Percentiles is a no-op.
-func (NilSample) Percentiles(ps []float64) []float64 {
- return make([]float64, len(ps))
-}
-
-// Size is a no-op.
-func (NilSample) Size() int { return 0 }
-
-// Sample is a no-op.
-func (NilSample) Snapshot() Sample { return NilSample{} }
-
-// StdDev is a no-op.
-func (NilSample) StdDev() float64 { return 0.0 }
-
-// Sum is a no-op.
-func (NilSample) Sum() int64 { return 0 }
-
-// Update is a no-op.
-func (NilSample) Update(v int64) {}
-
-// Values is a no-op.
-func (NilSample) Values() []int64 { return []int64{} }
-
-// Variance is a no-op.
-func (NilSample) Variance() float64 { return 0.0 }
-
-// SampleMax returns the maximum value of the slice of int64.
-func SampleMax(values []int64) int64 {
- if 0 == len(values) {
- return 0
- }
- var max int64 = math.MinInt64
- for _, v := range values {
- if max < v {
- max = v
- }
- }
- return max
-}
-
-// SampleMean returns the mean value of the slice of int64.
-func SampleMean(values []int64) float64 {
- if 0 == len(values) {
- return 0.0
- }
- return float64(SampleSum(values)) / float64(len(values))
-}
-
-// SampleMin returns the minimum value of the slice of int64.
-func SampleMin(values []int64) int64 {
- if 0 == len(values) {
- return 0
- }
- var min int64 = math.MaxInt64
- for _, v := range values {
- if min > v {
- min = v
- }
- }
- return min
-}
-
-// SamplePercentiles returns an arbitrary percentile of the slice of int64.
-func SamplePercentile(values int64Slice, p float64) float64 {
- return SamplePercentiles(values, []float64{p})[0]
-}
-
-// SamplePercentiles returns a slice of arbitrary percentiles of the slice of
-// int64.
-func SamplePercentiles(values int64Slice, ps []float64) []float64 {
- scores := make([]float64, len(ps))
- size := len(values)
- if size > 0 {
- sort.Sort(values)
- for i, p := range ps {
- pos := p * float64(size+1)
- if pos < 1.0 {
- scores[i] = float64(values[0])
- } else if pos >= float64(size) {
- scores[i] = float64(values[size-1])
- } else {
- lower := float64(values[int(pos)-1])
- upper := float64(values[int(pos)])
- scores[i] = lower + (pos-math.Floor(pos))*(upper-lower)
- }
- }
- }
- return scores
-}
-
-// SampleSnapshot is a read-only copy of another Sample.
-type SampleSnapshot struct {
- count int64
- values []int64
-}
-
-// Clear panics.
-func (*SampleSnapshot) Clear() {
- panic("Clear called on a SampleSnapshot")
-}
-
-// Count returns the count of inputs at the time the snapshot was taken.
-func (s *SampleSnapshot) Count() int64 { return s.count }
-
-// Max returns the maximal value at the time the snapshot was taken.
-func (s *SampleSnapshot) Max() int64 { return SampleMax(s.values) }
-
-// Mean returns the mean value at the time the snapshot was taken.
-func (s *SampleSnapshot) Mean() float64 { return SampleMean(s.values) }
-
-// Min returns the minimal value at the time the snapshot was taken.
-func (s *SampleSnapshot) Min() int64 { return SampleMin(s.values) }
-
-// Percentile returns an arbitrary percentile of values at the time the
-// snapshot was taken.
-func (s *SampleSnapshot) Percentile(p float64) float64 {
- return SamplePercentile(s.values, p)
-}
-
-// Percentiles returns a slice of arbitrary percentiles of values at the time
-// the snapshot was taken.
-func (s *SampleSnapshot) Percentiles(ps []float64) []float64 {
- return SamplePercentiles(s.values, ps)
-}
-
-// Size returns the size of the sample at the time the snapshot was taken.
-func (s *SampleSnapshot) Size() int { return len(s.values) }
-
-// Snapshot returns the snapshot.
-func (s *SampleSnapshot) Snapshot() Sample { return s }
-
-// StdDev returns the standard deviation of values at the time the snapshot was
-// taken.
-func (s *SampleSnapshot) StdDev() float64 { return SampleStdDev(s.values) }
-
-// Sum returns the sum of values at the time the snapshot was taken.
-func (s *SampleSnapshot) Sum() int64 { return SampleSum(s.values) }
-
-// Update panics.
-func (*SampleSnapshot) Update(int64) {
- panic("Update called on a SampleSnapshot")
-}
-
-// Values returns a copy of the values in the sample.
-func (s *SampleSnapshot) Values() []int64 {
- values := make([]int64, len(s.values))
- copy(values, s.values)
- return values
-}
-
-// Variance returns the variance of values at the time the snapshot was taken.
-func (s *SampleSnapshot) Variance() float64 { return SampleVariance(s.values) }
-
-// SampleStdDev returns the standard deviation of the slice of int64.
-func SampleStdDev(values []int64) float64 {
- return math.Sqrt(SampleVariance(values))
-}
-
-// SampleSum returns the sum of the slice of int64.
-func SampleSum(values []int64) int64 {
- var sum int64
- for _, v := range values {
- sum += v
- }
- return sum
-}
-
-// SampleVariance returns the variance of the slice of int64.
-func SampleVariance(values []int64) float64 {
- if 0 == len(values) {
- return 0.0
- }
- m := SampleMean(values)
- var sum float64
- for _, v := range values {
- d := float64(v) - m
- sum += d * d
- }
- return sum / float64(len(values))
-}
-
-// A uniform sample using Vitter's Algorithm R.
-//
-//
-type UniformSample struct {
- count int64
- mutex sync.Mutex
- reservoirSize int
- values []int64
-}
-
-// NewUniformSample constructs a new uniform sample with the given reservoir
-// size.
-func NewUniformSample(reservoirSize int) Sample {
- if UseNilMetrics {
- return NilSample{}
- }
- return &UniformSample{
- reservoirSize: reservoirSize,
- values: make([]int64, 0, reservoirSize),
- }
-}
-
-// Clear clears all samples.
-func (s *UniformSample) Clear() {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- s.count = 0
- s.values = make([]int64, 0, s.reservoirSize)
-}
-
-// Count returns the number of samples recorded, which may exceed the
-// reservoir size.
-func (s *UniformSample) Count() int64 {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- return s.count
-}
-
-// Max returns the maximum value in the sample, which may not be the maximum
-// value ever to be part of the sample.
-func (s *UniformSample) Max() int64 {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- return SampleMax(s.values)
-}
-
-// Mean returns the mean of the values in the sample.
-func (s *UniformSample) Mean() float64 {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- return SampleMean(s.values)
-}
-
-// Min returns the minimum value in the sample, which may not be the minimum
-// value ever to be part of the sample.
-func (s *UniformSample) Min() int64 {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- return SampleMin(s.values)
-}
-
-// Percentile returns an arbitrary percentile of values in the sample.
-func (s *UniformSample) Percentile(p float64) float64 {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- return SamplePercentile(s.values, p)
-}
-
-// Percentiles returns a slice of arbitrary percentiles of values in the
-// sample.
-func (s *UniformSample) Percentiles(ps []float64) []float64 {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- return SamplePercentiles(s.values, ps)
-}
-
-// Size returns the size of the sample, which is at most the reservoir size.
-func (s *UniformSample) Size() int {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- return len(s.values)
-}
-
-// Snapshot returns a read-only copy of the sample.
-func (s *UniformSample) Snapshot() Sample {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- values := make([]int64, len(s.values))
- copy(values, s.values)
- return &SampleSnapshot{
- count: s.count,
- values: values,
- }
-}
-
-// StdDev returns the standard deviation of the values in the sample.
-func (s *UniformSample) StdDev() float64 {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- return SampleStdDev(s.values)
-}
-
-// Sum returns the sum of the values in the sample.
-func (s *UniformSample) Sum() int64 {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- return SampleSum(s.values)
-}
-
-// Update samples a new value.
-func (s *UniformSample) Update(v int64) {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- s.count++
- if len(s.values) < s.reservoirSize {
- s.values = append(s.values, v)
- } else {
- r := rand.Int63n(s.count)
- if r < int64(len(s.values)) {
- s.values[int(r)] = v
- }
- }
-}
-
-// Values returns a copy of the values in the sample.
-func (s *UniformSample) Values() []int64 {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- values := make([]int64, len(s.values))
- copy(values, s.values)
- return values
-}
-
-// Variance returns the variance of the values in the sample.
-func (s *UniformSample) Variance() float64 {
- s.mutex.Lock()
- defer s.mutex.Unlock()
- return SampleVariance(s.values)
-}
-
-// expDecaySample represents an individual sample in a heap.
-type expDecaySample struct {
- k float64
- v int64
-}
-
-func newExpDecaySampleHeap(reservoirSize int) *expDecaySampleHeap {
- return &expDecaySampleHeap{make([]expDecaySample, 0, reservoirSize)}
-}
-
-// expDecaySampleHeap is a min-heap of expDecaySamples.
-// The internal implementation is copied from the standard library's container/heap
-type expDecaySampleHeap struct {
- s []expDecaySample
-}
-
-func (h *expDecaySampleHeap) Clear() {
- h.s = h.s[:0]
-}
-
-func (h *expDecaySampleHeap) Push(s expDecaySample) {
- n := len(h.s)
- h.s = h.s[0 : n+1]
- h.s[n] = s
- h.up(n)
-}
-
-func (h *expDecaySampleHeap) Pop() expDecaySample {
- n := len(h.s) - 1
- h.s[0], h.s[n] = h.s[n], h.s[0]
- h.down(0, n)
-
- n = len(h.s)
- s := h.s[n-1]
- h.s = h.s[0 : n-1]
- return s
-}
-
-func (h *expDecaySampleHeap) Size() int {
- return len(h.s)
-}
-
-func (h *expDecaySampleHeap) Values() []expDecaySample {
- return h.s
-}
-
-func (h *expDecaySampleHeap) up(j int) {
- for {
- i := (j - 1) / 2 // parent
- if i == j || !(h.s[j].k < h.s[i].k) {
- break
- }
- h.s[i], h.s[j] = h.s[j], h.s[i]
- j = i
- }
-}
-
-func (h *expDecaySampleHeap) down(i, n int) {
- for {
- j1 := 2*i + 1
- if j1 >= n || j1 < 0 { // j1 < 0 after int overflow
- break
- }
- j := j1 // left child
- if j2 := j1 + 1; j2 < n && !(h.s[j1].k < h.s[j2].k) {
- j = j2 // = 2*i + 2 // right child
- }
- if !(h.s[j].k < h.s[i].k) {
- break
- }
- h.s[i], h.s[j] = h.s[j], h.s[i]
- i = j
- }
-}
-
-type int64Slice []int64
-
-func (p int64Slice) Len() int { return len(p) }
-func (p int64Slice) Less(i, j int) bool { return p[i] < p[j] }
-func (p int64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/stathat/stathat.go b/containerd/vendor/github.com/rcrowley/go-metrics/stathat/stathat.go
deleted file mode 100644
index 0afcb48..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/stathat/stathat.go
+++ /dev/null
@@ -1,69 +0,0 @@
-// Metrics output to StatHat.
-package stathat
-
-import (
- "github.com/rcrowley/go-metrics"
- "github.com/stathat/go"
- "log"
- "time"
-)
-
-func Stathat(r metrics.Registry, d time.Duration, userkey string) {
- for {
- if err := sh(r, userkey); nil != err {
- log.Println(err)
- }
- time.Sleep(d)
- }
-}
-
-func sh(r metrics.Registry, userkey string) error {
- r.Each(func(name string, i interface{}) {
- switch metric := i.(type) {
- case metrics.Counter:
- stathat.PostEZCount(name, userkey, int(metric.Count()))
- case metrics.Gauge:
- stathat.PostEZValue(name, userkey, float64(metric.Value()))
- case metrics.GaugeFloat64:
- stathat.PostEZValue(name, userkey, float64(metric.Value()))
- case metrics.Histogram:
- h := metric.Snapshot()
- ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
- stathat.PostEZCount(name+".count", userkey, int(h.Count()))
- stathat.PostEZValue(name+".min", userkey, float64(h.Min()))
- stathat.PostEZValue(name+".max", userkey, float64(h.Max()))
- stathat.PostEZValue(name+".mean", userkey, float64(h.Mean()))
- stathat.PostEZValue(name+".std-dev", userkey, float64(h.StdDev()))
- stathat.PostEZValue(name+".50-percentile", userkey, float64(ps[0]))
- stathat.PostEZValue(name+".75-percentile", userkey, float64(ps[1]))
- stathat.PostEZValue(name+".95-percentile", userkey, float64(ps[2]))
- stathat.PostEZValue(name+".99-percentile", userkey, float64(ps[3]))
- stathat.PostEZValue(name+".999-percentile", userkey, float64(ps[4]))
- case metrics.Meter:
- m := metric.Snapshot()
- stathat.PostEZCount(name+".count", userkey, int(m.Count()))
- stathat.PostEZValue(name+".one-minute", userkey, float64(m.Rate1()))
- stathat.PostEZValue(name+".five-minute", userkey, float64(m.Rate5()))
- stathat.PostEZValue(name+".fifteen-minute", userkey, float64(m.Rate15()))
- stathat.PostEZValue(name+".mean", userkey, float64(m.RateMean()))
- case metrics.Timer:
- t := metric.Snapshot()
- ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
- stathat.PostEZCount(name+".count", userkey, int(t.Count()))
- stathat.PostEZValue(name+".min", userkey, float64(t.Min()))
- stathat.PostEZValue(name+".max", userkey, float64(t.Max()))
- stathat.PostEZValue(name+".mean", userkey, float64(t.Mean()))
- stathat.PostEZValue(name+".std-dev", userkey, float64(t.StdDev()))
- stathat.PostEZValue(name+".50-percentile", userkey, float64(ps[0]))
- stathat.PostEZValue(name+".75-percentile", userkey, float64(ps[1]))
- stathat.PostEZValue(name+".95-percentile", userkey, float64(ps[2]))
- stathat.PostEZValue(name+".99-percentile", userkey, float64(ps[3]))
- stathat.PostEZValue(name+".999-percentile", userkey, float64(ps[4]))
- stathat.PostEZValue(name+".one-minute", userkey, float64(t.Rate1()))
- stathat.PostEZValue(name+".five-minute", userkey, float64(t.Rate5()))
- stathat.PostEZValue(name+".fifteen-minute", userkey, float64(t.Rate15()))
- stathat.PostEZValue(name+".mean-rate", userkey, float64(t.RateMean()))
- }
- })
- return nil
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/syslog.go b/containerd/vendor/github.com/rcrowley/go-metrics/syslog.go
deleted file mode 100644
index 693f190..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/syslog.go
+++ /dev/null
@@ -1,78 +0,0 @@
-// +build !windows
-
-package metrics
-
-import (
- "fmt"
- "log/syslog"
- "time"
-)
-
-// Output each metric in the given registry to syslog periodically using
-// the given syslogger.
-func Syslog(r Registry, d time.Duration, w *syslog.Writer) {
- for _ = range time.Tick(d) {
- r.Each(func(name string, i interface{}) {
- switch metric := i.(type) {
- case Counter:
- w.Info(fmt.Sprintf("counter %s: count: %d", name, metric.Count()))
- case Gauge:
- w.Info(fmt.Sprintf("gauge %s: value: %d", name, metric.Value()))
- case GaugeFloat64:
- w.Info(fmt.Sprintf("gauge %s: value: %f", name, metric.Value()))
- case Healthcheck:
- metric.Check()
- w.Info(fmt.Sprintf("healthcheck %s: error: %v", name, metric.Error()))
- case Histogram:
- h := metric.Snapshot()
- ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
- w.Info(fmt.Sprintf(
- "histogram %s: count: %d min: %d max: %d mean: %.2f stddev: %.2f median: %.2f 75%%: %.2f 95%%: %.2f 99%%: %.2f 99.9%%: %.2f",
- name,
- h.Count(),
- h.Min(),
- h.Max(),
- h.Mean(),
- h.StdDev(),
- ps[0],
- ps[1],
- ps[2],
- ps[3],
- ps[4],
- ))
- case Meter:
- m := metric.Snapshot()
- w.Info(fmt.Sprintf(
- "meter %s: count: %d 1-min: %.2f 5-min: %.2f 15-min: %.2f mean: %.2f",
- name,
- m.Count(),
- m.Rate1(),
- m.Rate5(),
- m.Rate15(),
- m.RateMean(),
- ))
- case Timer:
- t := metric.Snapshot()
- ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
- w.Info(fmt.Sprintf(
- "timer %s: count: %d min: %d max: %d mean: %.2f stddev: %.2f median: %.2f 75%%: %.2f 95%%: %.2f 99%%: %.2f 99.9%%: %.2f 1-min: %.2f 5-min: %.2f 15-min: %.2f mean-rate: %.2f",
- name,
- t.Count(),
- t.Min(),
- t.Max(),
- t.Mean(),
- t.StdDev(),
- ps[0],
- ps[1],
- ps[2],
- ps[3],
- ps[4],
- t.Rate1(),
- t.Rate5(),
- t.Rate15(),
- t.RateMean(),
- ))
- }
- })
- }
-}
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/timer.go b/containerd/vendor/github.com/rcrowley/go-metrics/timer.go
deleted file mode 100644
index 17db8f8..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/timer.go
+++ /dev/null
@@ -1,311 +0,0 @@
-package metrics
-
-import (
- "sync"
- "time"
-)
-
-// Timers capture the duration and rate of events.
-type Timer interface {
- Count() int64
- Max() int64
- Mean() float64
- Min() int64
- Percentile(float64) float64
- Percentiles([]float64) []float64
- Rate1() float64
- Rate5() float64
- Rate15() float64
- RateMean() float64
- Snapshot() Timer
- StdDev() float64
- Sum() int64
- Time(func())
- Update(time.Duration)
- UpdateSince(time.Time)
- Variance() float64
-}
-
-// GetOrRegisterTimer returns an existing Timer or constructs and registers a
-// new StandardTimer.
-func GetOrRegisterTimer(name string, r Registry) Timer {
- if nil == r {
- r = DefaultRegistry
- }
- return r.GetOrRegister(name, NewTimer).(Timer)
-}
-
-// NewCustomTimer constructs a new StandardTimer from a Histogram and a Meter.
-func NewCustomTimer(h Histogram, m Meter) Timer {
- if UseNilMetrics {
- return NilTimer{}
- }
- return &StandardTimer{
- histogram: h,
- meter: m,
- }
-}
-
-// NewRegisteredTimer constructs and registers a new StandardTimer.
-func NewRegisteredTimer(name string, r Registry) Timer {
- c := NewTimer()
- if nil == r {
- r = DefaultRegistry
- }
- r.Register(name, c)
- return c
-}
-
-// NewTimer constructs a new StandardTimer using an exponentially-decaying
-// sample with the same reservoir size and alpha as UNIX load averages.
-func NewTimer() Timer {
- if UseNilMetrics {
- return NilTimer{}
- }
- return &StandardTimer{
- histogram: NewHistogram(NewExpDecaySample(1028, 0.015)),
- meter: NewMeter(),
- }
-}
-
-// NilTimer is a no-op Timer.
-type NilTimer struct {
- h Histogram
- m Meter
-}
-
-// Count is a no-op.
-func (NilTimer) Count() int64 { return 0 }
-
-// Max is a no-op.
-func (NilTimer) Max() int64 { return 0 }
-
-// Mean is a no-op.
-func (NilTimer) Mean() float64 { return 0.0 }
-
-// Min is a no-op.
-func (NilTimer) Min() int64 { return 0 }
-
-// Percentile is a no-op.
-func (NilTimer) Percentile(p float64) float64 { return 0.0 }
-
-// Percentiles is a no-op.
-func (NilTimer) Percentiles(ps []float64) []float64 {
- return make([]float64, len(ps))
-}
-
-// Rate1 is a no-op.
-func (NilTimer) Rate1() float64 { return 0.0 }
-
-// Rate5 is a no-op.
-func (NilTimer) Rate5() float64 { return 0.0 }
-
-// Rate15 is a no-op.
-func (NilTimer) Rate15() float64 { return 0.0 }
-
-// RateMean is a no-op.
-func (NilTimer) RateMean() float64 { return 0.0 }
-
-// Snapshot is a no-op.
-func (NilTimer) Snapshot() Timer { return NilTimer{} }
-
-// StdDev is a no-op.
-func (NilTimer) StdDev() float64 { return 0.0 }
-
-// Sum is a no-op.
-func (NilTimer) Sum() int64 { return 0 }
-
-// Time is a no-op.
-func (NilTimer) Time(func()) {}
-
-// Update is a no-op.
-func (NilTimer) Update(time.Duration) {}
-
-// UpdateSince is a no-op.
-func (NilTimer) UpdateSince(time.Time) {}
-
-// Variance is a no-op.
-func (NilTimer) Variance() float64 { return 0.0 }
-
-// StandardTimer is the standard implementation of a Timer and uses a Histogram
-// and Meter.
-type StandardTimer struct {
- histogram Histogram
- meter Meter
- mutex sync.Mutex
-}
-
-// Count returns the number of events recorded.
-func (t *StandardTimer) Count() int64 {
- return t.histogram.Count()
-}
-
-// Max returns the maximum value in the sample.
-func (t *StandardTimer) Max() int64 {
- return t.histogram.Max()
-}
-
-// Mean returns the mean of the values in the sample.
-func (t *StandardTimer) Mean() float64 {
- return t.histogram.Mean()
-}
-
-// Min returns the minimum value in the sample.
-func (t *StandardTimer) Min() int64 {
- return t.histogram.Min()
-}
-
-// Percentile returns an arbitrary percentile of the values in the sample.
-func (t *StandardTimer) Percentile(p float64) float64 {
- return t.histogram.Percentile(p)
-}
-
-// Percentiles returns a slice of arbitrary percentiles of the values in the
-// sample.
-func (t *StandardTimer) Percentiles(ps []float64) []float64 {
- return t.histogram.Percentiles(ps)
-}
-
-// Rate1 returns the one-minute moving average rate of events per second.
-func (t *StandardTimer) Rate1() float64 {
- return t.meter.Rate1()
-}
-
-// Rate5 returns the five-minute moving average rate of events per second.
-func (t *StandardTimer) Rate5() float64 {
- return t.meter.Rate5()
-}
-
-// Rate15 returns the fifteen-minute moving average rate of events per second.
-func (t *StandardTimer) Rate15() float64 {
- return t.meter.Rate15()
-}
-
-// RateMean returns the meter's mean rate of events per second.
-func (t *StandardTimer) RateMean() float64 {
- return t.meter.RateMean()
-}
-
-// Snapshot returns a read-only copy of the timer.
-func (t *StandardTimer) Snapshot() Timer {
- t.mutex.Lock()
- defer t.mutex.Unlock()
- return &TimerSnapshot{
- histogram: t.histogram.Snapshot().(*HistogramSnapshot),
- meter: t.meter.Snapshot().(*MeterSnapshot),
- }
-}
-
-// StdDev returns the standard deviation of the values in the sample.
-func (t *StandardTimer) StdDev() float64 {
- return t.histogram.StdDev()
-}
-
-// Sum returns the sum in the sample.
-func (t *StandardTimer) Sum() int64 {
- return t.histogram.Sum()
-}
-
-// Record the duration of the execution of the given function.
-func (t *StandardTimer) Time(f func()) {
- ts := time.Now()
- f()
- t.Update(time.Since(ts))
-}
-
-// Record the duration of an event.
-func (t *StandardTimer) Update(d time.Duration) {
- t.mutex.Lock()
- defer t.mutex.Unlock()
- t.histogram.Update(int64(d))
- t.meter.Mark(1)
-}
-
-// Record the duration of an event that started at a time and ends now.
-func (t *StandardTimer) UpdateSince(ts time.Time) {
- t.mutex.Lock()
- defer t.mutex.Unlock()
- t.histogram.Update(int64(time.Since(ts)))
- t.meter.Mark(1)
-}
-
-// Variance returns the variance of the values in the sample.
-func (t *StandardTimer) Variance() float64 {
- return t.histogram.Variance()
-}
-
-// TimerSnapshot is a read-only copy of another Timer.
-type TimerSnapshot struct {
- histogram *HistogramSnapshot
- meter *MeterSnapshot
-}
-
-// Count returns the number of events recorded at the time the snapshot was
-// taken.
-func (t *TimerSnapshot) Count() int64 { return t.histogram.Count() }
-
-// Max returns the maximum value at the time the snapshot was taken.
-func (t *TimerSnapshot) Max() int64 { return t.histogram.Max() }
-
-// Mean returns the mean value at the time the snapshot was taken.
-func (t *TimerSnapshot) Mean() float64 { return t.histogram.Mean() }
-
-// Min returns the minimum value at the time the snapshot was taken.
-func (t *TimerSnapshot) Min() int64 { return t.histogram.Min() }
-
-// Percentile returns an arbitrary percentile of sampled values at the time the
-// snapshot was taken.
-func (t *TimerSnapshot) Percentile(p float64) float64 {
- return t.histogram.Percentile(p)
-}
-
-// Percentiles returns a slice of arbitrary percentiles of sampled values at
-// the time the snapshot was taken.
-func (t *TimerSnapshot) Percentiles(ps []float64) []float64 {
- return t.histogram.Percentiles(ps)
-}
-
-// Rate1 returns the one-minute moving average rate of events per second at the
-// time the snapshot was taken.
-func (t *TimerSnapshot) Rate1() float64 { return t.meter.Rate1() }
-
-// Rate5 returns the five-minute moving average rate of events per second at
-// the time the snapshot was taken.
-func (t *TimerSnapshot) Rate5() float64 { return t.meter.Rate5() }
-
-// Rate15 returns the fifteen-minute moving average rate of events per second
-// at the time the snapshot was taken.
-func (t *TimerSnapshot) Rate15() float64 { return t.meter.Rate15() }
-
-// RateMean returns the meter's mean rate of events per second at the time the
-// snapshot was taken.
-func (t *TimerSnapshot) RateMean() float64 { return t.meter.RateMean() }
-
-// Snapshot returns the snapshot.
-func (t *TimerSnapshot) Snapshot() Timer { return t }
-
-// StdDev returns the standard deviation of the values at the time the snapshot
-// was taken.
-func (t *TimerSnapshot) StdDev() float64 { return t.histogram.StdDev() }
-
-// Sum returns the sum at the time the snapshot was taken.
-func (t *TimerSnapshot) Sum() int64 { return t.histogram.Sum() }
-
-// Time panics.
-func (*TimerSnapshot) Time(func()) {
- panic("Time called on a TimerSnapshot")
-}
-
-// Update panics.
-func (*TimerSnapshot) Update(time.Duration) {
- panic("Update called on a TimerSnapshot")
-}
-
-// UpdateSince panics.
-func (*TimerSnapshot) UpdateSince(time.Time) {
- panic("UpdateSince called on a TimerSnapshot")
-}
-
-// Variance returns the variance of the values at the time the snapshot was
-// taken.
-func (t *TimerSnapshot) Variance() float64 { return t.histogram.Variance() }
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/validate.sh b/containerd/vendor/github.com/rcrowley/go-metrics/validate.sh
deleted file mode 100644
index f649998..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/validate.sh
+++ /dev/null
@@ -1,10 +0,0 @@
-#!/bin/bash
-
-set -e
-
-# check there are no formatting issues
-GOFMT_LINES=`gofmt -l . | wc -l | xargs`
-test $GOFMT_LINES -eq 0 || echo "gofmt needs to be run, ${GOFMT_LINES} files have issues"
-
-# run the tests for the root package
-go test .
diff --git a/containerd/vendor/github.com/rcrowley/go-metrics/writer.go b/containerd/vendor/github.com/rcrowley/go-metrics/writer.go
deleted file mode 100644
index 091e971..0000000
--- a/containerd/vendor/github.com/rcrowley/go-metrics/writer.go
+++ /dev/null
@@ -1,100 +0,0 @@
-package metrics
-
-import (
- "fmt"
- "io"
- "sort"
- "time"
-)
-
-// Write sorts writes each metric in the given registry periodically to the
-// given io.Writer.
-func Write(r Registry, d time.Duration, w io.Writer) {
- for _ = range time.Tick(d) {
- WriteOnce(r, w)
- }
-}
-
-// WriteOnce sorts and writes metrics in the given registry to the given
-// io.Writer.
-func WriteOnce(r Registry, w io.Writer) {
- var namedMetrics namedMetricSlice
- r.Each(func(name string, i interface{}) {
- namedMetrics = append(namedMetrics, namedMetric{name, i})
- })
-
- sort.Sort(namedMetrics)
- for _, namedMetric := range namedMetrics {
- switch metric := namedMetric.m.(type) {
- case Counter:
- fmt.Fprintf(w, "counter %s\n", namedMetric.name)
- fmt.Fprintf(w, " count: %9d\n", metric.Count())
- case Gauge:
- fmt.Fprintf(w, "gauge %s\n", namedMetric.name)
- fmt.Fprintf(w, " value: %9d\n", metric.Value())
- case GaugeFloat64:
- fmt.Fprintf(w, "gauge %s\n", namedMetric.name)
- fmt.Fprintf(w, " value: %f\n", metric.Value())
- case Healthcheck:
- metric.Check()
- fmt.Fprintf(w, "healthcheck %s\n", namedMetric.name)
- fmt.Fprintf(w, " error: %v\n", metric.Error())
- case Histogram:
- h := metric.Snapshot()
- ps := h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
- fmt.Fprintf(w, "histogram %s\n", namedMetric.name)
- fmt.Fprintf(w, " count: %9d\n", h.Count())
- fmt.Fprintf(w, " min: %9d\n", h.Min())
- fmt.Fprintf(w, " max: %9d\n", h.Max())
- fmt.Fprintf(w, " mean: %12.2f\n", h.Mean())
- fmt.Fprintf(w, " stddev: %12.2f\n", h.StdDev())
- fmt.Fprintf(w, " median: %12.2f\n", ps[0])
- fmt.Fprintf(w, " 75%%: %12.2f\n", ps[1])
- fmt.Fprintf(w, " 95%%: %12.2f\n", ps[2])
- fmt.Fprintf(w, " 99%%: %12.2f\n", ps[3])
- fmt.Fprintf(w, " 99.9%%: %12.2f\n", ps[4])
- case Meter:
- m := metric.Snapshot()
- fmt.Fprintf(w, "meter %s\n", namedMetric.name)
- fmt.Fprintf(w, " count: %9d\n", m.Count())
- fmt.Fprintf(w, " 1-min rate: %12.2f\n", m.Rate1())
- fmt.Fprintf(w, " 5-min rate: %12.2f\n", m.Rate5())
- fmt.Fprintf(w, " 15-min rate: %12.2f\n", m.Rate15())
- fmt.Fprintf(w, " mean rate: %12.2f\n", m.RateMean())
- case Timer:
- t := metric.Snapshot()
- ps := t.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
- fmt.Fprintf(w, "timer %s\n", namedMetric.name)
- fmt.Fprintf(w, " count: %9d\n", t.Count())
- fmt.Fprintf(w, " min: %9d\n", t.Min())
- fmt.Fprintf(w, " max: %9d\n", t.Max())
- fmt.Fprintf(w, " mean: %12.2f\n", t.Mean())
- fmt.Fprintf(w, " stddev: %12.2f\n", t.StdDev())
- fmt.Fprintf(w, " median: %12.2f\n", ps[0])
- fmt.Fprintf(w, " 75%%: %12.2f\n", ps[1])
- fmt.Fprintf(w, " 95%%: %12.2f\n", ps[2])
- fmt.Fprintf(w, " 99%%: %12.2f\n", ps[3])
- fmt.Fprintf(w, " 99.9%%: %12.2f\n", ps[4])
- fmt.Fprintf(w, " 1-min rate: %12.2f\n", t.Rate1())
- fmt.Fprintf(w, " 5-min rate: %12.2f\n", t.Rate5())
- fmt.Fprintf(w, " 15-min rate: %12.2f\n", t.Rate15())
- fmt.Fprintf(w, " mean rate: %12.2f\n", t.RateMean())
- }
- }
-}
-
-type namedMetric struct {
- name string
- m interface{}
-}
-
-// namedMetricSlice is a slice of namedMetrics that implements sort.Interface.
-type namedMetricSlice []namedMetric
-
-func (nms namedMetricSlice) Len() int { return len(nms) }
-
-func (nms namedMetricSlice) Swap(i, j int) { nms[i], nms[j] = nms[j], nms[i] }
-
-func (nms namedMetricSlice) Less(i, j int) bool {
- return nms[i].name < nms[j].name
-}
diff --git a/containerd/vendor/github.com/syndtr/gocapability/capability/capability.go b/containerd/vendor/github.com/syndtr/gocapability/capability/capability.go
deleted file mode 100644
index c13f4e5..0000000
--- a/containerd/vendor/github.com/syndtr/gocapability/capability/capability.go
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright (c) 2013, Suryandaru Triandana
-// All rights reserved.
-//
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// Package capability provides utilities for manipulating POSIX capabilities.
-package capability
-
-type Capabilities interface {
- // Get check whether a capability present in the given
- // capabilities set. The 'which' value should be one of EFFECTIVE,
- // PERMITTED, INHERITABLE or BOUNDING.
- Get(which CapType, what Cap) bool
-
- // Empty check whether all capability bits of the given capabilities
- // set are zero. The 'which' value should be one of EFFECTIVE,
- // PERMITTED, INHERITABLE or BOUNDING.
- Empty(which CapType) bool
-
- // Full check whether all capability bits of the given capabilities
- // set are one. The 'which' value should be one of EFFECTIVE,
- // PERMITTED, INHERITABLE or BOUNDING.
- Full(which CapType) bool
-
- // Set sets capabilities of the given capabilities sets. The
- // 'which' value should be one or combination (OR'ed) of EFFECTIVE,
- // PERMITTED, INHERITABLE or BOUNDING.
- Set(which CapType, caps ...Cap)
-
- // Unset unsets capabilities of the given capabilities sets. The
- // 'which' value should be one or combination (OR'ed) of EFFECTIVE,
- // PERMITTED, INHERITABLE or BOUNDING.
- Unset(which CapType, caps ...Cap)
-
- // Fill sets all bits of the given capabilities kind to one. The
- // 'kind' value should be one or combination (OR'ed) of CAPS or
- // BOUNDS.
- Fill(kind CapType)
-
- // Clear sets all bits of the given capabilities kind to zero. The
- // 'kind' value should be one or combination (OR'ed) of CAPS or
- // BOUNDS.
- Clear(kind CapType)
-
- // String return current capabilities state of the given capabilities
- // set as string. The 'which' value should be one of EFFECTIVE,
- // PERMITTED, INHERITABLE or BOUNDING.
- StringCap(which CapType) string
-
- // String return current capabilities state as string.
- String() string
-
- // Load load actual capabilities value. This will overwrite all
- // outstanding changes.
- Load() error
-
- // Apply apply the capabilities settings, so all changes will take
- // effect.
- Apply(kind CapType) error
-}
-
-// NewPid create new initialized Capabilities object for given pid when it
-// is nonzero, or for the current pid if pid is 0
-func NewPid(pid int) (Capabilities, error) {
- return newPid(pid)
-}
-
-// NewFile create new initialized Capabilities object for given named file.
-func NewFile(name string) (Capabilities, error) {
- return newFile(name)
-}
diff --git a/containerd/vendor/github.com/syndtr/gocapability/capability/capability_linux.go b/containerd/vendor/github.com/syndtr/gocapability/capability/capability_linux.go
deleted file mode 100644
index 3dfcd39..0000000
--- a/containerd/vendor/github.com/syndtr/gocapability/capability/capability_linux.go
+++ /dev/null
@@ -1,608 +0,0 @@
-// Copyright (c) 2013, Suryandaru Triandana
-// All rights reserved.
-//
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-package capability
-
-import (
- "bufio"
- "errors"
- "fmt"
- "io"
- "os"
- "strings"
- "syscall"
-)
-
-var errUnknownVers = errors.New("unknown capability version")
-
-const (
- linuxCapVer1 = 0x19980330
- linuxCapVer2 = 0x20071026
- linuxCapVer3 = 0x20080522
-)
-
-var (
- capVers uint32
- capLastCap Cap
-)
-
-func init() {
- var hdr capHeader
- capget(&hdr, nil)
- capVers = hdr.version
-
- if initLastCap() == nil {
- CAP_LAST_CAP = capLastCap
- if capLastCap > 31 {
- capUpperMask = (uint32(1) << (uint(capLastCap) - 31)) - 1
- } else {
- capUpperMask = 0
- }
- }
-}
-
-func initLastCap() error {
- if capLastCap != 0 {
- return nil
- }
-
- f, err := os.Open("/proc/sys/kernel/cap_last_cap")
- if err != nil {
- return err
- }
- defer f.Close()
-
- var b []byte = make([]byte, 11)
- _, err = f.Read(b)
- if err != nil {
- return err
- }
-
- fmt.Sscanf(string(b), "%d", &capLastCap)
-
- return nil
-}
-
-func mkStringCap(c Capabilities, which CapType) (ret string) {
- for i, first := Cap(0), true; i <= CAP_LAST_CAP; i++ {
- if !c.Get(which, i) {
- continue
- }
- if first {
- first = false
- } else {
- ret += ", "
- }
- ret += i.String()
- }
- return
-}
-
-func mkString(c Capabilities, max CapType) (ret string) {
- ret = "{"
- for i := CapType(1); i <= max; i <<= 1 {
- ret += " " + i.String() + "=\""
- if c.Empty(i) {
- ret += "empty"
- } else if c.Full(i) {
- ret += "full"
- } else {
- ret += c.StringCap(i)
- }
- ret += "\""
- }
- ret += " }"
- return
-}
-
-func newPid(pid int) (c Capabilities, err error) {
- switch capVers {
- case linuxCapVer1:
- p := new(capsV1)
- p.hdr.version = capVers
- p.hdr.pid = pid
- c = p
- case linuxCapVer2, linuxCapVer3:
- p := new(capsV3)
- p.hdr.version = capVers
- p.hdr.pid = pid
- c = p
- default:
- err = errUnknownVers
- return
- }
- err = c.Load()
- if err != nil {
- c = nil
- }
- return
-}
-
-type capsV1 struct {
- hdr capHeader
- data capData
-}
-
-func (c *capsV1) Get(which CapType, what Cap) bool {
- if what > 32 {
- return false
- }
-
- switch which {
- case EFFECTIVE:
- return (1< 32 {
- continue
- }
-
- if which&EFFECTIVE != 0 {
- c.data.effective |= 1 << uint(what)
- }
- if which&PERMITTED != 0 {
- c.data.permitted |= 1 << uint(what)
- }
- if which&INHERITABLE != 0 {
- c.data.inheritable |= 1 << uint(what)
- }
- }
-}
-
-func (c *capsV1) Unset(which CapType, caps ...Cap) {
- for _, what := range caps {
- if what > 32 {
- continue
- }
-
- if which&EFFECTIVE != 0 {
- c.data.effective &= ^(1 << uint(what))
- }
- if which&PERMITTED != 0 {
- c.data.permitted &= ^(1 << uint(what))
- }
- if which&INHERITABLE != 0 {
- c.data.inheritable &= ^(1 << uint(what))
- }
- }
-}
-
-func (c *capsV1) Fill(kind CapType) {
- if kind&CAPS == CAPS {
- c.data.effective = 0x7fffffff
- c.data.permitted = 0x7fffffff
- c.data.inheritable = 0
- }
-}
-
-func (c *capsV1) Clear(kind CapType) {
- if kind&CAPS == CAPS {
- c.data.effective = 0
- c.data.permitted = 0
- c.data.inheritable = 0
- }
-}
-
-func (c *capsV1) StringCap(which CapType) (ret string) {
- return mkStringCap(c, which)
-}
-
-func (c *capsV1) String() (ret string) {
- return mkString(c, BOUNDING)
-}
-
-func (c *capsV1) Load() (err error) {
- return capget(&c.hdr, &c.data)
-}
-
-func (c *capsV1) Apply(kind CapType) error {
- if kind&CAPS == CAPS {
- return capset(&c.hdr, &c.data)
- }
- return nil
-}
-
-type capsV3 struct {
- hdr capHeader
- data [2]capData
- bounds [2]uint32
-}
-
-func (c *capsV3) Get(which CapType, what Cap) bool {
- var i uint
- if what > 31 {
- i = uint(what) >> 5
- what %= 32
- }
-
- switch which {
- case EFFECTIVE:
- return (1< 31 {
- i = uint(what) >> 5
- what %= 32
- }
-
- if which&EFFECTIVE != 0 {
- c.data[i].effective |= 1 << uint(what)
- }
- if which&PERMITTED != 0 {
- c.data[i].permitted |= 1 << uint(what)
- }
- if which&INHERITABLE != 0 {
- c.data[i].inheritable |= 1 << uint(what)
- }
- if which&BOUNDING != 0 {
- c.bounds[i] |= 1 << uint(what)
- }
- }
-}
-
-func (c *capsV3) Unset(which CapType, caps ...Cap) {
- for _, what := range caps {
- var i uint
- if what > 31 {
- i = uint(what) >> 5
- what %= 32
- }
-
- if which&EFFECTIVE != 0 {
- c.data[i].effective &= ^(1 << uint(what))
- }
- if which&PERMITTED != 0 {
- c.data[i].permitted &= ^(1 << uint(what))
- }
- if which&INHERITABLE != 0 {
- c.data[i].inheritable &= ^(1 << uint(what))
- }
- if which&BOUNDING != 0 {
- c.bounds[i] &= ^(1 << uint(what))
- }
- }
-}
-
-func (c *capsV3) Fill(kind CapType) {
- if kind&CAPS == CAPS {
- c.data[0].effective = 0xffffffff
- c.data[0].permitted = 0xffffffff
- c.data[0].inheritable = 0
- c.data[1].effective = 0xffffffff
- c.data[1].permitted = 0xffffffff
- c.data[1].inheritable = 0
- }
-
- if kind&BOUNDS == BOUNDS {
- c.bounds[0] = 0xffffffff
- c.bounds[1] = 0xffffffff
- }
-}
-
-func (c *capsV3) Clear(kind CapType) {
- if kind&CAPS == CAPS {
- c.data[0].effective = 0
- c.data[0].permitted = 0
- c.data[0].inheritable = 0
- c.data[1].effective = 0
- c.data[1].permitted = 0
- c.data[1].inheritable = 0
- }
-
- if kind&BOUNDS == BOUNDS {
- c.bounds[0] = 0
- c.bounds[1] = 0
- }
-}
-
-func (c *capsV3) StringCap(which CapType) (ret string) {
- return mkStringCap(c, which)
-}
-
-func (c *capsV3) String() (ret string) {
- return mkString(c, BOUNDING)
-}
-
-func (c *capsV3) Load() (err error) {
- err = capget(&c.hdr, &c.data[0])
- if err != nil {
- return
- }
-
- var status_path string
-
- if c.hdr.pid == 0 {
- status_path = fmt.Sprintf("/proc/self/status")
- } else {
- status_path = fmt.Sprintf("/proc/%d/status", c.hdr.pid)
- }
-
- f, err := os.Open(status_path)
- if err != nil {
- return
- }
- b := bufio.NewReader(f)
- for {
- line, e := b.ReadString('\n')
- if e != nil {
- if e != io.EOF {
- err = e
- }
- break
- }
- if strings.HasPrefix(line, "CapB") {
- fmt.Sscanf(line[4:], "nd: %08x%08x", &c.bounds[1], &c.bounds[0])
- break
- }
- }
- f.Close()
-
- return
-}
-
-func (c *capsV3) Apply(kind CapType) (err error) {
- if kind&BOUNDS == BOUNDS {
- var data [2]capData
- err = capget(&c.hdr, &data[0])
- if err != nil {
- return
- }
- if (1< 31 {
- if c.data.version == 1 {
- return false
- }
- i = uint(what) >> 5
- what %= 32
- }
-
- switch which {
- case EFFECTIVE:
- return (1< 31 {
- if c.data.version == 1 {
- continue
- }
- i = uint(what) >> 5
- what %= 32
- }
-
- if which&EFFECTIVE != 0 {
- c.data.effective[i] |= 1 << uint(what)
- }
- if which&PERMITTED != 0 {
- c.data.data[i].permitted |= 1 << uint(what)
- }
- if which&INHERITABLE != 0 {
- c.data.data[i].inheritable |= 1 << uint(what)
- }
- }
-}
-
-func (c *capsFile) Unset(which CapType, caps ...Cap) {
- for _, what := range caps {
- var i uint
- if what > 31 {
- if c.data.version == 1 {
- continue
- }
- i = uint(what) >> 5
- what %= 32
- }
-
- if which&EFFECTIVE != 0 {
- c.data.effective[i] &= ^(1 << uint(what))
- }
- if which&PERMITTED != 0 {
- c.data.data[i].permitted &= ^(1 << uint(what))
- }
- if which&INHERITABLE != 0 {
- c.data.data[i].inheritable &= ^(1 << uint(what))
- }
- }
-}
-
-func (c *capsFile) Fill(kind CapType) {
- if kind&CAPS == CAPS {
- c.data.effective[0] = 0xffffffff
- c.data.data[0].permitted = 0xffffffff
- c.data.data[0].inheritable = 0
- if c.data.version == 2 {
- c.data.effective[1] = 0xffffffff
- c.data.data[1].permitted = 0xffffffff
- c.data.data[1].inheritable = 0
- }
- }
-}
-
-func (c *capsFile) Clear(kind CapType) {
- if kind&CAPS == CAPS {
- c.data.effective[0] = 0
- c.data.data[0].permitted = 0
- c.data.data[0].inheritable = 0
- if c.data.version == 2 {
- c.data.effective[1] = 0
- c.data.data[1].permitted = 0
- c.data.data[1].inheritable = 0
- }
- }
-}
-
-func (c *capsFile) StringCap(which CapType) (ret string) {
- return mkStringCap(c, which)
-}
-
-func (c *capsFile) String() (ret string) {
- return mkString(c, INHERITABLE)
-}
-
-func (c *capsFile) Load() (err error) {
- return getVfsCap(c.path, &c.data)
-}
-
-func (c *capsFile) Apply(kind CapType) (err error) {
- if kind&CAPS == CAPS {
- return setVfsCap(c.path, &c.data)
- }
- return
-}
diff --git a/containerd/vendor/github.com/syndtr/gocapability/capability/capability_noop.go b/containerd/vendor/github.com/syndtr/gocapability/capability/capability_noop.go
deleted file mode 100644
index 9bb3070..0000000
--- a/containerd/vendor/github.com/syndtr/gocapability/capability/capability_noop.go
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright (c) 2013, Suryandaru Triandana
-// All rights reserved.
-//
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// +build !linux
-
-package capability
-
-import "errors"
-
-func newPid(pid int) (Capabilities, error) {
- return nil, errors.New("not supported")
-}
-
-func newFile(path string) (Capabilities, error) {
- return nil, errors.New("not supported")
-}
diff --git a/containerd/vendor/github.com/syndtr/gocapability/capability/enum.go b/containerd/vendor/github.com/syndtr/gocapability/capability/enum.go
deleted file mode 100644
index fd0ce7f..0000000
--- a/containerd/vendor/github.com/syndtr/gocapability/capability/enum.go
+++ /dev/null
@@ -1,264 +0,0 @@
-// Copyright (c) 2013, Suryandaru Triandana
-// All rights reserved.
-//
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-package capability
-
-type CapType uint
-
-func (c CapType) String() string {
- switch c {
- case EFFECTIVE:
- return "effective"
- case PERMITTED:
- return "permitted"
- case INHERITABLE:
- return "inheritable"
- case BOUNDING:
- return "bounding"
- case CAPS:
- return "caps"
- }
- return "unknown"
-}
-
-const (
- EFFECTIVE CapType = 1 << iota
- PERMITTED
- INHERITABLE
- BOUNDING
-
- CAPS = EFFECTIVE | PERMITTED | INHERITABLE
- BOUNDS = BOUNDING
-)
-
-//go:generate go run enumgen/gen.go
-type Cap int
-
-// POSIX-draft defined capabilities.
-const (
- // In a system with the [_POSIX_CHOWN_RESTRICTED] option defined, this
- // overrides the restriction of changing file ownership and group
- // ownership.
- CAP_CHOWN = Cap(0)
-
- // Override all DAC access, including ACL execute access if
- // [_POSIX_ACL] is defined. Excluding DAC access covered by
- // CAP_LINUX_IMMUTABLE.
- CAP_DAC_OVERRIDE = Cap(1)
-
- // Overrides all DAC restrictions regarding read and search on files
- // and directories, including ACL restrictions if [_POSIX_ACL] is
- // defined. Excluding DAC access covered by CAP_LINUX_IMMUTABLE.
- CAP_DAC_READ_SEARCH = Cap(2)
-
- // Overrides all restrictions about allowed operations on files, where
- // file owner ID must be equal to the user ID, except where CAP_FSETID
- // is applicable. It doesn't override MAC and DAC restrictions.
- CAP_FOWNER = Cap(3)
-
- // Overrides the following restrictions that the effective user ID
- // shall match the file owner ID when setting the S_ISUID and S_ISGID
- // bits on that file; that the effective group ID (or one of the
- // supplementary group IDs) shall match the file owner ID when setting
- // the S_ISGID bit on that file; that the S_ISUID and S_ISGID bits are
- // cleared on successful return from chown(2) (not implemented).
- CAP_FSETID = Cap(4)
-
- // Overrides the restriction that the real or effective user ID of a
- // process sending a signal must match the real or effective user ID
- // of the process receiving the signal.
- CAP_KILL = Cap(5)
-
- // Allows setgid(2) manipulation
- // Allows setgroups(2)
- // Allows forged gids on socket credentials passing.
- CAP_SETGID = Cap(6)
-
- // Allows set*uid(2) manipulation (including fsuid).
- // Allows forged pids on socket credentials passing.
- CAP_SETUID = Cap(7)
-
- // Linux-specific capabilities
-
- // Without VFS support for capabilities:
- // Transfer any capability in your permitted set to any pid,
- // remove any capability in your permitted set from any pid
- // With VFS support for capabilities (neither of above, but)
- // Add any capability from current's capability bounding set
- // to the current process' inheritable set
- // Allow taking bits out of capability bounding set
- // Allow modification of the securebits for a process
- CAP_SETPCAP = Cap(8)
-
- // Allow modification of S_IMMUTABLE and S_APPEND file attributes
- CAP_LINUX_IMMUTABLE = Cap(9)
-
- // Allows binding to TCP/UDP sockets below 1024
- // Allows binding to ATM VCIs below 32
- CAP_NET_BIND_SERVICE = Cap(10)
-
- // Allow broadcasting, listen to multicast
- CAP_NET_BROADCAST = Cap(11)
-
- // Allow interface configuration
- // Allow administration of IP firewall, masquerading and accounting
- // Allow setting debug option on sockets
- // Allow modification of routing tables
- // Allow setting arbitrary process / process group ownership on
- // sockets
- // Allow binding to any address for transparent proxying (also via NET_RAW)
- // Allow setting TOS (type of service)
- // Allow setting promiscuous mode
- // Allow clearing driver statistics
- // Allow multicasting
- // Allow read/write of device-specific registers
- // Allow activation of ATM control sockets
- CAP_NET_ADMIN = Cap(12)
-
- // Allow use of RAW sockets
- // Allow use of PACKET sockets
- // Allow binding to any address for transparent proxying (also via NET_ADMIN)
- CAP_NET_RAW = Cap(13)
-
- // Allow locking of shared memory segments
- // Allow mlock and mlockall (which doesn't really have anything to do
- // with IPC)
- CAP_IPC_LOCK = Cap(14)
-
- // Override IPC ownership checks
- CAP_IPC_OWNER = Cap(15)
-
- // Insert and remove kernel modules - modify kernel without limit
- CAP_SYS_MODULE = Cap(16)
-
- // Allow ioperm/iopl access
- // Allow sending USB messages to any device via /proc/bus/usb
- CAP_SYS_RAWIO = Cap(17)
-
- // Allow use of chroot()
- CAP_SYS_CHROOT = Cap(18)
-
- // Allow ptrace() of any process
- CAP_SYS_PTRACE = Cap(19)
-
- // Allow configuration of process accounting
- CAP_SYS_PACCT = Cap(20)
-
- // Allow configuration of the secure attention key
- // Allow administration of the random device
- // Allow examination and configuration of disk quotas
- // Allow setting the domainname
- // Allow setting the hostname
- // Allow calling bdflush()
- // Allow mount() and umount(), setting up new smb connection
- // Allow some autofs root ioctls
- // Allow nfsservctl
- // Allow VM86_REQUEST_IRQ
- // Allow to read/write pci config on alpha
- // Allow irix_prctl on mips (setstacksize)
- // Allow flushing all cache on m68k (sys_cacheflush)
- // Allow removing semaphores
- // Used instead of CAP_CHOWN to "chown" IPC message queues, semaphores
- // and shared memory
- // Allow locking/unlocking of shared memory segment
- // Allow turning swap on/off
- // Allow forged pids on socket credentials passing
- // Allow setting readahead and flushing buffers on block devices
- // Allow setting geometry in floppy driver
- // Allow turning DMA on/off in xd driver
- // Allow administration of md devices (mostly the above, but some
- // extra ioctls)
- // Allow tuning the ide driver
- // Allow access to the nvram device
- // Allow administration of apm_bios, serial and bttv (TV) device
- // Allow manufacturer commands in isdn CAPI support driver
- // Allow reading non-standardized portions of pci configuration space
- // Allow DDI debug ioctl on sbpcd driver
- // Allow setting up serial ports
- // Allow sending raw qic-117 commands
- // Allow enabling/disabling tagged queuing on SCSI controllers and sending
- // arbitrary SCSI commands
- // Allow setting encryption key on loopback filesystem
- // Allow setting zone reclaim policy
- CAP_SYS_ADMIN = Cap(21)
-
- // Allow use of reboot()
- CAP_SYS_BOOT = Cap(22)
-
- // Allow raising priority and setting priority on other (different
- // UID) processes
- // Allow use of FIFO and round-robin (realtime) scheduling on own
- // processes and setting the scheduling algorithm used by another
- // process.
- // Allow setting cpu affinity on other processes
- CAP_SYS_NICE = Cap(23)
-
- // Override resource limits. Set resource limits.
- // Override quota limits.
- // Override reserved space on ext2 filesystem
- // Modify data journaling mode on ext3 filesystem (uses journaling
- // resources)
- // NOTE: ext2 honors fsuid when checking for resource overrides, so
- // you can override using fsuid too
- // Override size restrictions on IPC message queues
- // Allow more than 64hz interrupts from the real-time clock
- // Override max number of consoles on console allocation
- // Override max number of keymaps
- CAP_SYS_RESOURCE = Cap(24)
-
- // Allow manipulation of system clock
- // Allow irix_stime on mips
- // Allow setting the real-time clock
- CAP_SYS_TIME = Cap(25)
-
- // Allow configuration of tty devices
- // Allow vhangup() of tty
- CAP_SYS_TTY_CONFIG = Cap(26)
-
- // Allow the privileged aspects of mknod()
- CAP_MKNOD = Cap(27)
-
- // Allow taking of leases on files
- CAP_LEASE = Cap(28)
-
- CAP_AUDIT_WRITE = Cap(29)
- CAP_AUDIT_CONTROL = Cap(30)
- CAP_SETFCAP = Cap(31)
-
- // Override MAC access.
- // The base kernel enforces no MAC policy.
- // An LSM may enforce a MAC policy, and if it does and it chooses
- // to implement capability based overrides of that policy, this is
- // the capability it should use to do so.
- CAP_MAC_OVERRIDE = Cap(32)
-
- // Allow MAC configuration or state changes.
- // The base kernel requires no MAC configuration.
- // An LSM may enforce a MAC policy, and if it does and it chooses
- // to implement capability based checks on modifications to that
- // policy or the data required to maintain it, this is the
- // capability it should use to do so.
- CAP_MAC_ADMIN = Cap(33)
-
- // Allow configuring the kernel's syslog (printk behaviour)
- CAP_SYSLOG = Cap(34)
-
- // Allow triggering something that will wake the system
- CAP_WAKE_ALARM = Cap(35)
-
- // Allow preventing system suspends
- CAP_BLOCK_SUSPEND = Cap(36)
-
- // Allow reading audit messages from the kernel
- CAP_AUDIT_READ = Cap(37)
-)
-
-var (
- // Highest valid capability of the running kernel.
- CAP_LAST_CAP = Cap(63)
-
- capUpperMask = ^uint32(0)
-)
diff --git a/containerd/vendor/github.com/syndtr/gocapability/capability/enum_gen.go b/containerd/vendor/github.com/syndtr/gocapability/capability/enum_gen.go
deleted file mode 100644
index b9e6d2d..0000000
--- a/containerd/vendor/github.com/syndtr/gocapability/capability/enum_gen.go
+++ /dev/null
@@ -1,129 +0,0 @@
-// generated file; DO NOT EDIT - use go generate in directory with source
-
-package capability
-
-func (c Cap) String() string {
- switch c {
- case CAP_CHOWN:
- return "chown"
- case CAP_DAC_OVERRIDE:
- return "dac_override"
- case CAP_DAC_READ_SEARCH:
- return "dac_read_search"
- case CAP_FOWNER:
- return "fowner"
- case CAP_FSETID:
- return "fsetid"
- case CAP_KILL:
- return "kill"
- case CAP_SETGID:
- return "setgid"
- case CAP_SETUID:
- return "setuid"
- case CAP_SETPCAP:
- return "setpcap"
- case CAP_LINUX_IMMUTABLE:
- return "linux_immutable"
- case CAP_NET_BIND_SERVICE:
- return "net_bind_service"
- case CAP_NET_BROADCAST:
- return "net_broadcast"
- case CAP_NET_ADMIN:
- return "net_admin"
- case CAP_NET_RAW:
- return "net_raw"
- case CAP_IPC_LOCK:
- return "ipc_lock"
- case CAP_IPC_OWNER:
- return "ipc_owner"
- case CAP_SYS_MODULE:
- return "sys_module"
- case CAP_SYS_RAWIO:
- return "sys_rawio"
- case CAP_SYS_CHROOT:
- return "sys_chroot"
- case CAP_SYS_PTRACE:
- return "sys_ptrace"
- case CAP_SYS_PACCT:
- return "sys_pacct"
- case CAP_SYS_ADMIN:
- return "sys_admin"
- case CAP_SYS_BOOT:
- return "sys_boot"
- case CAP_SYS_NICE:
- return "sys_nice"
- case CAP_SYS_RESOURCE:
- return "sys_resource"
- case CAP_SYS_TIME:
- return "sys_time"
- case CAP_SYS_TTY_CONFIG:
- return "sys_tty_config"
- case CAP_MKNOD:
- return "mknod"
- case CAP_LEASE:
- return "lease"
- case CAP_AUDIT_WRITE:
- return "audit_write"
- case CAP_AUDIT_CONTROL:
- return "audit_control"
- case CAP_SETFCAP:
- return "setfcap"
- case CAP_MAC_OVERRIDE:
- return "mac_override"
- case CAP_MAC_ADMIN:
- return "mac_admin"
- case CAP_SYSLOG:
- return "syslog"
- case CAP_WAKE_ALARM:
- return "wake_alarm"
- case CAP_BLOCK_SUSPEND:
- return "block_suspend"
- case CAP_AUDIT_READ:
- return "audit_read"
- }
- return "unknown"
-}
-
-// List returns list of all supported capabilities
-func List() []Cap {
- return []Cap{
- CAP_CHOWN,
- CAP_DAC_OVERRIDE,
- CAP_DAC_READ_SEARCH,
- CAP_FOWNER,
- CAP_FSETID,
- CAP_KILL,
- CAP_SETGID,
- CAP_SETUID,
- CAP_SETPCAP,
- CAP_LINUX_IMMUTABLE,
- CAP_NET_BIND_SERVICE,
- CAP_NET_BROADCAST,
- CAP_NET_ADMIN,
- CAP_NET_RAW,
- CAP_IPC_LOCK,
- CAP_IPC_OWNER,
- CAP_SYS_MODULE,
- CAP_SYS_RAWIO,
- CAP_SYS_CHROOT,
- CAP_SYS_PTRACE,
- CAP_SYS_PACCT,
- CAP_SYS_ADMIN,
- CAP_SYS_BOOT,
- CAP_SYS_NICE,
- CAP_SYS_RESOURCE,
- CAP_SYS_TIME,
- CAP_SYS_TTY_CONFIG,
- CAP_MKNOD,
- CAP_LEASE,
- CAP_AUDIT_WRITE,
- CAP_AUDIT_CONTROL,
- CAP_SETFCAP,
- CAP_MAC_OVERRIDE,
- CAP_MAC_ADMIN,
- CAP_SYSLOG,
- CAP_WAKE_ALARM,
- CAP_BLOCK_SUSPEND,
- CAP_AUDIT_READ,
- }
-}
diff --git a/containerd/vendor/github.com/syndtr/gocapability/capability/enumgen/gen.go b/containerd/vendor/github.com/syndtr/gocapability/capability/enumgen/gen.go
deleted file mode 100644
index 4c73380..0000000
--- a/containerd/vendor/github.com/syndtr/gocapability/capability/enumgen/gen.go
+++ /dev/null
@@ -1,92 +0,0 @@
-package main
-
-import (
- "bytes"
- "fmt"
- "go/ast"
- "go/format"
- "go/parser"
- "go/token"
- "io/ioutil"
- "log"
- "os"
- "strings"
-)
-
-const fileName = "enum.go"
-const genName = "enum_gen.go"
-
-type generator struct {
- buf bytes.Buffer
- caps []string
-}
-
-func (g *generator) writeHeader() {
- g.buf.WriteString("// generated file; DO NOT EDIT - use go generate in directory with source\n")
- g.buf.WriteString("\n")
- g.buf.WriteString("package capability")
-}
-
-func (g *generator) writeStringFunc() {
- g.buf.WriteString("\n")
- g.buf.WriteString("func (c Cap) String() string {\n")
- g.buf.WriteString("switch c {\n")
- for _, cap := range g.caps {
- fmt.Fprintf(&g.buf, "case %s:\n", cap)
- fmt.Fprintf(&g.buf, "return \"%s\"\n", strings.ToLower(cap[4:]))
- }
- g.buf.WriteString("}\n")
- g.buf.WriteString("return \"unknown\"\n")
- g.buf.WriteString("}\n")
-}
-
-func (g *generator) writeListFunc() {
- g.buf.WriteString("\n")
- g.buf.WriteString("// List returns list of all supported capabilities\n")
- g.buf.WriteString("func List() []Cap {\n")
- g.buf.WriteString("return []Cap{\n")
- for _, cap := range g.caps {
- fmt.Fprintf(&g.buf, "%s,\n", cap)
- }
- g.buf.WriteString("}\n")
- g.buf.WriteString("}\n")
-}
-
-func main() {
- fs := token.NewFileSet()
- parsedFile, err := parser.ParseFile(fs, fileName, nil, 0)
- if err != nil {
- log.Fatal(err)
- }
- var caps []string
- for _, decl := range parsedFile.Decls {
- decl, ok := decl.(*ast.GenDecl)
- if !ok || decl.Tok != token.CONST {
- continue
- }
- for _, spec := range decl.Specs {
- vspec := spec.(*ast.ValueSpec)
- name := vspec.Names[0].Name
- if strings.HasPrefix(name, "CAP_") {
- caps = append(caps, name)
- }
- }
- }
- g := &generator{caps: caps}
- g.writeHeader()
- g.writeStringFunc()
- g.writeListFunc()
- src, err := format.Source(g.buf.Bytes())
- if err != nil {
- fmt.Println("generated invalid Go code")
- fmt.Println(g.buf.String())
- log.Fatal(err)
- }
- fi, err := os.Stat(fileName)
- if err != nil {
- log.Fatal(err)
- }
- if err := ioutil.WriteFile(genName, src, fi.Mode().Perm()); err != nil {
- log.Fatal(err)
- }
-}
diff --git a/containerd/vendor/github.com/syndtr/gocapability/capability/syscall_linux.go b/containerd/vendor/github.com/syndtr/gocapability/capability/syscall_linux.go
deleted file mode 100644
index dd6f454..0000000
--- a/containerd/vendor/github.com/syndtr/gocapability/capability/syscall_linux.go
+++ /dev/null
@@ -1,145 +0,0 @@
-// Copyright (c) 2013, Suryandaru Triandana
-// All rights reserved.
-//
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-package capability
-
-import (
- "syscall"
- "unsafe"
-)
-
-type capHeader struct {
- version uint32
- pid int
-}
-
-type capData struct {
- effective uint32
- permitted uint32
- inheritable uint32
-}
-
-func capget(hdr *capHeader, data *capData) (err error) {
- _, _, e1 := syscall.Syscall(syscall.SYS_CAPGET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0)
- if e1 != 0 {
- err = e1
- }
- return
-}
-
-func capset(hdr *capHeader, data *capData) (err error) {
- _, _, e1 := syscall.Syscall(syscall.SYS_CAPSET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0)
- if e1 != 0 {
- err = e1
- }
- return
-}
-
-func prctl(option int, arg2, arg3, arg4, arg5 uintptr) (err error) {
- _, _, e1 := syscall.Syscall6(syscall.SYS_PRCTL, uintptr(option), arg2, arg3, arg4, arg5, 0)
- if e1 != 0 {
- err = e1
- }
- return
-}
-
-const (
- vfsXattrName = "security.capability"
-
- vfsCapVerMask = 0xff000000
- vfsCapVer1 = 0x01000000
- vfsCapVer2 = 0x02000000
-
- vfsCapFlagMask = ^vfsCapVerMask
- vfsCapFlageffective = 0x000001
-
- vfscapDataSizeV1 = 4 * (1 + 2*1)
- vfscapDataSizeV2 = 4 * (1 + 2*2)
-)
-
-type vfscapData struct {
- magic uint32
- data [2]struct {
- permitted uint32
- inheritable uint32
- }
- effective [2]uint32
- version int8
-}
-
-var (
- _vfsXattrName *byte
-)
-
-func init() {
- _vfsXattrName, _ = syscall.BytePtrFromString(vfsXattrName)
-}
-
-func getVfsCap(path string, dest *vfscapData) (err error) {
- var _p0 *byte
- _p0, err = syscall.BytePtrFromString(path)
- if err != nil {
- return
- }
- r0, _, e1 := syscall.Syscall6(syscall.SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_vfsXattrName)), uintptr(unsafe.Pointer(dest)), vfscapDataSizeV2, 0, 0)
- if e1 != 0 {
- if e1 == syscall.ENODATA {
- dest.version = 2
- return
- }
- err = e1
- }
- switch dest.magic & vfsCapVerMask {
- case vfsCapVer1:
- dest.version = 1
- if r0 != vfscapDataSizeV1 {
- return syscall.EINVAL
- }
- dest.data[1].permitted = 0
- dest.data[1].inheritable = 0
- case vfsCapVer2:
- dest.version = 2
- if r0 != vfscapDataSizeV2 {
- return syscall.EINVAL
- }
- default:
- return syscall.EINVAL
- }
- if dest.magic&vfsCapFlageffective != 0 {
- dest.effective[0] = dest.data[0].permitted | dest.data[0].inheritable
- dest.effective[1] = dest.data[1].permitted | dest.data[1].inheritable
- } else {
- dest.effective[0] = 0
- dest.effective[1] = 0
- }
- return
-}
-
-func setVfsCap(path string, data *vfscapData) (err error) {
- var _p0 *byte
- _p0, err = syscall.BytePtrFromString(path)
- if err != nil {
- return
- }
- var size uintptr
- if data.version == 1 {
- data.magic = vfsCapVer1
- size = vfscapDataSizeV1
- } else if data.version == 2 {
- data.magic = vfsCapVer2
- if data.effective[0] != 0 || data.effective[1] != 0 {
- data.magic |= vfsCapFlageffective
- }
- size = vfscapDataSizeV2
- } else {
- return syscall.EINVAL
- }
- _, _, e1 := syscall.Syscall6(syscall.SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_vfsXattrName)), uintptr(unsafe.Pointer(data)), size, 0, 0)
- if e1 != 0 {
- err = e1
- }
- return
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/.travis.yml b/containerd/vendor/github.com/vishvananda/netlink/.travis.yml
deleted file mode 100644
index 1970069..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/.travis.yml
+++ /dev/null
@@ -1,3 +0,0 @@
-language: go
-install:
- - go get github.com/vishvananda/netns
diff --git a/containerd/vendor/github.com/vishvananda/netlink/LICENSE b/containerd/vendor/github.com/vishvananda/netlink/LICENSE
deleted file mode 100644
index 9f64db8..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/LICENSE
+++ /dev/null
@@ -1,192 +0,0 @@
-
- Apache License
- Version 2.0, January 2004
- http://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 2014 Vishvananda Ishaya.
- Copyright 2014 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
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
diff --git a/containerd/vendor/github.com/vishvananda/netlink/Makefile b/containerd/vendor/github.com/vishvananda/netlink/Makefile
deleted file mode 100644
index b325018..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/Makefile
+++ /dev/null
@@ -1,29 +0,0 @@
-DIRS := \
- . \
- nl
-
-DEPS = \
- github.com/vishvananda/netns
-
-uniq = $(if $1,$(firstword $1) $(call uniq,$(filter-out $(firstword $1),$1)))
-testdirs = $(call uniq,$(foreach d,$(1),$(dir $(wildcard $(d)/*_test.go))))
-goroot = $(addprefix ../../../,$(1))
-unroot = $(subst ../../../,,$(1))
-fmt = $(addprefix fmt-,$(1))
-
-all: fmt
-
-$(call goroot,$(DEPS)):
- go get $(call unroot,$@)
-
-.PHONY: $(call testdirs,$(DIRS))
-$(call testdirs,$(DIRS)):
- sudo -E go test -v github.com/vishvananda/netlink/$@
-
-$(call fmt,$(call testdirs,$(DIRS))):
- ! gofmt -l $(subst fmt-,,$@)/*.go | grep ''
-
-.PHONY: fmt
-fmt: $(call fmt,$(call testdirs,$(DIRS)))
-
-test: fmt $(call goroot,$(DEPS)) $(call testdirs,$(DIRS))
diff --git a/containerd/vendor/github.com/vishvananda/netlink/README.md b/containerd/vendor/github.com/vishvananda/netlink/README.md
deleted file mode 100644
index 8cd50a9..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/README.md
+++ /dev/null
@@ -1,89 +0,0 @@
-# netlink - netlink library for go #
-
-[![Build Status](https://travis-ci.org/vishvananda/netlink.png?branch=master)](https://travis-ci.org/vishvananda/netlink) [![GoDoc](https://godoc.org/github.com/vishvananda/netlink?status.svg)](https://godoc.org/github.com/vishvananda/netlink)
-
-The netlink package provides a simple netlink library for go. Netlink
-is the interface a user-space program in linux uses to communicate with
-the kernel. It can be used to add and remove interfaces, set ip addresses
-and routes, and configure ipsec. Netlink communication requires elevated
-privileges, so in most cases this code needs to be run as root. Since
-low-level netlink messages are inscrutable at best, the library attempts
-to provide an api that is loosely modeled on the CLI provied by iproute2.
-Actions like `ip link add` will be accomplished via a similarly named
-function like AddLink(). This library began its life as a fork of the
-netlink functionality in
-[docker/libcontainer](https://github.com/docker/libcontainer) but was
-heavily rewritten to improve testability, performance, and to add new
-functionality like ipsec xfrm handling.
-
-## Local Build and Test ##
-
-You can use go get command:
-
- go get github.com/vishvananda/netlink
-
-Testing dependencies:
-
- go get github.com/vishvananda/netns
-
-Testing (requires root):
-
- sudo -E go test github.com/vishvananda/netlink
-
-## Examples ##
-
-Add a new bridge and add eth1 into it:
-
-```go
-package main
-
-import (
- "net"
- "github.com/vishvananda/netlink"
-)
-
-func main() {
- la := netlink.NewLinkAttrs()
- la.Name = "foo"
- mybridge := &netlink.Bridge{la}}
- _ := netlink.LinkAdd(mybridge)
- eth1, _ := netlink.LinkByName("eth1")
- netlink.LinkSetMaster(eth1, mybridge)
-}
-
-```
-Note `NewLinkAttrs` constructor, it sets default values in structure. For now
-it sets only `TxQLen` to `-1`, so kernel will set default by itself. If you're
-using simple initialization(`LinkAttrs{Name: "foo"}`) `TxQLen` will be set to
-`0` unless you specify it like `LinkAttrs{Name: "foo", TxQLen: 1000}`.
-
-Add a new ip address to loopback:
-
-```go
-package main
-
-import (
- "net"
- "github.com/vishvananda/netlink"
-)
-
-func main() {
- lo, _ := netlink.LinkByName("lo")
- addr, _ := netlink.ParseAddr("169.254.169.254/32")
- netlink.AddrAdd(lo, addr)
-}
-
-```
-
-## Future Work ##
-
-Many pieces of netlink are not yet fully supported in the high-level
-interface. Aspects of virtually all of the high-level objects don't exist.
-Many of the underlying primitives are there, so its a matter of putting
-the right fields into the high-level objects and making sure that they
-are serialized and deserialized correctly in the Add and List methods.
-
-There are also a few pieces of low level netlink functionality that still
-need to be implemented. Routing rules are not in place and some of the
-more advanced link types. Hopefully there is decent structure and testing
-in place to make these fairly straightforward to add.
diff --git a/containerd/vendor/github.com/vishvananda/netlink/addr.go b/containerd/vendor/github.com/vishvananda/netlink/addr.go
deleted file mode 100644
index 9bbaf50..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/addr.go
+++ /dev/null
@@ -1,43 +0,0 @@
-package netlink
-
-import (
- "fmt"
- "net"
- "strings"
-)
-
-// Addr represents an IP address from netlink. Netlink ip addresses
-// include a mask, so it stores the address as a net.IPNet.
-type Addr struct {
- *net.IPNet
- Label string
-}
-
-// String returns $ip/$netmask $label
-func (a Addr) String() string {
- return fmt.Sprintf("%s %s", a.IPNet, a.Label)
-}
-
-// ParseAddr parses the string representation of an address in the
-// form $ip/$netmask $label. The label portion is optional
-func ParseAddr(s string) (*Addr, error) {
- label := ""
- parts := strings.Split(s, " ")
- if len(parts) > 1 {
- s = parts[0]
- label = parts[1]
- }
- m, err := ParseIPNet(s)
- if err != nil {
- return nil, err
- }
- return &Addr{IPNet: m, Label: label}, nil
-}
-
-// Equal returns true if both Addrs have the same net.IPNet value.
-func (a Addr) Equal(x Addr) bool {
- sizea, _ := a.Mask.Size()
- sizeb, _ := x.Mask.Size()
- // ignore label for comparison
- return a.IP.Equal(x.IP) && sizea == sizeb
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/addr_linux.go b/containerd/vendor/github.com/vishvananda/netlink/addr_linux.go
deleted file mode 100644
index 19aac0f..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/addr_linux.go
+++ /dev/null
@@ -1,128 +0,0 @@
-package netlink
-
-import (
- "fmt"
- "net"
- "strings"
- "syscall"
-
- "github.com/vishvananda/netlink/nl"
-)
-
-// AddrAdd will add an IP address to a link device.
-// Equivalent to: `ip addr add $addr dev $link`
-func AddrAdd(link Link, addr *Addr) error {
-
- req := nl.NewNetlinkRequest(syscall.RTM_NEWADDR, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
- return addrHandle(link, addr, req)
-}
-
-// AddrDel will delete an IP address from a link device.
-// Equivalent to: `ip addr del $addr dev $link`
-func AddrDel(link Link, addr *Addr) error {
- req := nl.NewNetlinkRequest(syscall.RTM_DELADDR, syscall.NLM_F_ACK)
- return addrHandle(link, addr, req)
-}
-
-func addrHandle(link Link, addr *Addr, req *nl.NetlinkRequest) error {
- base := link.Attrs()
- if addr.Label != "" && !strings.HasPrefix(addr.Label, base.Name) {
- return fmt.Errorf("label must begin with interface name")
- }
- ensureIndex(base)
-
- family := nl.GetIPFamily(addr.IP)
-
- msg := nl.NewIfAddrmsg(family)
- msg.Index = uint32(base.Index)
- prefixlen, _ := addr.Mask.Size()
- msg.Prefixlen = uint8(prefixlen)
- req.AddData(msg)
-
- var addrData []byte
- if family == FAMILY_V4 {
- addrData = addr.IP.To4()
- } else {
- addrData = addr.IP.To16()
- }
-
- localData := nl.NewRtAttr(syscall.IFA_LOCAL, addrData)
- req.AddData(localData)
-
- addressData := nl.NewRtAttr(syscall.IFA_ADDRESS, addrData)
- req.AddData(addressData)
-
- if addr.Label != "" {
- labelData := nl.NewRtAttr(syscall.IFA_LABEL, nl.ZeroTerminated(addr.Label))
- req.AddData(labelData)
- }
-
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-// AddrList gets a list of IP addresses in the system.
-// Equivalent to: `ip addr show`.
-// The list can be filtered by link and ip family.
-func AddrList(link Link, family int) ([]Addr, error) {
- req := nl.NewNetlinkRequest(syscall.RTM_GETADDR, syscall.NLM_F_DUMP)
- msg := nl.NewIfInfomsg(family)
- req.AddData(msg)
-
- msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWADDR)
- if err != nil {
- return nil, err
- }
-
- index := 0
- if link != nil {
- base := link.Attrs()
- ensureIndex(base)
- index = base.Index
- }
-
- var res []Addr
- for _, m := range msgs {
- msg := nl.DeserializeIfAddrmsg(m)
-
- if link != nil && msg.Index != uint32(index) {
- // Ignore messages from other interfaces
- continue
- }
-
- attrs, err := nl.ParseRouteAttr(m[msg.Len():])
- if err != nil {
- return nil, err
- }
-
- var local, dst *net.IPNet
- var addr Addr
- for _, attr := range attrs {
- switch attr.Attr.Type {
- case syscall.IFA_ADDRESS:
- dst = &net.IPNet{
- IP: attr.Value,
- Mask: net.CIDRMask(int(msg.Prefixlen), 8*len(attr.Value)),
- }
- case syscall.IFA_LOCAL:
- local = &net.IPNet{
- IP: attr.Value,
- Mask: net.CIDRMask(int(msg.Prefixlen), 8*len(attr.Value)),
- }
- case syscall.IFA_LABEL:
- addr.Label = string(attr.Value[:len(attr.Value)-1])
- }
- }
-
- // IFA_LOCAL should be there but if not, fall back to IFA_ADDRESS
- if local != nil {
- addr.IPNet = local
- } else {
- addr.IPNet = dst
- }
-
- res = append(res, addr)
- }
-
- return res, nil
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/class.go b/containerd/vendor/github.com/vishvananda/netlink/class.go
deleted file mode 100644
index 35bdb33..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/class.go
+++ /dev/null
@@ -1,110 +0,0 @@
-package netlink
-
-import (
- "fmt"
-)
-
-type Class interface {
- Attrs() *ClassAttrs
- Type() string
-}
-
-// Class represents a netlink class. A filter is associated with a link,
-// has a handle and a parent. The root filter of a device should have a
-// parent == HANDLE_ROOT.
-type ClassAttrs struct {
- LinkIndex int
- Handle uint32
- Parent uint32
- Leaf uint32
-}
-
-func (q ClassAttrs) String() string {
- return fmt.Sprintf("{LinkIndex: %d, Handle: %s, Parent: %s, Leaf: %s}", q.LinkIndex, HandleStr(q.Handle), HandleStr(q.Parent), q.Leaf)
-}
-
-type HtbClassAttrs struct {
- // TODO handle all attributes
- Rate uint64
- Ceil uint64
- Buffer uint32
- Cbuffer uint32
- Quantum uint32
- Level uint32
- Prio uint32
-}
-
-func (q HtbClassAttrs) String() string {
- return fmt.Sprintf("{Rate: %d, Ceil: %d, Buffer: %d, Cbuffer: %d}", q.Rate, q.Ceil, q.Buffer, q.Cbuffer)
-}
-
-// Htb class
-type HtbClass struct {
- ClassAttrs
- Rate uint64
- Ceil uint64
- Buffer uint32
- Cbuffer uint32
- Quantum uint32
- Level uint32
- Prio uint32
-}
-
-func NewHtbClass(attrs ClassAttrs, cattrs HtbClassAttrs) *HtbClass {
- mtu := 1600
- rate := cattrs.Rate / 8
- ceil := cattrs.Ceil / 8
- buffer := cattrs.Buffer
- cbuffer := cattrs.Cbuffer
- if ceil == 0 {
- ceil = rate
- }
-
- if buffer == 0 {
- buffer = uint32(float64(rate)/Hz() + float64(mtu))
- }
- buffer = uint32(Xmittime(rate, buffer))
-
- if cbuffer == 0 {
- cbuffer = uint32(float64(ceil)/Hz() + float64(mtu))
- }
- cbuffer = uint32(Xmittime(ceil, cbuffer))
-
- return &HtbClass{
- ClassAttrs: attrs,
- Rate: rate,
- Ceil: ceil,
- Buffer: buffer,
- Cbuffer: cbuffer,
- Quantum: 10,
- Level: 0,
- Prio: 0,
- }
-}
-
-func (q HtbClass) String() string {
- return fmt.Sprintf("{Rate: %d, Ceil: %d, Buffer: %d, Cbuffer: %d}", q.Rate, q.Ceil, q.Buffer, q.Cbuffer)
-}
-
-func (class *HtbClass) Attrs() *ClassAttrs {
- return &class.ClassAttrs
-}
-
-func (class *HtbClass) Type() string {
- return "htb"
-}
-
-// GenericClass classes represent types that are not currently understood
-// by this netlink library.
-type GenericClass struct {
- ClassAttrs
- ClassType string
-}
-
-func (class *GenericClass) Attrs() *ClassAttrs {
- return &class.ClassAttrs
-}
-
-func (class *GenericClass) Type() string {
- return class.ClassType
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/class_linux.go b/containerd/vendor/github.com/vishvananda/netlink/class_linux.go
deleted file mode 100644
index 3dcc542..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/class_linux.go
+++ /dev/null
@@ -1,144 +0,0 @@
-package netlink
-
-import (
- "syscall"
-
- "github.com/vishvananda/netlink/nl"
-)
-
-// ClassDel will delete a class from the system.
-// Equivalent to: `tc class del $class`
-func ClassDel(class Class) error {
- req := nl.NewNetlinkRequest(syscall.RTM_DELTCLASS, syscall.NLM_F_ACK)
- base := class.Attrs()
- msg := &nl.TcMsg{
- Family: nl.FAMILY_ALL,
- Ifindex: int32(base.LinkIndex),
- Handle: base.Handle,
- Parent: base.Parent,
- }
- req.AddData(msg)
-
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-// ClassAdd will add a class to the system.
-// Equivalent to: `tc class add $class`
-func ClassAdd(class Class) error {
- req := nl.NewNetlinkRequest(syscall.RTM_NEWTCLASS, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
- base := class.Attrs()
- msg := &nl.TcMsg{
- Family: nl.FAMILY_ALL,
- Ifindex: int32(base.LinkIndex),
- Handle: base.Handle,
- Parent: base.Parent,
- }
- req.AddData(msg)
- req.AddData(nl.NewRtAttr(nl.TCA_KIND, nl.ZeroTerminated(class.Type())))
-
- options := nl.NewRtAttr(nl.TCA_OPTIONS, nil)
- if htb, ok := class.(*HtbClass); ok {
- opt := nl.TcHtbCopt{}
- opt.Rate.Rate = uint32(htb.Rate)
- opt.Ceil.Rate = uint32(htb.Ceil)
- opt.Buffer = htb.Buffer
- opt.Cbuffer = htb.Cbuffer
- opt.Quantum = htb.Quantum
- opt.Level = htb.Level
- opt.Prio = htb.Prio
- // TODO: Handle Debug properly. For now default to 0
- nl.NewRtAttrChild(options, nl.TCA_HTB_PARMS, opt.Serialize())
- }
- req.AddData(options)
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-// ClassList gets a list of classes in the system.
-// Equivalent to: `tc class show`.
-// Generally retunrs nothing if link and parent are not specified.
-func ClassList(link Link, parent uint32) ([]Class, error) {
- req := nl.NewNetlinkRequest(syscall.RTM_GETTCLASS, syscall.NLM_F_DUMP)
- msg := &nl.TcMsg{
- Family: nl.FAMILY_ALL,
- Parent: parent,
- }
- if link != nil {
- base := link.Attrs()
- ensureIndex(base)
- msg.Ifindex = int32(base.Index)
- }
- req.AddData(msg)
-
- msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWTCLASS)
- if err != nil {
- return nil, err
- }
-
- var res []Class
- for _, m := range msgs {
- msg := nl.DeserializeTcMsg(m)
-
- attrs, err := nl.ParseRouteAttr(m[msg.Len():])
- if err != nil {
- return nil, err
- }
-
- base := ClassAttrs{
- LinkIndex: int(msg.Ifindex),
- Handle: msg.Handle,
- Parent: msg.Parent,
- }
-
- var class Class
- classType := ""
- for _, attr := range attrs {
- switch attr.Attr.Type {
- case nl.TCA_KIND:
- classType = string(attr.Value[:len(attr.Value)-1])
- switch classType {
- case "htb":
- class = &HtbClass{}
- default:
- class = &GenericClass{ClassType: classType}
- }
- case nl.TCA_OPTIONS:
- switch classType {
- case "htb":
- data, err := nl.ParseRouteAttr(attr.Value)
- if err != nil {
- return nil, err
- }
- _, err = parseHtbClassData(class, data)
- if err != nil {
- return nil, err
- }
- }
- }
- }
- *class.Attrs() = base
- res = append(res, class)
- }
-
- return res, nil
-}
-
-func parseHtbClassData(class Class, data []syscall.NetlinkRouteAttr) (bool, error) {
- htb := class.(*HtbClass)
- detailed := false
- for _, datum := range data {
- switch datum.Attr.Type {
- case nl.TCA_HTB_PARMS:
- opt := nl.DeserializeTcHtbCopt(datum.Value)
- htb.Rate = uint64(opt.Rate.Rate)
- htb.Ceil = uint64(opt.Ceil.Rate)
- htb.Buffer = opt.Buffer
- htb.Cbuffer = opt.Cbuffer
- htb.Quantum = opt.Quantum
- htb.Level = opt.Level
- htb.Prio = opt.Prio
- }
- }
- return detailed, nil
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/filter.go b/containerd/vendor/github.com/vishvananda/netlink/filter.go
deleted file mode 100644
index 83ad700..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/filter.go
+++ /dev/null
@@ -1,55 +0,0 @@
-package netlink
-
-import (
- "fmt"
-)
-
-type Filter interface {
- Attrs() *FilterAttrs
- Type() string
-}
-
-// Filter represents a netlink filter. A filter is associated with a link,
-// has a handle and a parent. The root filter of a device should have a
-// parent == HANDLE_ROOT.
-type FilterAttrs struct {
- LinkIndex int
- Handle uint32
- Parent uint32
- Priority uint16 // lower is higher priority
- Protocol uint16 // syscall.ETH_P_*
-}
-
-func (q FilterAttrs) String() string {
- return fmt.Sprintf("{LinkIndex: %d, Handle: %s, Parent: %s, Priority: %d, Protocol: %d}", q.LinkIndex, HandleStr(q.Handle), HandleStr(q.Parent), q.Priority, q.Protocol)
-}
-
-// U32 filters on many packet related properties
-type U32 struct {
- FilterAttrs
- // Currently only supports redirecting to another interface
- RedirIndex int
-}
-
-func (filter *U32) Attrs() *FilterAttrs {
- return &filter.FilterAttrs
-}
-
-func (filter *U32) Type() string {
- return "u32"
-}
-
-// GenericFilter filters represent types that are not currently understood
-// by this netlink library.
-type GenericFilter struct {
- FilterAttrs
- FilterType string
-}
-
-func (filter *GenericFilter) Attrs() *FilterAttrs {
- return &filter.FilterAttrs
-}
-
-func (filter *GenericFilter) Type() string {
- return filter.FilterType
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/filter_linux.go b/containerd/vendor/github.com/vishvananda/netlink/filter_linux.go
deleted file mode 100644
index 1ec6987..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/filter_linux.go
+++ /dev/null
@@ -1,191 +0,0 @@
-package netlink
-
-import (
- "fmt"
- "syscall"
-
- "github.com/vishvananda/netlink/nl"
-)
-
-// FilterDel will delete a filter from the system.
-// Equivalent to: `tc filter del $filter`
-func FilterDel(filter Filter) error {
- req := nl.NewNetlinkRequest(syscall.RTM_DELTFILTER, syscall.NLM_F_ACK)
- base := filter.Attrs()
- msg := &nl.TcMsg{
- Family: nl.FAMILY_ALL,
- Ifindex: int32(base.LinkIndex),
- Handle: base.Handle,
- Parent: base.Parent,
- Info: MakeHandle(base.Priority, nl.Swap16(base.Protocol)),
- }
- req.AddData(msg)
-
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-// FilterAdd will add a filter to the system.
-// Equivalent to: `tc filter add $filter`
-func FilterAdd(filter Filter) error {
- req := nl.NewNetlinkRequest(syscall.RTM_NEWTFILTER, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
- base := filter.Attrs()
- msg := &nl.TcMsg{
- Family: nl.FAMILY_ALL,
- Ifindex: int32(base.LinkIndex),
- Handle: base.Handle,
- Parent: base.Parent,
- Info: MakeHandle(base.Priority, nl.Swap16(base.Protocol)),
- }
- req.AddData(msg)
- req.AddData(nl.NewRtAttr(nl.TCA_KIND, nl.ZeroTerminated(filter.Type())))
-
- options := nl.NewRtAttr(nl.TCA_OPTIONS, nil)
- if u32, ok := filter.(*U32); ok {
- // match all
- sel := nl.TcU32Sel{
- Nkeys: 1,
- Flags: nl.TC_U32_TERMINAL,
- }
- sel.Keys = append(sel.Keys, nl.TcU32Key{})
- nl.NewRtAttrChild(options, nl.TCA_U32_SEL, sel.Serialize())
- actions := nl.NewRtAttrChild(options, nl.TCA_U32_ACT, nil)
- table := nl.NewRtAttrChild(actions, nl.TCA_ACT_TAB, nil)
- nl.NewRtAttrChild(table, nl.TCA_KIND, nl.ZeroTerminated("mirred"))
- // redirect to other interface
- mir := nl.TcMirred{
- Action: nl.TC_ACT_STOLEN,
- Eaction: nl.TCA_EGRESS_REDIR,
- Ifindex: uint32(u32.RedirIndex),
- }
- aopts := nl.NewRtAttrChild(table, nl.TCA_OPTIONS, nil)
- nl.NewRtAttrChild(aopts, nl.TCA_MIRRED_PARMS, mir.Serialize())
- }
- req.AddData(options)
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-// FilterList gets a list of filters in the system.
-// Equivalent to: `tc filter show`.
-// Generally retunrs nothing if link and parent are not specified.
-func FilterList(link Link, parent uint32) ([]Filter, error) {
- req := nl.NewNetlinkRequest(syscall.RTM_GETTFILTER, syscall.NLM_F_DUMP)
- msg := &nl.TcMsg{
- Family: nl.FAMILY_ALL,
- Parent: parent,
- }
- if link != nil {
- base := link.Attrs()
- ensureIndex(base)
- msg.Ifindex = int32(base.Index)
- }
- req.AddData(msg)
-
- msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWTFILTER)
- if err != nil {
- return nil, err
- }
-
- var res []Filter
- for _, m := range msgs {
- msg := nl.DeserializeTcMsg(m)
-
- attrs, err := nl.ParseRouteAttr(m[msg.Len():])
- if err != nil {
- return nil, err
- }
-
- base := FilterAttrs{
- LinkIndex: int(msg.Ifindex),
- Handle: msg.Handle,
- Parent: msg.Parent,
- }
- base.Priority, base.Protocol = MajorMinor(msg.Info)
- base.Protocol = nl.Swap16(base.Protocol)
-
- var filter Filter
- filterType := ""
- detailed := false
- for _, attr := range attrs {
- switch attr.Attr.Type {
- case nl.TCA_KIND:
- filterType = string(attr.Value[:len(attr.Value)-1])
- switch filterType {
- case "u32":
- filter = &U32{}
- default:
- filter = &GenericFilter{FilterType: filterType}
- }
- case nl.TCA_OPTIONS:
- switch filterType {
- case "u32":
- data, err := nl.ParseRouteAttr(attr.Value)
- if err != nil {
- return nil, err
- }
- detailed, err = parseU32Data(filter, data)
- if err != nil {
- return nil, err
- }
- }
- }
- }
- // only return the detailed version of the filter
- if detailed {
- *filter.Attrs() = base
- res = append(res, filter)
- }
- }
-
- return res, nil
-}
-
-func parseU32Data(filter Filter, data []syscall.NetlinkRouteAttr) (bool, error) {
- native = nl.NativeEndian()
- u32 := filter.(*U32)
- detailed := false
- for _, datum := range data {
- switch datum.Attr.Type {
- case nl.TCA_U32_SEL:
- detailed = true
- sel := nl.DeserializeTcU32Sel(datum.Value)
- // only parse if we have a very basic redirect
- if sel.Flags&nl.TC_U32_TERMINAL == 0 || sel.Nkeys != 1 {
- return detailed, nil
- }
- case nl.TCA_U32_ACT:
- table, err := nl.ParseRouteAttr(datum.Value)
- if err != nil {
- return detailed, err
- }
- if len(table) != 1 || table[0].Attr.Type != nl.TCA_ACT_TAB {
- return detailed, fmt.Errorf("Action table not formed properly")
- }
- aattrs, err := nl.ParseRouteAttr(table[0].Value)
- for _, aattr := range aattrs {
- switch aattr.Attr.Type {
- case nl.TCA_KIND:
- actionType := string(aattr.Value[:len(aattr.Value)-1])
- // only parse if the action is mirred
- if actionType != "mirred" {
- return detailed, nil
- }
- case nl.TCA_OPTIONS:
- adata, err := nl.ParseRouteAttr(aattr.Value)
- if err != nil {
- return detailed, err
- }
- for _, adatum := range adata {
- switch adatum.Attr.Type {
- case nl.TCA_MIRRED_PARMS:
- mir := nl.DeserializeTcMirred(adatum.Value)
- u32.RedirIndex = int(mir.Ifindex)
- }
- }
- }
- }
- }
- }
- return detailed, nil
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/link.go b/containerd/vendor/github.com/vishvananda/netlink/link.go
deleted file mode 100644
index 18fd175..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/link.go
+++ /dev/null
@@ -1,223 +0,0 @@
-package netlink
-
-import "net"
-
-// Link represents a link device from netlink. Shared link attributes
-// like name may be retrieved using the Attrs() method. Unique data
-// can be retrieved by casting the object to the proper type.
-type Link interface {
- Attrs() *LinkAttrs
- Type() string
-}
-
-type (
- NsPid int
- NsFd int
-)
-
-// LinkAttrs represents data shared by most link types
-type LinkAttrs struct {
- Index int
- MTU int
- TxQLen int // Transmit Queue Length
- Name string
- HardwareAddr net.HardwareAddr
- Flags net.Flags
- ParentIndex int // index of the parent link device
- MasterIndex int // must be the index of a bridge
- Namespace interface{} // nil | NsPid | NsFd
-}
-
-// NewLinkAttrs returns LinkAttrs structure filled with default values
-func NewLinkAttrs() LinkAttrs {
- return LinkAttrs{
- TxQLen: -1,
- }
-}
-
-// Device links cannot be created via netlink. These links
-// are links created by udev like 'lo' and 'etho0'
-type Device struct {
- LinkAttrs
-}
-
-func (device *Device) Attrs() *LinkAttrs {
- return &device.LinkAttrs
-}
-
-func (device *Device) Type() string {
- return "device"
-}
-
-// Dummy links are dummy ethernet devices
-type Dummy struct {
- LinkAttrs
-}
-
-func (dummy *Dummy) Attrs() *LinkAttrs {
- return &dummy.LinkAttrs
-}
-
-func (dummy *Dummy) Type() string {
- return "dummy"
-}
-
-// Ifb links are advanced dummy devices for packet filtering
-type Ifb struct {
- LinkAttrs
-}
-
-func (ifb *Ifb) Attrs() *LinkAttrs {
- return &ifb.LinkAttrs
-}
-
-func (ifb *Ifb) Type() string {
- return "ifb"
-}
-
-// Bridge links are simple linux bridges
-type Bridge struct {
- LinkAttrs
-}
-
-func (bridge *Bridge) Attrs() *LinkAttrs {
- return &bridge.LinkAttrs
-}
-
-func (bridge *Bridge) Type() string {
- return "bridge"
-}
-
-// Vlan links have ParentIndex set in their Attrs()
-type Vlan struct {
- LinkAttrs
- VlanId int
-}
-
-func (vlan *Vlan) Attrs() *LinkAttrs {
- return &vlan.LinkAttrs
-}
-
-func (vlan *Vlan) Type() string {
- return "vlan"
-}
-
-type MacvlanMode uint16
-
-const (
- MACVLAN_MODE_DEFAULT MacvlanMode = iota
- MACVLAN_MODE_PRIVATE
- MACVLAN_MODE_VEPA
- MACVLAN_MODE_BRIDGE
- MACVLAN_MODE_PASSTHRU
- MACVLAN_MODE_SOURCE
-)
-
-// Macvlan links have ParentIndex set in their Attrs()
-type Macvlan struct {
- LinkAttrs
- Mode MacvlanMode
-}
-
-func (macvlan *Macvlan) Attrs() *LinkAttrs {
- return &macvlan.LinkAttrs
-}
-
-func (macvlan *Macvlan) Type() string {
- return "macvlan"
-}
-
-// Macvtap - macvtap is a virtual interfaces based on macvlan
-type Macvtap struct {
- Macvlan
-}
-
-func (macvtap Macvtap) Type() string {
- return "macvtap"
-}
-
-// Veth devices must specify PeerName on create
-type Veth struct {
- LinkAttrs
- PeerName string // veth on create only
-}
-
-func (veth *Veth) Attrs() *LinkAttrs {
- return &veth.LinkAttrs
-}
-
-func (veth *Veth) Type() string {
- return "veth"
-}
-
-// GenericLink links represent types that are not currently understood
-// by this netlink library.
-type GenericLink struct {
- LinkAttrs
- LinkType string
-}
-
-func (generic *GenericLink) Attrs() *LinkAttrs {
- return &generic.LinkAttrs
-}
-
-func (generic *GenericLink) Type() string {
- return generic.LinkType
-}
-
-type Vxlan struct {
- LinkAttrs
- VxlanId int
- VtepDevIndex int
- SrcAddr net.IP
- Group net.IP
- TTL int
- TOS int
- Learning bool
- Proxy bool
- RSC bool
- L2miss bool
- L3miss bool
- NoAge bool
- GBP bool
- Age int
- Limit int
- Port int
- PortLow int
- PortHigh int
-}
-
-func (vxlan *Vxlan) Attrs() *LinkAttrs {
- return &vxlan.LinkAttrs
-}
-
-func (vxlan *Vxlan) Type() string {
- return "vxlan"
-}
-
-type IPVlanMode uint16
-
-const (
- IPVLAN_MODE_L2 IPVlanMode = iota
- IPVLAN_MODE_L3
- IPVLAN_MODE_MAX
-)
-
-type IPVlan struct {
- LinkAttrs
- Mode IPVlanMode
-}
-
-func (ipvlan *IPVlan) Attrs() *LinkAttrs {
- return &ipvlan.LinkAttrs
-}
-
-func (ipvlan *IPVlan) Type() string {
- return "ipvlan"
-}
-
-// iproute2 supported devices;
-// vlan | veth | vcan | dummy | ifb | macvlan | macvtap |
-// bridge | bond | ipoib | ip6tnl | ipip | sit | vxlan |
-// gre | gretap | ip6gre | ip6gretap | vti | nlmon |
-// bond_slave | ipvlan
diff --git a/containerd/vendor/github.com/vishvananda/netlink/link_linux.go b/containerd/vendor/github.com/vishvananda/netlink/link_linux.go
deleted file mode 100644
index 842a21f..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/link_linux.go
+++ /dev/null
@@ -1,790 +0,0 @@
-package netlink
-
-import (
- "bytes"
- "encoding/binary"
- "fmt"
- "net"
- "syscall"
-
- "github.com/vishvananda/netlink/nl"
-)
-
-var native = nl.NativeEndian()
-var lookupByDump = false
-
-var macvlanModes = [...]uint32{
- 0,
- nl.MACVLAN_MODE_PRIVATE,
- nl.MACVLAN_MODE_VEPA,
- nl.MACVLAN_MODE_BRIDGE,
- nl.MACVLAN_MODE_PASSTHRU,
- nl.MACVLAN_MODE_SOURCE,
-}
-
-func ensureIndex(link *LinkAttrs) {
- if link != nil && link.Index == 0 {
- newlink, _ := LinkByName(link.Name)
- if newlink != nil {
- link.Index = newlink.Attrs().Index
- }
- }
-}
-
-// LinkSetUp enables the link device.
-// Equivalent to: `ip link set $link up`
-func LinkSetUp(link Link) error {
- base := link.Attrs()
- ensureIndex(base)
- req := nl.NewNetlinkRequest(syscall.RTM_NEWLINK, syscall.NLM_F_ACK)
-
- msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
- msg.Change = syscall.IFF_UP
- msg.Flags = syscall.IFF_UP
- msg.Index = int32(base.Index)
- req.AddData(msg)
-
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-// LinkSetDown disables link device.
-// Equivalent to: `ip link set $link down`
-func LinkSetDown(link Link) error {
- base := link.Attrs()
- ensureIndex(base)
- req := nl.NewNetlinkRequest(syscall.RTM_NEWLINK, syscall.NLM_F_ACK)
-
- msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
- msg.Change = syscall.IFF_UP
- msg.Flags = 0 & ^syscall.IFF_UP
- msg.Index = int32(base.Index)
- req.AddData(msg)
-
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-// LinkSetMTU sets the mtu of the link device.
-// Equivalent to: `ip link set $link mtu $mtu`
-func LinkSetMTU(link Link, mtu int) error {
- base := link.Attrs()
- ensureIndex(base)
- req := nl.NewNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
-
- msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
- msg.Index = int32(base.Index)
- req.AddData(msg)
-
- b := make([]byte, 4)
- native.PutUint32(b, uint32(mtu))
-
- data := nl.NewRtAttr(syscall.IFLA_MTU, b)
- req.AddData(data)
-
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-// LinkSetName sets the name of the link device.
-// Equivalent to: `ip link set $link name $name`
-func LinkSetName(link Link, name string) error {
- base := link.Attrs()
- ensureIndex(base)
- req := nl.NewNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
-
- msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
- msg.Index = int32(base.Index)
- req.AddData(msg)
-
- data := nl.NewRtAttr(syscall.IFLA_IFNAME, []byte(name))
- req.AddData(data)
-
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-// LinkSetHardwareAddr sets the hardware address of the link device.
-// Equivalent to: `ip link set $link address $hwaddr`
-func LinkSetHardwareAddr(link Link, hwaddr net.HardwareAddr) error {
- base := link.Attrs()
- ensureIndex(base)
- req := nl.NewNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
-
- msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
- msg.Index = int32(base.Index)
- req.AddData(msg)
-
- data := nl.NewRtAttr(syscall.IFLA_ADDRESS, []byte(hwaddr))
- req.AddData(data)
-
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-// LinkSetMaster sets the master of the link device.
-// Equivalent to: `ip link set $link master $master`
-func LinkSetMaster(link Link, master *Bridge) error {
- index := 0
- if master != nil {
- masterBase := master.Attrs()
- ensureIndex(masterBase)
- index = masterBase.Index
- }
- return LinkSetMasterByIndex(link, index)
-}
-
-// LinkSetMasterByIndex sets the master of the link device.
-// Equivalent to: `ip link set $link master $master`
-func LinkSetMasterByIndex(link Link, masterIndex int) error {
- base := link.Attrs()
- ensureIndex(base)
- req := nl.NewNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
-
- msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
- msg.Index = int32(base.Index)
- req.AddData(msg)
-
- b := make([]byte, 4)
- native.PutUint32(b, uint32(masterIndex))
-
- data := nl.NewRtAttr(syscall.IFLA_MASTER, b)
- req.AddData(data)
-
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-// LinkSetNsPid puts the device into a new network namespace. The
-// pid must be a pid of a running process.
-// Equivalent to: `ip link set $link netns $pid`
-func LinkSetNsPid(link Link, nspid int) error {
- base := link.Attrs()
- ensureIndex(base)
- req := nl.NewNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
-
- msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
- msg.Index = int32(base.Index)
- req.AddData(msg)
-
- b := make([]byte, 4)
- native.PutUint32(b, uint32(nspid))
-
- data := nl.NewRtAttr(syscall.IFLA_NET_NS_PID, b)
- req.AddData(data)
-
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-// LinkSetNsFd puts the device into a new network namespace. The
-// fd must be an open file descriptor to a network namespace.
-// Similar to: `ip link set $link netns $ns`
-func LinkSetNsFd(link Link, fd int) error {
- base := link.Attrs()
- ensureIndex(base)
- req := nl.NewNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
-
- msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
- msg.Index = int32(base.Index)
- req.AddData(msg)
-
- b := make([]byte, 4)
- native.PutUint32(b, uint32(fd))
-
- data := nl.NewRtAttr(nl.IFLA_NET_NS_FD, b)
- req.AddData(data)
-
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-func boolAttr(val bool) []byte {
- var v uint8
- if val {
- v = 1
- }
- return nl.Uint8Attr(v)
-}
-
-type vxlanPortRange struct {
- Lo, Hi uint16
-}
-
-func addVxlanAttrs(vxlan *Vxlan, linkInfo *nl.RtAttr) {
- data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_ID, nl.Uint32Attr(uint32(vxlan.VxlanId)))
- if vxlan.VtepDevIndex != 0 {
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_LINK, nl.Uint32Attr(uint32(vxlan.VtepDevIndex)))
- }
- if vxlan.SrcAddr != nil {
- ip := vxlan.SrcAddr.To4()
- if ip != nil {
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_LOCAL, []byte(ip))
- } else {
- ip = vxlan.SrcAddr.To16()
- if ip != nil {
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_LOCAL6, []byte(ip))
- }
- }
- }
- if vxlan.Group != nil {
- group := vxlan.Group.To4()
- if group != nil {
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_GROUP, []byte(group))
- } else {
- group = vxlan.Group.To16()
- if group != nil {
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_GROUP6, []byte(group))
- }
- }
- }
-
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_TTL, nl.Uint8Attr(uint8(vxlan.TTL)))
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_TOS, nl.Uint8Attr(uint8(vxlan.TOS)))
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_LEARNING, boolAttr(vxlan.Learning))
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_PROXY, boolAttr(vxlan.Proxy))
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_RSC, boolAttr(vxlan.RSC))
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_L2MISS, boolAttr(vxlan.L2miss))
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_L3MISS, boolAttr(vxlan.L3miss))
-
- if vxlan.GBP {
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_GBP, boolAttr(vxlan.GBP))
- }
-
- if vxlan.NoAge {
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_AGEING, nl.Uint32Attr(0))
- } else if vxlan.Age > 0 {
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_AGEING, nl.Uint32Attr(uint32(vxlan.Age)))
- }
- if vxlan.Limit > 0 {
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_LIMIT, nl.Uint32Attr(uint32(vxlan.Limit)))
- }
- if vxlan.Port > 0 {
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_PORT, nl.Uint16Attr(uint16(vxlan.Port)))
- }
- if vxlan.PortLow > 0 || vxlan.PortHigh > 0 {
- pr := vxlanPortRange{uint16(vxlan.PortLow), uint16(vxlan.PortHigh)}
-
- buf := new(bytes.Buffer)
- binary.Write(buf, binary.BigEndian, &pr)
-
- nl.NewRtAttrChild(data, nl.IFLA_VXLAN_PORT_RANGE, buf.Bytes())
- }
-}
-
-// LinkAdd adds a new link device. The type and features of the device
-// are taken fromt the parameters in the link object.
-// Equivalent to: `ip link add $link`
-func LinkAdd(link Link) error {
- // TODO: set mtu and hardware address
- // TODO: support extra data for macvlan
- base := link.Attrs()
-
- if base.Name == "" {
- return fmt.Errorf("LinkAttrs.Name cannot be empty!")
- }
-
- req := nl.NewNetlinkRequest(syscall.RTM_NEWLINK, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
-
- msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
- req.AddData(msg)
-
- if base.ParentIndex != 0 {
- b := make([]byte, 4)
- native.PutUint32(b, uint32(base.ParentIndex))
- data := nl.NewRtAttr(syscall.IFLA_LINK, b)
- req.AddData(data)
- } else if link.Type() == "ipvlan" {
- return fmt.Errorf("Can't create ipvlan link without ParentIndex")
- }
-
- nameData := nl.NewRtAttr(syscall.IFLA_IFNAME, nl.ZeroTerminated(base.Name))
- req.AddData(nameData)
-
- if base.MTU > 0 {
- mtu := nl.NewRtAttr(syscall.IFLA_MTU, nl.Uint32Attr(uint32(base.MTU)))
- req.AddData(mtu)
- }
-
- if base.TxQLen >= 0 {
- qlen := nl.NewRtAttr(syscall.IFLA_TXQLEN, nl.Uint32Attr(uint32(base.TxQLen)))
- req.AddData(qlen)
- }
-
- if base.Namespace != nil {
- var attr *nl.RtAttr
- switch base.Namespace.(type) {
- case NsPid:
- val := nl.Uint32Attr(uint32(base.Namespace.(NsPid)))
- attr = nl.NewRtAttr(syscall.IFLA_NET_NS_PID, val)
- case NsFd:
- val := nl.Uint32Attr(uint32(base.Namespace.(NsFd)))
- attr = nl.NewRtAttr(nl.IFLA_NET_NS_FD, val)
- }
-
- req.AddData(attr)
- }
-
- linkInfo := nl.NewRtAttr(syscall.IFLA_LINKINFO, nil)
- nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_KIND, nl.NonZeroTerminated(link.Type()))
-
- if vlan, ok := link.(*Vlan); ok {
- b := make([]byte, 2)
- native.PutUint16(b, uint16(vlan.VlanId))
- data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
- nl.NewRtAttrChild(data, nl.IFLA_VLAN_ID, b)
- } else if veth, ok := link.(*Veth); ok {
- data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
- peer := nl.NewRtAttrChild(data, nl.VETH_INFO_PEER, nil)
- nl.NewIfInfomsgChild(peer, syscall.AF_UNSPEC)
- nl.NewRtAttrChild(peer, syscall.IFLA_IFNAME, nl.ZeroTerminated(veth.PeerName))
- if base.TxQLen >= 0 {
- nl.NewRtAttrChild(peer, syscall.IFLA_TXQLEN, nl.Uint32Attr(uint32(base.TxQLen)))
- }
- if base.MTU > 0 {
- nl.NewRtAttrChild(peer, syscall.IFLA_MTU, nl.Uint32Attr(uint32(base.MTU)))
- }
-
- } else if vxlan, ok := link.(*Vxlan); ok {
- addVxlanAttrs(vxlan, linkInfo)
- } else if ipv, ok := link.(*IPVlan); ok {
- data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
- nl.NewRtAttrChild(data, nl.IFLA_IPVLAN_MODE, nl.Uint16Attr(uint16(ipv.Mode)))
- } else if macv, ok := link.(*Macvlan); ok {
- if macv.Mode != MACVLAN_MODE_DEFAULT {
- data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
- nl.NewRtAttrChild(data, nl.IFLA_MACVLAN_MODE, nl.Uint32Attr(macvlanModes[macv.Mode]))
- }
- }
-
- req.AddData(linkInfo)
-
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- if err != nil {
- return err
- }
-
- ensureIndex(base)
-
- // can't set master during create, so set it afterwards
- if base.MasterIndex != 0 {
- // TODO: verify MasterIndex is actually a bridge?
- return LinkSetMasterByIndex(link, base.MasterIndex)
- }
- return nil
-}
-
-// LinkDel deletes link device. Either Index or Name must be set in
-// the link object for it to be deleted. The other values are ignored.
-// Equivalent to: `ip link del $link`
-func LinkDel(link Link) error {
- base := link.Attrs()
-
- ensureIndex(base)
-
- req := nl.NewNetlinkRequest(syscall.RTM_DELLINK, syscall.NLM_F_ACK)
-
- msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
- msg.Index = int32(base.Index)
- req.AddData(msg)
-
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-func linkByNameDump(name string) (Link, error) {
- links, err := LinkList()
- if err != nil {
- return nil, err
- }
-
- for _, link := range links {
- if link.Attrs().Name == name {
- return link, nil
- }
- }
- return nil, fmt.Errorf("Link %s not found", name)
-}
-
-// LinkByName finds a link by name and returns a pointer to the object.
-func LinkByName(name string) (Link, error) {
- if lookupByDump {
- return linkByNameDump(name)
- }
-
- req := nl.NewNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_ACK)
-
- msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
- req.AddData(msg)
-
- nameData := nl.NewRtAttr(syscall.IFLA_IFNAME, nl.ZeroTerminated(name))
- req.AddData(nameData)
-
- link, err := execGetLink(req)
- if err == syscall.EINVAL {
- // older kernels don't support looking up via IFLA_IFNAME
- // so fall back to dumping all links
- lookupByDump = true
- return linkByNameDump(name)
- }
-
- return link, err
-}
-
-// LinkByIndex finds a link by index and returns a pointer to the object.
-func LinkByIndex(index int) (Link, error) {
- req := nl.NewNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_ACK)
-
- msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
- msg.Index = int32(index)
- req.AddData(msg)
-
- return execGetLink(req)
-}
-
-func execGetLink(req *nl.NetlinkRequest) (Link, error) {
- msgs, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- if err != nil {
- if errno, ok := err.(syscall.Errno); ok {
- if errno == syscall.ENODEV {
- return nil, fmt.Errorf("Link not found")
- }
- }
- return nil, err
- }
-
- switch {
- case len(msgs) == 0:
- return nil, fmt.Errorf("Link not found")
-
- case len(msgs) == 1:
- return linkDeserialize(msgs[0])
-
- default:
- return nil, fmt.Errorf("More than one link found")
- }
-}
-
-// linkDeserialize deserializes a raw message received from netlink into
-// a link object.
-func linkDeserialize(m []byte) (Link, error) {
- msg := nl.DeserializeIfInfomsg(m)
-
- attrs, err := nl.ParseRouteAttr(m[msg.Len():])
- if err != nil {
- return nil, err
- }
-
- base := LinkAttrs{Index: int(msg.Index), Flags: linkFlags(msg.Flags)}
- var link Link
- linkType := ""
- for _, attr := range attrs {
- switch attr.Attr.Type {
- case syscall.IFLA_LINKINFO:
- infos, err := nl.ParseRouteAttr(attr.Value)
- if err != nil {
- return nil, err
- }
- for _, info := range infos {
- switch info.Attr.Type {
- case nl.IFLA_INFO_KIND:
- linkType = string(info.Value[:len(info.Value)-1])
- switch linkType {
- case "dummy":
- link = &Dummy{}
- case "ifb":
- link = &Ifb{}
- case "bridge":
- link = &Bridge{}
- case "vlan":
- link = &Vlan{}
- case "veth":
- link = &Veth{}
- case "vxlan":
- link = &Vxlan{}
- case "ipvlan":
- link = &IPVlan{}
- case "macvlan":
- link = &Macvlan{}
- case "macvtap":
- link = &Macvtap{}
- default:
- link = &GenericLink{LinkType: linkType}
- }
- case nl.IFLA_INFO_DATA:
- data, err := nl.ParseRouteAttr(info.Value)
- if err != nil {
- return nil, err
- }
- switch linkType {
- case "vlan":
- parseVlanData(link, data)
- case "vxlan":
- parseVxlanData(link, data)
- case "ipvlan":
- parseIPVlanData(link, data)
- case "macvlan":
- parseMacvlanData(link, data)
- case "macvtap":
- parseMacvtapData(link, data)
- }
- }
- }
- case syscall.IFLA_ADDRESS:
- var nonzero bool
- for _, b := range attr.Value {
- if b != 0 {
- nonzero = true
- }
- }
- if nonzero {
- base.HardwareAddr = attr.Value[:]
- }
- case syscall.IFLA_IFNAME:
- base.Name = string(attr.Value[:len(attr.Value)-1])
- case syscall.IFLA_MTU:
- base.MTU = int(native.Uint32(attr.Value[0:4]))
- case syscall.IFLA_LINK:
- base.ParentIndex = int(native.Uint32(attr.Value[0:4]))
- case syscall.IFLA_MASTER:
- base.MasterIndex = int(native.Uint32(attr.Value[0:4]))
- case syscall.IFLA_TXQLEN:
- base.TxQLen = int(native.Uint32(attr.Value[0:4]))
- }
- }
- // Links that don't have IFLA_INFO_KIND are hardware devices
- if link == nil {
- link = &Device{}
- }
- *link.Attrs() = base
-
- return link, nil
-}
-
-// LinkList gets a list of link devices.
-// Equivalent to: `ip link show`
-func LinkList() ([]Link, error) {
- // NOTE(vish): This duplicates functionality in net/iface_linux.go, but we need
- // to get the message ourselves to parse link type.
- req := nl.NewNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_DUMP)
-
- msg := nl.NewIfInfomsg(syscall.AF_UNSPEC)
- req.AddData(msg)
-
- msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWLINK)
- if err != nil {
- return nil, err
- }
-
- var res []Link
- for _, m := range msgs {
- link, err := linkDeserialize(m)
- if err != nil {
- return nil, err
- }
- res = append(res, link)
- }
-
- return res, nil
-}
-
-// LinkUpdate is used to pass information back from LinkSubscribe()
-type LinkUpdate struct {
- nl.IfInfomsg
- Link
-}
-
-// LinkSubscribe takes a chan down which notifications will be sent
-// when links change. Close the 'done' chan to stop subscription.
-func LinkSubscribe(ch chan<- LinkUpdate, done <-chan struct{}) error {
- s, err := nl.Subscribe(syscall.NETLINK_ROUTE, syscall.RTNLGRP_LINK)
- if err != nil {
- return err
- }
- if done != nil {
- go func() {
- <-done
- s.Close()
- }()
- }
- go func() {
- defer close(ch)
- for {
- msgs, err := s.Receive()
- if err != nil {
- return
- }
- for _, m := range msgs {
- ifmsg := nl.DeserializeIfInfomsg(m.Data)
- link, err := linkDeserialize(m.Data)
- if err != nil {
- return
- }
- ch <- LinkUpdate{IfInfomsg: *ifmsg, Link: link}
- }
- }
- }()
-
- return nil
-}
-
-func LinkSetHairpin(link Link, mode bool) error {
- return setProtinfoAttr(link, mode, nl.IFLA_BRPORT_MODE)
-}
-
-func LinkSetGuard(link Link, mode bool) error {
- return setProtinfoAttr(link, mode, nl.IFLA_BRPORT_GUARD)
-}
-
-func LinkSetFastLeave(link Link, mode bool) error {
- return setProtinfoAttr(link, mode, nl.IFLA_BRPORT_FAST_LEAVE)
-}
-
-func LinkSetLearning(link Link, mode bool) error {
- return setProtinfoAttr(link, mode, nl.IFLA_BRPORT_LEARNING)
-}
-
-func LinkSetRootBlock(link Link, mode bool) error {
- return setProtinfoAttr(link, mode, nl.IFLA_BRPORT_PROTECT)
-}
-
-func LinkSetFlood(link Link, mode bool) error {
- return setProtinfoAttr(link, mode, nl.IFLA_BRPORT_UNICAST_FLOOD)
-}
-
-func setProtinfoAttr(link Link, mode bool, attr int) error {
- base := link.Attrs()
- ensureIndex(base)
- req := nl.NewNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
-
- msg := nl.NewIfInfomsg(syscall.AF_BRIDGE)
- msg.Index = int32(base.Index)
- req.AddData(msg)
-
- br := nl.NewRtAttr(syscall.IFLA_PROTINFO|syscall.NLA_F_NESTED, nil)
- nl.NewRtAttrChild(br, attr, boolToByte(mode))
- req.AddData(br)
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- if err != nil {
- return err
- }
- return nil
-}
-
-func parseVlanData(link Link, data []syscall.NetlinkRouteAttr) {
- vlan := link.(*Vlan)
- for _, datum := range data {
- switch datum.Attr.Type {
- case nl.IFLA_VLAN_ID:
- vlan.VlanId = int(native.Uint16(datum.Value[0:2]))
- }
- }
-}
-
-func parseVxlanData(link Link, data []syscall.NetlinkRouteAttr) {
- vxlan := link.(*Vxlan)
- for _, datum := range data {
- switch datum.Attr.Type {
- case nl.IFLA_VXLAN_ID:
- vxlan.VxlanId = int(native.Uint32(datum.Value[0:4]))
- case nl.IFLA_VXLAN_LINK:
- vxlan.VtepDevIndex = int(native.Uint32(datum.Value[0:4]))
- case nl.IFLA_VXLAN_LOCAL:
- vxlan.SrcAddr = net.IP(datum.Value[0:4])
- case nl.IFLA_VXLAN_LOCAL6:
- vxlan.SrcAddr = net.IP(datum.Value[0:16])
- case nl.IFLA_VXLAN_GROUP:
- vxlan.Group = net.IP(datum.Value[0:4])
- case nl.IFLA_VXLAN_GROUP6:
- vxlan.Group = net.IP(datum.Value[0:16])
- case nl.IFLA_VXLAN_TTL:
- vxlan.TTL = int(datum.Value[0])
- case nl.IFLA_VXLAN_TOS:
- vxlan.TOS = int(datum.Value[0])
- case nl.IFLA_VXLAN_LEARNING:
- vxlan.Learning = int8(datum.Value[0]) != 0
- case nl.IFLA_VXLAN_PROXY:
- vxlan.Proxy = int8(datum.Value[0]) != 0
- case nl.IFLA_VXLAN_RSC:
- vxlan.RSC = int8(datum.Value[0]) != 0
- case nl.IFLA_VXLAN_L2MISS:
- vxlan.L2miss = int8(datum.Value[0]) != 0
- case nl.IFLA_VXLAN_L3MISS:
- vxlan.L3miss = int8(datum.Value[0]) != 0
- case nl.IFLA_VXLAN_GBP:
- vxlan.GBP = int8(datum.Value[0]) != 0
- case nl.IFLA_VXLAN_AGEING:
- vxlan.Age = int(native.Uint32(datum.Value[0:4]))
- vxlan.NoAge = vxlan.Age == 0
- case nl.IFLA_VXLAN_LIMIT:
- vxlan.Limit = int(native.Uint32(datum.Value[0:4]))
- case nl.IFLA_VXLAN_PORT:
- vxlan.Port = int(native.Uint16(datum.Value[0:2]))
- case nl.IFLA_VXLAN_PORT_RANGE:
- buf := bytes.NewBuffer(datum.Value[0:4])
- var pr vxlanPortRange
- if binary.Read(buf, binary.BigEndian, &pr) != nil {
- vxlan.PortLow = int(pr.Lo)
- vxlan.PortHigh = int(pr.Hi)
- }
- }
- }
-}
-
-func parseIPVlanData(link Link, data []syscall.NetlinkRouteAttr) {
- ipv := link.(*IPVlan)
- for _, datum := range data {
- if datum.Attr.Type == nl.IFLA_IPVLAN_MODE {
- ipv.Mode = IPVlanMode(native.Uint32(datum.Value[0:4]))
- return
- }
- }
-}
-
-func parseMacvtapData(link Link, data []syscall.NetlinkRouteAttr) {
- macv := link.(*Macvtap)
- parseMacvlanData(&macv.Macvlan, data)
-}
-
-func parseMacvlanData(link Link, data []syscall.NetlinkRouteAttr) {
- macv := link.(*Macvlan)
- for _, datum := range data {
- if datum.Attr.Type == nl.IFLA_MACVLAN_MODE {
- switch native.Uint32(datum.Value[0:4]) {
- case nl.MACVLAN_MODE_PRIVATE:
- macv.Mode = MACVLAN_MODE_PRIVATE
- case nl.MACVLAN_MODE_VEPA:
- macv.Mode = MACVLAN_MODE_VEPA
- case nl.MACVLAN_MODE_BRIDGE:
- macv.Mode = MACVLAN_MODE_BRIDGE
- case nl.MACVLAN_MODE_PASSTHRU:
- macv.Mode = MACVLAN_MODE_PASSTHRU
- case nl.MACVLAN_MODE_SOURCE:
- macv.Mode = MACVLAN_MODE_SOURCE
- }
- return
- }
- }
-}
-
-// copied from pkg/net_linux.go
-func linkFlags(rawFlags uint32) net.Flags {
- var f net.Flags
- if rawFlags&syscall.IFF_UP != 0 {
- f |= net.FlagUp
- }
- if rawFlags&syscall.IFF_BROADCAST != 0 {
- f |= net.FlagBroadcast
- }
- if rawFlags&syscall.IFF_LOOPBACK != 0 {
- f |= net.FlagLoopback
- }
- if rawFlags&syscall.IFF_POINTOPOINT != 0 {
- f |= net.FlagPointToPoint
- }
- if rawFlags&syscall.IFF_MULTICAST != 0 {
- f |= net.FlagMulticast
- }
- return f
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/neigh.go b/containerd/vendor/github.com/vishvananda/netlink/neigh.go
deleted file mode 100644
index 0e5eb90..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/neigh.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package netlink
-
-import (
- "fmt"
- "net"
-)
-
-// Neigh represents a link layer neighbor from netlink.
-type Neigh struct {
- LinkIndex int
- Family int
- State int
- Type int
- Flags int
- IP net.IP
- HardwareAddr net.HardwareAddr
-}
-
-// String returns $ip/$hwaddr $label
-func (neigh *Neigh) String() string {
- return fmt.Sprintf("%s %s", neigh.IP, neigh.HardwareAddr)
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/neigh_linux.go b/containerd/vendor/github.com/vishvananda/netlink/neigh_linux.go
deleted file mode 100644
index 620a0ee..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/neigh_linux.go
+++ /dev/null
@@ -1,189 +0,0 @@
-package netlink
-
-import (
- "net"
- "syscall"
- "unsafe"
-
- "github.com/vishvananda/netlink/nl"
-)
-
-const (
- NDA_UNSPEC = iota
- NDA_DST
- NDA_LLADDR
- NDA_CACHEINFO
- NDA_PROBES
- NDA_VLAN
- NDA_PORT
- NDA_VNI
- NDA_IFINDEX
- NDA_MAX = NDA_IFINDEX
-)
-
-// Neighbor Cache Entry States.
-const (
- NUD_NONE = 0x00
- NUD_INCOMPLETE = 0x01
- NUD_REACHABLE = 0x02
- NUD_STALE = 0x04
- NUD_DELAY = 0x08
- NUD_PROBE = 0x10
- NUD_FAILED = 0x20
- NUD_NOARP = 0x40
- NUD_PERMANENT = 0x80
-)
-
-// Neighbor Flags
-const (
- NTF_USE = 0x01
- NTF_SELF = 0x02
- NTF_MASTER = 0x04
- NTF_PROXY = 0x08
- NTF_ROUTER = 0x80
-)
-
-type Ndmsg struct {
- Family uint8
- Index uint32
- State uint16
- Flags uint8
- Type uint8
-}
-
-func deserializeNdmsg(b []byte) *Ndmsg {
- var dummy Ndmsg
- return (*Ndmsg)(unsafe.Pointer(&b[0:unsafe.Sizeof(dummy)][0]))
-}
-
-func (msg *Ndmsg) Serialize() []byte {
- return (*(*[unsafe.Sizeof(*msg)]byte)(unsafe.Pointer(msg)))[:]
-}
-
-func (msg *Ndmsg) Len() int {
- return int(unsafe.Sizeof(*msg))
-}
-
-// NeighAdd will add an IP to MAC mapping to the ARP table
-// Equivalent to: `ip neigh add ....`
-func NeighAdd(neigh *Neigh) error {
- return neighAdd(neigh, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL)
-}
-
-// NeighAdd will add or replace an IP to MAC mapping to the ARP table
-// Equivalent to: `ip neigh replace....`
-func NeighSet(neigh *Neigh) error {
- return neighAdd(neigh, syscall.NLM_F_CREATE)
-}
-
-// NeighAppend will append an entry to FDB
-// Equivalent to: `bridge fdb append...`
-func NeighAppend(neigh *Neigh) error {
- return neighAdd(neigh, syscall.NLM_F_CREATE|syscall.NLM_F_APPEND)
-}
-
-func neighAdd(neigh *Neigh, mode int) error {
- req := nl.NewNetlinkRequest(syscall.RTM_NEWNEIGH, mode|syscall.NLM_F_ACK)
- return neighHandle(neigh, req)
-}
-
-// NeighDel will delete an IP address from a link device.
-// Equivalent to: `ip addr del $addr dev $link`
-func NeighDel(neigh *Neigh) error {
- req := nl.NewNetlinkRequest(syscall.RTM_DELNEIGH, syscall.NLM_F_ACK)
- return neighHandle(neigh, req)
-}
-
-func neighHandle(neigh *Neigh, req *nl.NetlinkRequest) error {
- var family int
- if neigh.Family > 0 {
- family = neigh.Family
- } else {
- family = nl.GetIPFamily(neigh.IP)
- }
-
- msg := Ndmsg{
- Family: uint8(family),
- Index: uint32(neigh.LinkIndex),
- State: uint16(neigh.State),
- Type: uint8(neigh.Type),
- Flags: uint8(neigh.Flags),
- }
- req.AddData(&msg)
-
- ipData := neigh.IP.To4()
- if ipData == nil {
- ipData = neigh.IP.To16()
- }
-
- dstData := nl.NewRtAttr(NDA_DST, ipData)
- req.AddData(dstData)
-
- hwData := nl.NewRtAttr(NDA_LLADDR, []byte(neigh.HardwareAddr))
- req.AddData(hwData)
-
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-// NeighList gets a list of IP-MAC mappings in the system (ARP table).
-// Equivalent to: `ip neighbor show`.
-// The list can be filtered by link and ip family.
-func NeighList(linkIndex, family int) ([]Neigh, error) {
- req := nl.NewNetlinkRequest(syscall.RTM_GETNEIGH, syscall.NLM_F_DUMP)
- msg := Ndmsg{
- Family: uint8(family),
- }
- req.AddData(&msg)
-
- msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWNEIGH)
- if err != nil {
- return nil, err
- }
-
- var res []Neigh
- for _, m := range msgs {
- ndm := deserializeNdmsg(m)
- if linkIndex != 0 && int(ndm.Index) != linkIndex {
- // Ignore messages from other interfaces
- continue
- }
-
- neigh, err := NeighDeserialize(m)
- if err != nil {
- continue
- }
-
- res = append(res, *neigh)
- }
-
- return res, nil
-}
-
-func NeighDeserialize(m []byte) (*Neigh, error) {
- msg := deserializeNdmsg(m)
-
- neigh := Neigh{
- LinkIndex: int(msg.Index),
- Family: int(msg.Family),
- State: int(msg.State),
- Type: int(msg.Type),
- Flags: int(msg.Flags),
- }
-
- attrs, err := nl.ParseRouteAttr(m[msg.Len():])
- if err != nil {
- return nil, err
- }
-
- for _, attr := range attrs {
- switch attr.Attr.Type {
- case NDA_DST:
- neigh.IP = net.IP(attr.Value)
- case NDA_LLADDR:
- neigh.HardwareAddr = net.HardwareAddr(attr.Value)
- }
- }
-
- return &neigh, nil
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/netlink.go b/containerd/vendor/github.com/vishvananda/netlink/netlink.go
deleted file mode 100644
index 41ebdb1..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/netlink.go
+++ /dev/null
@@ -1,39 +0,0 @@
-// Package netlink provides a simple library for netlink. Netlink is
-// the interface a user-space program in linux uses to communicate with
-// the kernel. It can be used to add and remove interfaces, set up ip
-// addresses and routes, and confiugre ipsec. Netlink communication
-// requires elevated privileges, so in most cases this code needs to
-// be run as root. The low level primitives for netlink are contained
-// in the nl subpackage. This package attempts to provide a high-level
-// interface that is loosly modeled on the iproute2 cli.
-package netlink
-
-import (
- "net"
-
- "github.com/vishvananda/netlink/nl"
-)
-
-const (
- // Family type definitions
- FAMILY_ALL = nl.FAMILY_ALL
- FAMILY_V4 = nl.FAMILY_V4
- FAMILY_V6 = nl.FAMILY_V6
-)
-
-// ParseIPNet parses a string in ip/net format and returns a net.IPNet.
-// This is valuable because addresses in netlink are often IPNets and
-// ParseCIDR returns an IPNet with the IP part set to the base IP of the
-// range.
-func ParseIPNet(s string) (*net.IPNet, error) {
- ip, ipNet, err := net.ParseCIDR(s)
- if err != nil {
- return nil, err
- }
- return &net.IPNet{IP: ip, Mask: ipNet.Mask}, nil
-}
-
-// NewIPNet generates an IPNet from an ip address using a netmask of 32.
-func NewIPNet(ip net.IP) *net.IPNet {
- return &net.IPNet{IP: ip, Mask: net.CIDRMask(32, 32)}
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/netlink_unspecified.go b/containerd/vendor/github.com/vishvananda/netlink/netlink_unspecified.go
deleted file mode 100644
index 10c49c1..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/netlink_unspecified.go
+++ /dev/null
@@ -1,143 +0,0 @@
-// +build !linux
-
-package netlink
-
-import (
- "errors"
-)
-
-var (
- ErrNotImplemented = errors.New("not implemented")
-)
-
-func LinkSetUp(link *Link) error {
- return ErrNotImplemented
-}
-
-func LinkSetDown(link *Link) error {
- return ErrNotImplemented
-}
-
-func LinkSetMTU(link *Link, mtu int) error {
- return ErrNotImplemented
-}
-
-func LinkSetMaster(link *Link, master *Link) error {
- return ErrNotImplemented
-}
-
-func LinkSetNsPid(link *Link, nspid int) error {
- return ErrNotImplemented
-}
-
-func LinkSetNsFd(link *Link, fd int) error {
- return ErrNotImplemented
-}
-
-func LinkAdd(link *Link) error {
- return ErrNotImplemented
-}
-
-func LinkDel(link *Link) error {
- return ErrNotImplemented
-}
-
-func SetHairpin(link Link, mode bool) error {
- return ErrNotImplemented
-}
-
-func SetGuard(link Link, mode bool) error {
- return ErrNotImplemented
-}
-
-func SetFastLeave(link Link, mode bool) error {
- return ErrNotImplemented
-}
-
-func SetLearning(link Link, mode bool) error {
- return ErrNotImplemented
-}
-
-func SetRootBlock(link Link, mode bool) error {
- return ErrNotImplemented
-}
-
-func SetFlood(link Link, mode bool) error {
- return ErrNotImplemented
-}
-
-func LinkList() ([]Link, error) {
- return nil, ErrNotImplemented
-}
-
-func AddrAdd(link *Link, addr *Addr) error {
- return ErrNotImplemented
-}
-
-func AddrDel(link *Link, addr *Addr) error {
- return ErrNotImplemented
-}
-
-func AddrList(link *Link, family int) ([]Addr, error) {
- return nil, ErrNotImplemented
-}
-
-func RouteAdd(route *Route) error {
- return ErrNotImplemented
-}
-
-func RouteDel(route *Route) error {
- return ErrNotImplemented
-}
-
-func RouteList(link *Link, family int) ([]Route, error) {
- return nil, ErrNotImplemented
-}
-
-func XfrmPolicyAdd(policy *XfrmPolicy) error {
- return ErrNotImplemented
-}
-
-func XfrmPolicyDel(policy *XfrmPolicy) error {
- return ErrNotImplemented
-}
-
-func XfrmPolicyList(family int) ([]XfrmPolicy, error) {
- return nil, ErrNotImplemented
-}
-
-func XfrmStateAdd(policy *XfrmState) error {
- return ErrNotImplemented
-}
-
-func XfrmStateDel(policy *XfrmState) error {
- return ErrNotImplemented
-}
-
-func XfrmStateList(family int) ([]XfrmState, error) {
- return nil, ErrNotImplemented
-}
-
-func NeighAdd(neigh *Neigh) error {
- return ErrNotImplemented
-}
-
-func NeighSet(neigh *Neigh) error {
- return ErrNotImplemented
-}
-
-func NeighAppend(neigh *Neigh) error {
- return ErrNotImplemented
-}
-
-func NeighDel(neigh *Neigh) error {
- return ErrNotImplemented
-}
-
-func NeighList(linkIndex, family int) ([]Neigh, error) {
- return nil, ErrNotImplemented
-}
-
-func NeighDeserialize(m []byte) (*Ndmsg, *Neigh, error) {
- return nil, nil, ErrNotImplemented
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/nl/addr_linux.go b/containerd/vendor/github.com/vishvananda/netlink/nl/addr_linux.go
deleted file mode 100644
index 17088fa..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/nl/addr_linux.go
+++ /dev/null
@@ -1,47 +0,0 @@
-package nl
-
-import (
- "syscall"
- "unsafe"
-)
-
-type IfAddrmsg struct {
- syscall.IfAddrmsg
-}
-
-func NewIfAddrmsg(family int) *IfAddrmsg {
- return &IfAddrmsg{
- IfAddrmsg: syscall.IfAddrmsg{
- Family: uint8(family),
- },
- }
-}
-
-// struct ifaddrmsg {
-// __u8 ifa_family;
-// __u8 ifa_prefixlen; /* The prefix length */
-// __u8 ifa_flags; /* Flags */
-// __u8 ifa_scope; /* Address scope */
-// __u32 ifa_index; /* Link index */
-// };
-
-// type IfAddrmsg struct {
-// Family uint8
-// Prefixlen uint8
-// Flags uint8
-// Scope uint8
-// Index uint32
-// }
-// SizeofIfAddrmsg = 0x8
-
-func DeserializeIfAddrmsg(b []byte) *IfAddrmsg {
- return (*IfAddrmsg)(unsafe.Pointer(&b[0:syscall.SizeofIfAddrmsg][0]))
-}
-
-func (msg *IfAddrmsg) Serialize() []byte {
- return (*(*[syscall.SizeofIfAddrmsg]byte)(unsafe.Pointer(msg)))[:]
-}
-
-func (msg *IfAddrmsg) Len() int {
- return syscall.SizeofIfAddrmsg
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/nl/link_linux.go b/containerd/vendor/github.com/vishvananda/netlink/nl/link_linux.go
deleted file mode 100644
index 1f9ab08..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/nl/link_linux.go
+++ /dev/null
@@ -1,104 +0,0 @@
-package nl
-
-const (
- DEFAULT_CHANGE = 0xFFFFFFFF
-)
-
-const (
- IFLA_INFO_UNSPEC = iota
- IFLA_INFO_KIND
- IFLA_INFO_DATA
- IFLA_INFO_XSTATS
- IFLA_INFO_MAX = IFLA_INFO_XSTATS
-)
-
-const (
- IFLA_VLAN_UNSPEC = iota
- IFLA_VLAN_ID
- IFLA_VLAN_FLAGS
- IFLA_VLAN_EGRESS_QOS
- IFLA_VLAN_INGRESS_QOS
- IFLA_VLAN_PROTOCOL
- IFLA_VLAN_MAX = IFLA_VLAN_PROTOCOL
-)
-
-const (
- VETH_INFO_UNSPEC = iota
- VETH_INFO_PEER
- VETH_INFO_MAX = VETH_INFO_PEER
-)
-
-const (
- IFLA_VXLAN_UNSPEC = iota
- IFLA_VXLAN_ID
- IFLA_VXLAN_GROUP
- IFLA_VXLAN_LINK
- IFLA_VXLAN_LOCAL
- IFLA_VXLAN_TTL
- IFLA_VXLAN_TOS
- IFLA_VXLAN_LEARNING
- IFLA_VXLAN_AGEING
- IFLA_VXLAN_LIMIT
- IFLA_VXLAN_PORT_RANGE
- IFLA_VXLAN_PROXY
- IFLA_VXLAN_RSC
- IFLA_VXLAN_L2MISS
- IFLA_VXLAN_L3MISS
- IFLA_VXLAN_PORT
- IFLA_VXLAN_GROUP6
- IFLA_VXLAN_LOCAL6
- IFLA_VXLAN_UDP_CSUM
- IFLA_VXLAN_UDP_ZERO_CSUM6_TX
- IFLA_VXLAN_UDP_ZERO_CSUM6_RX
- IFLA_VXLAN_REMCSUM_TX
- IFLA_VXLAN_REMCSUM_RX
- IFLA_VXLAN_GBP
- IFLA_VXLAN_REMCSUM_NOPARTIAL
- IFLA_VXLAN_FLOWBASED
- IFLA_VXLAN_MAX = IFLA_VXLAN_FLOWBASED
-)
-
-const (
- BRIDGE_MODE_UNSPEC = iota
- BRIDGE_MODE_HAIRPIN
-)
-
-const (
- IFLA_BRPORT_UNSPEC = iota
- IFLA_BRPORT_STATE
- IFLA_BRPORT_PRIORITY
- IFLA_BRPORT_COST
- IFLA_BRPORT_MODE
- IFLA_BRPORT_GUARD
- IFLA_BRPORT_PROTECT
- IFLA_BRPORT_FAST_LEAVE
- IFLA_BRPORT_LEARNING
- IFLA_BRPORT_UNICAST_FLOOD
- IFLA_BRPORT_MAX = IFLA_BRPORT_UNICAST_FLOOD
-)
-
-const (
- IFLA_IPVLAN_UNSPEC = iota
- IFLA_IPVLAN_MODE
- IFLA_IPVLAN_MAX = IFLA_IPVLAN_MODE
-)
-
-const (
- // not defined in syscall
- IFLA_NET_NS_FD = 28
-)
-
-const (
- IFLA_MACVLAN_UNSPEC = iota
- IFLA_MACVLAN_MODE
- IFLA_MACVLAN_FLAGS
- IFLA_MACVLAN_MAX = IFLA_MACVLAN_FLAGS
-)
-
-const (
- MACVLAN_MODE_PRIVATE = 1
- MACVLAN_MODE_VEPA = 2
- MACVLAN_MODE_BRIDGE = 4
- MACVLAN_MODE_PASSTHRU = 8
- MACVLAN_MODE_SOURCE = 16
-)
diff --git a/containerd/vendor/github.com/vishvananda/netlink/nl/nl_linux.go b/containerd/vendor/github.com/vishvananda/netlink/nl/nl_linux.go
deleted file mode 100644
index 8dbd92b..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/nl/nl_linux.go
+++ /dev/null
@@ -1,418 +0,0 @@
-// Package nl has low level primitives for making Netlink calls.
-package nl
-
-import (
- "bytes"
- "encoding/binary"
- "fmt"
- "net"
- "sync/atomic"
- "syscall"
- "unsafe"
-)
-
-const (
- // Family type definitions
- FAMILY_ALL = syscall.AF_UNSPEC
- FAMILY_V4 = syscall.AF_INET
- FAMILY_V6 = syscall.AF_INET6
-)
-
-var nextSeqNr uint32
-
-// GetIPFamily returns the family type of a net.IP.
-func GetIPFamily(ip net.IP) int {
- if len(ip) <= net.IPv4len {
- return FAMILY_V4
- }
- if ip.To4() != nil {
- return FAMILY_V4
- }
- return FAMILY_V6
-}
-
-var nativeEndian binary.ByteOrder
-
-// Get native endianness for the system
-func NativeEndian() binary.ByteOrder {
- if nativeEndian == nil {
- var x uint32 = 0x01020304
- if *(*byte)(unsafe.Pointer(&x)) == 0x01 {
- nativeEndian = binary.BigEndian
- } else {
- nativeEndian = binary.LittleEndian
- }
- }
- return nativeEndian
-}
-
-// Byte swap a 16 bit value if we aren't big endian
-func Swap16(i uint16) uint16 {
- if NativeEndian() == binary.BigEndian {
- return i
- }
- return (i&0xff00)>>8 | (i&0xff)<<8
-}
-
-// Byte swap a 32 bit value if aren't big endian
-func Swap32(i uint32) uint32 {
- if NativeEndian() == binary.BigEndian {
- return i
- }
- return (i&0xff000000)>>24 | (i&0xff0000)>>8 | (i&0xff00)<<8 | (i&0xff)<<24
-}
-
-type NetlinkRequestData interface {
- Len() int
- Serialize() []byte
-}
-
-// IfInfomsg is related to links, but it is used for list requests as well
-type IfInfomsg struct {
- syscall.IfInfomsg
-}
-
-// Create an IfInfomsg with family specified
-func NewIfInfomsg(family int) *IfInfomsg {
- return &IfInfomsg{
- IfInfomsg: syscall.IfInfomsg{
- Family: uint8(family),
- },
- }
-}
-
-func DeserializeIfInfomsg(b []byte) *IfInfomsg {
- return (*IfInfomsg)(unsafe.Pointer(&b[0:syscall.SizeofIfInfomsg][0]))
-}
-
-func (msg *IfInfomsg) Serialize() []byte {
- return (*(*[syscall.SizeofIfInfomsg]byte)(unsafe.Pointer(msg)))[:]
-}
-
-func (msg *IfInfomsg) Len() int {
- return syscall.SizeofIfInfomsg
-}
-
-func rtaAlignOf(attrlen int) int {
- return (attrlen + syscall.RTA_ALIGNTO - 1) & ^(syscall.RTA_ALIGNTO - 1)
-}
-
-func NewIfInfomsgChild(parent *RtAttr, family int) *IfInfomsg {
- msg := NewIfInfomsg(family)
- parent.children = append(parent.children, msg)
- return msg
-}
-
-// Extend RtAttr to handle data and children
-type RtAttr struct {
- syscall.RtAttr
- Data []byte
- children []NetlinkRequestData
-}
-
-// Create a new Extended RtAttr object
-func NewRtAttr(attrType int, data []byte) *RtAttr {
- return &RtAttr{
- RtAttr: syscall.RtAttr{
- Type: uint16(attrType),
- },
- children: []NetlinkRequestData{},
- Data: data,
- }
-}
-
-// Create a new RtAttr obj anc add it as a child of an existing object
-func NewRtAttrChild(parent *RtAttr, attrType int, data []byte) *RtAttr {
- attr := NewRtAttr(attrType, data)
- parent.children = append(parent.children, attr)
- return attr
-}
-
-func (a *RtAttr) Len() int {
- if len(a.children) == 0 {
- return (syscall.SizeofRtAttr + len(a.Data))
- }
-
- l := 0
- for _, child := range a.children {
- l += rtaAlignOf(child.Len())
- }
- l += syscall.SizeofRtAttr
- return rtaAlignOf(l + len(a.Data))
-}
-
-// Serialize the RtAttr into a byte array
-// This can't just unsafe.cast because it must iterate through children.
-func (a *RtAttr) Serialize() []byte {
- native := NativeEndian()
-
- length := a.Len()
- buf := make([]byte, rtaAlignOf(length))
-
- if a.Data != nil {
- copy(buf[4:], a.Data)
- } else {
- next := 4
- for _, child := range a.children {
- childBuf := child.Serialize()
- copy(buf[next:], childBuf)
- next += rtaAlignOf(len(childBuf))
- }
- }
-
- if l := uint16(length); l != 0 {
- native.PutUint16(buf[0:2], l)
- }
- native.PutUint16(buf[2:4], a.Type)
- return buf
-}
-
-type NetlinkRequest struct {
- syscall.NlMsghdr
- Data []NetlinkRequestData
-}
-
-// Serialize the Netlink Request into a byte array
-func (req *NetlinkRequest) Serialize() []byte {
- length := syscall.SizeofNlMsghdr
- dataBytes := make([][]byte, len(req.Data))
- for i, data := range req.Data {
- dataBytes[i] = data.Serialize()
- length = length + len(dataBytes[i])
- }
- req.Len = uint32(length)
- b := make([]byte, length)
- hdr := (*(*[syscall.SizeofNlMsghdr]byte)(unsafe.Pointer(req)))[:]
- next := syscall.SizeofNlMsghdr
- copy(b[0:next], hdr)
- for _, data := range dataBytes {
- for _, dataByte := range data {
- b[next] = dataByte
- next = next + 1
- }
- }
- return b
-}
-
-func (req *NetlinkRequest) AddData(data NetlinkRequestData) {
- if data != nil {
- req.Data = append(req.Data, data)
- }
-}
-
-// Execute the request against a the given sockType.
-// Returns a list of netlink messages in seriaized format, optionally filtered
-// by resType.
-func (req *NetlinkRequest) Execute(sockType int, resType uint16) ([][]byte, error) {
- s, err := getNetlinkSocket(sockType)
- if err != nil {
- return nil, err
- }
- defer s.Close()
-
- if err := s.Send(req); err != nil {
- return nil, err
- }
-
- pid, err := s.GetPid()
- if err != nil {
- return nil, err
- }
-
- var res [][]byte
-
-done:
- for {
- msgs, err := s.Receive()
- if err != nil {
- return nil, err
- }
- for _, m := range msgs {
- if m.Header.Seq != req.Seq {
- return nil, fmt.Errorf("Wrong Seq nr %d, expected 1", m.Header.Seq)
- }
- if m.Header.Pid != pid {
- return nil, fmt.Errorf("Wrong pid %d, expected %d", m.Header.Pid, pid)
- }
- if m.Header.Type == syscall.NLMSG_DONE {
- break done
- }
- if m.Header.Type == syscall.NLMSG_ERROR {
- native := NativeEndian()
- error := int32(native.Uint32(m.Data[0:4]))
- if error == 0 {
- break done
- }
- return nil, syscall.Errno(-error)
- }
- if resType != 0 && m.Header.Type != resType {
- continue
- }
- res = append(res, m.Data)
- if m.Header.Flags&syscall.NLM_F_MULTI == 0 {
- break done
- }
- }
- }
- return res, nil
-}
-
-// Create a new netlink request from proto and flags
-// Note the Len value will be inaccurate once data is added until
-// the message is serialized
-func NewNetlinkRequest(proto, flags int) *NetlinkRequest {
- return &NetlinkRequest{
- NlMsghdr: syscall.NlMsghdr{
- Len: uint32(syscall.SizeofNlMsghdr),
- Type: uint16(proto),
- Flags: syscall.NLM_F_REQUEST | uint16(flags),
- Seq: atomic.AddUint32(&nextSeqNr, 1),
- },
- }
-}
-
-type NetlinkSocket struct {
- fd int
- lsa syscall.SockaddrNetlink
-}
-
-func getNetlinkSocket(protocol int) (*NetlinkSocket, error) {
- fd, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW, protocol)
- if err != nil {
- return nil, err
- }
- s := &NetlinkSocket{
- fd: fd,
- }
- s.lsa.Family = syscall.AF_NETLINK
- if err := syscall.Bind(fd, &s.lsa); err != nil {
- syscall.Close(fd)
- return nil, err
- }
-
- return s, nil
-}
-
-// Create a netlink socket with a given protocol (e.g. NETLINK_ROUTE)
-// and subscribe it to multicast groups passed in variable argument list.
-// Returns the netlink socket on which Receive() method can be called
-// to retrieve the messages from the kernel.
-func Subscribe(protocol int, groups ...uint) (*NetlinkSocket, error) {
- fd, err := syscall.Socket(syscall.AF_NETLINK, syscall.SOCK_RAW, protocol)
- if err != nil {
- return nil, err
- }
- s := &NetlinkSocket{
- fd: fd,
- }
- s.lsa.Family = syscall.AF_NETLINK
-
- for _, g := range groups {
- s.lsa.Groups |= (1 << (g - 1))
- }
-
- if err := syscall.Bind(fd, &s.lsa); err != nil {
- syscall.Close(fd)
- return nil, err
- }
-
- return s, nil
-}
-
-func (s *NetlinkSocket) Close() {
- syscall.Close(s.fd)
-}
-
-func (s *NetlinkSocket) Send(request *NetlinkRequest) error {
- if err := syscall.Sendto(s.fd, request.Serialize(), 0, &s.lsa); err != nil {
- return err
- }
- return nil
-}
-
-func (s *NetlinkSocket) Receive() ([]syscall.NetlinkMessage, error) {
- rb := make([]byte, syscall.Getpagesize())
- nr, _, err := syscall.Recvfrom(s.fd, rb, 0)
- if err != nil {
- return nil, err
- }
- if nr < syscall.NLMSG_HDRLEN {
- return nil, fmt.Errorf("Got short response from netlink")
- }
- rb = rb[:nr]
- return syscall.ParseNetlinkMessage(rb)
-}
-
-func (s *NetlinkSocket) GetPid() (uint32, error) {
- lsa, err := syscall.Getsockname(s.fd)
- if err != nil {
- return 0, err
- }
- switch v := lsa.(type) {
- case *syscall.SockaddrNetlink:
- return v.Pid, nil
- }
- return 0, fmt.Errorf("Wrong socket type")
-}
-
-func ZeroTerminated(s string) []byte {
- bytes := make([]byte, len(s)+1)
- for i := 0; i < len(s); i++ {
- bytes[i] = s[i]
- }
- bytes[len(s)] = 0
- return bytes
-}
-
-func NonZeroTerminated(s string) []byte {
- bytes := make([]byte, len(s))
- for i := 0; i < len(s); i++ {
- bytes[i] = s[i]
- }
- return bytes
-}
-
-func BytesToString(b []byte) string {
- n := bytes.Index(b, []byte{0})
- return string(b[:n])
-}
-
-func Uint8Attr(v uint8) []byte {
- return []byte{byte(v)}
-}
-
-func Uint16Attr(v uint16) []byte {
- native := NativeEndian()
- bytes := make([]byte, 2)
- native.PutUint16(bytes, v)
- return bytes
-}
-
-func Uint32Attr(v uint32) []byte {
- native := NativeEndian()
- bytes := make([]byte, 4)
- native.PutUint32(bytes, v)
- return bytes
-}
-
-func ParseRouteAttr(b []byte) ([]syscall.NetlinkRouteAttr, error) {
- var attrs []syscall.NetlinkRouteAttr
- for len(b) >= syscall.SizeofRtAttr {
- a, vbuf, alen, err := netlinkRouteAttrAndValue(b)
- if err != nil {
- return nil, err
- }
- ra := syscall.NetlinkRouteAttr{Attr: *a, Value: vbuf[:int(a.Len)-syscall.SizeofRtAttr]}
- attrs = append(attrs, ra)
- b = b[alen:]
- }
- return attrs, nil
-}
-
-func netlinkRouteAttrAndValue(b []byte) (*syscall.RtAttr, []byte, int, error) {
- a := (*syscall.RtAttr)(unsafe.Pointer(&b[0]))
- if int(a.Len) < syscall.SizeofRtAttr || int(a.Len) > len(b) {
- return nil, nil, 0, syscall.EINVAL
- }
- return a, b[syscall.SizeofRtAttr:], rtaAlignOf(int(a.Len)), nil
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/nl/route_linux.go b/containerd/vendor/github.com/vishvananda/netlink/nl/route_linux.go
deleted file mode 100644
index 447e83e..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/nl/route_linux.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package nl
-
-import (
- "syscall"
- "unsafe"
-)
-
-type RtMsg struct {
- syscall.RtMsg
-}
-
-func NewRtMsg() *RtMsg {
- return &RtMsg{
- RtMsg: syscall.RtMsg{
- Table: syscall.RT_TABLE_MAIN,
- Scope: syscall.RT_SCOPE_UNIVERSE,
- Protocol: syscall.RTPROT_BOOT,
- Type: syscall.RTN_UNICAST,
- },
- }
-}
-
-func NewRtDelMsg() *RtMsg {
- return &RtMsg{
- RtMsg: syscall.RtMsg{
- Table: syscall.RT_TABLE_MAIN,
- Scope: syscall.RT_SCOPE_NOWHERE,
- },
- }
-}
-
-func (msg *RtMsg) Len() int {
- return syscall.SizeofRtMsg
-}
-
-func DeserializeRtMsg(b []byte) *RtMsg {
- return (*RtMsg)(unsafe.Pointer(&b[0:syscall.SizeofRtMsg][0]))
-}
-
-func (msg *RtMsg) Serialize() []byte {
- return (*(*[syscall.SizeofRtMsg]byte)(unsafe.Pointer(msg)))[:]
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/nl/tc_linux.go b/containerd/vendor/github.com/vishvananda/netlink/nl/tc_linux.go
deleted file mode 100644
index 890979e..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/nl/tc_linux.go
+++ /dev/null
@@ -1,425 +0,0 @@
-package nl
-
-import (
- "unsafe"
-)
-
-// Message types
-const (
- TCA_UNSPEC = iota
- TCA_KIND
- TCA_OPTIONS
- TCA_STATS
- TCA_XSTATS
- TCA_RATE
- TCA_FCNT
- TCA_STATS2
- TCA_STAB
- TCA_MAX = TCA_STAB
-)
-
-const (
- TCA_ACT_TAB = 1
- TCAA_MAX = 1
-)
-
-const (
- TCA_PRIO_UNSPEC = iota
- TCA_PRIO_MQ
- TCA_PRIO_MAX = TCA_PRIO_MQ
-)
-
-const (
- SizeofTcMsg = 0x14
- SizeofTcActionMsg = 0x04
- SizeofTcPrioMap = 0x14
- SizeofTcRateSpec = 0x0c
- SizeofTcTbfQopt = 2*SizeofTcRateSpec + 0x0c
- SizeofTcHtbCopt = 2*SizeofTcRateSpec + 0x14
- SizeofTcHtbGlob = 0x14
- SizeofTcU32Key = 0x10
- SizeofTcU32Sel = 0x10 // without keys
- SizeofTcMirred = 0x1c
-)
-
-// struct tcmsg {
-// unsigned char tcm_family;
-// unsigned char tcm__pad1;
-// unsigned short tcm__pad2;
-// int tcm_ifindex;
-// __u32 tcm_handle;
-// __u32 tcm_parent;
-// __u32 tcm_info;
-// };
-
-type TcMsg struct {
- Family uint8
- Pad [3]byte
- Ifindex int32
- Handle uint32
- Parent uint32
- Info uint32
-}
-
-func (msg *TcMsg) Len() int {
- return SizeofTcMsg
-}
-
-func DeserializeTcMsg(b []byte) *TcMsg {
- return (*TcMsg)(unsafe.Pointer(&b[0:SizeofTcMsg][0]))
-}
-
-func (x *TcMsg) Serialize() []byte {
- return (*(*[SizeofTcMsg]byte)(unsafe.Pointer(x)))[:]
-}
-
-// struct tcamsg {
-// unsigned char tca_family;
-// unsigned char tca__pad1;
-// unsigned short tca__pad2;
-// };
-
-type TcActionMsg struct {
- Family uint8
- Pad [3]byte
-}
-
-func (msg *TcActionMsg) Len() int {
- return SizeofTcActionMsg
-}
-
-func DeserializeTcActionMsg(b []byte) *TcActionMsg {
- return (*TcActionMsg)(unsafe.Pointer(&b[0:SizeofTcActionMsg][0]))
-}
-
-func (x *TcActionMsg) Serialize() []byte {
- return (*(*[SizeofTcActionMsg]byte)(unsafe.Pointer(x)))[:]
-}
-
-const (
- TC_PRIO_MAX = 15
-)
-
-// struct tc_prio_qopt {
-// int bands; /* Number of bands */
-// __u8 priomap[TC_PRIO_MAX+1]; /* Map: logical priority -> PRIO band */
-// };
-
-type TcPrioMap struct {
- Bands int32
- Priomap [TC_PRIO_MAX + 1]uint8
-}
-
-func (msg *TcPrioMap) Len() int {
- return SizeofTcPrioMap
-}
-
-func DeserializeTcPrioMap(b []byte) *TcPrioMap {
- return (*TcPrioMap)(unsafe.Pointer(&b[0:SizeofTcPrioMap][0]))
-}
-
-func (x *TcPrioMap) Serialize() []byte {
- return (*(*[SizeofTcPrioMap]byte)(unsafe.Pointer(x)))[:]
-}
-
-const (
- TCA_TBF_UNSPEC = iota
- TCA_TBF_PARMS
- TCA_TBF_RTAB
- TCA_TBF_PTAB
- TCA_TBF_RATE64
- TCA_TBF_PRATE64
- TCA_TBF_BURST
- TCA_TBF_PBURST
- TCA_TBF_MAX = TCA_TBF_PBURST
-)
-
-// struct tc_ratespec {
-// unsigned char cell_log;
-// __u8 linklayer; /* lower 4 bits */
-// unsigned short overhead;
-// short cell_align;
-// unsigned short mpu;
-// __u32 rate;
-// };
-
-type TcRateSpec struct {
- CellLog uint8
- Linklayer uint8
- Overhead uint16
- CellAlign int16
- Mpu uint16
- Rate uint32
-}
-
-func (msg *TcRateSpec) Len() int {
- return SizeofTcRateSpec
-}
-
-func DeserializeTcRateSpec(b []byte) *TcRateSpec {
- return (*TcRateSpec)(unsafe.Pointer(&b[0:SizeofTcRateSpec][0]))
-}
-
-func (x *TcRateSpec) Serialize() []byte {
- return (*(*[SizeofTcRateSpec]byte)(unsafe.Pointer(x)))[:]
-}
-
-// struct tc_tbf_qopt {
-// struct tc_ratespec rate;
-// struct tc_ratespec peakrate;
-// __u32 limit;
-// __u32 buffer;
-// __u32 mtu;
-// };
-
-type TcTbfQopt struct {
- Rate TcRateSpec
- Peakrate TcRateSpec
- Limit uint32
- Buffer uint32
- Mtu uint32
-}
-
-func (msg *TcTbfQopt) Len() int {
- return SizeofTcTbfQopt
-}
-
-func DeserializeTcTbfQopt(b []byte) *TcTbfQopt {
- return (*TcTbfQopt)(unsafe.Pointer(&b[0:SizeofTcTbfQopt][0]))
-}
-
-func (x *TcTbfQopt) Serialize() []byte {
- return (*(*[SizeofTcTbfQopt]byte)(unsafe.Pointer(x)))[:]
-}
-
-const (
- TCA_HTB_UNSPEC = iota
- TCA_HTB_PARMS
- TCA_HTB_INIT
- TCA_HTB_CTAB
- TCA_HTB_RTAB
- TCA_HTB_DIRECT_QLEN
- TCA_HTB_RATE64
- TCA_HTB_CEIL64
- TCA_HTB_MAX = TCA_HTB_CEIL64
-)
-
-//struct tc_htb_opt {
-// struct tc_ratespec rate;
-// struct tc_ratespec ceil;
-// __u32 buffer;
-// __u32 cbuffer;
-// __u32 quantum;
-// __u32 level; /* out only */
-// __u32 prio;
-//};
-
-type TcHtbCopt struct {
- Rate TcRateSpec
- Ceil TcRateSpec
- Buffer uint32
- Cbuffer uint32
- Quantum uint32
- Level uint32
- Prio uint32
-}
-
-func (msg *TcHtbCopt) Len() int {
- return SizeofTcHtbCopt
-}
-
-func DeserializeTcHtbCopt(b []byte) *TcHtbCopt {
- return (*TcHtbCopt)(unsafe.Pointer(&b[0:SizeofTcHtbCopt][0]))
-}
-
-func (x *TcHtbCopt) Serialize() []byte {
- return (*(*[SizeofTcHtbCopt]byte)(unsafe.Pointer(x)))[:]
-}
-
-type TcHtbGlob struct {
- Version uint32
- Rate2Quantum uint32
- Defcls uint32
- Debug uint32
- DirectPkts uint32
-}
-
-func (msg *TcHtbGlob) Len() int {
- return SizeofTcHtbGlob
-}
-
-func DeserializeTcHtbGlob(b []byte) *TcHtbGlob {
- return (*TcHtbGlob)(unsafe.Pointer(&b[0:SizeofTcHtbGlob][0]))
-}
-
-func (x *TcHtbGlob) Serialize() []byte {
- return (*(*[SizeofTcHtbGlob]byte)(unsafe.Pointer(x)))[:]
-}
-
-const (
- TCA_U32_UNSPEC = iota
- TCA_U32_CLASSID
- TCA_U32_HASH
- TCA_U32_LINK
- TCA_U32_DIVISOR
- TCA_U32_SEL
- TCA_U32_POLICE
- TCA_U32_ACT
- TCA_U32_INDEV
- TCA_U32_PCNT
- TCA_U32_MARK
- TCA_U32_MAX = TCA_U32_MARK
-)
-
-// struct tc_u32_key {
-// __be32 mask;
-// __be32 val;
-// int off;
-// int offmask;
-// };
-
-type TcU32Key struct {
- Mask uint32 // big endian
- Val uint32 // big endian
- Off int32
- OffMask int32
-}
-
-func (msg *TcU32Key) Len() int {
- return SizeofTcU32Key
-}
-
-func DeserializeTcU32Key(b []byte) *TcU32Key {
- return (*TcU32Key)(unsafe.Pointer(&b[0:SizeofTcU32Key][0]))
-}
-
-func (x *TcU32Key) Serialize() []byte {
- return (*(*[SizeofTcU32Key]byte)(unsafe.Pointer(x)))[:]
-}
-
-// struct tc_u32_sel {
-// unsigned char flags;
-// unsigned char offshift;
-// unsigned char nkeys;
-//
-// __be16 offmask;
-// __u16 off;
-// short offoff;
-//
-// short hoff;
-// __be32 hmask;
-// struct tc_u32_key keys[0];
-// };
-
-const (
- TC_U32_TERMINAL = 1 << iota
- TC_U32_OFFSET = 1 << iota
- TC_U32_VAROFFSET = 1 << iota
- TC_U32_EAT = 1 << iota
-)
-
-type TcU32Sel struct {
- Flags uint8
- Offshift uint8
- Nkeys uint8
- Pad uint8
- Offmask uint16 // big endian
- Off uint16
- Offoff int16
- Hoff int16
- Hmask uint32 // big endian
- Keys []TcU32Key
-}
-
-func (msg *TcU32Sel) Len() int {
- return SizeofTcU32Sel + int(msg.Nkeys)*SizeofTcU32Key
-}
-
-func DeserializeTcU32Sel(b []byte) *TcU32Sel {
- x := &TcU32Sel{}
- copy((*(*[SizeofTcU32Sel]byte)(unsafe.Pointer(x)))[:], b)
- next := SizeofTcU32Sel
- var i uint8
- for i = 0; i < x.Nkeys; i++ {
- x.Keys = append(x.Keys, *DeserializeTcU32Key(b[next:]))
- next += SizeofTcU32Key
- }
- return x
-}
-
-func (x *TcU32Sel) Serialize() []byte {
- // This can't just unsafe.cast because it must iterate through keys.
- buf := make([]byte, x.Len())
- copy(buf, (*(*[SizeofTcU32Sel]byte)(unsafe.Pointer(x)))[:])
- next := SizeofTcU32Sel
- for _, key := range x.Keys {
- keyBuf := key.Serialize()
- copy(buf[next:], keyBuf)
- next += SizeofTcU32Key
- }
- return buf
-}
-
-const (
- TCA_ACT_MIRRED = 8
-)
-
-const (
- TCA_MIRRED_UNSPEC = iota
- TCA_MIRRED_TM
- TCA_MIRRED_PARMS
- TCA_MIRRED_MAX = TCA_MIRRED_PARMS
-)
-
-const (
- TCA_EGRESS_REDIR = 1 /* packet redirect to EGRESS*/
- TCA_EGRESS_MIRROR = 2 /* mirror packet to EGRESS */
- TCA_INGRESS_REDIR = 3 /* packet redirect to INGRESS*/
- TCA_INGRESS_MIRROR = 4 /* mirror packet to INGRESS */
-)
-
-const (
- TC_ACT_UNSPEC = int32(-1)
- TC_ACT_OK = 0
- TC_ACT_RECLASSIFY = 1
- TC_ACT_SHOT = 2
- TC_ACT_PIPE = 3
- TC_ACT_STOLEN = 4
- TC_ACT_QUEUED = 5
- TC_ACT_REPEAT = 6
- TC_ACT_JUMP = 0x10000000
-)
-
-// #define tc_gen \
-// __u32 index; \
-// __u32 capab; \
-// int action; \
-// int refcnt; \
-// int bindcnt
-// struct tc_mirred {
-// tc_gen;
-// int eaction; /* one of IN/EGRESS_MIRROR/REDIR */
-// __u32 ifindex; /* ifindex of egress port */
-// };
-
-type TcMirred struct {
- Index uint32
- Capab uint32
- Action int32
- Refcnt int32
- Bindcnt int32
- Eaction int32
- Ifindex uint32
-}
-
-func (msg *TcMirred) Len() int {
- return SizeofTcMirred
-}
-
-func DeserializeTcMirred(b []byte) *TcMirred {
- return (*TcMirred)(unsafe.Pointer(&b[0:SizeofTcMirred][0]))
-}
-
-func (x *TcMirred) Serialize() []byte {
- return (*(*[SizeofTcMirred]byte)(unsafe.Pointer(x)))[:]
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/nl/xfrm_linux.go b/containerd/vendor/github.com/vishvananda/netlink/nl/xfrm_linux.go
deleted file mode 100644
index d24637d..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/nl/xfrm_linux.go
+++ /dev/null
@@ -1,258 +0,0 @@
-package nl
-
-import (
- "bytes"
- "net"
- "unsafe"
-)
-
-// Infinity for packet and byte counts
-const (
- XFRM_INF = ^uint64(0)
-)
-
-// Message Types
-const (
- XFRM_MSG_BASE = 0x10
- XFRM_MSG_NEWSA = 0x10
- XFRM_MSG_DELSA = 0x11
- XFRM_MSG_GETSA = 0x12
- XFRM_MSG_NEWPOLICY = 0x13
- XFRM_MSG_DELPOLICY = 0x14
- XFRM_MSG_GETPOLICY = 0x15
- XFRM_MSG_ALLOCSPI = 0x16
- XFRM_MSG_ACQUIRE = 0x17
- XFRM_MSG_EXPIRE = 0x18
- XFRM_MSG_UPDPOLICY = 0x19
- XFRM_MSG_UPDSA = 0x1a
- XFRM_MSG_POLEXPIRE = 0x1b
- XFRM_MSG_FLUSHSA = 0x1c
- XFRM_MSG_FLUSHPOLICY = 0x1d
- XFRM_MSG_NEWAE = 0x1e
- XFRM_MSG_GETAE = 0x1f
- XFRM_MSG_REPORT = 0x20
- XFRM_MSG_MIGRATE = 0x21
- XFRM_MSG_NEWSADINFO = 0x22
- XFRM_MSG_GETSADINFO = 0x23
- XFRM_MSG_NEWSPDINFO = 0x24
- XFRM_MSG_GETSPDINFO = 0x25
- XFRM_MSG_MAPPING = 0x26
- XFRM_MSG_MAX = 0x26
- XFRM_NR_MSGTYPES = 0x17
-)
-
-// Attribute types
-const (
- /* Netlink message attributes. */
- XFRMA_UNSPEC = 0x00
- XFRMA_ALG_AUTH = 0x01 /* struct xfrm_algo */
- XFRMA_ALG_CRYPT = 0x02 /* struct xfrm_algo */
- XFRMA_ALG_COMP = 0x03 /* struct xfrm_algo */
- XFRMA_ENCAP = 0x04 /* struct xfrm_algo + struct xfrm_encap_tmpl */
- XFRMA_TMPL = 0x05 /* 1 or more struct xfrm_user_tmpl */
- XFRMA_SA = 0x06 /* struct xfrm_usersa_info */
- XFRMA_POLICY = 0x07 /* struct xfrm_userpolicy_info */
- XFRMA_SEC_CTX = 0x08 /* struct xfrm_sec_ctx */
- XFRMA_LTIME_VAL = 0x09
- XFRMA_REPLAY_VAL = 0x0a
- XFRMA_REPLAY_THRESH = 0x0b
- XFRMA_ETIMER_THRESH = 0x0c
- XFRMA_SRCADDR = 0x0d /* xfrm_address_t */
- XFRMA_COADDR = 0x0e /* xfrm_address_t */
- XFRMA_LASTUSED = 0x0f /* unsigned long */
- XFRMA_POLICY_TYPE = 0x10 /* struct xfrm_userpolicy_type */
- XFRMA_MIGRATE = 0x11
- XFRMA_ALG_AEAD = 0x12 /* struct xfrm_algo_aead */
- XFRMA_KMADDRESS = 0x13 /* struct xfrm_user_kmaddress */
- XFRMA_ALG_AUTH_TRUNC = 0x14 /* struct xfrm_algo_auth */
- XFRMA_MARK = 0x15 /* struct xfrm_mark */
- XFRMA_TFCPAD = 0x16 /* __u32 */
- XFRMA_REPLAY_ESN_VAL = 0x17 /* struct xfrm_replay_esn */
- XFRMA_SA_EXTRA_FLAGS = 0x18 /* __u32 */
- XFRMA_MAX = 0x18
-)
-
-const (
- SizeofXfrmAddress = 0x10
- SizeofXfrmSelector = 0x38
- SizeofXfrmLifetimeCfg = 0x40
- SizeofXfrmLifetimeCur = 0x20
- SizeofXfrmId = 0x18
-)
-
-// typedef union {
-// __be32 a4;
-// __be32 a6[4];
-// } xfrm_address_t;
-
-type XfrmAddress [SizeofXfrmAddress]byte
-
-func (x *XfrmAddress) ToIP() net.IP {
- var empty = [12]byte{}
- ip := make(net.IP, net.IPv6len)
- if bytes.Equal(x[4:16], empty[:]) {
- ip[10] = 0xff
- ip[11] = 0xff
- copy(ip[12:16], x[0:4])
- } else {
- copy(ip[:], x[:])
- }
- return ip
-}
-
-func (x *XfrmAddress) ToIPNet(prefixlen uint8) *net.IPNet {
- ip := x.ToIP()
- if GetIPFamily(ip) == FAMILY_V4 {
- return &net.IPNet{IP: ip, Mask: net.CIDRMask(int(prefixlen), 32)}
- }
- return &net.IPNet{IP: ip, Mask: net.CIDRMask(int(prefixlen), 128)}
-}
-
-func (x *XfrmAddress) FromIP(ip net.IP) {
- var empty = [16]byte{}
- if len(ip) < net.IPv4len {
- copy(x[4:16], empty[:])
- } else if GetIPFamily(ip) == FAMILY_V4 {
- copy(x[0:4], ip.To4()[0:4])
- copy(x[4:16], empty[:12])
- } else {
- copy(x[0:16], ip.To16()[0:16])
- }
-}
-
-func DeserializeXfrmAddress(b []byte) *XfrmAddress {
- return (*XfrmAddress)(unsafe.Pointer(&b[0:SizeofXfrmAddress][0]))
-}
-
-func (x *XfrmAddress) Serialize() []byte {
- return (*(*[SizeofXfrmAddress]byte)(unsafe.Pointer(x)))[:]
-}
-
-// struct xfrm_selector {
-// xfrm_address_t daddr;
-// xfrm_address_t saddr;
-// __be16 dport;
-// __be16 dport_mask;
-// __be16 sport;
-// __be16 sport_mask;
-// __u16 family;
-// __u8 prefixlen_d;
-// __u8 prefixlen_s;
-// __u8 proto;
-// int ifindex;
-// __kernel_uid32_t user;
-// };
-
-type XfrmSelector struct {
- Daddr XfrmAddress
- Saddr XfrmAddress
- Dport uint16 // big endian
- DportMask uint16 // big endian
- Sport uint16 // big endian
- SportMask uint16 // big endian
- Family uint16
- PrefixlenD uint8
- PrefixlenS uint8
- Proto uint8
- Pad [3]byte
- Ifindex int32
- User uint32
-}
-
-func (msg *XfrmSelector) Len() int {
- return SizeofXfrmSelector
-}
-
-func DeserializeXfrmSelector(b []byte) *XfrmSelector {
- return (*XfrmSelector)(unsafe.Pointer(&b[0:SizeofXfrmSelector][0]))
-}
-
-func (msg *XfrmSelector) Serialize() []byte {
- return (*(*[SizeofXfrmSelector]byte)(unsafe.Pointer(msg)))[:]
-}
-
-// struct xfrm_lifetime_cfg {
-// __u64 soft_byte_limit;
-// __u64 hard_byte_limit;
-// __u64 soft_packet_limit;
-// __u64 hard_packet_limit;
-// __u64 soft_add_expires_seconds;
-// __u64 hard_add_expires_seconds;
-// __u64 soft_use_expires_seconds;
-// __u64 hard_use_expires_seconds;
-// };
-//
-
-type XfrmLifetimeCfg struct {
- SoftByteLimit uint64
- HardByteLimit uint64
- SoftPacketLimit uint64
- HardPacketLimit uint64
- SoftAddExpiresSeconds uint64
- HardAddExpiresSeconds uint64
- SoftUseExpiresSeconds uint64
- HardUseExpiresSeconds uint64
-}
-
-func (msg *XfrmLifetimeCfg) Len() int {
- return SizeofXfrmLifetimeCfg
-}
-
-func DeserializeXfrmLifetimeCfg(b []byte) *XfrmLifetimeCfg {
- return (*XfrmLifetimeCfg)(unsafe.Pointer(&b[0:SizeofXfrmLifetimeCfg][0]))
-}
-
-func (msg *XfrmLifetimeCfg) Serialize() []byte {
- return (*(*[SizeofXfrmLifetimeCfg]byte)(unsafe.Pointer(msg)))[:]
-}
-
-// struct xfrm_lifetime_cur {
-// __u64 bytes;
-// __u64 packets;
-// __u64 add_time;
-// __u64 use_time;
-// };
-
-type XfrmLifetimeCur struct {
- Bytes uint64
- Packets uint64
- AddTime uint64
- UseTime uint64
-}
-
-func (msg *XfrmLifetimeCur) Len() int {
- return SizeofXfrmLifetimeCur
-}
-
-func DeserializeXfrmLifetimeCur(b []byte) *XfrmLifetimeCur {
- return (*XfrmLifetimeCur)(unsafe.Pointer(&b[0:SizeofXfrmLifetimeCur][0]))
-}
-
-func (msg *XfrmLifetimeCur) Serialize() []byte {
- return (*(*[SizeofXfrmLifetimeCur]byte)(unsafe.Pointer(msg)))[:]
-}
-
-// struct xfrm_id {
-// xfrm_address_t daddr;
-// __be32 spi;
-// __u8 proto;
-// };
-
-type XfrmId struct {
- Daddr XfrmAddress
- Spi uint32 // big endian
- Proto uint8
- Pad [3]byte
-}
-
-func (msg *XfrmId) Len() int {
- return SizeofXfrmId
-}
-
-func DeserializeXfrmId(b []byte) *XfrmId {
- return (*XfrmId)(unsafe.Pointer(&b[0:SizeofXfrmId][0]))
-}
-
-func (msg *XfrmId) Serialize() []byte {
- return (*(*[SizeofXfrmId]byte)(unsafe.Pointer(msg)))[:]
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/nl/xfrm_policy_linux.go b/containerd/vendor/github.com/vishvananda/netlink/nl/xfrm_policy_linux.go
deleted file mode 100644
index 66f7e03..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/nl/xfrm_policy_linux.go
+++ /dev/null
@@ -1,119 +0,0 @@
-package nl
-
-import (
- "unsafe"
-)
-
-const (
- SizeofXfrmUserpolicyId = 0x40
- SizeofXfrmUserpolicyInfo = 0xa8
- SizeofXfrmUserTmpl = 0x40
-)
-
-// struct xfrm_userpolicy_id {
-// struct xfrm_selector sel;
-// __u32 index;
-// __u8 dir;
-// };
-//
-
-type XfrmUserpolicyId struct {
- Sel XfrmSelector
- Index uint32
- Dir uint8
- Pad [3]byte
-}
-
-func (msg *XfrmUserpolicyId) Len() int {
- return SizeofXfrmUserpolicyId
-}
-
-func DeserializeXfrmUserpolicyId(b []byte) *XfrmUserpolicyId {
- return (*XfrmUserpolicyId)(unsafe.Pointer(&b[0:SizeofXfrmUserpolicyId][0]))
-}
-
-func (msg *XfrmUserpolicyId) Serialize() []byte {
- return (*(*[SizeofXfrmUserpolicyId]byte)(unsafe.Pointer(msg)))[:]
-}
-
-// struct xfrm_userpolicy_info {
-// struct xfrm_selector sel;
-// struct xfrm_lifetime_cfg lft;
-// struct xfrm_lifetime_cur curlft;
-// __u32 priority;
-// __u32 index;
-// __u8 dir;
-// __u8 action;
-// #define XFRM_POLICY_ALLOW 0
-// #define XFRM_POLICY_BLOCK 1
-// __u8 flags;
-// #define XFRM_POLICY_LOCALOK 1 /* Allow user to override global policy */
-// /* Automatically expand selector to include matching ICMP payloads. */
-// #define XFRM_POLICY_ICMP 2
-// __u8 share;
-// };
-
-type XfrmUserpolicyInfo struct {
- Sel XfrmSelector
- Lft XfrmLifetimeCfg
- Curlft XfrmLifetimeCur
- Priority uint32
- Index uint32
- Dir uint8
- Action uint8
- Flags uint8
- Share uint8
- Pad [4]byte
-}
-
-func (msg *XfrmUserpolicyInfo) Len() int {
- return SizeofXfrmUserpolicyInfo
-}
-
-func DeserializeXfrmUserpolicyInfo(b []byte) *XfrmUserpolicyInfo {
- return (*XfrmUserpolicyInfo)(unsafe.Pointer(&b[0:SizeofXfrmUserpolicyInfo][0]))
-}
-
-func (msg *XfrmUserpolicyInfo) Serialize() []byte {
- return (*(*[SizeofXfrmUserpolicyInfo]byte)(unsafe.Pointer(msg)))[:]
-}
-
-// struct xfrm_user_tmpl {
-// struct xfrm_id id;
-// __u16 family;
-// xfrm_address_t saddr;
-// __u32 reqid;
-// __u8 mode;
-// __u8 share;
-// __u8 optional;
-// __u32 aalgos;
-// __u32 ealgos;
-// __u32 calgos;
-// }
-
-type XfrmUserTmpl struct {
- XfrmId XfrmId
- Family uint16
- Pad1 [2]byte
- Saddr XfrmAddress
- Reqid uint32
- Mode uint8
- Share uint8
- Optional uint8
- Pad2 byte
- Aalgos uint32
- Ealgos uint32
- Calgos uint32
-}
-
-func (msg *XfrmUserTmpl) Len() int {
- return SizeofXfrmUserTmpl
-}
-
-func DeserializeXfrmUserTmpl(b []byte) *XfrmUserTmpl {
- return (*XfrmUserTmpl)(unsafe.Pointer(&b[0:SizeofXfrmUserTmpl][0]))
-}
-
-func (msg *XfrmUserTmpl) Serialize() []byte {
- return (*(*[SizeofXfrmUserTmpl]byte)(unsafe.Pointer(msg)))[:]
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/nl/xfrm_state_linux.go b/containerd/vendor/github.com/vishvananda/netlink/nl/xfrm_state_linux.go
deleted file mode 100644
index 4876ce4..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/nl/xfrm_state_linux.go
+++ /dev/null
@@ -1,221 +0,0 @@
-package nl
-
-import (
- "unsafe"
-)
-
-const (
- SizeofXfrmUsersaId = 0x18
- SizeofXfrmStats = 0x0c
- SizeofXfrmUsersaInfo = 0xe0
- SizeofXfrmAlgo = 0x44
- SizeofXfrmAlgoAuth = 0x48
- SizeofXfrmEncapTmpl = 0x18
-)
-
-// struct xfrm_usersa_id {
-// xfrm_address_t daddr;
-// __be32 spi;
-// __u16 family;
-// __u8 proto;
-// };
-
-type XfrmUsersaId struct {
- Daddr XfrmAddress
- Spi uint32 // big endian
- Family uint16
- Proto uint8
- Pad byte
-}
-
-func (msg *XfrmUsersaId) Len() int {
- return SizeofXfrmUsersaId
-}
-
-func DeserializeXfrmUsersaId(b []byte) *XfrmUsersaId {
- return (*XfrmUsersaId)(unsafe.Pointer(&b[0:SizeofXfrmUsersaId][0]))
-}
-
-func (msg *XfrmUsersaId) Serialize() []byte {
- return (*(*[SizeofXfrmUsersaId]byte)(unsafe.Pointer(msg)))[:]
-}
-
-// struct xfrm_stats {
-// __u32 replay_window;
-// __u32 replay;
-// __u32 integrity_failed;
-// };
-
-type XfrmStats struct {
- ReplayWindow uint32
- Replay uint32
- IntegrityFailed uint32
-}
-
-func (msg *XfrmStats) Len() int {
- return SizeofXfrmStats
-}
-
-func DeserializeXfrmStats(b []byte) *XfrmStats {
- return (*XfrmStats)(unsafe.Pointer(&b[0:SizeofXfrmStats][0]))
-}
-
-func (msg *XfrmStats) Serialize() []byte {
- return (*(*[SizeofXfrmStats]byte)(unsafe.Pointer(msg)))[:]
-}
-
-// struct xfrm_usersa_info {
-// struct xfrm_selector sel;
-// struct xfrm_id id;
-// xfrm_address_t saddr;
-// struct xfrm_lifetime_cfg lft;
-// struct xfrm_lifetime_cur curlft;
-// struct xfrm_stats stats;
-// __u32 seq;
-// __u32 reqid;
-// __u16 family;
-// __u8 mode; /* XFRM_MODE_xxx */
-// __u8 replay_window;
-// __u8 flags;
-// #define XFRM_STATE_NOECN 1
-// #define XFRM_STATE_DECAP_DSCP 2
-// #define XFRM_STATE_NOPMTUDISC 4
-// #define XFRM_STATE_WILDRECV 8
-// #define XFRM_STATE_ICMP 16
-// #define XFRM_STATE_AF_UNSPEC 32
-// #define XFRM_STATE_ALIGN4 64
-// #define XFRM_STATE_ESN 128
-// };
-//
-// #define XFRM_SA_XFLAG_DONT_ENCAP_DSCP 1
-//
-
-type XfrmUsersaInfo struct {
- Sel XfrmSelector
- Id XfrmId
- Saddr XfrmAddress
- Lft XfrmLifetimeCfg
- Curlft XfrmLifetimeCur
- Stats XfrmStats
- Seq uint32
- Reqid uint32
- Family uint16
- Mode uint8
- ReplayWindow uint8
- Flags uint8
- Pad [7]byte
-}
-
-func (msg *XfrmUsersaInfo) Len() int {
- return SizeofXfrmUsersaInfo
-}
-
-func DeserializeXfrmUsersaInfo(b []byte) *XfrmUsersaInfo {
- return (*XfrmUsersaInfo)(unsafe.Pointer(&b[0:SizeofXfrmUsersaInfo][0]))
-}
-
-func (msg *XfrmUsersaInfo) Serialize() []byte {
- return (*(*[SizeofXfrmUsersaInfo]byte)(unsafe.Pointer(msg)))[:]
-}
-
-// struct xfrm_algo {
-// char alg_name[64];
-// unsigned int alg_key_len; /* in bits */
-// char alg_key[0];
-// };
-
-type XfrmAlgo struct {
- AlgName [64]byte
- AlgKeyLen uint32
- AlgKey []byte
-}
-
-func (msg *XfrmAlgo) Len() int {
- return SizeofXfrmAlgo + int(msg.AlgKeyLen/8)
-}
-
-func DeserializeXfrmAlgo(b []byte) *XfrmAlgo {
- ret := XfrmAlgo{}
- copy(ret.AlgName[:], b[0:64])
- ret.AlgKeyLen = *(*uint32)(unsafe.Pointer(&b[64]))
- ret.AlgKey = b[68:ret.Len()]
- return &ret
-}
-
-func (msg *XfrmAlgo) Serialize() []byte {
- b := make([]byte, msg.Len())
- copy(b[0:64], msg.AlgName[:])
- copy(b[64:68], (*(*[4]byte)(unsafe.Pointer(&msg.AlgKeyLen)))[:])
- copy(b[68:msg.Len()], msg.AlgKey[:])
- return b
-}
-
-// struct xfrm_algo_auth {
-// char alg_name[64];
-// unsigned int alg_key_len; /* in bits */
-// unsigned int alg_trunc_len; /* in bits */
-// char alg_key[0];
-// };
-
-type XfrmAlgoAuth struct {
- AlgName [64]byte
- AlgKeyLen uint32
- AlgTruncLen uint32
- AlgKey []byte
-}
-
-func (msg *XfrmAlgoAuth) Len() int {
- return SizeofXfrmAlgoAuth + int(msg.AlgKeyLen/8)
-}
-
-func DeserializeXfrmAlgoAuth(b []byte) *XfrmAlgoAuth {
- ret := XfrmAlgoAuth{}
- copy(ret.AlgName[:], b[0:64])
- ret.AlgKeyLen = *(*uint32)(unsafe.Pointer(&b[64]))
- ret.AlgTruncLen = *(*uint32)(unsafe.Pointer(&b[68]))
- ret.AlgKey = b[72:ret.Len()]
- return &ret
-}
-
-func (msg *XfrmAlgoAuth) Serialize() []byte {
- b := make([]byte, msg.Len())
- copy(b[0:64], msg.AlgName[:])
- copy(b[64:68], (*(*[4]byte)(unsafe.Pointer(&msg.AlgKeyLen)))[:])
- copy(b[68:72], (*(*[4]byte)(unsafe.Pointer(&msg.AlgTruncLen)))[:])
- copy(b[72:msg.Len()], msg.AlgKey[:])
- return b
-}
-
-// struct xfrm_algo_aead {
-// char alg_name[64];
-// unsigned int alg_key_len; /* in bits */
-// unsigned int alg_icv_len; /* in bits */
-// char alg_key[0];
-// }
-
-// struct xfrm_encap_tmpl {
-// __u16 encap_type;
-// __be16 encap_sport;
-// __be16 encap_dport;
-// xfrm_address_t encap_oa;
-// };
-
-type XfrmEncapTmpl struct {
- EncapType uint16
- EncapSport uint16 // big endian
- EncapDport uint16 // big endian
- Pad [2]byte
- EncapOa XfrmAddress
-}
-
-func (msg *XfrmEncapTmpl) Len() int {
- return SizeofXfrmEncapTmpl
-}
-
-func DeserializeXfrmEncapTmpl(b []byte) *XfrmEncapTmpl {
- return (*XfrmEncapTmpl)(unsafe.Pointer(&b[0:SizeofXfrmEncapTmpl][0]))
-}
-
-func (msg *XfrmEncapTmpl) Serialize() []byte {
- return (*(*[SizeofXfrmEncapTmpl]byte)(unsafe.Pointer(msg)))[:]
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/protinfo.go b/containerd/vendor/github.com/vishvananda/netlink/protinfo.go
deleted file mode 100644
index f39ab8f..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/protinfo.go
+++ /dev/null
@@ -1,53 +0,0 @@
-package netlink
-
-import (
- "strings"
-)
-
-// Protinfo represents bridge flags from netlink.
-type Protinfo struct {
- Hairpin bool
- Guard bool
- FastLeave bool
- RootBlock bool
- Learning bool
- Flood bool
-}
-
-// String returns a list of enabled flags
-func (prot *Protinfo) String() string {
- var boolStrings []string
- if prot.Hairpin {
- boolStrings = append(boolStrings, "Hairpin")
- }
- if prot.Guard {
- boolStrings = append(boolStrings, "Guard")
- }
- if prot.FastLeave {
- boolStrings = append(boolStrings, "FastLeave")
- }
- if prot.RootBlock {
- boolStrings = append(boolStrings, "RootBlock")
- }
- if prot.Learning {
- boolStrings = append(boolStrings, "Learning")
- }
- if prot.Flood {
- boolStrings = append(boolStrings, "Flood")
- }
- return strings.Join(boolStrings, " ")
-}
-
-func boolToByte(x bool) []byte {
- if x {
- return []byte{1}
- }
- return []byte{0}
-}
-
-func byteToBool(x byte) bool {
- if uint8(x) != 0 {
- return true
- }
- return false
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/protinfo_linux.go b/containerd/vendor/github.com/vishvananda/netlink/protinfo_linux.go
deleted file mode 100644
index 7181eba..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/protinfo_linux.go
+++ /dev/null
@@ -1,60 +0,0 @@
-package netlink
-
-import (
- "fmt"
- "syscall"
-
- "github.com/vishvananda/netlink/nl"
-)
-
-func LinkGetProtinfo(link Link) (Protinfo, error) {
- base := link.Attrs()
- ensureIndex(base)
- var pi Protinfo
- req := nl.NewNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_DUMP)
- msg := nl.NewIfInfomsg(syscall.AF_BRIDGE)
- req.AddData(msg)
- msgs, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- if err != nil {
- return pi, err
- }
-
- for _, m := range msgs {
- ans := nl.DeserializeIfInfomsg(m)
- if int(ans.Index) != base.Index {
- continue
- }
- attrs, err := nl.ParseRouteAttr(m[ans.Len():])
- if err != nil {
- return pi, err
- }
- for _, attr := range attrs {
- if attr.Attr.Type != syscall.IFLA_PROTINFO|syscall.NLA_F_NESTED {
- continue
- }
- infos, err := nl.ParseRouteAttr(attr.Value)
- if err != nil {
- return pi, err
- }
- var pi Protinfo
- for _, info := range infos {
- switch info.Attr.Type {
- case nl.IFLA_BRPORT_MODE:
- pi.Hairpin = byteToBool(info.Value[0])
- case nl.IFLA_BRPORT_GUARD:
- pi.Guard = byteToBool(info.Value[0])
- case nl.IFLA_BRPORT_FAST_LEAVE:
- pi.FastLeave = byteToBool(info.Value[0])
- case nl.IFLA_BRPORT_PROTECT:
- pi.RootBlock = byteToBool(info.Value[0])
- case nl.IFLA_BRPORT_LEARNING:
- pi.Learning = byteToBool(info.Value[0])
- case nl.IFLA_BRPORT_UNICAST_FLOOD:
- pi.Flood = byteToBool(info.Value[0])
- }
- }
- return pi, nil
- }
- }
- return pi, fmt.Errorf("Device with index %d not found", base.Index)
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/qdisc.go b/containerd/vendor/github.com/vishvananda/netlink/qdisc.go
deleted file mode 100644
index 41a4aa8..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/qdisc.go
+++ /dev/null
@@ -1,167 +0,0 @@
-package netlink
-
-import (
- "fmt"
-)
-
-const (
- HANDLE_NONE = 0
- HANDLE_INGRESS = 0xFFFFFFF1
- HANDLE_ROOT = 0xFFFFFFFF
- PRIORITY_MAP_LEN = 16
-)
-
-type Qdisc interface {
- Attrs() *QdiscAttrs
- Type() string
-}
-
-// Qdisc represents a netlink qdisc. A qdisc is associated with a link,
-// has a handle, a parent and a refcnt. The root qdisc of a device should
-// have parent == HANDLE_ROOT.
-type QdiscAttrs struct {
- LinkIndex int
- Handle uint32
- Parent uint32
- Refcnt uint32 // read only
-}
-
-func (q QdiscAttrs) String() string {
- return fmt.Sprintf("{LinkIndex: %d, Handle: %s, Parent: %s, Refcnt: %s}", q.LinkIndex, HandleStr(q.Handle), HandleStr(q.Parent), q.Refcnt)
-}
-
-func MakeHandle(major, minor uint16) uint32 {
- return (uint32(major) << 16) | uint32(minor)
-}
-
-func MajorMinor(handle uint32) (uint16, uint16) {
- return uint16((handle & 0xFFFF0000) >> 16), uint16(handle & 0x0000FFFFF)
-}
-
-func HandleStr(handle uint32) string {
- switch handle {
- case HANDLE_NONE:
- return "none"
- case HANDLE_INGRESS:
- return "ingress"
- case HANDLE_ROOT:
- return "root"
- default:
- major, minor := MajorMinor(handle)
- return fmt.Sprintf("%x:%x", major, minor)
- }
-}
-
-// PfifoFast is the default qdisc created by the kernel if one has not
-// been defined for the interface
-type PfifoFast struct {
- QdiscAttrs
- Bands uint8
- PriorityMap [PRIORITY_MAP_LEN]uint8
-}
-
-func (qdisc *PfifoFast) Attrs() *QdiscAttrs {
- return &qdisc.QdiscAttrs
-}
-
-func (qdisc *PfifoFast) Type() string {
- return "pfifo_fast"
-}
-
-// Prio is a basic qdisc that works just like PfifoFast
-type Prio struct {
- QdiscAttrs
- Bands uint8
- PriorityMap [PRIORITY_MAP_LEN]uint8
-}
-
-func NewPrio(attrs QdiscAttrs) *Prio {
- return &Prio{
- QdiscAttrs: attrs,
- Bands: 3,
- PriorityMap: [PRIORITY_MAP_LEN]uint8{1, 2, 2, 2, 1, 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1},
- }
-}
-
-func (qdisc *Prio) Attrs() *QdiscAttrs {
- return &qdisc.QdiscAttrs
-}
-
-func (qdisc *Prio) Type() string {
- return "prio"
-}
-
-// Htb is a classful qdisc that rate limits based on tokens
-type Htb struct {
- QdiscAttrs
- Version uint32
- Rate2Quantum uint32
- Defcls uint32
- Debug uint32
- DirectPkts uint32
-}
-
-func NewHtb(attrs QdiscAttrs) *Htb {
- return &Htb{
- QdiscAttrs: attrs,
- Version: 3,
- Defcls: 0,
- Rate2Quantum: 10,
- Debug: 0,
- DirectPkts: 0,
- }
-}
-
-func (qdisc *Htb) Attrs() *QdiscAttrs {
- return &qdisc.QdiscAttrs
-}
-
-func (qdisc *Htb) Type() string {
- return "htb"
-}
-
-// Tbf is a classless qdisc that rate limits based on tokens
-type Tbf struct {
- QdiscAttrs
- // TODO: handle 64bit rate properly
- Rate uint64
- Limit uint32
- Buffer uint32
- // TODO: handle other settings
-}
-
-func (qdisc *Tbf) Attrs() *QdiscAttrs {
- return &qdisc.QdiscAttrs
-}
-
-func (qdisc *Tbf) Type() string {
- return "tbf"
-}
-
-// Ingress is a qdisc for adding ingress filters
-type Ingress struct {
- QdiscAttrs
-}
-
-func (qdisc *Ingress) Attrs() *QdiscAttrs {
- return &qdisc.QdiscAttrs
-}
-
-func (qdisc *Ingress) Type() string {
- return "ingress"
-}
-
-// GenericQdisc qdiscs represent types that are not currently understood
-// by this netlink library.
-type GenericQdisc struct {
- QdiscAttrs
- QdiscType string
-}
-
-func (qdisc *GenericQdisc) Attrs() *QdiscAttrs {
- return &qdisc.QdiscAttrs
-}
-
-func (qdisc *GenericQdisc) Type() string {
- return qdisc.QdiscType
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/qdisc_linux.go b/containerd/vendor/github.com/vishvananda/netlink/qdisc_linux.go
deleted file mode 100644
index a16eb99..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/qdisc_linux.go
+++ /dev/null
@@ -1,316 +0,0 @@
-package netlink
-
-import (
- "fmt"
- "io/ioutil"
- "strconv"
- "strings"
- "syscall"
-
- "github.com/vishvananda/netlink/nl"
-)
-
-// QdiscDel will delete a qdisc from the system.
-// Equivalent to: `tc qdisc del $qdisc`
-func QdiscDel(qdisc Qdisc) error {
- req := nl.NewNetlinkRequest(syscall.RTM_DELQDISC, syscall.NLM_F_ACK)
- base := qdisc.Attrs()
- msg := &nl.TcMsg{
- Family: nl.FAMILY_ALL,
- Ifindex: int32(base.LinkIndex),
- Handle: base.Handle,
- Parent: base.Parent,
- }
- req.AddData(msg)
-
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-// QdiscAdd will add a qdisc to the system.
-// Equivalent to: `tc qdisc add $qdisc`
-func QdiscAdd(qdisc Qdisc) error {
- req := nl.NewNetlinkRequest(syscall.RTM_NEWQDISC, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
- base := qdisc.Attrs()
- msg := &nl.TcMsg{
- Family: nl.FAMILY_ALL,
- Ifindex: int32(base.LinkIndex),
- Handle: base.Handle,
- Parent: base.Parent,
- }
- req.AddData(msg)
- req.AddData(nl.NewRtAttr(nl.TCA_KIND, nl.ZeroTerminated(qdisc.Type())))
-
- options := nl.NewRtAttr(nl.TCA_OPTIONS, nil)
- if prio, ok := qdisc.(*Prio); ok {
- tcmap := nl.TcPrioMap{
- Bands: int32(prio.Bands),
- Priomap: prio.PriorityMap,
- }
- options = nl.NewRtAttr(nl.TCA_OPTIONS, tcmap.Serialize())
- } else if tbf, ok := qdisc.(*Tbf); ok {
- opt := nl.TcTbfQopt{}
- // TODO: handle rate > uint32
- opt.Rate.Rate = uint32(tbf.Rate)
- opt.Limit = tbf.Limit
- opt.Buffer = tbf.Buffer
- nl.NewRtAttrChild(options, nl.TCA_TBF_PARMS, opt.Serialize())
- } else if htb, ok := qdisc.(*Htb); ok {
- opt := nl.TcHtbGlob{}
- opt.Version = htb.Version
- opt.Rate2Quantum = htb.Rate2Quantum
- opt.Defcls = htb.Defcls
- // TODO: Handle Debug properly. For now default to 0
- opt.Debug = htb.Debug
- opt.DirectPkts = htb.DirectPkts
- nl.NewRtAttrChild(options, nl.TCA_HTB_INIT, opt.Serialize())
- // nl.NewRtAttrChild(options, nl.TCA_HTB_DIRECT_QLEN, opt.Serialize())
- } else if _, ok := qdisc.(*Ingress); ok {
- // ingress filters must use the proper handle
- if msg.Parent != HANDLE_INGRESS {
- return fmt.Errorf("Ingress filters must set Parent to HANDLE_INGRESS")
- }
- }
- req.AddData(options)
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-// QdiscList gets a list of qdiscs in the system.
-// Equivalent to: `tc qdisc show`.
-// The list can be filtered by link.
-func QdiscList(link Link) ([]Qdisc, error) {
- req := nl.NewNetlinkRequest(syscall.RTM_GETQDISC, syscall.NLM_F_DUMP)
- index := int32(0)
- if link != nil {
- base := link.Attrs()
- ensureIndex(base)
- index = int32(base.Index)
- }
- msg := &nl.TcMsg{
- Family: nl.FAMILY_ALL,
- Ifindex: index,
- }
- req.AddData(msg)
-
- msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWQDISC)
- if err != nil {
- return nil, err
- }
-
- var res []Qdisc
- for _, m := range msgs {
- msg := nl.DeserializeTcMsg(m)
-
- attrs, err := nl.ParseRouteAttr(m[msg.Len():])
- if err != nil {
- return nil, err
- }
-
- // skip qdiscs from other interfaces
- if link != nil && msg.Ifindex != index {
- continue
- }
-
- base := QdiscAttrs{
- LinkIndex: int(msg.Ifindex),
- Handle: msg.Handle,
- Parent: msg.Parent,
- Refcnt: msg.Info,
- }
- var qdisc Qdisc
- qdiscType := ""
- for _, attr := range attrs {
- switch attr.Attr.Type {
- case nl.TCA_KIND:
- qdiscType = string(attr.Value[:len(attr.Value)-1])
- switch qdiscType {
- case "pfifo_fast":
- qdisc = &PfifoFast{}
- case "prio":
- qdisc = &Prio{}
- case "tbf":
- qdisc = &Tbf{}
- case "ingress":
- qdisc = &Ingress{}
- case "htb":
- qdisc = &Htb{}
- default:
- qdisc = &GenericQdisc{QdiscType: qdiscType}
- }
- case nl.TCA_OPTIONS:
- switch qdiscType {
- case "pfifo_fast":
- // pfifo returns TcPrioMap directly without wrapping it in rtattr
- if err := parsePfifoFastData(qdisc, attr.Value); err != nil {
- return nil, err
- }
- case "prio":
- // prio returns TcPrioMap directly without wrapping it in rtattr
- if err := parsePrioData(qdisc, attr.Value); err != nil {
- return nil, err
- }
- case "tbf":
- data, err := nl.ParseRouteAttr(attr.Value)
- if err != nil {
- return nil, err
- }
- if err := parseTbfData(qdisc, data); err != nil {
- return nil, err
- }
- case "htb":
- data, err := nl.ParseRouteAttr(attr.Value)
- if err != nil {
- return nil, err
- }
- if err := parseHtbData(qdisc, data); err != nil {
- return nil, err
- }
-
- // no options for ingress
- }
- }
- }
- *qdisc.Attrs() = base
- res = append(res, qdisc)
- }
-
- return res, nil
-}
-
-func parsePfifoFastData(qdisc Qdisc, value []byte) error {
- pfifo := qdisc.(*PfifoFast)
- tcmap := nl.DeserializeTcPrioMap(value)
- pfifo.PriorityMap = tcmap.Priomap
- pfifo.Bands = uint8(tcmap.Bands)
- return nil
-}
-
-func parsePrioData(qdisc Qdisc, value []byte) error {
- prio := qdisc.(*Prio)
- tcmap := nl.DeserializeTcPrioMap(value)
- prio.PriorityMap = tcmap.Priomap
- prio.Bands = uint8(tcmap.Bands)
- return nil
-}
-
-func parseHtbData(qdisc Qdisc, data []syscall.NetlinkRouteAttr) error {
- native = nl.NativeEndian()
- htb := qdisc.(*Htb)
- for _, datum := range data {
- switch datum.Attr.Type {
- case nl.TCA_HTB_INIT:
- opt := nl.DeserializeTcHtbGlob(datum.Value)
- htb.Version = opt.Version
- htb.Rate2Quantum = opt.Rate2Quantum
- htb.Defcls = opt.Defcls
- htb.Debug = opt.Debug
- htb.DirectPkts = opt.DirectPkts
- case nl.TCA_HTB_DIRECT_QLEN:
- // TODO
- //htb.DirectQlen = native.uint32(datum.Value)
- }
- }
- return nil
-}
-func parseTbfData(qdisc Qdisc, data []syscall.NetlinkRouteAttr) error {
- native = nl.NativeEndian()
- tbf := qdisc.(*Tbf)
- for _, datum := range data {
- switch datum.Attr.Type {
- case nl.TCA_TBF_PARMS:
- opt := nl.DeserializeTcTbfQopt(datum.Value)
- tbf.Rate = uint64(opt.Rate.Rate)
- tbf.Limit = opt.Limit
- tbf.Buffer = opt.Buffer
- case nl.TCA_TBF_RATE64:
- tbf.Rate = native.Uint64(datum.Value[0:4])
- }
- }
- return nil
-}
-
-const (
- TIME_UNITS_PER_SEC = 1000000
-)
-
-var (
- tickInUsec float64 = 0.0
- clockFactor float64 = 0.0
- hz float64 = 0.0
-)
-
-func initClock() {
- data, err := ioutil.ReadFile("/proc/net/psched")
- if err != nil {
- return
- }
- parts := strings.Split(strings.TrimSpace(string(data)), " ")
- if len(parts) < 3 {
- return
- }
- var vals [3]uint64
- for i := range vals {
- val, err := strconv.ParseUint(parts[i], 16, 32)
- if err != nil {
- return
- }
- vals[i] = val
- }
- // compatibility
- if vals[2] == 1000000000 {
- vals[0] = vals[1]
- }
- clockFactor = float64(vals[2]) / TIME_UNITS_PER_SEC
- tickInUsec = float64(vals[0]) / float64(vals[1]) * clockFactor
- hz = float64(vals[0])
-}
-
-func TickInUsec() float64 {
- if tickInUsec == 0.0 {
- initClock()
- }
- return tickInUsec
-}
-
-func ClockFactor() float64 {
- if clockFactor == 0.0 {
- initClock()
- }
- return clockFactor
-}
-
-func Hz() float64 {
- if hz == 0.0 {
- initClock()
- }
- return hz
-}
-
-func time2Tick(time uint32) uint32 {
- return uint32(float64(time) * TickInUsec())
-}
-
-func tick2Time(tick uint32) uint32 {
- return uint32(float64(tick) / TickInUsec())
-}
-
-func time2Ktime(time uint32) uint32 {
- return uint32(float64(time) * ClockFactor())
-}
-
-func ktime2Time(ktime uint32) uint32 {
- return uint32(float64(ktime) / ClockFactor())
-}
-
-func burst(rate uint64, buffer uint32) uint32 {
- return uint32(float64(rate) * float64(tick2Time(buffer)) / TIME_UNITS_PER_SEC)
-}
-
-func latency(rate uint64, limit, buffer uint32) float64 {
- return TIME_UNITS_PER_SEC*(float64(limit)/float64(rate)) - float64(tick2Time(buffer))
-}
-
-func Xmittime(rate uint64, size uint32) float64 {
- return TickInUsec() * TIME_UNITS_PER_SEC * (float64(size) / float64(rate))
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/route.go b/containerd/vendor/github.com/vishvananda/netlink/route.go
deleted file mode 100644
index 578270f..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/route.go
+++ /dev/null
@@ -1,41 +0,0 @@
-package netlink
-
-import (
- "fmt"
- "net"
- "syscall"
-)
-
-// Scope is an enum representing a route scope.
-type Scope uint8
-
-const (
- SCOPE_UNIVERSE Scope = syscall.RT_SCOPE_UNIVERSE
- SCOPE_SITE Scope = syscall.RT_SCOPE_SITE
- SCOPE_LINK Scope = syscall.RT_SCOPE_LINK
- SCOPE_HOST Scope = syscall.RT_SCOPE_HOST
- SCOPE_NOWHERE Scope = syscall.RT_SCOPE_NOWHERE
-)
-
-// Route represents a netlink route. A route is associated with a link,
-// has a destination network, an optional source ip, and optional
-// gateway. Advanced route parameters and non-main routing tables are
-// currently not supported.
-type Route struct {
- LinkIndex int
- Scope Scope
- Dst *net.IPNet
- Src net.IP
- Gw net.IP
-}
-
-func (r Route) String() string {
- return fmt.Sprintf("{Ifindex: %d Dst: %s Src: %s Gw: %s}", r.LinkIndex, r.Dst,
- r.Src, r.Gw)
-}
-
-// RouteUpdate is sent when a route changes - type is RTM_NEWROUTE or RTM_DELROUTE
-type RouteUpdate struct {
- Type uint16
- Route
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/route_linux.go b/containerd/vendor/github.com/vishvananda/netlink/route_linux.go
deleted file mode 100644
index 693e6cb..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/route_linux.go
+++ /dev/null
@@ -1,249 +0,0 @@
-package netlink
-
-import (
- "fmt"
- "net"
- "syscall"
-
- "github.com/vishvananda/netlink/nl"
-)
-
-// RtAttr is shared so it is in netlink_linux.go
-
-// RouteAdd will add a route to the system.
-// Equivalent to: `ip route add $route`
-func RouteAdd(route *Route) error {
- req := nl.NewNetlinkRequest(syscall.RTM_NEWROUTE, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
- return routeHandle(route, req, nl.NewRtMsg())
-}
-
-// RouteDel will delete a route from the system.
-// Equivalent to: `ip route del $route`
-func RouteDel(route *Route) error {
- req := nl.NewNetlinkRequest(syscall.RTM_DELROUTE, syscall.NLM_F_ACK)
- return routeHandle(route, req, nl.NewRtDelMsg())
-}
-
-func routeHandle(route *Route, req *nl.NetlinkRequest, msg *nl.RtMsg) error {
- if (route.Dst == nil || route.Dst.IP == nil) && route.Src == nil && route.Gw == nil {
- return fmt.Errorf("one of Dst.IP, Src, or Gw must not be nil")
- }
-
- msg.Scope = uint8(route.Scope)
- family := -1
- var rtAttrs []*nl.RtAttr
-
- if route.Dst != nil && route.Dst.IP != nil {
- dstLen, _ := route.Dst.Mask.Size()
- msg.Dst_len = uint8(dstLen)
- dstFamily := nl.GetIPFamily(route.Dst.IP)
- family = dstFamily
- var dstData []byte
- if dstFamily == FAMILY_V4 {
- dstData = route.Dst.IP.To4()
- } else {
- dstData = route.Dst.IP.To16()
- }
- rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_DST, dstData))
- }
-
- if route.Src != nil {
- srcFamily := nl.GetIPFamily(route.Src)
- if family != -1 && family != srcFamily {
- return fmt.Errorf("source and destination ip are not the same IP family")
- }
- family = srcFamily
- var srcData []byte
- if srcFamily == FAMILY_V4 {
- srcData = route.Src.To4()
- } else {
- srcData = route.Src.To16()
- }
- // The commonly used src ip for routes is actually PREFSRC
- rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_PREFSRC, srcData))
- }
-
- if route.Gw != nil {
- gwFamily := nl.GetIPFamily(route.Gw)
- if family != -1 && family != gwFamily {
- return fmt.Errorf("gateway, source, and destination ip are not the same IP family")
- }
- family = gwFamily
- var gwData []byte
- if gwFamily == FAMILY_V4 {
- gwData = route.Gw.To4()
- } else {
- gwData = route.Gw.To16()
- }
- rtAttrs = append(rtAttrs, nl.NewRtAttr(syscall.RTA_GATEWAY, gwData))
- }
-
- msg.Family = uint8(family)
-
- req.AddData(msg)
- for _, attr := range rtAttrs {
- req.AddData(attr)
- }
-
- var (
- b = make([]byte, 4)
- native = nl.NativeEndian()
- )
- native.PutUint32(b, uint32(route.LinkIndex))
-
- req.AddData(nl.NewRtAttr(syscall.RTA_OIF, b))
-
- _, err := req.Execute(syscall.NETLINK_ROUTE, 0)
- return err
-}
-
-// RouteList gets a list of routes in the system.
-// Equivalent to: `ip route show`.
-// The list can be filtered by link and ip family.
-func RouteList(link Link, family int) ([]Route, error) {
- req := nl.NewNetlinkRequest(syscall.RTM_GETROUTE, syscall.NLM_F_DUMP)
- msg := nl.NewIfInfomsg(family)
- req.AddData(msg)
-
- msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWROUTE)
- if err != nil {
- return nil, err
- }
-
- index := 0
- if link != nil {
- base := link.Attrs()
- ensureIndex(base)
- index = base.Index
- }
-
- var res []Route
- for _, m := range msgs {
- msg := nl.DeserializeRtMsg(m)
-
- if msg.Flags&syscall.RTM_F_CLONED != 0 {
- // Ignore cloned routes
- continue
- }
-
- if msg.Table != syscall.RT_TABLE_MAIN {
- // Ignore non-main tables
- continue
- }
-
- route, err := deserializeRoute(m)
- if err != nil {
- return nil, err
- }
-
- if link != nil && route.LinkIndex != index {
- // Ignore routes from other interfaces
- continue
- }
- res = append(res, route)
- }
-
- return res, nil
-}
-
-// deserializeRoute decodes a binary netlink message into a Route struct
-func deserializeRoute(m []byte) (Route, error) {
- route := Route{}
- msg := nl.DeserializeRtMsg(m)
- attrs, err := nl.ParseRouteAttr(m[msg.Len():])
- if err != nil {
- return route, err
- }
- route.Scope = Scope(msg.Scope)
-
- native := nl.NativeEndian()
- for _, attr := range attrs {
- switch attr.Attr.Type {
- case syscall.RTA_GATEWAY:
- route.Gw = net.IP(attr.Value)
- case syscall.RTA_PREFSRC:
- route.Src = net.IP(attr.Value)
- case syscall.RTA_DST:
- route.Dst = &net.IPNet{
- IP: attr.Value,
- Mask: net.CIDRMask(int(msg.Dst_len), 8*len(attr.Value)),
- }
- case syscall.RTA_OIF:
- routeIndex := int(native.Uint32(attr.Value[0:4]))
- route.LinkIndex = routeIndex
- }
- }
- return route, nil
-}
-
-// RouteGet gets a route to a specific destination from the host system.
-// Equivalent to: 'ip route get'.
-func RouteGet(destination net.IP) ([]Route, error) {
- req := nl.NewNetlinkRequest(syscall.RTM_GETROUTE, syscall.NLM_F_REQUEST)
- family := nl.GetIPFamily(destination)
- var destinationData []byte
- var bitlen uint8
- if family == FAMILY_V4 {
- destinationData = destination.To4()
- bitlen = 32
- } else {
- destinationData = destination.To16()
- bitlen = 128
- }
- msg := &nl.RtMsg{}
- msg.Family = uint8(family)
- msg.Dst_len = bitlen
- req.AddData(msg)
-
- rtaDst := nl.NewRtAttr(syscall.RTA_DST, destinationData)
- req.AddData(rtaDst)
-
- msgs, err := req.Execute(syscall.NETLINK_ROUTE, syscall.RTM_NEWROUTE)
- if err != nil {
- return nil, err
- }
-
- var res []Route
- for _, m := range msgs {
- route, err := deserializeRoute(m)
- if err != nil {
- return nil, err
- }
- res = append(res, route)
- }
- return res, nil
-
-}
-
-// RouteSubscribe takes a chan down which notifications will be sent
-// when routes are added or deleted. Close the 'done' chan to stop subscription.
-func RouteSubscribe(ch chan<- RouteUpdate, done <-chan struct{}) error {
- s, err := nl.Subscribe(syscall.NETLINK_ROUTE, syscall.RTNLGRP_IPV4_ROUTE, syscall.RTNLGRP_IPV6_ROUTE)
- if err != nil {
- return err
- }
- if done != nil {
- go func() {
- <-done
- s.Close()
- }()
- }
- go func() {
- defer close(ch)
- for {
- msgs, err := s.Receive()
- if err != nil {
- return
- }
- for _, m := range msgs {
- route, err := deserializeRoute(m.Data)
- if err != nil {
- return
- }
- ch <- RouteUpdate{Type: m.Header.Type, Route: route}
- }
- }
- }()
-
- return nil
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/xfrm.go b/containerd/vendor/github.com/vishvananda/netlink/xfrm.go
deleted file mode 100644
index 621ffb6..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/xfrm.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package netlink
-
-import (
- "fmt"
- "syscall"
-)
-
-// Proto is an enum representing an ipsec protocol.
-type Proto uint8
-
-const (
- XFRM_PROTO_ROUTE2 Proto = syscall.IPPROTO_ROUTING
- XFRM_PROTO_ESP Proto = syscall.IPPROTO_ESP
- XFRM_PROTO_AH Proto = syscall.IPPROTO_AH
- XFRM_PROTO_HAO Proto = syscall.IPPROTO_DSTOPTS
- XFRM_PROTO_COMP Proto = syscall.IPPROTO_COMP
- XFRM_PROTO_IPSEC_ANY Proto = syscall.IPPROTO_RAW
-)
-
-func (p Proto) String() string {
- switch p {
- case XFRM_PROTO_ROUTE2:
- return "route2"
- case XFRM_PROTO_ESP:
- return "esp"
- case XFRM_PROTO_AH:
- return "ah"
- case XFRM_PROTO_HAO:
- return "hao"
- case XFRM_PROTO_COMP:
- return "comp"
- case XFRM_PROTO_IPSEC_ANY:
- return "ipsec-any"
- }
- return fmt.Sprintf("%d", p)
-}
-
-// Mode is an enum representing an ipsec transport.
-type Mode uint8
-
-const (
- XFRM_MODE_TRANSPORT Mode = iota
- XFRM_MODE_TUNNEL
- XFRM_MODE_ROUTEOPTIMIZATION
- XFRM_MODE_IN_TRIGGER
- XFRM_MODE_BEET
- XFRM_MODE_MAX
-)
-
-func (m Mode) String() string {
- switch m {
- case XFRM_MODE_TRANSPORT:
- return "transport"
- case XFRM_MODE_TUNNEL:
- return "tunnel"
- case XFRM_MODE_ROUTEOPTIMIZATION:
- return "ro"
- case XFRM_MODE_IN_TRIGGER:
- return "in_trigger"
- case XFRM_MODE_BEET:
- return "beet"
- }
- return fmt.Sprintf("%d", m)
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/xfrm_policy.go b/containerd/vendor/github.com/vishvananda/netlink/xfrm_policy.go
deleted file mode 100644
index d85c65d..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/xfrm_policy.go
+++ /dev/null
@@ -1,59 +0,0 @@
-package netlink
-
-import (
- "fmt"
- "net"
-)
-
-// Dir is an enum representing an ipsec template direction.
-type Dir uint8
-
-const (
- XFRM_DIR_IN Dir = iota
- XFRM_DIR_OUT
- XFRM_DIR_FWD
- XFRM_SOCKET_IN
- XFRM_SOCKET_OUT
- XFRM_SOCKET_FWD
-)
-
-func (d Dir) String() string {
- switch d {
- case XFRM_DIR_IN:
- return "dir in"
- case XFRM_DIR_OUT:
- return "dir out"
- case XFRM_DIR_FWD:
- return "dir fwd"
- case XFRM_SOCKET_IN:
- return "socket in"
- case XFRM_SOCKET_OUT:
- return "socket out"
- case XFRM_SOCKET_FWD:
- return "socket fwd"
- }
- return fmt.Sprintf("socket %d", d-XFRM_SOCKET_IN)
-}
-
-// XfrmPolicyTmpl encapsulates a rule for the base addresses of an ipsec
-// policy. These rules are matched with XfrmState to determine encryption
-// and authentication algorithms.
-type XfrmPolicyTmpl struct {
- Dst net.IP
- Src net.IP
- Proto Proto
- Mode Mode
- Reqid int
-}
-
-// XfrmPolicy represents an ipsec policy. It represents the overlay network
-// and has a list of XfrmPolicyTmpls representing the base addresses of
-// the policy.
-type XfrmPolicy struct {
- Dst *net.IPNet
- Src *net.IPNet
- Dir Dir
- Priority int
- Index int
- Tmpls []XfrmPolicyTmpl
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/xfrm_policy_linux.go b/containerd/vendor/github.com/vishvananda/netlink/xfrm_policy_linux.go
deleted file mode 100644
index 2daf6dc..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/xfrm_policy_linux.go
+++ /dev/null
@@ -1,127 +0,0 @@
-package netlink
-
-import (
- "syscall"
-
- "github.com/vishvananda/netlink/nl"
-)
-
-func selFromPolicy(sel *nl.XfrmSelector, policy *XfrmPolicy) {
- sel.Family = uint16(nl.GetIPFamily(policy.Dst.IP))
- sel.Daddr.FromIP(policy.Dst.IP)
- sel.Saddr.FromIP(policy.Src.IP)
- prefixlenD, _ := policy.Dst.Mask.Size()
- sel.PrefixlenD = uint8(prefixlenD)
- prefixlenS, _ := policy.Src.Mask.Size()
- sel.PrefixlenS = uint8(prefixlenS)
-}
-
-// XfrmPolicyAdd will add an xfrm policy to the system.
-// Equivalent to: `ip xfrm policy add $policy`
-func XfrmPolicyAdd(policy *XfrmPolicy) error {
- req := nl.NewNetlinkRequest(nl.XFRM_MSG_NEWPOLICY, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
-
- msg := &nl.XfrmUserpolicyInfo{}
- selFromPolicy(&msg.Sel, policy)
- msg.Priority = uint32(policy.Priority)
- msg.Index = uint32(policy.Index)
- msg.Dir = uint8(policy.Dir)
- msg.Lft.SoftByteLimit = nl.XFRM_INF
- msg.Lft.HardByteLimit = nl.XFRM_INF
- msg.Lft.SoftPacketLimit = nl.XFRM_INF
- msg.Lft.HardPacketLimit = nl.XFRM_INF
- req.AddData(msg)
-
- tmplData := make([]byte, nl.SizeofXfrmUserTmpl*len(policy.Tmpls))
- for i, tmpl := range policy.Tmpls {
- start := i * nl.SizeofXfrmUserTmpl
- userTmpl := nl.DeserializeXfrmUserTmpl(tmplData[start : start+nl.SizeofXfrmUserTmpl])
- userTmpl.XfrmId.Daddr.FromIP(tmpl.Dst)
- userTmpl.Saddr.FromIP(tmpl.Src)
- userTmpl.XfrmId.Proto = uint8(tmpl.Proto)
- userTmpl.Mode = uint8(tmpl.Mode)
- userTmpl.Reqid = uint32(tmpl.Reqid)
- userTmpl.Aalgos = ^uint32(0)
- userTmpl.Ealgos = ^uint32(0)
- userTmpl.Calgos = ^uint32(0)
- }
- if len(tmplData) > 0 {
- tmpls := nl.NewRtAttr(nl.XFRMA_TMPL, tmplData)
- req.AddData(tmpls)
- }
-
- _, err := req.Execute(syscall.NETLINK_XFRM, 0)
- return err
-}
-
-// XfrmPolicyDel will delete an xfrm policy from the system. Note that
-// the Tmpls are ignored when matching the policy to delete.
-// Equivalent to: `ip xfrm policy del $policy`
-func XfrmPolicyDel(policy *XfrmPolicy) error {
- req := nl.NewNetlinkRequest(nl.XFRM_MSG_DELPOLICY, syscall.NLM_F_ACK)
-
- msg := &nl.XfrmUserpolicyId{}
- selFromPolicy(&msg.Sel, policy)
- msg.Index = uint32(policy.Index)
- msg.Dir = uint8(policy.Dir)
- req.AddData(msg)
-
- _, err := req.Execute(syscall.NETLINK_XFRM, 0)
- return err
-}
-
-// XfrmPolicyList gets a list of xfrm policies in the system.
-// Equivalent to: `ip xfrm policy show`.
-// The list can be filtered by ip family.
-func XfrmPolicyList(family int) ([]XfrmPolicy, error) {
- req := nl.NewNetlinkRequest(nl.XFRM_MSG_GETPOLICY, syscall.NLM_F_DUMP)
-
- msg := nl.NewIfInfomsg(family)
- req.AddData(msg)
-
- msgs, err := req.Execute(syscall.NETLINK_XFRM, nl.XFRM_MSG_NEWPOLICY)
- if err != nil {
- return nil, err
- }
-
- var res []XfrmPolicy
- for _, m := range msgs {
- msg := nl.DeserializeXfrmUserpolicyInfo(m)
-
- if family != FAMILY_ALL && family != int(msg.Sel.Family) {
- continue
- }
-
- var policy XfrmPolicy
-
- policy.Dst = msg.Sel.Daddr.ToIPNet(msg.Sel.PrefixlenD)
- policy.Src = msg.Sel.Saddr.ToIPNet(msg.Sel.PrefixlenS)
- policy.Priority = int(msg.Priority)
- policy.Index = int(msg.Index)
- policy.Dir = Dir(msg.Dir)
-
- attrs, err := nl.ParseRouteAttr(m[msg.Len():])
- if err != nil {
- return nil, err
- }
-
- for _, attr := range attrs {
- switch attr.Attr.Type {
- case nl.XFRMA_TMPL:
- max := len(attr.Value)
- for i := 0; i < max; i += nl.SizeofXfrmUserTmpl {
- var resTmpl XfrmPolicyTmpl
- tmpl := nl.DeserializeXfrmUserTmpl(attr.Value[i : i+nl.SizeofXfrmUserTmpl])
- resTmpl.Dst = tmpl.XfrmId.Daddr.ToIP()
- resTmpl.Src = tmpl.Saddr.ToIP()
- resTmpl.Proto = Proto(tmpl.XfrmId.Proto)
- resTmpl.Mode = Mode(tmpl.Mode)
- resTmpl.Reqid = int(tmpl.Reqid)
- policy.Tmpls = append(policy.Tmpls, resTmpl)
- }
- }
- }
- res = append(res, policy)
- }
- return res, nil
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/xfrm_state.go b/containerd/vendor/github.com/vishvananda/netlink/xfrm_state.go
deleted file mode 100644
index 5b8f2df..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/xfrm_state.go
+++ /dev/null
@@ -1,53 +0,0 @@
-package netlink
-
-import (
- "net"
-)
-
-// XfrmStateAlgo represents the algorithm to use for the ipsec encryption.
-type XfrmStateAlgo struct {
- Name string
- Key []byte
- TruncateLen int // Auth only
-}
-
-// EncapType is an enum representing an ipsec template direction.
-type EncapType uint8
-
-const (
- XFRM_ENCAP_ESPINUDP_NONIKE EncapType = iota + 1
- XFRM_ENCAP_ESPINUDP
-)
-
-func (e EncapType) String() string {
- switch e {
- case XFRM_ENCAP_ESPINUDP_NONIKE:
- return "espinudp-nonike"
- case XFRM_ENCAP_ESPINUDP:
- return "espinudp"
- }
- return "unknown"
-}
-
-// XfrmEncap represents the encapsulation to use for the ipsec encryption.
-type XfrmStateEncap struct {
- Type EncapType
- SrcPort int
- DstPort int
- OriginalAddress net.IP
-}
-
-// XfrmState represents the state of an ipsec policy. It optionally
-// contains an XfrmStateAlgo for encryption and one for authentication.
-type XfrmState struct {
- Dst net.IP
- Src net.IP
- Proto Proto
- Mode Mode
- Spi int
- Reqid int
- ReplayWindow int
- Auth *XfrmStateAlgo
- Crypt *XfrmStateAlgo
- Encap *XfrmStateEncap
-}
diff --git a/containerd/vendor/github.com/vishvananda/netlink/xfrm_state_linux.go b/containerd/vendor/github.com/vishvananda/netlink/xfrm_state_linux.go
deleted file mode 100644
index 5f44ec8..0000000
--- a/containerd/vendor/github.com/vishvananda/netlink/xfrm_state_linux.go
+++ /dev/null
@@ -1,181 +0,0 @@
-package netlink
-
-import (
- "fmt"
- "syscall"
-
- "github.com/vishvananda/netlink/nl"
-)
-
-func writeStateAlgo(a *XfrmStateAlgo) []byte {
- algo := nl.XfrmAlgo{
- AlgKeyLen: uint32(len(a.Key) * 8),
- AlgKey: a.Key,
- }
- end := len(a.Name)
- if end > 64 {
- end = 64
- }
- copy(algo.AlgName[:end], a.Name)
- return algo.Serialize()
-}
-
-func writeStateAlgoAuth(a *XfrmStateAlgo) []byte {
- algo := nl.XfrmAlgoAuth{
- AlgKeyLen: uint32(len(a.Key) * 8),
- AlgTruncLen: uint32(a.TruncateLen),
- AlgKey: a.Key,
- }
- end := len(a.Name)
- if end > 64 {
- end = 64
- }
- copy(algo.AlgName[:end], a.Name)
- return algo.Serialize()
-}
-
-// XfrmStateAdd will add an xfrm state to the system.
-// Equivalent to: `ip xfrm state add $state`
-func XfrmStateAdd(state *XfrmState) error {
- // A state with spi 0 can't be deleted so don't allow it to be set
- if state.Spi == 0 {
- return fmt.Errorf("Spi must be set when adding xfrm state.")
- }
- req := nl.NewNetlinkRequest(nl.XFRM_MSG_NEWSA, syscall.NLM_F_CREATE|syscall.NLM_F_EXCL|syscall.NLM_F_ACK)
-
- msg := &nl.XfrmUsersaInfo{}
- msg.Family = uint16(nl.GetIPFamily(state.Dst))
- msg.Id.Daddr.FromIP(state.Dst)
- msg.Saddr.FromIP(state.Src)
- msg.Id.Proto = uint8(state.Proto)
- msg.Mode = uint8(state.Mode)
- msg.Id.Spi = nl.Swap32(uint32(state.Spi))
- msg.Reqid = uint32(state.Reqid)
- msg.ReplayWindow = uint8(state.ReplayWindow)
- msg.Lft.SoftByteLimit = nl.XFRM_INF
- msg.Lft.HardByteLimit = nl.XFRM_INF
- msg.Lft.SoftPacketLimit = nl.XFRM_INF
- msg.Lft.HardPacketLimit = nl.XFRM_INF
- req.AddData(msg)
-
- if state.Auth != nil {
- out := nl.NewRtAttr(nl.XFRMA_ALG_AUTH_TRUNC, writeStateAlgoAuth(state.Auth))
- req.AddData(out)
- }
- if state.Crypt != nil {
- out := nl.NewRtAttr(nl.XFRMA_ALG_CRYPT, writeStateAlgo(state.Crypt))
- req.AddData(out)
- }
- if state.Encap != nil {
- encapData := make([]byte, nl.SizeofXfrmEncapTmpl)
- encap := nl.DeserializeXfrmEncapTmpl(encapData)
- encap.EncapType = uint16(state.Encap.Type)
- encap.EncapSport = nl.Swap16(uint16(state.Encap.SrcPort))
- encap.EncapDport = nl.Swap16(uint16(state.Encap.DstPort))
- encap.EncapOa.FromIP(state.Encap.OriginalAddress)
- out := nl.NewRtAttr(nl.XFRMA_ENCAP, encapData)
- req.AddData(out)
- }
-
- _, err := req.Execute(syscall.NETLINK_XFRM, 0)
- return err
-}
-
-// XfrmStateDel will delete an xfrm state from the system. Note that
-// the Algos are ignored when matching the state to delete.
-// Equivalent to: `ip xfrm state del $state`
-func XfrmStateDel(state *XfrmState) error {
- req := nl.NewNetlinkRequest(nl.XFRM_MSG_DELSA, syscall.NLM_F_ACK)
-
- msg := &nl.XfrmUsersaId{}
- msg.Daddr.FromIP(state.Dst)
- msg.Family = uint16(nl.GetIPFamily(state.Dst))
- msg.Proto = uint8(state.Proto)
- msg.Spi = nl.Swap32(uint32(state.Spi))
- req.AddData(msg)
-
- saddr := nl.XfrmAddress{}
- saddr.FromIP(state.Src)
- srcdata := nl.NewRtAttr(nl.XFRMA_SRCADDR, saddr.Serialize())
-
- req.AddData(srcdata)
-
- _, err := req.Execute(syscall.NETLINK_XFRM, 0)
- return err
-}
-
-// XfrmStateList gets a list of xfrm states in the system.
-// Equivalent to: `ip xfrm state show`.
-// The list can be filtered by ip family.
-func XfrmStateList(family int) ([]XfrmState, error) {
- req := nl.NewNetlinkRequest(nl.XFRM_MSG_GETSA, syscall.NLM_F_DUMP)
-
- msg := nl.NewIfInfomsg(family)
- req.AddData(msg)
-
- msgs, err := req.Execute(syscall.NETLINK_XFRM, nl.XFRM_MSG_NEWSA)
- if err != nil {
- return nil, err
- }
-
- var res []XfrmState
- for _, m := range msgs {
- msg := nl.DeserializeXfrmUsersaInfo(m)
-
- if family != FAMILY_ALL && family != int(msg.Family) {
- continue
- }
-
- var state XfrmState
-
- state.Dst = msg.Id.Daddr.ToIP()
- state.Src = msg.Saddr.ToIP()
- state.Proto = Proto(msg.Id.Proto)
- state.Mode = Mode(msg.Mode)
- state.Spi = int(nl.Swap32(msg.Id.Spi))
- state.Reqid = int(msg.Reqid)
- state.ReplayWindow = int(msg.ReplayWindow)
-
- attrs, err := nl.ParseRouteAttr(m[msg.Len():])
- if err != nil {
- return nil, err
- }
-
- for _, attr := range attrs {
- switch attr.Attr.Type {
- case nl.XFRMA_ALG_AUTH, nl.XFRMA_ALG_CRYPT:
- var resAlgo *XfrmStateAlgo
- if attr.Attr.Type == nl.XFRMA_ALG_AUTH {
- if state.Auth == nil {
- state.Auth = new(XfrmStateAlgo)
- }
- resAlgo = state.Auth
- } else {
- state.Crypt = new(XfrmStateAlgo)
- resAlgo = state.Crypt
- }
- algo := nl.DeserializeXfrmAlgo(attr.Value[:])
- (*resAlgo).Name = nl.BytesToString(algo.AlgName[:])
- (*resAlgo).Key = algo.AlgKey
- case nl.XFRMA_ALG_AUTH_TRUNC:
- if state.Auth == nil {
- state.Auth = new(XfrmStateAlgo)
- }
- algo := nl.DeserializeXfrmAlgoAuth(attr.Value[:])
- state.Auth.Name = nl.BytesToString(algo.AlgName[:])
- state.Auth.Key = algo.AlgKey
- state.Auth.TruncateLen = int(algo.AlgTruncLen)
- case nl.XFRMA_ENCAP:
- encap := nl.DeserializeXfrmEncapTmpl(attr.Value[:])
- state.Encap = new(XfrmStateEncap)
- state.Encap.Type = EncapType(encap.EncapType)
- state.Encap.SrcPort = int(nl.Swap16(encap.EncapSport))
- state.Encap.DstPort = int(nl.Swap16(encap.EncapDport))
- state.Encap.OriginalAddress = encap.EncapOa.ToIP()
- }
-
- }
- res = append(res, state)
- }
- return res, nil
-}
diff --git a/event.go b/event.go
index f4735dd..af1949f 100644
--- a/event.go
+++ b/event.go
@@ -27,11 +27,17 @@ func NewEvent(t EventType) *Event {
}
}
+type Stdio struct {
+ Stderr string `json:"stderr,omitempty"`
+ Stdout string `json:"stdout,omitempty"`
+}
+
type Event struct {
Type EventType `json:"type"`
Timestamp time.Time `json:"timestamp"`
ID string `json:"id,omitempty"`
BundlePath string `json:"bundlePath,omitempty"`
+ Stdio *Stdio `json:"stdio,omitempty"`
Pid int `json:"pid,omitempty"`
Status int `json:"status,omitempty"`
Signal os.Signal `json:"signal,omitempty"`
diff --git a/runtime.go b/runtime.go
index 72daf9a..c74230a 100644
--- a/runtime.go
+++ b/runtime.go
@@ -4,6 +4,6 @@ import "github.com/opencontainers/specs"
// runtime handles containers, containers handle their own actions.
type Runtime interface {
- Create(id, bundlePath string) (Container, error)
- StartProcess(Container, specs.Process) (Process, error)
+ Create(id, bundlePath string, stdio *Stdio) (Container, error)
+ StartProcess(Container, specs.Process, *Stdio) (Process, error)
}
diff --git a/runtime_linux.go b/runtime_linux.go
index c840280..eee7f02 100644
--- a/runtime_linux.go
+++ b/runtime_linux.go
@@ -5,6 +5,7 @@ package containerd
import (
"encoding/json"
"fmt"
+ "io"
"os"
"path/filepath"
"runtime"
@@ -12,6 +13,7 @@ import (
"strings"
"syscall"
+ "github.com/Sirupsen/logrus"
"github.com/opencontainers/runc/libcontainer"
"github.com/opencontainers/runc/libcontainer/configs"
_ "github.com/opencontainers/runc/libcontainer/nsenter"
@@ -275,7 +277,7 @@ type libcontainerRuntime struct {
factory libcontainer.Factory
}
-func (r *libcontainerRuntime) Create(id, bundlePath string) (Container, error) {
+func (r *libcontainerRuntime) Create(id, bundlePath string, stdio *Stdio) (Container, error) {
spec, rspec, err := r.loadSpec(
filepath.Join(bundlePath, "config.json"),
filepath.Join(bundlePath, "runtime.json"),
@@ -291,7 +293,10 @@ func (r *libcontainerRuntime) Create(id, bundlePath string) (Container, error) {
if err != nil {
return nil, err
}
- process := r.newProcess(spec.Process)
+ process, err := r.newProcess(spec.Process, stdio)
+ if err != nil {
+ return nil, err
+ }
c := &libcontainerContainer{
c: container,
additionalProcesses: make(map[int]*libcontainerProcess),
@@ -304,12 +309,15 @@ func (r *libcontainerRuntime) Create(id, bundlePath string) (Container, error) {
return c, nil
}
-func (r *libcontainerRuntime) StartProcess(ci Container, p specs.Process) (Process, error) {
+func (r *libcontainerRuntime) StartProcess(ci Container, p specs.Process, stdio *Stdio) (Process, error) {
c, ok := ci.(*libcontainerContainer)
if !ok {
return nil, errInvalidContainerType
}
- process := r.newProcess(p)
+ process, err := r.newProcess(p, stdio)
+ if err != nil {
+ return nil, err
+ }
if err := c.c.Start(process); err != nil {
return nil, err
}
@@ -327,14 +335,36 @@ func (r *libcontainerRuntime) StartProcess(ci Container, p specs.Process) (Proce
// newProcess returns a new libcontainer Process with the arguments from the
// spec and stdio from the current process.
-func (r *libcontainerRuntime) newProcess(p specs.Process) *libcontainer.Process {
+func (r *libcontainerRuntime) newProcess(p specs.Process, stdio *Stdio) (*libcontainer.Process, error) {
+ var (
+ stderr, stdout io.Writer
+ )
+ if stdio != nil {
+ if stdio.Stdout != "" {
+ logrus.Debug("adding stdout")
+ f, err := os.OpenFile(stdio.Stdout, os.O_CREATE|os.O_WRONLY, 0755)
+ if err != nil {
+ return nil, err
+ }
+ stdout = f
+ }
+ if stdio.Stderr != "" {
+ f, err := os.OpenFile(stdio.Stderr, os.O_CREATE|os.O_WRONLY, 0755)
+ if err != nil {
+ return nil, err
+ }
+ stderr = f
+ }
+ }
return &libcontainer.Process{
Args: p.Args,
Env: p.Env,
// TODO: fix libcontainer's API to better support uid/gid in a typesafe way.
- User: fmt.Sprintf("%d:%d", p.User.UID, p.User.GID),
- Cwd: p.Cwd,
- }
+ User: fmt.Sprintf("%d:%d", p.User.UID, p.User.GID),
+ Cwd: p.Cwd,
+ Stderr: stderr,
+ Stdout: stdout,
+ }, nil
}
// loadSpec loads the specification from the provided path.
diff --git a/supervisor.go b/supervisor.go
index 35594ca..e664c66 100644
--- a/supervisor.go
+++ b/supervisor.go
@@ -101,7 +101,7 @@ func (s *Supervisor) Start(events chan *Event) error {
ne.ID = container.ID()
s.SendEvent(ne)
case StartContainerEventType:
- container, err := s.runtime.Create(e.ID, e.BundlePath)
+ container, err := s.runtime.Create(e.ID, e.BundlePath, e.Stdio)
if err != nil {
e.Err <- err
continue
@@ -147,7 +147,7 @@ func (s *Supervisor) Start(events chan *Event) error {
e.Err <- ErrContainerNotFound
continue
}
- p, err := s.runtime.StartProcess(container, *e.Process)
+ p, err := s.runtime.StartProcess(container, *e.Process, e.Stdio)
if err != nil {
e.Err <- err
continue