diff --git a/Gopkg.lock b/Gopkg.lock
deleted file mode 100644
index c2b3fde..0000000
--- a/Gopkg.lock
+++ /dev/null
@@ -1,36 +0,0 @@
-memo = "1deea5082a90ba9354cb673741e7fe51536ec1e85cd5653a96bf07da354c8647"
-
-[[projects]]
- name = "github.com/Sirupsen/logrus"
- packages = [".","hooks/test"]
- revision = "ba1b36c82c5e05c4f912a88eab0dcd91a171688f"
- version = "v0.11.5"
-
-[[projects]]
- name = "github.com/containers/virtcontainers"
- packages = ["pkg/hyperstart","pkg/hyperstart/mock"]
- revision = "93aa8226e6fa7e9bb2d553b571209f4f94e96348"
-
-[[projects]]
- name = "github.com/davecgh/go-spew"
- packages = ["spew"]
- revision = "346938d642f2ec3594ed81d874461961cd0faa76"
- version = "v1.1.0"
-
-[[projects]]
- name = "github.com/pmezard/go-difflib"
- packages = ["difflib"]
- revision = "792786c7400a136282c1664665ae0a8db921c6c2"
- version = "v1.0.0"
-
-[[projects]]
- branch = "master"
- name = "github.com/stretchr/testify"
- packages = ["assert"]
- revision = "4d4bfba8f1d1027c4fdbe371823030df51419987"
-
-[[projects]]
- branch = "master"
- name = "golang.org/x/sys"
- packages = ["unix"]
- revision = "ea9bcade75cb975a0b9738936568ab388b845617"
diff --git a/Gopkg.toml b/Gopkg.toml
deleted file mode 100644
index 25d8a14..0000000
--- a/Gopkg.toml
+++ /dev/null
@@ -1,12 +0,0 @@
-
-[[dependencies]]
- name = "github.com/containers/virtcontainers"
- revision = "93aa8226e6fa7e9bb2d553b571209f4f94e96348"
-
-[[dependencies]]
- branch = "master"
- name = "github.com/golang/glog"
-
-[[dependencies]]
- branch = "master"
- name = "github.com/stretchr/testify"
diff --git a/vendor/github.com/Sirupsen/logrus/.gitignore b/vendor/github.com/Sirupsen/logrus/.gitignore
deleted file mode 100644
index 66be63a..0000000
--- a/vendor/github.com/Sirupsen/logrus/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-logrus
diff --git a/vendor/github.com/Sirupsen/logrus/.travis.yml b/vendor/github.com/Sirupsen/logrus/.travis.yml
deleted file mode 100644
index 804c569..0000000
--- a/vendor/github.com/Sirupsen/logrus/.travis.yml
+++ /dev/null
@@ -1,8 +0,0 @@
-language: go
-go:
- - 1.6
- - 1.7
- - tip
-install:
- - go get -t ./...
-script: GOMAXPROCS=4 GORACE="halt_on_error=1" go test -race -v ./...
diff --git a/vendor/github.com/Sirupsen/logrus/CHANGELOG.md b/vendor/github.com/Sirupsen/logrus/CHANGELOG.md
deleted file mode 100644
index 747e4d8..0000000
--- a/vendor/github.com/Sirupsen/logrus/CHANGELOG.md
+++ /dev/null
@@ -1,94 +0,0 @@
-# 0.11.5
-
-* feature: add writer and writerlevel to entry (#372)
-
-# 0.11.4
-
-* bug: fix undefined variable on solaris (#493)
-
-# 0.11.3
-
-* formatter: configure quoting of empty values (#484)
-* formatter: configure quoting character (default is `"`) (#484)
-* bug: fix not importing io correctly in non-linux environments (#481)
-
-# 0.11.2
-
-* bug: fix windows terminal detection (#476)
-
-# 0.11.1
-
-* bug: fix tty detection with custom out (#471)
-
-# 0.11.0
-
-* performance: Use bufferpool to allocate (#370)
-* terminal: terminal detection for app-engine (#343)
-* feature: exit handler (#375)
-
-# 0.10.0
-
-* feature: Add a test hook (#180)
-* feature: `ParseLevel` is now case-insensitive (#326)
-* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308)
-* performance: avoid re-allocations on `WithFields` (#335)
-
-# 0.9.0
-
-* logrus/text_formatter: don't emit empty msg
-* logrus/hooks/airbrake: move out of main repository
-* logrus/hooks/sentry: move out of main repository
-* logrus/hooks/papertrail: move out of main repository
-* logrus/hooks/bugsnag: move out of main repository
-* logrus/core: run tests with `-race`
-* logrus/core: detect TTY based on `stderr`
-* logrus/core: support `WithError` on logger
-* logrus/core: Solaris support
-
-# 0.8.7
-
-* logrus/core: fix possible race (#216)
-* logrus/doc: small typo fixes and doc improvements
-
-
-# 0.8.6
-
-* hooks/raven: allow passing an initialized client
-
-# 0.8.5
-
-* logrus/core: revert #208
-
-# 0.8.4
-
-* formatter/text: fix data race (#218)
-
-# 0.8.3
-
-* logrus/core: fix entry log level (#208)
-* logrus/core: improve performance of text formatter by 40%
-* logrus/core: expose `LevelHooks` type
-* logrus/core: add support for DragonflyBSD and NetBSD
-* formatter/text: print structs more verbosely
-
-# 0.8.2
-
-* logrus: fix more Fatal family functions
-
-# 0.8.1
-
-* logrus: fix not exiting on `Fatalf` and `Fatalln`
-
-# 0.8.0
-
-* logrus: defaults to stderr instead of stdout
-* hooks/sentry: add special field for `*http.Request`
-* formatter/text: ignore Windows for colors
-
-# 0.7.3
-
-* formatter/\*: allow configuration of timestamp layout
-
-# 0.7.2
-
-* formatter/text: Add configuration option for time format (#158)
diff --git a/vendor/github.com/Sirupsen/logrus/LICENSE b/vendor/github.com/Sirupsen/logrus/LICENSE
deleted file mode 100644
index f090cb4..0000000
--- a/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/vendor/github.com/Sirupsen/logrus/README.md b/vendor/github.com/Sirupsen/logrus/README.md
deleted file mode 100644
index 640cf61..0000000
--- a/vendor/github.com/Sirupsen/logrus/README.md
+++ /dev/null
@@ -1,476 +0,0 @@
-# Logrus [![Build Status](https://travis-ci.org/Sirupsen/logrus.svg?branch=master)](https://travis-ci.org/Sirupsen/logrus) [![GoDoc](https://godoc.org/github.com/Sirupsen/logrus?status.svg)](https://godoc.org/github.com/Sirupsen/logrus)
-
-**Seeing weird case-sensitive problems?** See [this
-issue](https://github.com/sirupsen/logrus/issues/451#issuecomment-264332021).
-This change has been reverted. I apologize for causing this. I greatly
-underestimated the impact this would have. Logrus strives for stability and
-backwards compatibility and failed to provide that.
-
-Logrus is a structured logger for Go (golang), completely API compatible with
-the standard library logger. [Godoc][godoc]. **Please note the Logrus API is not
-yet stable (pre 1.0). Logrus itself is completely stable and has been used in
-many large deployments. The core API is unlikely to change much but please
-version control your Logrus to make sure you aren't fetching latest `master` on
-every build.**
-
-Nicely color-coded in development (when a TTY is attached, otherwise just
-plain text):
-
-![Colored](http://i.imgur.com/PY7qMwd.png)
-
-With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash
-or Splunk:
-
-```json
-{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the
-ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"}
-
-{"level":"warning","msg":"The group's number increased tremendously!",
-"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"}
-
-{"animal":"walrus","level":"info","msg":"A giant walrus appears!",
-"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"}
-
-{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.",
-"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"}
-
-{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,
-"time":"2014-03-10 19:57:38.562543128 -0400 EDT"}
-```
-
-With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not
-attached, the output is compatible with the
-[logfmt](http://godoc.org/github.com/kr/logfmt) format:
-
-```text
-time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8
-time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
-time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true
-time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4
-time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009
-time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true
-exit status 1
-```
-
-#### Example
-
-The simplest way to use Logrus is simply the package-level exported logger:
-
-```go
-package main
-
-import (
- log "github.com/Sirupsen/logrus"
-)
-
-func main() {
- log.WithFields(log.Fields{
- "animal": "walrus",
- }).Info("A walrus appears")
-}
-```
-
-Note that it's completely api-compatible with the stdlib logger, so you can
-replace your `log` imports everywhere with `log "github.com/Sirupsen/logrus"`
-and you'll now have the flexibility of Logrus. You can customize it all you
-want:
-
-```go
-package main
-
-import (
- "os"
- log "github.com/Sirupsen/logrus"
-)
-
-func init() {
- // Log as JSON instead of the default ASCII formatter.
- log.SetFormatter(&log.JSONFormatter{})
-
- // Output to stdout instead of the default stderr
- // Can be any io.Writer, see below for File example
- log.SetOutput(os.Stdout)
-
- // 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.Stdout
-
- // You could set this to any `io.Writer` such as a file
- // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY, 0666)
- // if err == nil {
- // log.Out = file
- // } else {
- // log.Info("Failed to log to file, using default 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.
-
-#### Default Fields
-
-Often it's helpful to have fields _always_ attached to log statements in an
-application or parts of one. For example, you may want to always log the
-`request_id` and `user_ip` in the context of a request. Instead of writing
-`log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on
-every line, you can create a `logrus.Entry` to pass around instead:
-
-```go
-requestLogger := log.WithFields(log.Fields{"request_id": request_id, user_ip: user_ip})
-requestLogger.Info("something happened on that request") # will log request_id and user_ip
-requestLogger.Warn("something not great happened")
-```
-
-#### Hooks
-
-You can add hooks for logging levels. For example to send errors to an exception
-tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to
-multiple places simultaneously, e.g. syslog.
-
-Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in
-`init`:
-
-```go
-import (
- log "github.com/Sirupsen/logrus"
- "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "aibrake"
- logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog"
- "log/syslog"
-)
-
-func init() {
-
- // Use the Airbrake hook to report errors that have Error severity or above to
- // an exception tracker. You can create custom hooks, see the Hooks section.
- log.AddHook(airbrake.NewHook(123, "xyz", "production"))
-
- hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
- if err != nil {
- log.Error("Unable to connect to local syslog daemon")
- } else {
- log.AddHook(hook)
- }
-}
-```
-Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md).
-
-| Hook | Description |
-| ----- | ----------- |
-| [Airbrake "legacy"](https://github.com/gemnasium/logrus-airbrake-legacy-hook) | Send errors to an exception tracking service compatible with the Airbrake API V2. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. |
-| [Airbrake](https://github.com/gemnasium/logrus-airbrake-hook) | Send errors to the Airbrake API V3. Uses the official [`gobrake`](https://github.com/airbrake/gobrake) behind the scenes. |
-| [Amazon Kinesis](https://github.com/evalphobia/logrus_kinesis) | Hook for logging to [Amazon Kinesis](https://aws.amazon.com/kinesis/) |
-| [Amqp-Hook](https://github.com/vladoatanasov/logrus_amqp) | Hook for logging to Amqp broker (Like RabbitMQ) |
-| [Bugsnag](https://github.com/Shopify/logrus-bugsnag/blob/master/bugsnag.go) | Send errors to the Bugsnag exception tracking service. |
-| [DeferPanic](https://github.com/deferpanic/dp-logrus) | Hook for logging to DeferPanic |
-| [ElasticSearch](https://github.com/sohlich/elogrus) | Hook for logging to ElasticSearch|
-| [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd |
-| [Go-Slack](https://github.com/multiplay/go-slack) | Hook for logging to [Slack](https://slack.com) |
-| [Graylog](https://github.com/gemnasium/logrus-graylog-hook) | Hook for logging to [Graylog](http://graylog2.org/) |
-| [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. |
-| [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger |
-| [InfluxDB](https://github.com/Abramovic/logrus_influxdb) | Hook for logging to influxdb |
-| [Influxus] (http://github.com/vlad-doru/influxus) | Hook for concurrently logging to [InfluxDB] (http://influxdata.com/) |
-| [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` |
-| [KafkaLogrus](https://github.com/goibibo/KafkaLogrus) | Hook for logging to kafka |
-| [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem |
-| [Logentries](https://github.com/jcftang/logentriesrus) | Hook for logging to [Logentries](https://logentries.com/) |
-| [Logentrus](https://github.com/puddingfactory/logentrus) | Hook for logging to [Logentries](https://logentries.com/) |
-| [Logmatic.io](https://github.com/logmatic/logmatic-go) | Hook for logging to [Logmatic.io](http://logmatic.io/) |
-| [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) |
-| [Logstash](https://github.com/bshuster-repo/logrus-logstash-hook) | Hook for logging to [Logstash](https://www.elastic.co/products/logstash) |
-| [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail |
-| [Mongodb](https://github.com/weekface/mgorus) | Hook for logging to mongodb |
-| [NATS-Hook](https://github.com/rybit/nats_logrus_hook) | Hook for logging to [NATS](https://nats.io) |
-| [Octokit](https://github.com/dorajistyle/logrus-octokit-hook) | Hook for logging to github via octokit |
-| [Papertrail](https://github.com/polds/logrus-papertrail-hook) | Send errors to the [Papertrail](https://papertrailapp.com) hosted logging service via UDP. |
-| [PostgreSQL](https://github.com/gemnasium/logrus-postgresql-hook) | Send logs to [PostgreSQL](http://postgresql.org) |
-| [Pushover](https://github.com/toorop/logrus_pushover) | Send error via [Pushover](https://pushover.net) |
-| [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) |
-| [Redis-Hook](https://github.com/rogierlommers/logrus-redis-hook) | Hook for logging to a ELK stack (through Redis) |
-| [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar |
-| [Scribe](https://github.com/sagar8192/logrus-scribe-hook) | Hook for logging to [Scribe](https://github.com/facebookarchive/scribe)|
-| [Sentry](https://github.com/evalphobia/logrus_sentry) | Send errors to the Sentry error logging and aggregation service. |
-| [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. |
-| [Stackdriver](https://github.com/knq/sdhook) | Hook for logging to [Google Stackdriver](https://cloud.google.com/logging/) |
-| [Sumorus](https://github.com/doublefree/sumorus) | Hook for logging to [SumoLogic](https://www.sumologic.com/)|
-| [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. |
-| [TraceView](https://github.com/evalphobia/logrus_appneta) | Hook for logging to [AppNeta TraceView](https://www.appneta.com/products/traceview/) |
-| [Typetalk](https://github.com/dragon3/logrus-typetalk-hook) | Hook for logging to [Typetalk](https://www.typetalk.in/) |
-| [logz.io](https://github.com/ripcurld00d/logrus-logzio-hook) | Hook for logging to [logz.io](https://logz.io), a Log as a Service using Logstash |
-
-#### Level logging
-
-Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic.
-
-```go
-log.Debug("Useful debugging information.")
-log.Info("Something noteworthy happened!")
-log.Warn("You should probably take a look at this.")
-log.Error("Something failed but I'm not quitting.")
-// Calls os.Exit(1) after logging
-log.Fatal("Bye.")
-// Calls panic() after logging
-log.Panic("I'm bailing.")
-```
-
-You can set the logging level on a `Logger`, then it will only log entries with
-that severity or anything above it:
-
-```go
-// Will log anything that is info or above (warn, error, fatal, panic). Default.
-log.SetLevel(log.InfoLevel)
-```
-
-It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose
-environment if your application has that.
-
-#### Entries
-
-Besides the fields added with `WithField` or `WithFields` some fields are
-automatically added to all logging events:
-
-1. `time`. The timestamp when the entry was created.
-2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after
- the `AddFields` call. E.g. `Failed to send event.`
-3. `level`. The logging level. E.g. `info`.
-
-#### Environments
-
-Logrus has no notion of environment.
-
-If you wish for hooks and formatters to only be used in specific environments,
-you should handle that yourself. For example, if your application has a global
-variable `Environment`, which is a string representation of the environment you
-could do:
-
-```go
-import (
- log "github.com/Sirupsen/logrus"
-)
-
-init() {
- // do something here to set environment depending on an environment variable
- // or command-line flag
- if Environment == "production" {
- log.SetFormatter(&log.JSONFormatter{})
- } else {
- // The TextFormatter is default, you don't actually have to do this.
- log.SetFormatter(&log.TextFormatter{})
- }
-}
-```
-
-This configuration is how `logrus` was intended to be used, but JSON in
-production is mostly only useful if you do log aggregation with tools like
-Splunk or Logstash.
-
-#### Formatters
-
-The built-in logging formatters are:
-
-* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise
- without colors.
- * *Note:* to force colored output when there is no TTY, set the `ForceColors`
- field to `true`. To force no colored output even if there is a TTY set the
- `DisableColors` field to `true`. For Windows, see
- [github.com/mattn/go-colorable](https://github.com/mattn/go-colorable).
- * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter).
-* `logrus.JSONFormatter`. Logs fields as JSON.
- * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter).
-
-Third party logging formatters:
-
-* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events.
-* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout.
-* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦.
-
-You can define your formatter by implementing the `Formatter` interface,
-requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a
-`Fields` type (`map[string]interface{}`) with all your fields as well as the
-default ones (see Entries section above):
-
-```go
-type MyJSONFormatter struct {
-}
-
-log.SetFormatter(new(MyJSONFormatter))
-
-func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
- // Note this doesn't include Time, Level and Message which are available on
- // the Entry. Consult `godoc` on information about those fields or read the
- // source of the official loggers.
- serialized, err := json.Marshal(entry.Data)
- if err != nil {
- return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
- }
- return append(serialized, '\n'), nil
-}
-```
-
-#### Logger as an `io.Writer`
-
-Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it.
-
-```go
-w := logger.Writer()
-defer w.Close()
-
-srv := http.Server{
- // create a stdlib log.Logger that writes to
- // logrus.Logger.
- ErrorLog: log.New(w, "", 0),
-}
-```
-
-Each line written to that writer will be printed the usual way, using formatters
-and hooks. The level for those entries is `info`.
-
-This means that we can override the standard library logger easily:
-
-```go
-logger := logrus.New()
-logger.Formatter = &logrus.JSONFormatter{}
-
-// Use logrus for standard log output
-// Note that `log` here references stdlib's log
-// Not logrus imported under the name `log`.
-log.SetOutput(logger.Writer())
-```
-
-#### Rotation
-
-Log rotation is not provided with Logrus. Log rotation should be done by an
-external program (like `logrotate(8)`) that can compress and delete old log
-entries. It should not be a feature of the application-level logger.
-
-#### Tools
-
-| Tool | Description |
-| ---- | ----------- |
-|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.|
-|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper arround Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) |
-
-#### Testing
-
-Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides:
-
-* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook
-* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any):
-
-```go
-logger, hook := NewNullLogger()
-logger.Error("Hello error")
-
-assert.Equal(1, len(hook.Entries))
-assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
-assert.Equal("Hello error", hook.LastEntry().Message)
-
-hook.Reset()
-assert.Nil(hook.LastEntry())
-```
-
-#### Fatal handlers
-
-Logrus can register one or more functions that will be called when any `fatal`
-level message is logged. The registered handlers will be executed before
-logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need
-to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted.
-
-```
-...
-handler := func() {
- // gracefully shutdown something...
-}
-logrus.RegisterExitHandler(handler)
-...
-```
-
-#### Thread safety
-
-By default Logger is protected by mutex for concurrent writes, this mutex is invoked when calling hooks and writing logs.
-If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking.
-
-Situation when locking is not needed includes:
-
-* You have no hooks registered, or hooks calling is already thread-safe.
-
-* Writing to logger.Out is already thread-safe, for example:
-
- 1) logger.Out is protected by locks.
-
- 2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing)
-
- (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/)
diff --git a/vendor/github.com/Sirupsen/logrus/alt_exit.go b/vendor/github.com/Sirupsen/logrus/alt_exit.go
deleted file mode 100644
index b4c9e84..0000000
--- a/vendor/github.com/Sirupsen/logrus/alt_exit.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package logrus
-
-// The following code was sourced and modified from the
-// https://bitbucket.org/tebeka/atexit package governed by the following license:
-//
-// Copyright (c) 2012 Miki Tebeka .
-//
-// 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.
-
-import (
- "fmt"
- "os"
-)
-
-var handlers = []func(){}
-
-func runHandler(handler func()) {
- defer func() {
- if err := recover(); err != nil {
- fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err)
- }
- }()
-
- handler()
-}
-
-func runHandlers() {
- for _, handler := range handlers {
- runHandler(handler)
- }
-}
-
-// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)
-func Exit(code int) {
- runHandlers()
- os.Exit(code)
-}
-
-// RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke
-// all handlers. The handlers will also be invoked when any Fatal log entry is
-// made.
-//
-// This method is useful when a caller wishes to use logrus to log a fatal
-// message but also needs to gracefully shutdown. An example usecase could be
-// closing database connections, or sending a alert that the application is
-// closing.
-func RegisterExitHandler(handler func()) {
- handlers = append(handlers, handler)
-}
diff --git a/vendor/github.com/Sirupsen/logrus/alt_exit_test.go b/vendor/github.com/Sirupsen/logrus/alt_exit_test.go
deleted file mode 100644
index 022b778..0000000
--- a/vendor/github.com/Sirupsen/logrus/alt_exit_test.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package logrus
-
-import (
- "io/ioutil"
- "os/exec"
- "testing"
- "time"
-)
-
-func TestRegister(t *testing.T) {
- current := len(handlers)
- RegisterExitHandler(func() {})
- if len(handlers) != current+1 {
- t.Fatalf("can't add handler")
- }
-}
-
-func TestHandler(t *testing.T) {
- gofile := "/tmp/testprog.go"
- if err := ioutil.WriteFile(gofile, testprog, 0666); err != nil {
- t.Fatalf("can't create go file")
- }
-
- outfile := "/tmp/testprog.out"
- arg := time.Now().UTC().String()
- err := exec.Command("go", "run", gofile, outfile, arg).Run()
- if err == nil {
- t.Fatalf("completed normally, should have failed")
- }
-
- data, err := ioutil.ReadFile(outfile)
- if err != nil {
- t.Fatalf("can't read output file %s", outfile)
- }
-
- if string(data) != arg {
- t.Fatalf("bad data")
- }
-}
-
-var testprog = []byte(`
-// Test program for atexit, gets output file and data as arguments and writes
-// data to output file in atexit handler.
-package main
-
-import (
- "github.com/Sirupsen/logrus"
- "flag"
- "fmt"
- "io/ioutil"
-)
-
-var outfile = ""
-var data = ""
-
-func handler() {
- ioutil.WriteFile(outfile, []byte(data), 0666)
-}
-
-func badHandler() {
- n := 0
- fmt.Println(1/n)
-}
-
-func main() {
- flag.Parse()
- outfile = flag.Arg(0)
- data = flag.Arg(1)
-
- logrus.RegisterExitHandler(handler)
- logrus.RegisterExitHandler(badHandler)
- logrus.Fatal("Bye bye")
-}
-`)
diff --git a/vendor/github.com/Sirupsen/logrus/doc.go b/vendor/github.com/Sirupsen/logrus/doc.go
deleted file mode 100644
index dddd5f8..0000000
--- a/vendor/github.com/Sirupsen/logrus/doc.go
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
-Package logrus is a structured logger for Go, completely API compatible with the standard library logger.
-
-
-The simplest way to use Logrus is simply the package-level exported logger:
-
- package main
-
- import (
- log "github.com/Sirupsen/logrus"
- )
-
- func main() {
- log.WithFields(log.Fields{
- "animal": "walrus",
- "number": 1,
- "size": 10,
- }).Info("A walrus appears")
- }
-
-Output:
- time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10
-
-For a full guide visit https://github.com/Sirupsen/logrus
-*/
-package logrus
diff --git a/vendor/github.com/Sirupsen/logrus/entry.go b/vendor/github.com/Sirupsen/logrus/entry.go
deleted file mode 100644
index 4edbe7a..0000000
--- a/vendor/github.com/Sirupsen/logrus/entry.go
+++ /dev/null
@@ -1,275 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "fmt"
- "os"
- "sync"
- "time"
-)
-
-var bufferPool *sync.Pool
-
-func init() {
- bufferPool = &sync.Pool{
- New: func() interface{} {
- return new(bytes.Buffer)
- },
- }
-}
-
-// Defines the key when adding errors using WithError.
-var ErrorKey = "error"
-
-// 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
-
- // When formatter is called in entry.log(), an Buffer may be set to entry
- Buffer *bytes.Buffer
-}
-
-func NewEntry(logger *Logger) *Entry {
- return &Entry{
- Logger: logger,
- // Default is three fields, give a little extra room
- Data: make(Fields, 5),
- }
-}
-
-// Returns the string representation from the reader and ultimately the
-// formatter.
-func (entry *Entry) String() (string, error) {
- serialized, err := entry.Logger.Formatter.Format(entry)
- if err != nil {
- return "", err
- }
- str := string(serialized)
- return str, nil
-}
-
-// Add an error as single field (using the key defined in ErrorKey) to the Entry.
-func (entry *Entry) WithError(err error) *Entry {
- return entry.WithField(ErrorKey, 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 := make(Fields, len(entry.Data)+len(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}
-}
-
-// This function is not declared with a pointer value because otherwise
-// race conditions will occur when using multiple goroutines
-func (entry Entry) log(level Level, msg string) {
- var buffer *bytes.Buffer
- 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()
- }
- buffer = bufferPool.Get().(*bytes.Buffer)
- buffer.Reset()
- defer bufferPool.Put(buffer)
- entry.Buffer = buffer
- serialized, err := entry.Logger.Formatter.Format(&entry)
- entry.Buffer = nil
- if err != nil {
- entry.Logger.mu.Lock()
- fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
- entry.Logger.mu.Unlock()
- } else {
- entry.Logger.mu.Lock()
- _, err = entry.Logger.Out.Write(serialized)
- if err != nil {
- fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
- }
- entry.Logger.mu.Unlock()
- }
-
- // 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...))
- }
- 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...))
- }
- Exit(1)
-}
-
-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...))
- }
- Exit(1)
-}
-
-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/vendor/github.com/Sirupsen/logrus/entry_test.go b/vendor/github.com/Sirupsen/logrus/entry_test.go
deleted file mode 100644
index 99c3b41..0000000
--- a/vendor/github.com/Sirupsen/logrus/entry_test.go
+++ /dev/null
@@ -1,77 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "fmt"
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestEntryWithError(t *testing.T) {
-
- assert := assert.New(t)
-
- defer func() {
- ErrorKey = "error"
- }()
-
- err := fmt.Errorf("kaboom at layer %d", 4711)
-
- assert.Equal(err, WithError(err).Data["error"])
-
- logger := New()
- logger.Out = &bytes.Buffer{}
- entry := NewEntry(logger)
-
- assert.Equal(err, entry.WithError(err).Data["error"])
-
- ErrorKey = "err"
-
- assert.Equal(err, entry.WithError(err).Data["err"])
-
-}
-
-func TestEntryPanicln(t *testing.T) {
- errBoom := fmt.Errorf("boom time")
-
- defer func() {
- p := recover()
- assert.NotNil(t, p)
-
- switch pVal := p.(type) {
- case *Entry:
- assert.Equal(t, "kaboom", pVal.Message)
- assert.Equal(t, errBoom, pVal.Data["err"])
- default:
- t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal)
- }
- }()
-
- logger := New()
- logger.Out = &bytes.Buffer{}
- entry := NewEntry(logger)
- entry.WithField("err", errBoom).Panicln("kaboom")
-}
-
-func TestEntryPanicf(t *testing.T) {
- errBoom := fmt.Errorf("boom again")
-
- defer func() {
- p := recover()
- assert.NotNil(t, p)
-
- switch pVal := p.(type) {
- case *Entry:
- assert.Equal(t, "kaboom true", pVal.Message)
- assert.Equal(t, errBoom, pVal.Data["err"])
- default:
- t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal)
- }
- }()
-
- logger := New()
- logger.Out = &bytes.Buffer{}
- entry := NewEntry(logger)
- entry.WithField("err", errBoom).Panicf("kaboom %v", true)
-}
diff --git a/vendor/github.com/Sirupsen/logrus/exported.go b/vendor/github.com/Sirupsen/logrus/exported.go
deleted file mode 100644
index 9a0120a..0000000
--- a/vendor/github.com/Sirupsen/logrus/exported.go
+++ /dev/null
@@ -1,193 +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)
-}
-
-// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.
-func WithError(err error) *Entry {
- return std.WithField(ErrorKey, err)
-}
-
-// 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/vendor/github.com/Sirupsen/logrus/formatter.go b/vendor/github.com/Sirupsen/logrus/formatter.go
deleted file mode 100644
index b5fbe93..0000000
--- a/vendor/github.com/Sirupsen/logrus/formatter.go
+++ /dev/null
@@ -1,45 +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) {
- if t, ok := data["time"]; ok {
- data["fields.time"] = t
- }
-
- if m, ok := data["msg"]; ok {
- data["fields.msg"] = m
- }
-
- if l, ok := data["level"]; ok {
- data["fields.level"] = l
- }
-}
diff --git a/vendor/github.com/Sirupsen/logrus/formatter_bench_test.go b/vendor/github.com/Sirupsen/logrus/formatter_bench_test.go
deleted file mode 100644
index d948158..0000000
--- a/vendor/github.com/Sirupsen/logrus/formatter_bench_test.go
+++ /dev/null
@@ -1,101 +0,0 @@
-package logrus
-
-import (
- "fmt"
- "testing"
- "time"
-)
-
-// smallFields is a small size data set for benchmarking
-var smallFields = Fields{
- "foo": "bar",
- "baz": "qux",
- "one": "two",
- "three": "four",
-}
-
-// largeFields is a large size data set for benchmarking
-var largeFields = Fields{
- "foo": "bar",
- "baz": "qux",
- "one": "two",
- "three": "four",
- "five": "six",
- "seven": "eight",
- "nine": "ten",
- "eleven": "twelve",
- "thirteen": "fourteen",
- "fifteen": "sixteen",
- "seventeen": "eighteen",
- "nineteen": "twenty",
- "a": "b",
- "c": "d",
- "e": "f",
- "g": "h",
- "i": "j",
- "k": "l",
- "m": "n",
- "o": "p",
- "q": "r",
- "s": "t",
- "u": "v",
- "w": "x",
- "y": "z",
- "this": "will",
- "make": "thirty",
- "entries": "yeah",
-}
-
-var errorFields = Fields{
- "foo": fmt.Errorf("bar"),
- "baz": fmt.Errorf("qux"),
-}
-
-func BenchmarkErrorTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{DisableColors: true}, errorFields)
-}
-
-func BenchmarkSmallTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{DisableColors: true}, smallFields)
-}
-
-func BenchmarkLargeTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{DisableColors: true}, largeFields)
-}
-
-func BenchmarkSmallColoredTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{ForceColors: true}, smallFields)
-}
-
-func BenchmarkLargeColoredTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{ForceColors: true}, largeFields)
-}
-
-func BenchmarkSmallJSONFormatter(b *testing.B) {
- doBenchmark(b, &JSONFormatter{}, smallFields)
-}
-
-func BenchmarkLargeJSONFormatter(b *testing.B) {
- doBenchmark(b, &JSONFormatter{}, largeFields)
-}
-
-func doBenchmark(b *testing.B, formatter Formatter, fields Fields) {
- logger := New()
-
- entry := &Entry{
- Time: time.Time{},
- Level: InfoLevel,
- Message: "message",
- Data: fields,
- Logger: logger,
- }
- var d []byte
- var err error
- for i := 0; i < b.N; i++ {
- d, err = formatter.Format(entry)
- if err != nil {
- b.Fatal(err)
- }
- b.SetBytes(int64(len(d)))
- }
-}
diff --git a/vendor/github.com/Sirupsen/logrus/hook_test.go b/vendor/github.com/Sirupsen/logrus/hook_test.go
deleted file mode 100644
index 13f34cb..0000000
--- a/vendor/github.com/Sirupsen/logrus/hook_test.go
+++ /dev/null
@@ -1,122 +0,0 @@
-package logrus
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-type TestHook struct {
- Fired bool
-}
-
-func (hook *TestHook) Fire(entry *Entry) error {
- hook.Fired = true
- return nil
-}
-
-func (hook *TestHook) Levels() []Level {
- return []Level{
- DebugLevel,
- InfoLevel,
- WarnLevel,
- ErrorLevel,
- FatalLevel,
- PanicLevel,
- }
-}
-
-func TestHookFires(t *testing.T) {
- hook := new(TestHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook)
- assert.Equal(t, hook.Fired, false)
-
- log.Print("test")
- }, func(fields Fields) {
- assert.Equal(t, hook.Fired, true)
- })
-}
-
-type ModifyHook struct {
-}
-
-func (hook *ModifyHook) Fire(entry *Entry) error {
- entry.Data["wow"] = "whale"
- return nil
-}
-
-func (hook *ModifyHook) Levels() []Level {
- return []Level{
- DebugLevel,
- InfoLevel,
- WarnLevel,
- ErrorLevel,
- FatalLevel,
- PanicLevel,
- }
-}
-
-func TestHookCanModifyEntry(t *testing.T) {
- hook := new(ModifyHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook)
- log.WithField("wow", "elephant").Print("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["wow"], "whale")
- })
-}
-
-func TestCanFireMultipleHooks(t *testing.T) {
- hook1 := new(ModifyHook)
- hook2 := new(TestHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook1)
- log.Hooks.Add(hook2)
-
- log.WithField("wow", "elephant").Print("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["wow"], "whale")
- assert.Equal(t, hook2.Fired, true)
- })
-}
-
-type ErrorHook struct {
- Fired bool
-}
-
-func (hook *ErrorHook) Fire(entry *Entry) error {
- hook.Fired = true
- return nil
-}
-
-func (hook *ErrorHook) Levels() []Level {
- return []Level{
- ErrorLevel,
- }
-}
-
-func TestErrorHookShouldntFireOnInfo(t *testing.T) {
- hook := new(ErrorHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook)
- log.Info("test")
- }, func(fields Fields) {
- assert.Equal(t, hook.Fired, false)
- })
-}
-
-func TestErrorHookShouldFireOnError(t *testing.T) {
- hook := new(ErrorHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook)
- log.Error("test")
- }, func(fields Fields) {
- assert.Equal(t, hook.Fired, true)
- })
-}
diff --git a/vendor/github.com/Sirupsen/logrus/hooks.go b/vendor/github.com/Sirupsen/logrus/hooks.go
deleted file mode 100644
index 3f151cd..0000000
--- a/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/vendor/github.com/Sirupsen/logrus/hooks/test/test.go b/vendor/github.com/Sirupsen/logrus/hooks/test/test.go
deleted file mode 100644
index 0688125..0000000
--- a/vendor/github.com/Sirupsen/logrus/hooks/test/test.go
+++ /dev/null
@@ -1,67 +0,0 @@
-package test
-
-import (
- "io/ioutil"
-
- "github.com/Sirupsen/logrus"
-)
-
-// test.Hook is a hook designed for dealing with logs in test scenarios.
-type Hook struct {
- Entries []*logrus.Entry
-}
-
-// Installs a test hook for the global logger.
-func NewGlobal() *Hook {
-
- hook := new(Hook)
- logrus.AddHook(hook)
-
- return hook
-
-}
-
-// Installs a test hook for a given local logger.
-func NewLocal(logger *logrus.Logger) *Hook {
-
- hook := new(Hook)
- logger.Hooks.Add(hook)
-
- return hook
-
-}
-
-// Creates a discarding logger and installs the test hook.
-func NewNullLogger() (*logrus.Logger, *Hook) {
-
- logger := logrus.New()
- logger.Out = ioutil.Discard
-
- return logger, NewLocal(logger)
-
-}
-
-func (t *Hook) Fire(e *logrus.Entry) error {
- t.Entries = append(t.Entries, e)
- return nil
-}
-
-func (t *Hook) Levels() []logrus.Level {
- return logrus.AllLevels
-}
-
-// LastEntry returns the last entry that was logged or nil.
-func (t *Hook) LastEntry() (l *logrus.Entry) {
-
- if i := len(t.Entries) - 1; i < 0 {
- return nil
- } else {
- return t.Entries[i]
- }
-
-}
-
-// Reset removes all Entries from this test hook.
-func (t *Hook) Reset() {
- t.Entries = make([]*logrus.Entry, 0)
-}
diff --git a/vendor/github.com/Sirupsen/logrus/hooks/test/test_test.go b/vendor/github.com/Sirupsen/logrus/hooks/test/test_test.go
deleted file mode 100644
index d69455b..0000000
--- a/vendor/github.com/Sirupsen/logrus/hooks/test/test_test.go
+++ /dev/null
@@ -1,39 +0,0 @@
-package test
-
-import (
- "testing"
-
- "github.com/Sirupsen/logrus"
- "github.com/stretchr/testify/assert"
-)
-
-func TestAllHooks(t *testing.T) {
-
- assert := assert.New(t)
-
- logger, hook := NewNullLogger()
- assert.Nil(hook.LastEntry())
- assert.Equal(0, len(hook.Entries))
-
- logger.Error("Hello error")
- assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
- assert.Equal("Hello error", hook.LastEntry().Message)
- assert.Equal(1, len(hook.Entries))
-
- logger.Warn("Hello warning")
- assert.Equal(logrus.WarnLevel, hook.LastEntry().Level)
- assert.Equal("Hello warning", hook.LastEntry().Message)
- assert.Equal(2, len(hook.Entries))
-
- hook.Reset()
- assert.Nil(hook.LastEntry())
- assert.Equal(0, len(hook.Entries))
-
- hook = NewGlobal()
-
- logrus.Error("Hello error")
- assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
- assert.Equal("Hello error", hook.LastEntry().Message)
- assert.Equal(1, len(hook.Entries))
-
-}
diff --git a/vendor/github.com/Sirupsen/logrus/json_formatter.go b/vendor/github.com/Sirupsen/logrus/json_formatter.go
deleted file mode 100644
index 266554e..0000000
--- a/vendor/github.com/Sirupsen/logrus/json_formatter.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package logrus
-
-import (
- "encoding/json"
- "fmt"
-)
-
-type fieldKey string
-type FieldMap map[fieldKey]string
-
-const (
- FieldKeyMsg = "msg"
- FieldKeyLevel = "level"
- FieldKeyTime = "time"
-)
-
-func (f FieldMap) resolve(key fieldKey) string {
- if k, ok := f[key]; ok {
- return k
- }
-
- return string(key)
-}
-
-type JSONFormatter struct {
- // TimestampFormat sets the format used for marshaling timestamps.
- TimestampFormat string
-
- // DisableTimestamp allows disabling automatic timestamps in output
- DisableTimestamp bool
-
- // FieldMap allows users to customize the names of keys for various fields.
- // As an example:
- // formatter := &JSONFormatter{
- // FieldMap: FieldMap{
- // FieldKeyTime: "@timestamp",
- // FieldKeyLevel: "@level",
- // FieldKeyLevel: "@message",
- // },
- // }
- FieldMap FieldMap
-}
-
-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)
-
- timestampFormat := f.TimestampFormat
- if timestampFormat == "" {
- timestampFormat = DefaultTimestampFormat
- }
-
- if !f.DisableTimestamp {
- data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat)
- }
- data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message
- data[f.FieldMap.resolve(FieldKeyLevel)] = 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/vendor/github.com/Sirupsen/logrus/json_formatter_test.go b/vendor/github.com/Sirupsen/logrus/json_formatter_test.go
deleted file mode 100644
index 51093a7..0000000
--- a/vendor/github.com/Sirupsen/logrus/json_formatter_test.go
+++ /dev/null
@@ -1,199 +0,0 @@
-package logrus
-
-import (
- "encoding/json"
- "errors"
- "strings"
- "testing"
-)
-
-func TestErrorNotLost(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("error", errors.New("wild walrus")))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["error"] != "wild walrus" {
- t.Fatal("Error field not set")
- }
-}
-
-func TestErrorNotLostOnFieldNotNamedError(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("omg", errors.New("wild walrus")))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["omg"] != "wild walrus" {
- t.Fatal("Error field not set")
- }
-}
-
-func TestFieldClashWithTime(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("time", "right now!"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["fields.time"] != "right now!" {
- t.Fatal("fields.time not set to original time field")
- }
-
- if entry["time"] != "0001-01-01T00:00:00Z" {
- t.Fatal("time field not set to current time, was: ", entry["time"])
- }
-}
-
-func TestFieldClashWithMsg(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("msg", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["fields.msg"] != "something" {
- t.Fatal("fields.msg not set to original msg field")
- }
-}
-
-func TestFieldClashWithLevel(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("level", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["fields.level"] != "something" {
- t.Fatal("fields.level not set to original level field")
- }
-}
-
-func TestJSONEntryEndsWithNewline(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("level", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- if b[len(b)-1] != '\n' {
- t.Fatal("Expected JSON log entry to end with a newline")
- }
-}
-
-func TestJSONMessageKey(t *testing.T) {
- formatter := &JSONFormatter{
- FieldMap: FieldMap{
- FieldKeyMsg: "message",
- },
- }
-
- b, err := formatter.Format(&Entry{Message: "oh hai"})
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
- s := string(b)
- if !(strings.Contains(s, "message") && strings.Contains(s, "oh hai")) {
- t.Fatal("Expected JSON to format message key")
- }
-}
-
-func TestJSONLevelKey(t *testing.T) {
- formatter := &JSONFormatter{
- FieldMap: FieldMap{
- FieldKeyLevel: "somelevel",
- },
- }
-
- b, err := formatter.Format(WithField("level", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
- s := string(b)
- if !strings.Contains(s, "somelevel") {
- t.Fatal("Expected JSON to format level key")
- }
-}
-
-func TestJSONTimeKey(t *testing.T) {
- formatter := &JSONFormatter{
- FieldMap: FieldMap{
- FieldKeyTime: "timeywimey",
- },
- }
-
- b, err := formatter.Format(WithField("level", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
- s := string(b)
- if !strings.Contains(s, "timeywimey") {
- t.Fatal("Expected JSON to format time key")
- }
-}
-
-func TestJSONDisableTimestamp(t *testing.T) {
- formatter := &JSONFormatter{
- DisableTimestamp: true,
- }
-
- b, err := formatter.Format(WithField("level", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
- s := string(b)
- if strings.Contains(s, FieldKeyTime) {
- t.Error("Did not prevent timestamp", s)
- }
-}
-
-func TestJSONEnableTimestamp(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("level", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
- s := string(b)
- if !strings.Contains(s, FieldKeyTime) {
- t.Error("Timestamp not present", s)
- }
-}
diff --git a/vendor/github.com/Sirupsen/logrus/logger.go b/vendor/github.com/Sirupsen/logrus/logger.go
deleted file mode 100644
index b769f3d..0000000
--- a/vendor/github.com/Sirupsen/logrus/logger.go
+++ /dev/null
@@ -1,308 +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.Stderr`. 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. Locking is enabled by Default
- mu MutexWrap
- // Reusable empty entry
- entryPool sync.Pool
-}
-
-type MutexWrap struct {
- lock sync.Mutex
- disabled bool
-}
-
-func (mw *MutexWrap) Lock() {
- if !mw.disabled {
- mw.lock.Lock()
- }
-}
-
-func (mw *MutexWrap) Unlock() {
- if !mw.disabled {
- mw.lock.Unlock()
- }
-}
-
-func (mw *MutexWrap) Disable() {
- mw.disabled = true
-}
-
-// 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.Stderr,
- Formatter: new(TextFormatter),
- Hooks: make(LevelHooks),
- Level: InfoLevel,
- }
-}
-
-func (logger *Logger) newEntry() *Entry {
- entry, ok := logger.entryPool.Get().(*Entry)
- if ok {
- return entry
- }
- return NewEntry(logger)
-}
-
-func (logger *Logger) releaseEntry(entry *Entry) {
- logger.entryPool.Put(entry)
-}
-
-// Adds a field to the log entry, note that it doesn't log until you call
-// Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry.
-// If you want multiple fields, use `WithFields`.
-func (logger *Logger) WithField(key string, value interface{}) *Entry {
- entry := logger.newEntry()
- defer logger.releaseEntry(entry)
- return entry.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 {
- entry := logger.newEntry()
- defer logger.releaseEntry(entry)
- return entry.WithFields(fields)
-}
-
-// Add an error as single field to the log entry. All it does is call
-// `WithError` for the given `error`.
-func (logger *Logger) WithError(err error) *Entry {
- entry := logger.newEntry()
- defer logger.releaseEntry(entry)
- return entry.WithError(err)
-}
-
-func (logger *Logger) Debugf(format string, args ...interface{}) {
- if logger.Level >= DebugLevel {
- entry := logger.newEntry()
- entry.Debugf(format, args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Infof(format string, args ...interface{}) {
- if logger.Level >= InfoLevel {
- entry := logger.newEntry()
- entry.Infof(format, args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Printf(format string, args ...interface{}) {
- entry := logger.newEntry()
- entry.Printf(format, args...)
- logger.releaseEntry(entry)
-}
-
-func (logger *Logger) Warnf(format string, args ...interface{}) {
- if logger.Level >= WarnLevel {
- entry := logger.newEntry()
- entry.Warnf(format, args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Warningf(format string, args ...interface{}) {
- if logger.Level >= WarnLevel {
- entry := logger.newEntry()
- entry.Warnf(format, args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Errorf(format string, args ...interface{}) {
- if logger.Level >= ErrorLevel {
- entry := logger.newEntry()
- entry.Errorf(format, args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Fatalf(format string, args ...interface{}) {
- if logger.Level >= FatalLevel {
- entry := logger.newEntry()
- entry.Fatalf(format, args...)
- logger.releaseEntry(entry)
- }
- Exit(1)
-}
-
-func (logger *Logger) Panicf(format string, args ...interface{}) {
- if logger.Level >= PanicLevel {
- entry := logger.newEntry()
- entry.Panicf(format, args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Debug(args ...interface{}) {
- if logger.Level >= DebugLevel {
- entry := logger.newEntry()
- entry.Debug(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Info(args ...interface{}) {
- if logger.Level >= InfoLevel {
- entry := logger.newEntry()
- entry.Info(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Print(args ...interface{}) {
- entry := logger.newEntry()
- entry.Info(args...)
- logger.releaseEntry(entry)
-}
-
-func (logger *Logger) Warn(args ...interface{}) {
- if logger.Level >= WarnLevel {
- entry := logger.newEntry()
- entry.Warn(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Warning(args ...interface{}) {
- if logger.Level >= WarnLevel {
- entry := logger.newEntry()
- entry.Warn(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Error(args ...interface{}) {
- if logger.Level >= ErrorLevel {
- entry := logger.newEntry()
- entry.Error(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Fatal(args ...interface{}) {
- if logger.Level >= FatalLevel {
- entry := logger.newEntry()
- entry.Fatal(args...)
- logger.releaseEntry(entry)
- }
- Exit(1)
-}
-
-func (logger *Logger) Panic(args ...interface{}) {
- if logger.Level >= PanicLevel {
- entry := logger.newEntry()
- entry.Panic(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Debugln(args ...interface{}) {
- if logger.Level >= DebugLevel {
- entry := logger.newEntry()
- entry.Debugln(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Infoln(args ...interface{}) {
- if logger.Level >= InfoLevel {
- entry := logger.newEntry()
- entry.Infoln(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Println(args ...interface{}) {
- entry := logger.newEntry()
- entry.Println(args...)
- logger.releaseEntry(entry)
-}
-
-func (logger *Logger) Warnln(args ...interface{}) {
- if logger.Level >= WarnLevel {
- entry := logger.newEntry()
- entry.Warnln(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Warningln(args ...interface{}) {
- if logger.Level >= WarnLevel {
- entry := logger.newEntry()
- entry.Warnln(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Errorln(args ...interface{}) {
- if logger.Level >= ErrorLevel {
- entry := logger.newEntry()
- entry.Errorln(args...)
- logger.releaseEntry(entry)
- }
-}
-
-func (logger *Logger) Fatalln(args ...interface{}) {
- if logger.Level >= FatalLevel {
- entry := logger.newEntry()
- entry.Fatalln(args...)
- logger.releaseEntry(entry)
- }
- Exit(1)
-}
-
-func (logger *Logger) Panicln(args ...interface{}) {
- if logger.Level >= PanicLevel {
- entry := logger.newEntry()
- entry.Panicln(args...)
- logger.releaseEntry(entry)
- }
-}
-
-//When file is opened with appending mode, it's safe to
-//write concurrently to a file (within 4k message on Linux).
-//In these cases user can choose to disable the lock.
-func (logger *Logger) SetNoLock() {
- logger.mu.Disable()
-}
diff --git a/vendor/github.com/Sirupsen/logrus/logger_bench_test.go b/vendor/github.com/Sirupsen/logrus/logger_bench_test.go
deleted file mode 100644
index dd23a35..0000000
--- a/vendor/github.com/Sirupsen/logrus/logger_bench_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-package logrus
-
-import (
- "os"
- "testing"
-)
-
-// smallFields is a small size data set for benchmarking
-var loggerFields = Fields{
- "foo": "bar",
- "baz": "qux",
- "one": "two",
- "three": "four",
-}
-
-func BenchmarkDummyLogger(b *testing.B) {
- nullf, err := os.OpenFile("/dev/null", os.O_WRONLY, 0666)
- if err != nil {
- b.Fatalf("%v", err)
- }
- defer nullf.Close()
- doLoggerBenchmark(b, nullf, &TextFormatter{DisableColors: true}, smallFields)
-}
-
-func BenchmarkDummyLoggerNoLock(b *testing.B) {
- nullf, err := os.OpenFile("/dev/null", os.O_WRONLY|os.O_APPEND, 0666)
- if err != nil {
- b.Fatalf("%v", err)
- }
- defer nullf.Close()
- doLoggerBenchmarkNoLock(b, nullf, &TextFormatter{DisableColors: true}, smallFields)
-}
-
-func doLoggerBenchmark(b *testing.B, out *os.File, formatter Formatter, fields Fields) {
- logger := Logger{
- Out: out,
- Level: InfoLevel,
- Formatter: formatter,
- }
- entry := logger.WithFields(fields)
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- entry.Info("aaa")
- }
- })
-}
-
-func doLoggerBenchmarkNoLock(b *testing.B, out *os.File, formatter Formatter, fields Fields) {
- logger := Logger{
- Out: out,
- Level: InfoLevel,
- Formatter: formatter,
- }
- logger.SetNoLock()
- entry := logger.WithFields(fields)
- b.RunParallel(func(pb *testing.PB) {
- for pb.Next() {
- entry.Info("aaa")
- }
- })
-}
diff --git a/vendor/github.com/Sirupsen/logrus/logrus.go b/vendor/github.com/Sirupsen/logrus/logrus.go
deleted file mode 100644
index e596691..0000000
--- a/vendor/github.com/Sirupsen/logrus/logrus.go
+++ /dev/null
@@ -1,143 +0,0 @@
-package logrus
-
-import (
- "fmt"
- "log"
- "strings"
-)
-
-// 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 strings.ToLower(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)
-}
-
-// A constant exposing all logging levels
-var AllLevels = []Level{
- PanicLevel,
- FatalLevel,
- ErrorLevel,
- WarnLevel,
- InfoLevel,
- DebugLevel,
-}
-
-// 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 = &Entry{}
- _ StdLogger = &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{})
-}
-
-// The FieldLogger interface generalizes the Entry and Logger types
-type FieldLogger interface {
- WithField(key string, value interface{}) *Entry
- WithFields(fields Fields) *Entry
- WithError(err error) *Entry
-
- Debugf(format string, args ...interface{})
- Infof(format string, args ...interface{})
- Printf(format string, args ...interface{})
- Warnf(format string, args ...interface{})
- Warningf(format string, args ...interface{})
- Errorf(format string, args ...interface{})
- Fatalf(format string, args ...interface{})
- Panicf(format string, args ...interface{})
-
- Debug(args ...interface{})
- Info(args ...interface{})
- Print(args ...interface{})
- Warn(args ...interface{})
- Warning(args ...interface{})
- Error(args ...interface{})
- Fatal(args ...interface{})
- Panic(args ...interface{})
-
- Debugln(args ...interface{})
- Infoln(args ...interface{})
- Println(args ...interface{})
- Warnln(args ...interface{})
- Warningln(args ...interface{})
- Errorln(args ...interface{})
- Fatalln(args ...interface{})
- Panicln(args ...interface{})
-}
diff --git a/vendor/github.com/Sirupsen/logrus/logrus_test.go b/vendor/github.com/Sirupsen/logrus/logrus_test.go
deleted file mode 100644
index 78cbc28..0000000
--- a/vendor/github.com/Sirupsen/logrus/logrus_test.go
+++ /dev/null
@@ -1,386 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "encoding/json"
- "strconv"
- "strings"
- "sync"
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func LogAndAssertJSON(t *testing.T, log func(*Logger), assertions func(fields Fields)) {
- var buffer bytes.Buffer
- var fields Fields
-
- logger := New()
- logger.Out = &buffer
- logger.Formatter = new(JSONFormatter)
-
- log(logger)
-
- err := json.Unmarshal(buffer.Bytes(), &fields)
- assert.Nil(t, err)
-
- assertions(fields)
-}
-
-func LogAndAssertText(t *testing.T, log func(*Logger), assertions func(fields map[string]string)) {
- var buffer bytes.Buffer
-
- logger := New()
- logger.Out = &buffer
- logger.Formatter = &TextFormatter{
- DisableColors: true,
- }
-
- log(logger)
-
- fields := make(map[string]string)
- for _, kv := range strings.Split(buffer.String(), " ") {
- if !strings.Contains(kv, "=") {
- continue
- }
- kvArr := strings.Split(kv, "=")
- key := strings.TrimSpace(kvArr[0])
- val := kvArr[1]
- if kvArr[1][0] == '"' {
- var err error
- val, err = strconv.Unquote(val)
- assert.NoError(t, err)
- }
- fields[key] = val
- }
- assertions(fields)
-}
-
-func TestPrint(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Print("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- assert.Equal(t, fields["level"], "info")
- })
-}
-
-func TestInfo(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- assert.Equal(t, fields["level"], "info")
- })
-}
-
-func TestWarn(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Warn("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- assert.Equal(t, fields["level"], "warning")
- })
-}
-
-func TestInfolnShouldAddSpacesBetweenStrings(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Infoln("test", "test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test test")
- })
-}
-
-func TestInfolnShouldAddSpacesBetweenStringAndNonstring(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Infoln("test", 10)
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test 10")
- })
-}
-
-func TestInfolnShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Infoln(10, 10)
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "10 10")
- })
-}
-
-func TestInfoShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Infoln(10, 10)
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "10 10")
- })
-}
-
-func TestInfoShouldNotAddSpacesBetweenStringAndNonstring(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Info("test", 10)
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test10")
- })
-}
-
-func TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Info("test", "test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "testtest")
- })
-}
-
-func TestWithFieldsShouldAllowAssignments(t *testing.T) {
- var buffer bytes.Buffer
- var fields Fields
-
- logger := New()
- logger.Out = &buffer
- logger.Formatter = new(JSONFormatter)
-
- localLog := logger.WithFields(Fields{
- "key1": "value1",
- })
-
- localLog.WithField("key2", "value2").Info("test")
- err := json.Unmarshal(buffer.Bytes(), &fields)
- assert.Nil(t, err)
-
- assert.Equal(t, "value2", fields["key2"])
- assert.Equal(t, "value1", fields["key1"])
-
- buffer = bytes.Buffer{}
- fields = Fields{}
- localLog.Info("test")
- err = json.Unmarshal(buffer.Bytes(), &fields)
- assert.Nil(t, err)
-
- _, ok := fields["key2"]
- assert.Equal(t, false, ok)
- assert.Equal(t, "value1", fields["key1"])
-}
-
-func TestUserSuppliedFieldDoesNotOverwriteDefaults(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.WithField("msg", "hello").Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- })
-}
-
-func TestUserSuppliedMsgFieldHasPrefix(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.WithField("msg", "hello").Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- assert.Equal(t, fields["fields.msg"], "hello")
- })
-}
-
-func TestUserSuppliedTimeFieldHasPrefix(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.WithField("time", "hello").Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["fields.time"], "hello")
- })
-}
-
-func TestUserSuppliedLevelFieldHasPrefix(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.WithField("level", 1).Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["level"], "info")
- assert.Equal(t, fields["fields.level"], 1.0) // JSON has floats only
- })
-}
-
-func TestDefaultFieldsAreNotPrefixed(t *testing.T) {
- LogAndAssertText(t, func(log *Logger) {
- ll := log.WithField("herp", "derp")
- ll.Info("hello")
- ll.Info("bye")
- }, func(fields map[string]string) {
- for _, fieldName := range []string{"fields.level", "fields.time", "fields.msg"} {
- if _, ok := fields[fieldName]; ok {
- t.Fatalf("should not have prefixed %q: %v", fieldName, fields)
- }
- }
- })
-}
-
-func TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) {
-
- var buffer bytes.Buffer
- var fields Fields
-
- logger := New()
- logger.Out = &buffer
- logger.Formatter = new(JSONFormatter)
-
- llog := logger.WithField("context", "eating raw fish")
-
- llog.Info("looks delicious")
-
- err := json.Unmarshal(buffer.Bytes(), &fields)
- assert.NoError(t, err, "should have decoded first message")
- assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields")
- assert.Equal(t, fields["msg"], "looks delicious")
- assert.Equal(t, fields["context"], "eating raw fish")
-
- buffer.Reset()
-
- llog.Warn("omg it is!")
-
- err = json.Unmarshal(buffer.Bytes(), &fields)
- assert.NoError(t, err, "should have decoded second message")
- assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields")
- assert.Equal(t, fields["msg"], "omg it is!")
- assert.Equal(t, fields["context"], "eating raw fish")
- assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry")
-
-}
-
-func TestConvertLevelToString(t *testing.T) {
- assert.Equal(t, "debug", DebugLevel.String())
- assert.Equal(t, "info", InfoLevel.String())
- assert.Equal(t, "warning", WarnLevel.String())
- assert.Equal(t, "error", ErrorLevel.String())
- assert.Equal(t, "fatal", FatalLevel.String())
- assert.Equal(t, "panic", PanicLevel.String())
-}
-
-func TestParseLevel(t *testing.T) {
- l, err := ParseLevel("panic")
- assert.Nil(t, err)
- assert.Equal(t, PanicLevel, l)
-
- l, err = ParseLevel("PANIC")
- assert.Nil(t, err)
- assert.Equal(t, PanicLevel, l)
-
- l, err = ParseLevel("fatal")
- assert.Nil(t, err)
- assert.Equal(t, FatalLevel, l)
-
- l, err = ParseLevel("FATAL")
- assert.Nil(t, err)
- assert.Equal(t, FatalLevel, l)
-
- l, err = ParseLevel("error")
- assert.Nil(t, err)
- assert.Equal(t, ErrorLevel, l)
-
- l, err = ParseLevel("ERROR")
- assert.Nil(t, err)
- assert.Equal(t, ErrorLevel, l)
-
- l, err = ParseLevel("warn")
- assert.Nil(t, err)
- assert.Equal(t, WarnLevel, l)
-
- l, err = ParseLevel("WARN")
- assert.Nil(t, err)
- assert.Equal(t, WarnLevel, l)
-
- l, err = ParseLevel("warning")
- assert.Nil(t, err)
- assert.Equal(t, WarnLevel, l)
-
- l, err = ParseLevel("WARNING")
- assert.Nil(t, err)
- assert.Equal(t, WarnLevel, l)
-
- l, err = ParseLevel("info")
- assert.Nil(t, err)
- assert.Equal(t, InfoLevel, l)
-
- l, err = ParseLevel("INFO")
- assert.Nil(t, err)
- assert.Equal(t, InfoLevel, l)
-
- l, err = ParseLevel("debug")
- assert.Nil(t, err)
- assert.Equal(t, DebugLevel, l)
-
- l, err = ParseLevel("DEBUG")
- assert.Nil(t, err)
- assert.Equal(t, DebugLevel, l)
-
- l, err = ParseLevel("invalid")
- assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error())
-}
-
-func TestGetSetLevelRace(t *testing.T) {
- wg := sync.WaitGroup{}
- for i := 0; i < 100; i++ {
- wg.Add(1)
- go func(i int) {
- defer wg.Done()
- if i%2 == 0 {
- SetLevel(InfoLevel)
- } else {
- GetLevel()
- }
- }(i)
-
- }
- wg.Wait()
-}
-
-func TestLoggingRace(t *testing.T) {
- logger := New()
-
- var wg sync.WaitGroup
- wg.Add(100)
-
- for i := 0; i < 100; i++ {
- go func() {
- logger.Info("info")
- wg.Done()
- }()
- }
- wg.Wait()
-}
-
-// Compile test
-func TestLogrusInterface(t *testing.T) {
- var buffer bytes.Buffer
- fn := func(l FieldLogger) {
- b := l.WithField("key", "value")
- b.Debug("Test")
- }
- // test logger
- logger := New()
- logger.Out = &buffer
- fn(logger)
-
- // test Entry
- e := logger.WithField("another", "value")
- fn(e)
-}
-
-// Implements io.Writer using channels for synchronization, so we can wait on
-// the Entry.Writer goroutine to write in a non-racey way. This does assume that
-// there is a single call to Logger.Out for each message.
-type channelWriter chan []byte
-
-func (cw channelWriter) Write(p []byte) (int, error) {
- cw <- p
- return len(p), nil
-}
-
-func TestEntryWriter(t *testing.T) {
- cw := channelWriter(make(chan []byte, 1))
- log := New()
- log.Out = cw
- log.Formatter = new(JSONFormatter)
- log.WithField("foo", "bar").WriterLevel(WarnLevel).Write([]byte("hello\n"))
-
- bs := <-cw
- var fields Fields
- err := json.Unmarshal(bs, &fields)
- assert.Nil(t, err)
- assert.Equal(t, fields["foo"], "bar")
- assert.Equal(t, fields["level"], "warning")
-}
diff --git a/vendor/github.com/Sirupsen/logrus/terminal_appengine.go b/vendor/github.com/Sirupsen/logrus/terminal_appengine.go
deleted file mode 100644
index e011a86..0000000
--- a/vendor/github.com/Sirupsen/logrus/terminal_appengine.go
+++ /dev/null
@@ -1,10 +0,0 @@
-// +build appengine
-
-package logrus
-
-import "io"
-
-// IsTerminal returns true if stderr's file descriptor is a terminal.
-func IsTerminal(f io.Writer) bool {
- return true
-}
diff --git a/vendor/github.com/Sirupsen/logrus/terminal_bsd.go b/vendor/github.com/Sirupsen/logrus/terminal_bsd.go
deleted file mode 100644
index 5f6be4d..0000000
--- a/vendor/github.com/Sirupsen/logrus/terminal_bsd.go
+++ /dev/null
@@ -1,10 +0,0 @@
-// +build darwin freebsd openbsd netbsd dragonfly
-// +build !appengine
-
-package logrus
-
-import "syscall"
-
-const ioctlReadTermios = syscall.TIOCGETA
-
-type Termios syscall.Termios
diff --git a/vendor/github.com/Sirupsen/logrus/terminal_linux.go b/vendor/github.com/Sirupsen/logrus/terminal_linux.go
deleted file mode 100644
index 308160c..0000000
--- a/vendor/github.com/Sirupsen/logrus/terminal_linux.go
+++ /dev/null
@@ -1,14 +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.
-
-// +build !appengine
-
-package logrus
-
-import "syscall"
-
-const ioctlReadTermios = syscall.TCGETS
-
-type Termios syscall.Termios
diff --git a/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go b/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go
deleted file mode 100644
index 190297a..0000000
--- a/vendor/github.com/Sirupsen/logrus/terminal_notwindows.go
+++ /dev/null
@@ -1,28 +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 netbsd dragonfly
-// +build !appengine
-
-package logrus
-
-import (
- "io"
- "os"
- "syscall"
- "unsafe"
-)
-
-// IsTerminal returns true if stderr's file descriptor is a terminal.
-func IsTerminal(f io.Writer) bool {
- var termios Termios
- switch v := f.(type) {
- case *os.File:
- _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(v.Fd()), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
- return err == 0
- default:
- return false
- }
-}
diff --git a/vendor/github.com/Sirupsen/logrus/terminal_solaris.go b/vendor/github.com/Sirupsen/logrus/terminal_solaris.go
deleted file mode 100644
index 3c86b1a..0000000
--- a/vendor/github.com/Sirupsen/logrus/terminal_solaris.go
+++ /dev/null
@@ -1,21 +0,0 @@
-// +build solaris,!appengine
-
-package logrus
-
-import (
- "io"
- "os"
-
- "golang.org/x/sys/unix"
-)
-
-// IsTerminal returns true if the given file descriptor is a terminal.
-func IsTerminal(f io.Writer) bool {
- switch v := f.(type) {
- case *os.File:
- _, err := unix.IoctlGetTermios(int(v.Fd()), unix.TCGETA)
- return err == nil
- default:
- return false
- }
-}
diff --git a/vendor/github.com/Sirupsen/logrus/terminal_windows.go b/vendor/github.com/Sirupsen/logrus/terminal_windows.go
deleted file mode 100644
index 05d2f91..0000000
--- a/vendor/github.com/Sirupsen/logrus/terminal_windows.go
+++ /dev/null
@@ -1,33 +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,!appengine
-
-package logrus
-
-import (
- "io"
- "os"
- "syscall"
- "unsafe"
-)
-
-var kernel32 = syscall.NewLazyDLL("kernel32.dll")
-
-var (
- procGetConsoleMode = kernel32.NewProc("GetConsoleMode")
-)
-
-// IsTerminal returns true if stderr's file descriptor is a terminal.
-func IsTerminal(f io.Writer) bool {
- switch v := f.(type) {
- case *os.File:
- var st uint32
- r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(v.Fd()), uintptr(unsafe.Pointer(&st)), 0)
- return r != 0 && e == 0
- default:
- return false
- }
-}
diff --git a/vendor/github.com/Sirupsen/logrus/text_formatter.go b/vendor/github.com/Sirupsen/logrus/text_formatter.go
deleted file mode 100644
index ba88854..0000000
--- a/vendor/github.com/Sirupsen/logrus/text_formatter.go
+++ /dev/null
@@ -1,189 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "fmt"
- "sort"
- "strings"
- "sync"
- "time"
-)
-
-const (
- nocolor = 0
- red = 31
- green = 32
- yellow = 33
- blue = 34
- gray = 37
-)
-
-var (
- baseTimestamp time.Time
-)
-
-func init() {
- baseTimestamp = time.Now()
-}
-
-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
-
- // QuoteEmptyFields will wrap empty fields in quotes if true
- QuoteEmptyFields bool
-
- // QuoteCharacter can be set to the override the default quoting character "
- // with something else. For example: ', or `.
- QuoteCharacter string
-
- // Whether the logger's out is to a terminal
- isTerminal bool
-
- sync.Once
-}
-
-func (f *TextFormatter) init(entry *Entry) {
- if len(f.QuoteCharacter) == 0 {
- f.QuoteCharacter = "\""
- }
- if entry.Logger != nil {
- f.isTerminal = IsTerminal(entry.Logger.Out)
- }
-}
-
-func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
- var b *bytes.Buffer
- keys := make([]string, 0, len(entry.Data))
- for k := range entry.Data {
- keys = append(keys, k)
- }
-
- if !f.DisableSorting {
- sort.Strings(keys)
- }
- if entry.Buffer != nil {
- b = entry.Buffer
- } else {
- b = &bytes.Buffer{}
- }
-
- prefixFieldClashes(entry.Data)
-
- f.Do(func() { f.init(entry) })
-
- isColored := (f.ForceColors || f.isTerminal) && !f.DisableColors
-
- timestampFormat := f.TimestampFormat
- if timestampFormat == "" {
- timestampFormat = DefaultTimestampFormat
- }
- if isColored {
- f.printColored(b, entry, keys, timestampFormat)
- } else {
- if !f.DisableTimestamp {
- f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat))
- }
- f.appendKeyValue(b, "level", entry.Level.String())
- if entry.Message != "" {
- 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, timestampFormat 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.DisableTimestamp {
- fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m %-44s ", levelColor, levelText, entry.Message)
- } else if !f.FullTimestamp {
- fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), entry.Message)
- } else {
- fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message)
- }
- for _, k := range keys {
- v := entry.Data[k]
- fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k)
- f.appendValue(b, v)
- }
-}
-
-func (f *TextFormatter) needsQuoting(text string) bool {
- if f.QuoteEmptyFields && len(text) == 0 {
- return true
- }
- for _, ch := range text {
- if !((ch >= 'a' && ch <= 'z') ||
- (ch >= 'A' && ch <= 'Z') ||
- (ch >= '0' && ch <= '9') ||
- ch == '-' || ch == '.') {
- return true
- }
- }
- return false
-}
-
-func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
-
- b.WriteString(key)
- b.WriteByte('=')
- f.appendValue(b, value)
- b.WriteByte(' ')
-}
-
-func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
- switch value := value.(type) {
- case string:
- if !f.needsQuoting(value) {
- b.WriteString(value)
- } else {
- fmt.Fprintf(b, "%s%v%s", f.QuoteCharacter, value, f.QuoteCharacter)
- }
- case error:
- errmsg := value.Error()
- if !f.needsQuoting(errmsg) {
- b.WriteString(errmsg)
- } else {
- fmt.Fprintf(b, "%s%v%s", f.QuoteCharacter, errmsg, f.QuoteCharacter)
- }
- default:
- fmt.Fprint(b, value)
- }
-}
diff --git a/vendor/github.com/Sirupsen/logrus/text_formatter_test.go b/vendor/github.com/Sirupsen/logrus/text_formatter_test.go
deleted file mode 100644
index 9793b5f..0000000
--- a/vendor/github.com/Sirupsen/logrus/text_formatter_test.go
+++ /dev/null
@@ -1,87 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "errors"
- "strings"
- "testing"
- "time"
-)
-
-func TestQuoting(t *testing.T) {
- tf := &TextFormatter{DisableColors: true}
-
- checkQuoting := func(q bool, value interface{}) {
- b, _ := tf.Format(WithField("test", value))
- idx := bytes.Index(b, ([]byte)("test="))
- cont := bytes.Contains(b[idx+5:], []byte(tf.QuoteCharacter))
- if cont != q {
- if q {
- t.Errorf("quoting expected for: %#v", value)
- } else {
- t.Errorf("quoting not expected for: %#v", value)
- }
- }
- }
-
- checkQuoting(false, "")
- checkQuoting(false, "abcd")
- checkQuoting(false, "v1.0")
- checkQuoting(false, "1234567890")
- checkQuoting(true, "/foobar")
- checkQuoting(true, "x y")
- checkQuoting(true, "x,y")
- checkQuoting(false, errors.New("invalid"))
- checkQuoting(true, errors.New("invalid argument"))
-
- // Test for custom quote character.
- tf.QuoteCharacter = "`"
- checkQuoting(false, "")
- checkQuoting(false, "abcd")
- checkQuoting(true, "/foobar")
- checkQuoting(true, errors.New("invalid argument"))
-
- // Test for multi-character quotes.
- tf.QuoteCharacter = "§~±"
- checkQuoting(false, "abcd")
- checkQuoting(true, errors.New("invalid argument"))
-
- // Test for quoting empty fields.
- tf.QuoteEmptyFields = true
- checkQuoting(true, "")
- checkQuoting(false, "abcd")
- checkQuoting(true, errors.New("invalid argument"))
-}
-
-func TestTimestampFormat(t *testing.T) {
- checkTimeStr := func(format string) {
- customFormatter := &TextFormatter{DisableColors: true, TimestampFormat: format}
- customStr, _ := customFormatter.Format(WithField("test", "test"))
- timeStart := bytes.Index(customStr, ([]byte)("time="))
- timeEnd := bytes.Index(customStr, ([]byte)("level="))
- timeStr := customStr[timeStart+5+len(customFormatter.QuoteCharacter) : timeEnd-1-len(customFormatter.QuoteCharacter)]
- if format == "" {
- format = time.RFC3339
- }
- _, e := time.Parse(format, (string)(timeStr))
- if e != nil {
- t.Errorf("time string \"%s\" did not match provided time format \"%s\": %s", timeStr, format, e)
- }
- }
-
- checkTimeStr("2006-01-02T15:04:05.000000000Z07:00")
- checkTimeStr("Mon Jan _2 15:04:05 2006")
- checkTimeStr("")
-}
-
-func TestDisableTimestampWithColoredOutput(t *testing.T) {
- tf := &TextFormatter{DisableTimestamp: true, ForceColors: true}
-
- b, _ := tf.Format(WithField("test", "test"))
- if strings.Contains(string(b), "[0000]") {
- t.Error("timestamp not expected when DisableTimestamp is true")
- }
-}
-
-// TODO add tests for sorting etc., this requires a parser for the text
-// formatter output.
diff --git a/vendor/github.com/Sirupsen/logrus/writer.go b/vendor/github.com/Sirupsen/logrus/writer.go
deleted file mode 100644
index 7bdebed..0000000
--- a/vendor/github.com/Sirupsen/logrus/writer.go
+++ /dev/null
@@ -1,62 +0,0 @@
-package logrus
-
-import (
- "bufio"
- "io"
- "runtime"
-)
-
-func (logger *Logger) Writer() *io.PipeWriter {
- return logger.WriterLevel(InfoLevel)
-}
-
-func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
- return NewEntry(logger).WriterLevel(level)
-}
-
-func (entry *Entry) Writer() *io.PipeWriter {
- return entry.WriterLevel(InfoLevel)
-}
-
-func (entry *Entry) WriterLevel(level Level) *io.PipeWriter {
- reader, writer := io.Pipe()
-
- var printFunc func(args ...interface{})
-
- switch level {
- case DebugLevel:
- printFunc = entry.Debug
- case InfoLevel:
- printFunc = entry.Info
- case WarnLevel:
- printFunc = entry.Warn
- case ErrorLevel:
- printFunc = entry.Error
- case FatalLevel:
- printFunc = entry.Fatal
- case PanicLevel:
- printFunc = entry.Panic
- default:
- printFunc = entry.Print
- }
-
- go entry.writerScanner(reader, printFunc)
- runtime.SetFinalizer(writer, writerFinalizer)
-
- return writer
-}
-
-func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
- scanner := bufio.NewScanner(reader)
- for scanner.Scan() {
- printFunc(scanner.Text())
- }
- if err := scanner.Err(); err != nil {
- entry.Errorf("Error while reading from Writer: %s", err)
- }
- reader.Close()
-}
-
-func writerFinalizer(writer *io.PipeWriter) {
- writer.Close()
-}
diff --git a/vendor/github.com/containers/virtcontainers/.gitignore b/vendor/github.com/containers/virtcontainers/.gitignore
deleted file mode 100644
index 2d64b27..0000000
--- a/vendor/github.com/containers/virtcontainers/.gitignore
+++ /dev/null
@@ -1,4 +0,0 @@
-*.patch
-*.o
-/hack/virtc/virtc
-/pause/pause
diff --git a/vendor/github.com/containers/virtcontainers/.pullapprove.yml b/vendor/github.com/containers/virtcontainers/.pullapprove.yml
deleted file mode 100644
index 7d93d80..0000000
--- a/vendor/github.com/containers/virtcontainers/.pullapprove.yml
+++ /dev/null
@@ -1,31 +0,0 @@
-version: 2
-
-requirements:
- signed_off_by:
- required: true
-
-# Disallow approval of PRs still under development
-always_pending:
- title_regex: 'WIP'
- labels:
- - do-not-merge
- - wip
- explanation: 'Work in progress - do not merge'
-
-group_defaults:
- approve_by_comment:
- enabled: true
- approve_regex: '^(LGTM|lgtm|Approved|\+1|:\+1:)'
- reject_regex: '^(Rejected|-1|:-1:)'
- reset_on_push:
- enabled: false
- reset_on_reopened:
- enabled: false
- author_approval:
- ignored: true
-
-groups:
- code-reviewers:
- required: 1
- teams:
- - virtcontainers-maintainers
diff --git a/vendor/github.com/containers/virtcontainers/.travis.yml b/vendor/github.com/containers/virtcontainers/.travis.yml
deleted file mode 100644
index c15efb9..0000000
--- a/vendor/github.com/containers/virtcontainers/.travis.yml
+++ /dev/null
@@ -1,49 +0,0 @@
-language: go
-sudo: required
-go:
-- 1.7
-- 1.8
-- tip
-go_import_path: github.com/containers/virtcontainers
-
-env:
-- COVERALLS_TOKEN=3NUr5Z9zvjIoGRlKi6WIA3Q9em3x22rZp
-
-services:
-- docker
-
-before_install:
-- go get github.com/mattn/goveralls
-- go get golang.org/x/tools/cmd/cover
-- go get github.com/pierrre/gotestcover
-- go get github.com/fzipp/gocyclo
-- go get github.com/gordonklaus/ineffassign
-- go get github.com/golang/lint/golint
-- go get github.com/client9/misspell/cmd/misspell
-- go get github.com/01org/ciao/test-cases
-- go get github.com/opencontainers/runc/libcontainer/configs
-
-install:
-- sudo env "PATH=$PATH" bash $GOPATH/src/github.com/containers/virtcontainers/ci/ci-setup.sh
-- go_packages=$(go list ./... | grep -v vendor)
-- go_files=`go list -f '{{.Dir}}/*.go' $go_packages`
-- go get -t -v $go_packages
-
-script:
-- go env
-- misspell -error $go_packages
-- go vet $go_packages
-- if [[ "$TRAVIS_GO_VERSION" != "tip" ]] ; then golint $go_packages; fi
-- gocyclo -over 15 $go_files
-- go list -f '{{.Dir}}' $go_packages | xargs -L 1 ineffassign
-- gofmt -s -l $go_files | wc -l | xargs -I % bash -c "test % -eq 0"
-- make
-- export GOROOT=`go env GOROOT` && sudo -E PATH=$PATH:$GOROOT/bin:/tmp/cni/bin $GOPATH/bin/test-cases
- -v -timeout 9 -short -coverprofile /tmp/cover.out $go_packages
-
-after_success:
-- "$GOPATH/bin/goveralls -service=travis-ci -coverprofile=/tmp/cover.out"
-
-notifications:
- slack:
- secure: ZZrkxKslIWyb4hoTfsKNNPayP1RVNMMm0z2HiYLE/hFXSg8kY01cnPMHUsVya//qw1J/t8O0jCByM7/nQrXEYPhKuU4cBt+hniZu8UL7aG4aBiTpimz5AlQ9mZA2DsnWkAGbYX0NZx1K8avD0jl4hzJFap4SAS+ZRLQun7QgzDu7VlAiu1YXEjjN1c22sFJzYJc+7Sl3r3KdLbsjAGWcJeOoiJRHJlWyxUyi8Z9MQfZnb2/tjChqZxi6f3HWDD2X2YReMhxUDcEuuntj0HHFXZnWsdDZOQgzB5jfnhR73fGwoEA3A7mswToF9NZbY57jbadQ5cO/1WguZD4sCIrtmuWbrvgwHMmyJUnhrh9t3S6J4aNu+cj8HV3eMddHOiEpi1/wb2lOXVBhltrynardGsLmy8gIGKo22yjovViwdtjF9vrcBqbzMGMK/bWLaprS3/TQ0VgHh3cgF/NiiVG9CULr8P9Zp8SMM0iu91pIzqw2BiunmczJ7L+bmKpDUvA1wMoyFHzKArfr0l2jAHJC5ptbNlZg3hIDI4xff633nnEWvHUK0j5tgz0aafqpW8NudO8FzgKXGvNHBoTRsbzGup9KIVECsl+J5rSW5gV9fNL4GB+J7H+xj0j7JNrACy2ept/Wi9UyosdN1On6NFiw5ucf71MJeaiS5g+xZqdrIuo=
diff --git a/vendor/github.com/containers/virtcontainers/CONTRIBUTING.md b/vendor/github.com/containers/virtcontainers/CONTRIBUTING.md
deleted file mode 100644
index 79afb7c..0000000
--- a/vendor/github.com/containers/virtcontainers/CONTRIBUTING.md
+++ /dev/null
@@ -1,97 +0,0 @@
-# Contributing to virtcontainers
-
-virtcontainers is an open source project licensed under the [Apache License, Version 2.0] (https://www.apache.org/licenses/LICENSE-2.0).
-
-## Coding Style (Go)
-
-The usual Go style, enforced by `gofmt`, should be used. Additionally, the [Go
-Code Review](https://github.com/golang/go/wiki/CodeReviewComments) document
-contains a few common errors to be mindful of.
-
-
-## Certificate of Origin
-
-In order to get a clear contribution chain of trust we use the [signed-off-by language] (https://01.org/community/signed-process)
-used by the Linux kernel project.
-
-## Patch format
-
-Beside the signed-off-by footer, we expect each patch to comply with the following format:
-
-```
- Subsystem: Change summary (no longer than 75 characters)
-
- More detailed explanation of your changes: Why and how.
- Wrap it to 72 characters.
- See:
- http://chris.beams.io/posts/git-commit/
- for some more good advice, and the Linux Kernel document:
- https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/Documentation/SubmittingPatches
-
- Signed-off-by:
-```
-
-For example:
-
-```
- pod: Remove token from Cmd structure
-
- The token and pid data will be hold by the new Process structure and
- they are related to a container.
-
- Signed-off-by: Sebastien Boeuf
-```
-
-Note, that the body of the message should not just be a continuation of the subject line, and is not used to extend the subject line beyond its length limit. They should stand alone as complete sentence and paragraphs.
-
-It is recommended that each of your patches fixes one thing. Smaller patches are easier to review, and are thus more likely to be accepted and merged, and problems are more likely to be picked up during review.
-
-## Pull requests
-
-We accept [github pull requests] (https://github.com/containers/virtcontainers/pulls).
-
-Github has a basic introduction to the process [here] (https://help.github.com/articles/using-pull-requests/).
-
-When submitting your Pull Request (PR), treat the Pull Request message the same you would a patch message, including pre-fixing the title with a subsystem name. Github by default seems to copy the message from your first patch, which many times is appropriate, but please ensure your message is accurate and complete for the whole Pull Request, as it ends up in the git log as the merge message.
-
-Your pull request may get some feedback and comments, and require some rework. The recommended procedure for reworking is to rework your branch to a new clean state and 'force push' it to your github. GitHub understands this action, and does sensible things in the online comment history. Do not pile patches on patches to rework your branch. Any relevant information from the github comments section should be re-worked into your patch set, as the ultimate place where your patches are documented is in the git log, and not in the github comments section.
-
-For more information on github 'force push' workflows see [here] (http://blog.adamspiers.org/2015/03/24/why-and-how-to-correctly-amend-github-pull-requests/).
-
-It is perfectly fine for your Pull Request to contain more than one patch - use as many patches as you need to implement the Request (see the previously mentioned 'small patch' thoughts). Each Pull Request should only cover one topic - if you mix up different items in your patches or pull requests then you will most likely be asked to rework them.
-
-## Reviews
-
-Before your Pull Requests are merged into the main code base, they will be reviewed. Anybody can review any Pull Request and leave feedback (in fact, it is encouraged).
-
-We use an 'acknowledge' system for people to note if they agree, or disagree, with a Pull Request. We utilise some automated systems that can spot common acknowledge patterns, which include placing any of these at the beginning of a comment line:
-
- - LGTM
- - lgtm
- - +1
- - Approve
-
-## Issue tracking
-
-To report a bug that is not already documented, please [open an
-issue in github](https://github.com/containers/virtcontainers/issues/new) so we all get
-visibility on the problem and work toward resolution.
-
-## Closing issues
-
-You can either close issues manually by adding the fixing commit SHA1 to the issue
-comments or by adding the `Fixes` keyword to your commit message:
-
-```
- pod: Remove token from Cmd structure
-
- The token and pid data will be hold by the new Process structure and
- they are related to a container.
-
- Fixes #123
-
- Signed-off-by: Sebastien Boeuf
-```
-
-Github will then automatically close that issue when parsing the
-[commit message](https://help.github.com/articles/closing-issues-via-commit-messages/).
diff --git a/vendor/github.com/containers/virtcontainers/LICENSE b/vendor/github.com/containers/virtcontainers/LICENSE
deleted file mode 100644
index 8dada3e..0000000
--- a/vendor/github.com/containers/virtcontainers/LICENSE
+++ /dev/null
@@ -1,201 +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
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "{}"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright {yyyy} {name of copyright owner}
-
- 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/vendor/github.com/containers/virtcontainers/Makefile b/vendor/github.com/containers/virtcontainers/Makefile
deleted file mode 100644
index dd7eab9..0000000
--- a/vendor/github.com/containers/virtcontainers/Makefile
+++ /dev/null
@@ -1,25 +0,0 @@
-all: binaries
- go build $(go list ./... | grep -v /vendor/)
- cd hack/virtc && go build
-
-pause:
- make -C $@
-
-binaries: pause
-
-clean:
- make -C pause clean
- rm -f hack/virtc/virtc
-
-install:
- install -D -m 755 pause/pause /usr/bin/pause
-
-uninstall:
- rm -f /usr/bin/pause
-
-.PHONY: \
- binaries \
- clean \
- install \
- pause \
- uninstall
diff --git a/vendor/github.com/containers/virtcontainers/NEWS b/vendor/github.com/containers/virtcontainers/NEWS
deleted file mode 100644
index 6f7daec..0000000
--- a/vendor/github.com/containers/virtcontainers/NEWS
+++ /dev/null
@@ -1,42 +0,0 @@
-0.7.0:
- Added Clear Containers 3.0 shim support
- Added Clear Containers 3.0 proxy protocol support
- Added self contained hyperstart package
- Added full build scripts
- Added hypervisor and pod debug options
- Added command line and function arguments validity checks
- Added logrus support, replacing glog
- Added OCI runtime vendoring
- Added structured and separated error definitions
- Fixed networking support and unit testing
- Fixed code layering by keeping generic code out of interface implementations
- Fixed benchmarks
-
-0.6.0:
- Added pullapprove support
- Added Slack integration
- Added KillContainer API
- Added networking documentation
- Added a Process structure for describing container processes
- Added a more complete pod and container status structure
- Fixed hyperstart implementation for stopping containers
-
-0.5.0:
- Changed the CreatePod/StartPod logic
- Added an OCI config file conversion package
- Added initial benchmarks
- Added more CNI network unit tests
- Moved all non virtcontainers packages under pkg/
- Fixed netns race conditions
-
-0.4.0:
- Added CNM network model support
- Added hyperstart asynchronous events support
- Added low level CTL routines
- Added OCI compatible hooks support
- Added Travis code coverage report
-
-0.3.0:
- Added support for the latest hyperstart changes
- Added proxy interface and cc-proxy implementation
- Added CNI unit tests
diff --git a/vendor/github.com/containers/virtcontainers/README.md b/vendor/github.com/containers/virtcontainers/README.md
deleted file mode 100644
index 7a83cbf..0000000
--- a/vendor/github.com/containers/virtcontainers/README.md
+++ /dev/null
@@ -1,184 +0,0 @@
-[![Build Status](https://travis-ci.org/containers/virtcontainers.svg?branch=master)](https://travis-ci.org/containers/virtcontainers)
-[![Go Report Card](https://goreportcard.com/badge/github.com/containers/virtcontainers)](https://goreportcard.com/report/github.com/containers/virtcontainers)
-[![Coverage Status](https://coveralls.io/repos/github/containers/virtcontainers/badge.svg?branch=master)](https://coveralls.io/github/containers/virtcontainers?branch=master)
-[![GoDoc](https://godoc.org/github.com/containers/virtcontainers?status.svg)](https://godoc.org/github.com/containers/virtcontainers)
-
-# virtcontainers
-
-`virtcontainers` is a Go library that can be used to build hardware-virtualized container
-runtimes.
-
-## Background
-
-The few existing VM-based container runtimes (Clear Containers, runv, rkt's
-kvm stage 1) all share the same hardware virtualization semantics but use different
-code bases to implement them. `virtcontainers`'s goal is to factorize this code into
-a common Go library.
-
-Ideally, VM-based container runtime implementations would become translation
-layers from the runtime specification they implement (e.g. the [OCI runtime-spec][oci]
-or the [Kubernetes CRI][cri]) to the `virtcontainers` API.
-
-[oci]: https://github.com/opencontainers/runtime-spec
-[cri]: https://github.com/kubernetes/kubernetes/blob/master/docs/proposals/container-runtime-interface-v1.md
-
-## Out of scope
-
-Implementing a container runtime tool is out of scope for this project. Any
-tools or executables in this repository are only provided for demonstration or
-testing purposes.
-
-### virtcontainers and CRI
-
-`virtcontainers`'s API is loosely inspired by the Kubernetes [CRI][cri] because
-we believe it provides the right level of abstractions for containerized pods.
-However, despite the API similarities between the two projects, the goal of
-`virtcontainers` is _not_ to build a CRI implementation, but instead to provide a
-generic, runtime-specification agnostic, hardware-virtualized containers
-library that other projects could leverage to implement CRI themselves.
-
-## Design
-
-### Pods
-
-The `virtcontainers` execution unit is a _pod_, i.e. `virtcontainers` users start pods where
-containers will be running.
-
-`virtcontainers` creates a pod by starting a virtual machine and setting the pod
-up within that environment. Starting a pod means launching all containers with
-the VM pod runtime environment.
-
-### Hypervisors
-
-The `virtcontainers` package relies on hypervisors to start and stop virtual machine where
-pods will be running. An hypervisor is defined by an Hypervisor interface implementation,
-and the default implementation is the QEMU one.
-
-### Agents
-
-During the lifecycle of a container, the runtime running on the host needs to interact with
-the virtual machine guest OS in order to start new commands to be executed as part of a given
-container workload, set new networking routes or interfaces, fetch a container standard or
-error output, and so on.
-There are many existing and potential solutions to resolve that problem and `virtcontainers` abstracts
-this through the Agent interface.
-
-## API
-
-The high level `virtcontainers` API is the following one:
-
-### Pod API
-
-* `CreatePod(podConfig PodConfig)` creates a Pod.
-The virtual machine is started and the Pod is prepared.
-
-* `DeletePod(podID string)` deletes a Pod.
-The virtual machine is shut down and all information related to the Pod are removed.
-The function will fail if the Pod is running. In that case `StopPod()` has to be called first.
-
-* `StartPod(podID string)` starts an already created Pod.
-The Pod and all its containers are started.
-
-* `RunPod(podConfig PodConfig)` creates and starts a Pod.
-This performs `CreatePod()` + `StartPod()`.
-
-* `StopPod(podID string)` stops an already running Pod.
-The Pod and all its containers are stopped.
-
-* `StatusPod(podID string)` returns a detailed Pod status.
-
-* `ListPod()` lists all Pods on the host.
-It returns a detailed status for every Pod.
-
-### Container API
-
-* `CreateContainer(podID string, containerConfig ContainerConfig)` creates a Container on an existing Pod.
-
-* `DeleteContainer(podID, containerID string)` deletes a Container from a Pod.
-If the Container is running it has to be stopped first.
-
-* `StartContainer(podID, containerID string)` starts an already created Container.
-The Pod has to be running.
-
-* `StopContainer(podID, containerID string)` stops an already running Container.
-
-* `EnterContainer(podID, containerID string, cmd Cmd)` enters an already running Container and runs a given command.
-
-* `StatusContainer(podID, containerID string)` returns a detailed Container status.
-
-
-An example tool using the `virtcontainers` API is provided in the `hack/virtc` package.
-
-## Networking
-
-Virtcontainers implements two different way of setting up pod's network:
-
-### CNM
-
-![High-level CNM Diagram](documentation/network/CNM_overall_diagram.png)
-
-__CNM lifecycle__
-
-1. RequestPool
-
-2. CreateNetwork
-
-3. RequestAddress
-
-4. CreateEndPoint
-
-5. CreateContainer
-
-6. Create config.json
-
-7. Create PID and network namespace
-
-8. ProcessExternalKey
-
-9. JoinEndPoint
-
-10. LaunchContainer
-
-11. Launch
-
-12. Run container
-
-![Detailed CNM Diagram](documentation/network/CNM_detailed_diagram.png)
-
-__Runtime network setup with CNM__
-
-1. Read config.json
-
-2. Create the network namespace ([code](https://github.com/containers/virtcontainers/blob/0.5.0/cnm.go#L108-L120))
-
-3. Call the prestart hook (from inside the netns) ([code](https://github.com/containers/virtcontainers/blob/0.5.0/api.go#L46-L49))
-
-4. Scan network interfaces inside netns and get the name of the interface created by prestart hook ([code](https://github.com/containers/virtcontainers/blob/0.5.0/cnm.go#L70-L106))
-
-5. Create bridge, TAP, and link all together with network interface previously created ([code](https://github.com/containers/virtcontainers/blob/0.5.0/network.go#L123-L205))
-
-6. Start VM inside the netns and start the container ([code](https://github.com/containers/virtcontainers/blob/0.5.0/api.go#L66-L70))
-
-__Drawbacks of CNM__
-
-There are three drawbacks about using CNM instead of CNI:
-* The way we call into it is not very explicit: Have to re-exec dockerd binary so that it can accept parameters and execute the prestart hook related to network setup.
-* Implicit way to designate the network namespace: Instead of explicitely giving the netns to dockerd, we give it the PID of our runtime so that it can find the netns from this PID. This means we have to make sure being in the right netns while calling the hook, otherwise the veth pair will be created with the wrong netns.
-* No results are back from the hook: We have to scan the network interfaces to discover which one has been created inside the netns. This introduces more latency in the code because it forces us to scan the network in the CreatePod path, which is critical for starting the VM as quick as possible.
-
-
-### CNI
-
-![CNI Diagram](documentation/network/CNI_diagram.png)
-
-__Runtime network setup with CNI__
-
-1. Create the network namespace ([code](https://github.com/containers/virtcontainers/blob/0.5.0/cni.go#L64-L76))
-
-2. Get CNI plugin information ([code](https://github.com/containers/virtcontainers/blob/0.5.0/cni.go#L29-L32))
-
-3. Start the plugin (providing previously created netns) to add a network described into /etc/cni/net.d/ directory. At that time, the CNI plugin will create the cni0 network interface and a veth pair between the host and the created netns. It links cni0 to the veth pair before to exit. ([code](https://github.com/containers/virtcontainers/blob/0.5.0/cni.go#L34-L45))
-
-4. Create bridge, TAP, and link all together with network interface previously created ([code](https://github.com/containers/virtcontainers/blob/0.5.0/network.go#L123-L205))
-
-5. Start VM inside the netns and start the container ([code](https://github.com/containers/virtcontainers/blob/0.5.0/api.go#L66-L70))
diff --git a/vendor/github.com/containers/virtcontainers/agent.go b/vendor/github.com/containers/virtcontainers/agent.go
deleted file mode 100644
index a7af309..0000000
--- a/vendor/github.com/containers/virtcontainers/agent.go
+++ /dev/null
@@ -1,140 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
- "syscall"
-
- "github.com/mitchellh/mapstructure"
-)
-
-// AgentType describes the type of guest agent a Pod should run.
-type AgentType string
-
-const (
- // NoopAgentType is the No-Op agent.
- NoopAgentType AgentType = "noop"
-
- // SSHdAgent is the SSH daemon agent.
- SSHdAgent AgentType = "sshd"
-
- // HyperstartAgent is the Hyper hyperstart agent.
- HyperstartAgent AgentType = "hyperstart"
-)
-
-// Set sets an agent type based on the input string.
-func (agentType *AgentType) Set(value string) error {
- switch value {
- case "noop":
- *agentType = NoopAgentType
- return nil
- case "sshd":
- *agentType = SSHdAgent
- return nil
- case "hyperstart":
- *agentType = HyperstartAgent
- return nil
- default:
- return fmt.Errorf("Unknown agent type %s", value)
- }
-}
-
-// String converts an agent type to a string.
-func (agentType *AgentType) String() string {
- switch *agentType {
- case NoopAgentType:
- return string(NoopAgentType)
- case SSHdAgent:
- return string(SSHdAgent)
- case HyperstartAgent:
- return string(HyperstartAgent)
- default:
- return ""
- }
-}
-
-// newAgent returns an agent from an agent type.
-func newAgent(agentType AgentType) agent {
- switch agentType {
- case NoopAgentType:
- return &noopAgent{}
- case SSHdAgent:
- return &sshd{}
- case HyperstartAgent:
- return &hyper{}
- default:
- return &noopAgent{}
- }
-}
-
-// newAgentConfig returns an agent config from a generic PodConfig interface.
-func newAgentConfig(config PodConfig) interface{} {
- switch config.AgentType {
- case NoopAgentType:
- return nil
- case SSHdAgent:
- var sshdConfig SshdConfig
- err := mapstructure.Decode(config.AgentConfig, &sshdConfig)
- if err != nil {
- return err
- }
- return sshdConfig
- case HyperstartAgent:
- var hyperConfig HyperConfig
- err := mapstructure.Decode(config.AgentConfig, &hyperConfig)
- if err != nil {
- return err
- }
- return hyperConfig
- default:
- return nil
- }
-}
-
-// agent is the virtcontainers agent interface.
-// Agents are running in the guest VM and handling
-// communications between the host and guest.
-type agent interface {
- // init is used to pass agent specific configuration to the agent implementation.
- // agent implementations also will typically start listening for agent events from
- // init().
- // After init() is called, agent implementations should be initialized and ready
- // to handle all other Agent interface methods.
- init(pod *Pod, config interface{}) error
-
- // exec will tell the agent to run a command in an already running container.
- exec(pod *Pod, c Container, process Process, cmd Cmd) error
-
- // startPod will tell the agent to start all containers related to the Pod.
- startPod(pod Pod) error
-
- // stopPod will tell the agent to stop all containers related to the Pod.
- stopPod(pod Pod) error
-
- // createContainer will tell the agent to create a container related to a Pod.
- createContainer(pod *Pod, c *Container) error
-
- // startContainer will tell the agent to start a container related to a Pod.
- startContainer(pod Pod, c Container) error
-
- // stopContainer will tell the agent to stop a container related to a Pod.
- stopContainer(pod Pod, c Container) error
-
- // killContainer will tell the agent to send a signal to a container related to a Pod.
- killContainer(pod Pod, c Container, signal syscall.Signal) error
-}
diff --git a/vendor/github.com/containers/virtcontainers/agent_test.go b/vendor/github.com/containers/virtcontainers/agent_test.go
deleted file mode 100644
index 65f4973..0000000
--- a/vendor/github.com/containers/virtcontainers/agent_test.go
+++ /dev/null
@@ -1,157 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "reflect"
- "testing"
-)
-
-func testSetAgentType(t *testing.T, value string, expected AgentType) {
- var agentType AgentType
-
- err := (&agentType).Set(value)
- if err != nil {
- t.Fatal(err)
- }
-
- if agentType != expected {
- t.Fatal(err)
- }
-}
-
-func TestSetNoopAgentType(t *testing.T) {
- testSetAgentType(t, "noop", NoopAgentType)
-}
-
-func TestSetSSHdAgentType(t *testing.T) {
- testSetAgentType(t, "sshd", SSHdAgent)
-}
-
-func TestSetHyperstartAgentType(t *testing.T) {
- testSetAgentType(t, "hyperstart", HyperstartAgent)
-}
-
-func TestSetUnknownAgentType(t *testing.T) {
- var agentType AgentType
-
- err := (&agentType).Set("unknown")
- if err == nil {
- t.Fatal()
- }
-
- if agentType == NoopAgentType ||
- agentType == SSHdAgent ||
- agentType == HyperstartAgent {
- t.Fatal()
- }
-}
-
-func testStringFromAgentType(t *testing.T, agentType AgentType, expected string) {
- agentTypeStr := (&agentType).String()
- if agentTypeStr != expected {
- t.Fatal()
- }
-}
-
-func TestStringFromNoopAgentType(t *testing.T) {
- testStringFromAgentType(t, NoopAgentType, "noop")
-}
-
-func TestStringFromSSHdAgentType(t *testing.T) {
- testStringFromAgentType(t, SSHdAgent, "sshd")
-}
-
-func TestStringFromHyperstartAgentType(t *testing.T) {
- testStringFromAgentType(t, HyperstartAgent, "hyperstart")
-}
-
-func TestStringFromUnknownAgentType(t *testing.T) {
- var agentType AgentType
- testStringFromAgentType(t, agentType, "")
-}
-
-func testNewAgentFromAgentType(t *testing.T, agentType AgentType, expected agent) {
- ag := newAgent(agentType)
-
- if reflect.DeepEqual(ag, expected) == false {
- t.Fatal()
- }
-}
-
-func TestNewAgentFromNoopAgentType(t *testing.T) {
- testNewAgentFromAgentType(t, NoopAgentType, &noopAgent{})
-}
-
-func TestNewAgentFromSSHdAgentType(t *testing.T) {
- testNewAgentFromAgentType(t, SSHdAgent, &sshd{})
-}
-
-func TestNewAgentFromHyperstartAgentType(t *testing.T) {
- testNewAgentFromAgentType(t, HyperstartAgent, &hyper{})
-}
-
-func TestNewAgentFromUnknownAgentType(t *testing.T) {
- var agentType AgentType
- testNewAgentFromAgentType(t, agentType, &noopAgent{})
-}
-
-func testNewAgentConfig(t *testing.T, config PodConfig, expected interface{}) {
- agentConfig := newAgentConfig(config)
- if reflect.DeepEqual(agentConfig, expected) == false {
- t.Fatal()
- }
-}
-
-func TestNewAgentConfigFromNoopAgentType(t *testing.T) {
- var agentConfig interface{}
-
- podConfig := PodConfig{
- AgentType: NoopAgentType,
- AgentConfig: agentConfig,
- }
-
- testNewAgentConfig(t, podConfig, agentConfig)
-}
-
-func TestNewAgentConfigFromSSHdAgentType(t *testing.T) {
- agentConfig := SshdConfig{}
-
- podConfig := PodConfig{
- AgentType: SSHdAgent,
- AgentConfig: agentConfig,
- }
-
- testNewAgentConfig(t, podConfig, agentConfig)
-}
-
-func TestNewAgentConfigFromHyperstartAgentType(t *testing.T) {
- agentConfig := HyperConfig{}
-
- podConfig := PodConfig{
- AgentType: HyperstartAgent,
- AgentConfig: agentConfig,
- }
-
- testNewAgentConfig(t, podConfig, agentConfig)
-}
-
-func TestNewAgentConfigFromUnknownAgentType(t *testing.T) {
- var agentConfig interface{}
-
- testNewAgentConfig(t, PodConfig{}, agentConfig)
-}
diff --git a/vendor/github.com/containers/virtcontainers/api.go b/vendor/github.com/containers/virtcontainers/api.go
deleted file mode 100644
index 429312f..0000000
--- a/vendor/github.com/containers/virtcontainers/api.go
+++ /dev/null
@@ -1,694 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "os"
- "runtime"
- "syscall"
-
- "github.com/Sirupsen/logrus"
-)
-
-func init() {
- runtime.LockOSThread()
-}
-
-var virtLog = logrus.New()
-
-// SetLog sets the logger for virtcontainers package.
-func SetLog(logger *logrus.Logger) {
- virtLog = logger
-}
-
-// CreatePod is the virtcontainers pod creation entry point.
-// CreatePod creates a pod and its containers. It does not start them.
-func CreatePod(podConfig PodConfig) (*Pod, error) {
- // Create the pod.
- p, err := createPod(podConfig)
- if err != nil {
- return nil, err
- }
-
- // Store it.
- err = p.storePod()
- if err != nil {
- return nil, err
- }
-
- // Initialize the network.
- err = p.network.init(&(p.config.NetworkConfig))
- if err != nil {
- return nil, err
- }
-
- // Execute prestart hooks inside netns
- err = p.network.run(p.config.NetworkConfig.NetNSPath, func() error {
- return p.config.Hooks.preStartHooks()
- })
- if err != nil {
- return nil, err
- }
-
- // Add the network
- networkNS, err := p.network.add(*p, p.config.NetworkConfig)
- if err != nil {
- return nil, err
- }
-
- // Store the network
- err = p.storage.storePodNetwork(p.id, networkNS)
- if err != nil {
- return nil, err
- }
-
- // Start the VM
- err = p.startVM()
- if err != nil {
- return nil, err
- }
-
- // Start shims
- if err := p.startShims(); err != nil {
- return nil, err
- }
-
- err = p.endSession()
- if err != nil {
- return nil, err
- }
-
- return p, nil
-}
-
-// DeletePod is the virtcontainers pod deletion entry point.
-// DeletePod will stop an already running container and then delete it.
-func DeletePod(podID string) (*Pod, error) {
- if podID == "" {
- return nil, errNeedPodID
- }
-
- lockFile, err := lockPod(podID)
- if err != nil {
- return nil, err
- }
- defer unlockPod(lockFile)
-
- // Fetch the pod from storage and create it.
- p, err := fetchPod(podID)
- if err != nil {
- return nil, err
- }
-
- // Fetch the network config
- networkNS, err := p.storage.fetchPodNetwork(podID)
- if err != nil {
- return nil, err
- }
-
- // Stop the VM
- err = p.stopVM()
- if err != nil {
- return nil, err
- }
-
- // Remove the network
- err = p.network.remove(*p, networkNS)
- if err != nil {
- return nil, err
- }
-
- // Delete it.
- err = p.delete()
- if err != nil {
- return nil, err
- }
-
- err = p.endSession()
- if err != nil {
- return nil, err
- }
-
- return p, nil
-}
-
-// StartPod is the virtcontainers pod starting entry point.
-// StartPod will talk to the given hypervisor to start an existing
-// pod and all its containers.
-// It returns the pod ID.
-func StartPod(podID string) (*Pod, error) {
- if podID == "" {
- return nil, errNeedPodID
- }
-
- lockFile, err := lockPod(podID)
- if err != nil {
- return nil, err
- }
- defer unlockPod(lockFile)
-
- // Fetch the pod from storage and create it.
- p, err := fetchPod(podID)
- if err != nil {
- return nil, err
- }
-
- // Fetch the network config
- networkNS, err := p.storage.fetchPodNetwork(podID)
- if err != nil {
- return nil, err
- }
-
- // Start it
- err = p.start()
- if err != nil {
- return nil, err
- }
-
- // Execute poststart hooks inside netns
- err = p.network.run(networkNS.NetNsPath, func() error {
- return p.config.Hooks.postStartHooks()
- })
- if err != nil {
- return nil, err
- }
-
- err = p.endSession()
- if err != nil {
- return nil, err
- }
-
- return p, nil
-}
-
-// StopPod is the virtcontainers pod stopping entry point.
-// StopPod will talk to the given agent to stop an existing pod and destroy all containers within that pod.
-func StopPod(podID string) (*Pod, error) {
- if podID == "" {
- return nil, errNeedPod
- }
-
- lockFile, err := lockPod(podID)
- if err != nil {
- return nil, err
- }
- defer unlockPod(lockFile)
-
- // Fetch the pod from storage and create it.
- p, err := fetchPod(podID)
- if err != nil {
- return nil, err
- }
-
- // Fetch the network config
- networkNS, err := p.storage.fetchPodNetwork(podID)
- if err != nil {
- return nil, err
- }
-
- // Stop it.
- err = p.stop()
- if err != nil {
- p.delete()
- return nil, err
- }
-
- // Execute poststop hooks inside netns
- err = p.network.run(networkNS.NetNsPath, func() error {
- return p.config.Hooks.postStopHooks()
- })
- if err != nil {
- p.delete()
- return nil, err
- }
-
- err = p.endSession()
- if err != nil {
- return nil, err
- }
-
- return p, nil
-}
-
-// RunPod is the virtcontainers pod running entry point.
-// RunPod creates a pod and its containers and then it starts them.
-func RunPod(podConfig PodConfig) (*Pod, error) {
- // Create the pod.
- p, err := createPod(podConfig)
- if err != nil {
- return nil, err
- }
-
- // Store it.
- err = p.storePod()
- if err != nil {
- return nil, err
- }
-
- lockFile, err := lockPod(p.id)
- if err != nil {
- return nil, err
- }
- defer unlockPod(lockFile)
-
- // Initialize the network.
- err = p.network.init(&(p.config.NetworkConfig))
- if err != nil {
- return nil, err
- }
-
- // Execute prestart hooks inside netns
- err = p.network.run(p.config.NetworkConfig.NetNSPath, func() error {
- return p.config.Hooks.preStartHooks()
- })
- if err != nil {
- return nil, err
- }
-
- // Add the network
- networkNS, err := p.network.add(*p, p.config.NetworkConfig)
- if err != nil {
- return nil, err
- }
-
- // Store the network
- err = p.storage.storePodNetwork(p.id, networkNS)
- if err != nil {
- return nil, err
- }
-
- // Start the VM
- err = p.startVM()
- if err != nil {
- return nil, err
- }
-
- // Start shims
- if err := p.startShims(); err != nil {
- return nil, err
- }
-
- // Start the pod
- err = p.start()
- if err != nil {
- p.delete()
- return nil, err
- }
-
- // Execute poststart hooks inside netns
- err = p.network.run(networkNS.NetNsPath, func() error {
- return p.config.Hooks.postStartHooks()
- })
- if err != nil {
- return nil, err
- }
-
- err = p.endSession()
- if err != nil {
- return nil, err
- }
-
- return p, nil
-}
-
-// ListPod is the virtcontainers pod listing entry point.
-func ListPod() ([]PodStatus, error) {
- dir, err := os.Open(configStoragePath)
- if err != nil {
- if os.IsNotExist(err) {
- // No pod directory is not an error
- return []PodStatus{}, nil
- }
- return []PodStatus{}, err
- }
-
- defer dir.Close()
-
- podsID, err := dir.Readdirnames(0)
- if err != nil {
- return []PodStatus{}, err
- }
-
- var podStatusList []PodStatus
-
- for _, podID := range podsID {
- podStatus, err := StatusPod(podID)
- if err != nil {
- continue
- }
-
- podStatusList = append(podStatusList, podStatus)
- }
-
- return podStatusList, nil
-}
-
-// StatusPod is the virtcontainers pod status entry point.
-func StatusPod(podID string) (PodStatus, error) {
- if podID == "" {
- return PodStatus{}, errNeedPodID
- }
-
- pod, err := fetchPod(podID)
- if err != nil {
- return PodStatus{}, err
- }
-
- var contStatusList []ContainerStatus
- for _, container := range pod.containers {
- contStatus := ContainerStatus{
- ID: container.id,
- State: container.state,
- PID: container.process.Pid,
- RootFs: container.config.RootFs,
- }
-
- contStatusList = append(contStatusList, contStatus)
- }
-
- podStatus := PodStatus{
- ID: pod.id,
- State: pod.state,
- Hypervisor: pod.config.HypervisorType,
- Agent: pod.config.AgentType,
- ContainersStatus: contStatusList,
- }
-
- return podStatus, nil
-}
-
-// CreateContainer is the virtcontainers container creation entry point.
-// CreateContainer creates a container on a given pod.
-func CreateContainer(podID string, containerConfig ContainerConfig) (*Pod, *Container, error) {
- if podID == "" {
- return nil, nil, errNeedPodID
- }
-
- lockFile, err := lockPod(podID)
- if err != nil {
- return nil, nil, err
- }
- defer unlockPod(lockFile)
-
- p, err := fetchPod(podID)
- if err != nil {
- return nil, nil, err
- }
-
- // Create the container.
- c, err := createContainer(p, containerConfig)
- if err != nil {
- return nil, nil, err
- }
-
- // Store it.
- err = c.storeContainer()
- if err != nil {
- return nil, nil, err
- }
-
- // Update pod config.
- p.config.Containers = append(p.config.Containers, containerConfig)
- err = p.storage.storePodResource(podID, configFileType, *(p.config))
- if err != nil {
- return nil, nil, err
- }
-
- err = p.endSession()
- if err != nil {
- return nil, nil, err
- }
-
- return p, c, nil
-}
-
-// DeleteContainer is the virtcontainers container deletion entry point.
-// DeleteContainer deletes a Container from a Pod. If the container is running,
-// it needs to be stopped first.
-func DeleteContainer(podID, containerID string) (*Container, error) {
- if podID == "" {
- return nil, errNeedPodID
- }
-
- if containerID == "" {
- return nil, errNeedContainerID
- }
-
- lockFile, err := lockPod(podID)
- if err != nil {
- return nil, err
- }
- defer unlockPod(lockFile)
-
- p, err := fetchPod(podID)
- if err != nil {
- return nil, err
- }
-
- // Fetch the container.
- c, err := fetchContainer(p, containerID)
- if err != nil {
- return nil, err
- }
-
- // Delete it.
- err = c.delete()
- if err != nil {
- return nil, err
- }
-
- // Update pod config
- for idx, contConfig := range p.config.Containers {
- if contConfig.ID == containerID {
- p.config.Containers = append(p.config.Containers[:idx], p.config.Containers[idx+1:]...)
- break
- }
- }
- err = p.storage.storePodResource(podID, configFileType, *(p.config))
- if err != nil {
- return nil, err
- }
-
- err = p.endSession()
- if err != nil {
- return nil, err
- }
-
- return c, nil
-}
-
-// StartContainer is the virtcontainers container starting entry point.
-// StartContainer starts an already created container.
-func StartContainer(podID, containerID string) (*Container, error) {
- if podID == "" {
- return nil, errNeedPodID
- }
-
- if containerID == "" {
- return nil, errNeedContainerID
- }
-
- lockFile, err := lockPod(podID)
- if err != nil {
- return nil, err
- }
- defer unlockPod(lockFile)
-
- p, err := fetchPod(podID)
- if err != nil {
- return nil, err
- }
-
- // Fetch the container.
- c, err := fetchContainer(p, containerID)
- if err != nil {
- return nil, err
- }
-
- // Start it.
- err = c.start()
- if err != nil {
- c.delete()
- return nil, err
- }
-
- err = p.endSession()
- if err != nil {
- return nil, err
- }
-
- return c, nil
-}
-
-// StopContainer is the virtcontainers container stopping entry point.
-// StopContainer stops an already running container.
-func StopContainer(podID, containerID string) (*Container, error) {
- if podID == "" {
- return nil, errNeedPodID
- }
-
- if containerID == "" {
- return nil, errNeedContainerID
- }
-
- lockFile, err := lockPod(podID)
- if err != nil {
- return nil, err
- }
- defer unlockPod(lockFile)
-
- p, err := fetchPod(podID)
- if err != nil {
- return nil, err
- }
-
- // Fetch the container.
- c, err := fetchContainer(p, containerID)
- if err != nil {
- return nil, err
- }
-
- // Stop it.
- err = c.stop()
- if err != nil {
- c.delete()
- return nil, err
- }
-
- err = p.endSession()
- if err != nil {
- return nil, err
- }
-
- return c, nil
-}
-
-// EnterContainer is the virtcontainers container command execution entry point.
-// EnterContainer enters an already running container and runs a given command.
-func EnterContainer(podID, containerID string, cmd Cmd) (*Pod, *Container, *Process, error) {
- if podID == "" {
- return nil, nil, nil, errNeedPodID
- }
-
- if containerID == "" {
- return nil, nil, nil, errNeedContainerID
- }
-
- lockFile, err := lockPod(podID)
- if err != nil {
- return nil, nil, nil, err
- }
- defer unlockPod(lockFile)
-
- p, err := fetchPod(podID)
- if err != nil {
- return nil, nil, nil, err
- }
-
- // Fetch the container.
- c, err := fetchContainer(p, containerID)
- if err != nil {
- return nil, nil, nil, err
- }
-
- // Enter it.
- process, err := c.enter(cmd)
- if err != nil {
- return nil, nil, nil, err
- }
-
- err = p.endSession()
- if err != nil {
- return nil, nil, nil, err
- }
-
- return p, c, process, nil
-}
-
-// StatusContainer is the virtcontainers container status entry point.
-// StatusContainer returns a detailed container status.
-func StatusContainer(podID, containerID string) (ContainerStatus, error) {
- if podID == "" {
- return ContainerStatus{}, errNeedPodID
- }
-
- if containerID == "" {
- return ContainerStatus{}, errNeedContainerID
- }
-
- var contStatus ContainerStatus
-
- pod, err := fetchPod(podID)
- if err != nil {
- return ContainerStatus{}, err
- }
-
- for _, container := range pod.containers {
- if container.id == containerID {
- contStatus = ContainerStatus{
- ID: container.id,
- State: container.state,
- PID: container.process.Pid,
- RootFs: container.config.RootFs,
- }
- }
- }
-
- return contStatus, nil
-}
-
-// KillContainer is the virtcontainers entry point to send a signal
-// to a container running inside a pod.
-func KillContainer(podID, containerID string, signal syscall.Signal) error {
- if podID == "" {
- return errNeedPodID
- }
-
- if containerID == "" {
- return errNeedContainerID
- }
-
- lockFile, err := lockPod(podID)
- if err != nil {
- return err
- }
- defer unlockPod(lockFile)
-
- p, err := fetchPod(podID)
- if err != nil {
- return err
- }
-
- // Fetch the container.
- c, err := fetchContainer(p, containerID)
- if err != nil {
- return err
- }
-
- // Send a signal to the process.
- err = c.kill(signal)
- if err != nil {
- return err
- }
-
- err = p.endSession()
- if err != nil {
- return err
- }
-
- return nil
-}
diff --git a/vendor/github.com/containers/virtcontainers/api_test.go b/vendor/github.com/containers/virtcontainers/api_test.go
deleted file mode 100644
index ffa080c..0000000
--- a/vendor/github.com/containers/virtcontainers/api_test.go
+++ /dev/null
@@ -1,1520 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "strings"
- "testing"
-)
-
-const (
- testHyperstartPausePath = "/tmp/bundles/pause_bundle/rootfs/bin"
- testHyperstartPauseBinName = "pause"
- containerID = "1"
-)
-
-func newBasicTestCmd() Cmd {
- envs := []EnvVar{
- {
- Var: "PATH",
- Value: "/bin:/usr/bin:/sbin:/usr/sbin",
- },
- }
-
- cmd := Cmd{
- Args: strings.Split("/bin/sh", " "),
- Envs: envs,
- WorkDir: "/",
- }
-
- return cmd
-}
-
-func newTestPodConfigNoop() PodConfig {
- // Define the container command and bundle.
- container := ContainerConfig{
- ID: containerID,
- RootFs: filepath.Join(testDir, testBundle),
- Cmd: newBasicTestCmd(),
- }
-
- // Sets the hypervisor configuration.
- hypervisorConfig := HypervisorConfig{
- KernelPath: filepath.Join(testDir, testKernel),
- ImagePath: filepath.Join(testDir, testImage),
- HypervisorPath: filepath.Join(testDir, testHypervisor),
- }
-
- podConfig := PodConfig{
- ID: testPodID,
- HypervisorType: MockHypervisor,
- HypervisorConfig: hypervisorConfig,
-
- AgentType: NoopAgentType,
-
- Containers: []ContainerConfig{container},
- }
-
- return podConfig
-}
-
-func newTestPodConfigHyperstartAgent() PodConfig {
- // Define the container command and bundle.
- container := ContainerConfig{
- ID: containerID,
- RootFs: filepath.Join(testDir, testBundle),
- Cmd: newBasicTestCmd(),
- }
-
- // Sets the hypervisor configuration.
- hypervisorConfig := HypervisorConfig{
- KernelPath: filepath.Join(testDir, testKernel),
- ImagePath: filepath.Join(testDir, testImage),
- HypervisorPath: filepath.Join(testDir, testHypervisor),
- }
-
- sockets := []Socket{{}, {}}
-
- agentConfig := HyperConfig{
- SockCtlName: testHyperstartCtlSocket,
- SockTtyName: testHyperstartTtySocket,
- Sockets: sockets,
- }
-
- podConfig := PodConfig{
- ID: testPodID,
- HypervisorType: MockHypervisor,
- HypervisorConfig: hypervisorConfig,
-
- AgentType: HyperstartAgent,
- AgentConfig: agentConfig,
-
- Containers: []ContainerConfig{container},
- }
-
- return podConfig
-}
-
-func newTestPodConfigHyperstartAgentCNINetwork() PodConfig {
- // Define the container command and bundle.
- container := ContainerConfig{
- ID: containerID,
- RootFs: filepath.Join(testDir, testBundle),
- Cmd: newBasicTestCmd(),
- }
-
- // Sets the hypervisor configuration.
- hypervisorConfig := HypervisorConfig{
- KernelPath: filepath.Join(testDir, testKernel),
- ImagePath: filepath.Join(testDir, testImage),
- HypervisorPath: filepath.Join(testDir, testHypervisor),
- }
-
- sockets := []Socket{{}, {}}
-
- agentConfig := HyperConfig{
- SockCtlName: testHyperstartCtlSocket,
- SockTtyName: testHyperstartTtySocket,
- Sockets: sockets,
- }
-
- netConfig := NetworkConfig{
- NumInterfaces: 1,
- }
-
- podConfig := PodConfig{
- ID: testPodID,
- HypervisorType: MockHypervisor,
- HypervisorConfig: hypervisorConfig,
-
- AgentType: HyperstartAgent,
- AgentConfig: agentConfig,
-
- NetworkModel: CNINetworkModel,
- NetworkConfig: netConfig,
-
- Containers: []ContainerConfig{container},
- }
-
- return podConfig
-}
-
-func newTestPodConfigHyperstartAgentCNMNetwork() PodConfig {
- // Define the container command and bundle.
- container := ContainerConfig{
- ID: containerID,
- RootFs: filepath.Join(testDir, testBundle),
- Cmd: newBasicTestCmd(),
- }
-
- // Sets the hypervisor configuration.
- hypervisorConfig := HypervisorConfig{
- KernelPath: filepath.Join(testDir, testKernel),
- ImagePath: filepath.Join(testDir, testImage),
- HypervisorPath: filepath.Join(testDir, testHypervisor),
- }
-
- sockets := []Socket{{}, {}}
-
- agentConfig := HyperConfig{
- SockCtlName: testHyperstartCtlSocket,
- SockTtyName: testHyperstartTtySocket,
- Sockets: sockets,
- }
-
- hooks := Hooks{
- PreStartHooks: []Hook{
- {
- Path: testBinHookPath,
- Args: []string{testKeyHook, testContainerIDHook, testControllerIDHook},
- },
- },
- PostStartHooks: []Hook{},
- PostStopHooks: []Hook{},
- }
-
- netConfig := NetworkConfig{
- NumInterfaces: len(hooks.PreStartHooks),
- }
-
- podConfig := PodConfig{
- ID: testPodID,
- Hooks: hooks,
-
- HypervisorType: MockHypervisor,
- HypervisorConfig: hypervisorConfig,
-
- AgentType: HyperstartAgent,
- AgentConfig: agentConfig,
-
- NetworkModel: CNMNetworkModel,
- NetworkConfig: netConfig,
-
- Containers: []ContainerConfig{container},
- }
-
- return podConfig
-}
-
-func TestCreatePodNoopAgentSuccessful(t *testing.T) {
- cleanUp()
-
- config := newTestPodConfigNoop()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- podDir := filepath.Join(configStoragePath, p.id)
- _, err = os.Stat(podDir)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestCreatePodHyperstartAgentSuccessful(t *testing.T) {
- cleanUp()
-
- config := newTestPodConfigHyperstartAgent()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- podDir := filepath.Join(configStoragePath, p.id)
- _, err = os.Stat(podDir)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestCreatePodFailing(t *testing.T) {
- cleanUp()
-
- config := PodConfig{}
-
- p, err := CreatePod(config)
- if p != nil || err == nil {
- t.Fatal()
- }
-}
-
-func TestDeletePodNoopAgentSuccessful(t *testing.T) {
- cleanUp()
-
- config := newTestPodConfigNoop()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- podDir := filepath.Join(configStoragePath, p.id)
- _, err = os.Stat(podDir)
- if err != nil {
- t.Fatal(err)
- }
-
- p, err = DeletePod(p.id)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- _, err = os.Stat(podDir)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestDeletePodHyperstartAgentSuccessful(t *testing.T) {
- cleanUp()
-
- config := newTestPodConfigHyperstartAgent()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- podDir := filepath.Join(configStoragePath, p.id)
- _, err = os.Stat(podDir)
- if err != nil {
- t.Fatal(err)
- }
-
- p, err = DeletePod(p.id)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- _, err = os.Stat(podDir)
- if err == nil {
- t.Fatal(err)
- }
-}
-
-func TestDeletePodFailing(t *testing.T) {
- cleanUp()
-
- podDir := filepath.Join(configStoragePath, testPodID)
- os.Remove(podDir)
-
- p, err := DeletePod(testPodID)
- if p != nil || err == nil {
- t.Fatal()
- }
-}
-
-func TestStartPodNoopAgentSuccessful(t *testing.T) {
- cleanUp()
-
- config := newTestPodConfigNoop()
-
- p, _, err := createAndStartPod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-}
-
-func TestStartPodHyperstartAgentSuccessful(t *testing.T) {
- cleanUp()
-
- if os.Geteuid() != 0 {
- t.Skip(testDisabledAsNonRoot)
- }
-
- config := newTestPodConfigHyperstartAgent()
-
- pauseBinPath := filepath.Join(testDir, testHyperstartPauseBinName)
- _, err := os.Create(pauseBinPath)
- if err != nil {
- t.Fatal(err)
- }
-
- hyperConfig := config.AgentConfig.(HyperConfig)
- hyperConfig.PauseBinPath = pauseBinPath
- config.AgentConfig = hyperConfig
-
- p, _, err := createAndStartPod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- p.agent.(*hyper).bindUnmountAllRootfs(*p)
-
- err = os.Remove(pauseBinPath)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestStartPodFailing(t *testing.T) {
- cleanUp()
-
- podDir := filepath.Join(configStoragePath, testPodID)
- os.Remove(podDir)
-
- p, err := StartPod(testPodID)
- if p != nil || err == nil {
- t.Fatal()
- }
-}
-
-func TestStopPodNoopAgentSuccessful(t *testing.T) {
- cleanUp()
-
- config := newTestPodConfigNoop()
-
- p, _, err := createAndStartPod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- p, err = StopPod(p.id)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-}
-
-func TestStopPodHyperstartAgentSuccessful(t *testing.T) {
- if os.Geteuid() != 0 {
- t.Skip(testDisabledAsNonRoot)
- }
-
- cleanUp()
-
- config := newTestPodConfigHyperstartAgent()
-
- pauseBinPath := filepath.Join(testDir, testHyperstartPauseBinName)
- _, err := os.Create(pauseBinPath)
- if err != nil {
- t.Fatal(err)
- }
-
- hyperConfig := config.AgentConfig.(HyperConfig)
- hyperConfig.PauseBinPath = pauseBinPath
- config.AgentConfig = hyperConfig
-
- p, _, err := createAndStartPod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- p, err = StopPod(p.id)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- err = os.Remove(pauseBinPath)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestStopPodFailing(t *testing.T) {
- cleanUp()
-
- podDir := filepath.Join(configStoragePath, testPodID)
- os.Remove(podDir)
-
- p, err := StopPod(testPodID)
- if p != nil || err == nil {
- t.Fatal()
- }
-}
-
-func TestRunPodNoopAgentSuccessful(t *testing.T) {
- cleanUp()
-
- config := newTestPodConfigNoop()
-
- p, err := RunPod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- podDir := filepath.Join(configStoragePath, p.id)
- _, err = os.Stat(podDir)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestRunPodHyperstartAgentSuccessful(t *testing.T) {
- if os.Geteuid() != 0 {
- t.Skip(testDisabledAsNonRoot)
- }
-
- cleanUp()
-
- config := newTestPodConfigHyperstartAgent()
-
- pauseBinPath := filepath.Join(testDir, testHyperstartPauseBinName)
- _, err := os.Create(pauseBinPath)
- if err != nil {
- t.Fatal(err)
- }
-
- hyperConfig := config.AgentConfig.(HyperConfig)
- hyperConfig.PauseBinPath = pauseBinPath
- config.AgentConfig = hyperConfig
-
- p, err := RunPod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- podDir := filepath.Join(configStoragePath, p.id)
- _, err = os.Stat(podDir)
- if err != nil {
- t.Fatal(err)
- }
-
- p.agent.(*hyper).bindUnmountAllRootfs(*p)
-
- err = os.Remove(pauseBinPath)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestRunPodFailing(t *testing.T) {
- cleanUp()
-
- config := PodConfig{}
-
- p, err := RunPod(config)
- if p != nil || err == nil {
- t.Fatal()
- }
-}
-
-func TestListPodSuccessful(t *testing.T) {
- cleanUp()
-
- os.RemoveAll(configStoragePath)
-
- config := newTestPodConfigNoop()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- _, err = ListPod()
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestListPodNoPodDirectory(t *testing.T) {
- cleanUp()
-
- os.RemoveAll(configStoragePath)
-
- _, err := ListPod()
- if err != nil {
- t.Fatal(fmt.Sprintf("unexpected ListPod error from non-existent pod directory: %v", err))
- }
-}
-
-func TestStatusPodSuccessful(t *testing.T) {
- cleanUp()
-
- config := newTestPodConfigNoop()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- _, err = StatusPod(p.id)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestStatusPodFailingFetchPodConfig(t *testing.T) {
- cleanUp()
-
- config := newTestPodConfigNoop()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- path := filepath.Join(configStoragePath, p.id)
- os.RemoveAll(path)
-
- _, err = StatusPod(p.id)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestStatusPodPodFailingFetchPodState(t *testing.T) {
- cleanUp()
-
- config := newTestPodConfigNoop()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- os.RemoveAll(p.configPath)
-
- _, err = StatusPod(p.id)
- if err == nil {
- t.Fatal()
- }
-}
-
-func newTestContainerConfigNoop(contID string) ContainerConfig {
- // Define the container command and bundle.
- container := ContainerConfig{
- ID: contID,
- RootFs: filepath.Join(testDir, testBundle),
- Cmd: newBasicTestCmd(),
- }
-
- return container
-}
-
-func TestCreateContainerSuccessful(t *testing.T) {
- cleanUp()
-
- contID := "100"
- config := newTestPodConfigNoop()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- podDir := filepath.Join(configStoragePath, p.id)
- _, err = os.Stat(podDir)
- if err != nil {
- t.Fatal(err)
- }
-
- contConfig := newTestContainerConfigNoop(contID)
-
- _, c, err := CreateContainer(p.id, contConfig)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-
- contDir := filepath.Join(podDir, contID)
- _, err = os.Stat(contDir)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestCreateContainerFailingNoPod(t *testing.T) {
- cleanUp()
-
- contID := "100"
- config := newTestPodConfigNoop()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- p, err = DeletePod(p.id)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- podDir := filepath.Join(configStoragePath, p.id)
- _, err = os.Stat(podDir)
- if err == nil {
- t.Fatal()
- }
-
- contConfig := newTestContainerConfigNoop(contID)
-
- _, c, err := CreateContainer(p.id, contConfig)
- if c != nil || err == nil {
- t.Fatal(err)
- }
-}
-
-func TestDeleteContainerSuccessful(t *testing.T) {
- cleanUp()
-
- contID := "100"
- config := newTestPodConfigNoop()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- podDir := filepath.Join(configStoragePath, p.id)
- _, err = os.Stat(podDir)
- if err != nil {
- t.Fatal(err)
- }
-
- contConfig := newTestContainerConfigNoop(contID)
-
- _, c, err := CreateContainer(p.id, contConfig)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-
- contDir := filepath.Join(podDir, contID)
- _, err = os.Stat(contDir)
- if err != nil {
- t.Fatal(err)
- }
-
- c, err = DeleteContainer(p.id, contID)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-
- _, err = os.Stat(contDir)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestDeleteContainerFailingNoPod(t *testing.T) {
- cleanUp()
-
- podDir := filepath.Join(configStoragePath, testPodID)
- contID := "100"
- os.RemoveAll(podDir)
-
- c, err := DeleteContainer(testPodID, contID)
- if c != nil || err == nil {
- t.Fatal()
- }
-}
-
-func TestDeleteContainerFailingNoContainer(t *testing.T) {
- cleanUp()
-
- contID := "100"
- config := newTestPodConfigNoop()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- podDir := filepath.Join(configStoragePath, p.id)
- _, err = os.Stat(podDir)
- if err != nil {
- t.Fatal(err)
- }
-
- c, err := DeleteContainer(p.id, contID)
- if c != nil || err == nil {
- t.Fatal()
- }
-}
-
-func TestStartContainerNoopAgentSuccessful(t *testing.T) {
- cleanUp()
-
- contID := "100"
- config := newTestPodConfigNoop()
-
- p, podDir, err := createAndStartPod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
- contConfig := newTestContainerConfigNoop(contID)
-
- _, c, err := CreateContainer(p.id, contConfig)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-
- contDir := filepath.Join(podDir, contID)
- _, err = os.Stat(contDir)
- if err != nil {
- t.Fatal(err)
- }
-
- c, err = StartContainer(p.id, contID)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-}
-
-func TestStartContainerFailingNoPod(t *testing.T) {
- cleanUp()
-
- podDir := filepath.Join(configStoragePath, testPodID)
- contID := "100"
- os.RemoveAll(podDir)
-
- c, err := StartContainer(testPodID, contID)
- if c != nil || err == nil {
- t.Fatal()
- }
-}
-
-func TestStartContainerFailingNoContainer(t *testing.T) {
- cleanUp()
-
- contID := "100"
- config := newTestPodConfigNoop()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- podDir := filepath.Join(configStoragePath, p.id)
- _, err = os.Stat(podDir)
- if err != nil {
- t.Fatal(err)
- }
-
- c, err := StartContainer(p.id, contID)
- if c != nil || err == nil {
- t.Fatal()
- }
-}
-
-func TestStartContainerFailingPodNotStarted(t *testing.T) {
- cleanUp()
-
- contID := "100"
- config := newTestPodConfigNoop()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- podDir := filepath.Join(configStoragePath, p.id)
- _, err = os.Stat(podDir)
- if err != nil {
- t.Fatal(err)
- }
-
- contConfig := newTestContainerConfigNoop(contID)
-
- _, c, err := CreateContainer(p.id, contConfig)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-
- contDir := filepath.Join(podDir, contID)
- _, err = os.Stat(contDir)
- if err != nil {
- t.Fatal(err)
- }
-
- c, err = StartContainer(p.id, contID)
- if c != nil || err == nil {
- t.Fatal()
- }
-}
-
-func TestStopContainerNoopAgentSuccessful(t *testing.T) {
- cleanUp()
-
- contID := "100"
- config := newTestPodConfigNoop()
-
- p, podDir, err := createAndStartPod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- contConfig := newTestContainerConfigNoop(contID)
-
- _, c, err := CreateContainer(p.id, contConfig)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-
- contDir := filepath.Join(podDir, contID)
- _, err = os.Stat(contDir)
- if err != nil {
- t.Fatal(err)
- }
-
- c, err = StartContainer(p.id, contID)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-
- c, err = StopContainer(p.id, contID)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-}
-
-func TestStartStopContainerHyperstartAgentSuccessful(t *testing.T) {
- if os.Geteuid() != 0 {
- t.Skip(testDisabledAsNonRoot)
- }
-
- cleanUp()
-
- contID := "100"
- config := newTestPodConfigHyperstartAgent()
-
- pauseBinPath := filepath.Join(testDir, testHyperstartPauseBinName)
- _, err := os.Create(pauseBinPath)
- if err != nil {
- t.Fatal(err)
- }
-
- hyperConfig := config.AgentConfig.(HyperConfig)
- hyperConfig.PauseBinPath = pauseBinPath
- config.AgentConfig = hyperConfig
-
- p, podDir, err := createAndStartPod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- contConfig := newTestContainerConfigNoop(contID)
-
- _, c, err := CreateContainer(p.id, contConfig)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-
- contDir := filepath.Join(podDir, contID)
- _, err = os.Stat(contDir)
- if err != nil {
- t.Fatal(err)
- }
-
- c, err = StartContainer(p.id, contID)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-
- c, err = StopContainer(p.id, contID)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-
- p.agent.(*hyper).bindUnmountAllRootfs(*p)
-
- err = os.Remove(pauseBinPath)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestStartStopPodHyperstartAgentSuccessfulWithCNINetwork(t *testing.T) {
- if os.Geteuid() != 0 {
- t.Skip(testDisabledAsNonRoot)
- }
-
- cleanUp()
-
- config := newTestPodConfigHyperstartAgentCNINetwork()
-
- pauseBinPath := filepath.Join(testDir, testHyperstartPauseBinName)
- _, err := os.Create(pauseBinPath)
- if err != nil {
- t.Fatal(err)
- }
-
- hyperConfig := config.AgentConfig.(HyperConfig)
- hyperConfig.PauseBinPath = pauseBinPath
- config.AgentConfig = hyperConfig
-
- p, _, err := createAndStartPod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- p, err = StopPod(p.id)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- p, err = DeletePod(p.id)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- err = os.Remove(pauseBinPath)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestStartStopPodHyperstartAgentSuccessfulWithCNMNetwork(t *testing.T) {
- if os.Geteuid() != 0 {
- t.Skip(testDisabledAsNonRoot)
- }
-
- config := newTestPodConfigHyperstartAgentCNMNetwork()
-
- pauseBinPath := filepath.Join(testDir, testHyperstartPauseBinName)
- _, err := os.Create(pauseBinPath)
- if err != nil {
- t.Fatal(err)
- }
-
- hyperConfig := config.AgentConfig.(HyperConfig)
- hyperConfig.PauseBinPath = pauseBinPath
- config.AgentConfig = hyperConfig
-
- p, _, err := createAndStartPod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- p, err = StopPod(p.id)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- p, err = DeletePod(p.id)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- err = os.Remove(pauseBinPath)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestStopContainerFailingNoPod(t *testing.T) {
- cleanUp()
-
- podDir := filepath.Join(configStoragePath, testPodID)
- contID := "100"
- os.RemoveAll(podDir)
-
- c, err := StopContainer(testPodID, contID)
- if c != nil || err == nil {
- t.Fatal()
- }
-}
-
-func TestStopContainerFailingNoContainer(t *testing.T) {
- cleanUp()
-
- contID := "100"
- config := newTestPodConfigNoop()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- podDir := filepath.Join(configStoragePath, p.id)
- _, err = os.Stat(podDir)
- if err != nil {
- t.Fatal(err)
- }
-
- c, err := StopContainer(p.id, contID)
- if c != nil || err == nil {
- t.Fatal()
- }
-}
-
-func TestStopContainerFailingContNotStarted(t *testing.T) {
- cleanUp()
-
- contID := "100"
- config := newTestPodConfigNoop()
-
- p, podDir, err := createAndStartPod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- contConfig := newTestContainerConfigNoop(contID)
-
- _, c, err := CreateContainer(p.id, contConfig)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-
- contDir := filepath.Join(podDir, contID)
- _, err = os.Stat(contDir)
- if err != nil {
- t.Fatal(err)
- }
-
- c, err = StopContainer(p.id, contID)
- if c != nil || err == nil {
- t.Fatal()
- }
-}
-
-func TestEnterContainerNoopAgentSuccessful(t *testing.T) {
- cleanUp()
-
- contID := "100"
- config := newTestPodConfigNoop()
-
- p, podDir, err := createAndStartPod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- contConfig := newTestContainerConfigNoop(contID)
-
- _, c, err := CreateContainer(p.id, contConfig)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-
- contDir := filepath.Join(podDir, contID)
- _, err = os.Stat(contDir)
- if err != nil {
- t.Fatal(err)
- }
-
- c, err = StartContainer(p.id, contID)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-
- cmd := newBasicTestCmd()
-
- _, c, _, err = EnterContainer(p.id, contID, cmd)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-}
-
-func TestEnterContainerHyperstartAgentSuccessful(t *testing.T) {
- if os.Geteuid() != 0 {
- t.Skip(testDisabledAsNonRoot)
- }
-
- cleanUp()
-
- contID := "100"
- config := newTestPodConfigHyperstartAgent()
-
- pauseBinPath := filepath.Join(testDir, testHyperstartPauseBinName)
- _, err := os.Create(pauseBinPath)
- if err != nil {
- t.Fatal(err)
- }
-
- hyperConfig := config.AgentConfig.(HyperConfig)
- hyperConfig.PauseBinPath = pauseBinPath
- config.AgentConfig = hyperConfig
-
- p, podDir, err := createAndStartPod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- contConfig := newTestContainerConfigNoop(contID)
-
- _, _, err = CreateContainer(p.id, contConfig)
- if err != nil {
- t.Fatal(err)
- }
-
- contDir := filepath.Join(podDir, contID)
- _, err = os.Stat(contDir)
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = StartContainer(p.id, contID)
- if err != nil {
- t.Fatal(err)
- }
-
- cmd := newBasicTestCmd()
-
- _, _, _, err = EnterContainer(p.id, contID, cmd)
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = StopContainer(p.id, contID)
- if err != nil {
- t.Fatal(err)
- }
-
- p.agent.(*hyper).bindUnmountAllRootfs(*p)
-
- err = os.Remove(pauseBinPath)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestEnterContainerFailingNoPod(t *testing.T) {
- cleanUp()
-
- podDir := filepath.Join(configStoragePath, testPodID)
- contID := "100"
- os.RemoveAll(podDir)
-
- cmd := newBasicTestCmd()
-
- _, c, _, err := EnterContainer(testPodID, contID, cmd)
- if c != nil || err == nil {
- t.Fatal()
- }
-}
-
-func TestEnterContainerFailingNoContainer(t *testing.T) {
- cleanUp()
-
- contID := "100"
- config := newTestPodConfigNoop()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- podDir := filepath.Join(configStoragePath, p.id)
- _, err = os.Stat(podDir)
- if err != nil {
- t.Fatal(err)
- }
-
- cmd := newBasicTestCmd()
-
- _, c, _, err := EnterContainer(p.id, contID, cmd)
- if c != nil || err == nil {
- t.Fatal()
- }
-}
-
-func TestEnterContainerFailingContNotStarted(t *testing.T) {
- cleanUp()
-
- contID := "100"
- config := newTestPodConfigNoop()
-
- p, podDir, err := createAndStartPod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- contConfig := newTestContainerConfigNoop(contID)
-
- _, c, err := CreateContainer(p.id, contConfig)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-
- contDir := filepath.Join(podDir, contID)
- _, err = os.Stat(contDir)
- if err != nil {
- t.Fatal(err)
- }
-
- cmd := newBasicTestCmd()
-
- _, c, _, err = EnterContainer(p.id, contID, cmd)
- if c != nil || err == nil {
- t.Fatal()
- }
-}
-
-func TestStatusContainerSuccessful(t *testing.T) {
- cleanUp()
-
- contID := "100"
- config := newTestPodConfigNoop()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- podDir := filepath.Join(configStoragePath, p.id)
- _, err = os.Stat(podDir)
- if err != nil {
- t.Fatal(err)
- }
-
- contConfig := newTestContainerConfigNoop(contID)
-
- _, c, err := CreateContainer(p.id, contConfig)
- if c == nil || err != nil {
- t.Fatal(err)
- }
-
- contDir := filepath.Join(podDir, contID)
- _, err = os.Stat(contDir)
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = StatusContainer(p.id, contID)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestStatusContainerFailing(t *testing.T) {
- cleanUp()
-
- contID := "100"
- config := newTestPodConfigNoop()
-
- p, err := CreatePod(config)
- if p == nil || err != nil {
- t.Fatal(err)
- }
-
- os.RemoveAll(p.configPath)
-
- _, err = StatusContainer(p.id, contID)
- if err == nil {
- t.Fatal()
- }
-}
-
-/*
- * Benchmarks
- */
-
-func createNewPodConfig(hType HypervisorType, aType AgentType, aConfig interface{}, netModel NetworkModel) PodConfig {
- hypervisorConfig := HypervisorConfig{
- KernelPath: "/usr/share/clear-containers/vmlinux.container",
- ImagePath: "/usr/share/clear-containers/clear-containers.img",
- HypervisorPath: "/usr/bin/qemu-lite-system-x86_64",
- }
-
- netConfig := NetworkConfig{
- NumInterfaces: 1,
- }
-
- return PodConfig{
- ID: testPodID,
- HypervisorType: hType,
- HypervisorConfig: hypervisorConfig,
-
- AgentType: aType,
- AgentConfig: aConfig,
-
- NetworkModel: netModel,
- NetworkConfig: netConfig,
- }
-}
-
-func createNewContainerConfigs(numOfContainers int) []ContainerConfig {
- var contConfigs []ContainerConfig
-
- envs := []EnvVar{
- {
- Var: "PATH",
- Value: "/bin:/usr/bin:/sbin:/usr/sbin",
- },
- }
-
- cmd := Cmd{
- Args: strings.Split("/bin/ps -A", " "),
- Envs: envs,
- WorkDir: "/",
- }
-
- rootFs := "/tmp/bundles/busybox/"
-
- for i := 0; i < numOfContainers; i++ {
- contConfig := ContainerConfig{
- ID: fmt.Sprintf("%d", i),
- RootFs: rootFs,
- Cmd: cmd,
- }
-
- contConfigs = append(contConfigs, contConfig)
- }
-
- return contConfigs
-}
-
-// createAndStartPod handles the common test operation of creating and
-// starting a pod.
-func createAndStartPod(config PodConfig) (pod *Pod, podDir string,
- err error) {
-
- // Create pod
- pod, err = CreatePod(config)
- if pod == nil || err != nil {
- return nil, "", err
- }
-
- podDir = filepath.Join(configStoragePath, pod.id)
- _, err = os.Stat(podDir)
- if err != nil {
- return nil, "", err
- }
-
- // Start pod
- pod, err = StartPod(pod.id)
- if pod == nil || err != nil {
- return nil, "", err
- }
-
- return pod, podDir, nil
-}
-
-func createStartStopDeletePod(b *testing.B, podConfig PodConfig) {
- p, _, err := createAndStartPod(podConfig)
- if p == nil || err != nil {
- b.Fatalf("Could not create and start pod: %s", err)
- }
-
- // Stop pod
- _, err = StopPod(p.id)
- if err != nil {
- b.Fatalf("Could not stop pod: %s", err)
- }
-
- // Delete pod
- _, err = DeletePod(p.id)
- if err != nil {
- b.Fatalf("Could not delete pod: %s", err)
- }
-}
-
-func createStartStopDeleteContainers(b *testing.B, podConfig PodConfig, contConfigs []ContainerConfig) {
- // Create pod
- p, err := CreatePod(podConfig)
- if err != nil {
- b.Fatalf("Could not create pod: %s", err)
- }
-
- // Start pod
- _, err = StartPod(p.id)
- if err != nil {
- b.Fatalf("Could not start pod: %s", err)
- }
-
- // Create containers
- for _, contConfig := range contConfigs {
- _, _, err := CreateContainer(p.id, contConfig)
- if err != nil {
- b.Fatalf("Could not create container %s: %s", contConfig.ID, err)
- }
- }
-
- // Start containers
- for _, contConfig := range contConfigs {
- _, err := StartContainer(p.id, contConfig.ID)
- if err != nil {
- b.Fatalf("Could not start container %s: %s", contConfig.ID, err)
- }
- }
-
- // Stop containers
- for _, contConfig := range contConfigs {
- _, err := StopContainer(p.id, contConfig.ID)
- if err != nil {
- b.Fatalf("Could not stop container %s: %s", contConfig.ID, err)
- }
- }
-
- // Delete containers
- for _, contConfig := range contConfigs {
- _, err := DeleteContainer(p.id, contConfig.ID)
- if err != nil {
- b.Fatalf("Could not delete container %s: %s", contConfig.ID, err)
- }
- }
-
- // Stop pod
- _, err = StopPod(p.id)
- if err != nil {
- b.Fatalf("Could not stop pod: %s", err)
- }
-
- // Delete pod
- _, err = DeletePod(p.id)
- if err != nil {
- b.Fatalf("Could not delete pod: %s", err)
- }
-}
-
-var benchmarkHyperConfig = HyperConfig{
- PauseBinPath: filepath.Join(testHyperstartPausePath, testHyperstartPauseBinName),
-}
-
-func BenchmarkCreateStartStopDeletePodQemuHypervisorHyperstartAgentNetworkCNI(b *testing.B) {
- for i := 0; i < b.N; i++ {
- podConfig := createNewPodConfig(QemuHypervisor, HyperstartAgent, benchmarkHyperConfig, CNINetworkModel)
- createStartStopDeletePod(b, podConfig)
- }
-}
-
-func BenchmarkCreateStartStopDeletePodQemuHypervisorNoopAgentNetworkCNI(b *testing.B) {
- for i := 0; i < b.N; i++ {
- podConfig := createNewPodConfig(QemuHypervisor, NoopAgentType, nil, CNINetworkModel)
- createStartStopDeletePod(b, podConfig)
- }
-}
-
-func BenchmarkCreateStartStopDeletePodQemuHypervisorHyperstartAgentNetworkNoop(b *testing.B) {
- for i := 0; i < b.N; i++ {
- podConfig := createNewPodConfig(QemuHypervisor, HyperstartAgent, benchmarkHyperConfig, NoopNetworkModel)
- createStartStopDeletePod(b, podConfig)
- }
-}
-
-func BenchmarkCreateStartStopDeletePodQemuHypervisorNoopAgentNetworkNoop(b *testing.B) {
- for i := 0; i < b.N; i++ {
- podConfig := createNewPodConfig(QemuHypervisor, NoopAgentType, nil, NoopNetworkModel)
- createStartStopDeletePod(b, podConfig)
- }
-}
-
-func BenchmarkCreateStartStopDeletePodMockHypervisorNoopAgentNetworkNoop(b *testing.B) {
- for i := 0; i < b.N; i++ {
- podConfig := createNewPodConfig(MockHypervisor, NoopAgentType, nil, NoopNetworkModel)
- createStartStopDeletePod(b, podConfig)
- }
-}
-
-func BenchmarkStartStop1ContainerQemuHypervisorHyperstartAgentNetworkNoop(b *testing.B) {
- for i := 0; i < b.N; i++ {
- podConfig := createNewPodConfig(QemuHypervisor, HyperstartAgent, benchmarkHyperConfig, NoopNetworkModel)
- contConfigs := createNewContainerConfigs(1)
- createStartStopDeleteContainers(b, podConfig, contConfigs)
- }
-}
-
-func BenchmarkStartStop10ContainerQemuHypervisorHyperstartAgentNetworkNoop(b *testing.B) {
- for i := 0; i < b.N; i++ {
- podConfig := createNewPodConfig(QemuHypervisor, HyperstartAgent, benchmarkHyperConfig, NoopNetworkModel)
- contConfigs := createNewContainerConfigs(10)
- createStartStopDeleteContainers(b, podConfig, contConfigs)
- }
-}
diff --git a/vendor/github.com/containers/virtcontainers/cc_proxy.go b/vendor/github.com/containers/virtcontainers/cc_proxy.go
deleted file mode 100644
index 4874d39..0000000
--- a/vendor/github.com/containers/virtcontainers/cc_proxy.go
+++ /dev/null
@@ -1,211 +0,0 @@
-//
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
- "net"
- "net/url"
-
- "github.com/clearcontainers/proxy/client"
-)
-
-var defaultCCProxyURL = "unix:///run/cc-oci-runtime/proxy.sock"
-
-type ccProxy struct {
- client *client.Client
-}
-
-// CCProxyConfig is a structure storing information needed for
-// the Clear Containers proxy initialization.
-type CCProxyConfig struct {
- URL string
-}
-
-func (p *ccProxy) connectProxy(proxyURL string) (*client.Client, error) {
- if proxyURL == "" {
- proxyURL = defaultCCProxyURL
- }
-
- u, err := url.Parse(proxyURL)
- if err != nil {
- return nil, err
- }
-
- if u.Scheme == "" {
- return nil, fmt.Errorf("URL scheme cannot be empty")
- }
-
- address := u.Host
- if address == "" {
- if u.Path == "" {
- return nil, fmt.Errorf("URL host and path cannot be empty")
- }
-
- address = u.Path
- }
-
- conn, err := net.Dial(u.Scheme, address)
- if err != nil {
- return nil, err
- }
-
- return client.NewClient(conn), nil
-}
-
-// register is the proxy register implementation for ccProxy.
-func (p *ccProxy) register(pod Pod) ([]ProxyInfo, string, error) {
- var err error
- var proxyInfos []ProxyInfo
-
- ccConfig, ok := newProxyConfig(*(pod.config)).(CCProxyConfig)
- if !ok {
- return []ProxyInfo{}, "", fmt.Errorf("Wrong proxy config type, should be CCProxyConfig type")
- }
-
- p.client, err = p.connectProxy(ccConfig.URL)
- if err != nil {
- return []ProxyInfo{}, "", err
- }
-
- hyperConfig, ok := newAgentConfig(*(pod.config)).(HyperConfig)
- if !ok {
- return []ProxyInfo{}, "", fmt.Errorf("Wrong agent config type, should be HyperConfig type")
- }
-
- registerVMOptions := &client.RegisterVMOptions{
- Console: pod.hypervisor.getPodConsole(pod.id),
- NumIOStreams: len(pod.containers),
- }
-
- registerVMReturn, err := p.client.RegisterVM(pod.id, hyperConfig.SockCtlName,
- hyperConfig.SockTtyName, registerVMOptions)
- if err != nil {
- return []ProxyInfo{}, "", err
- }
-
- url := registerVMReturn.IO.URL
- if url == "" {
- url = defaultCCProxyURL
- }
-
- if len(registerVMReturn.IO.Tokens) != len(pod.containers) {
- return []ProxyInfo{}, "", fmt.Errorf("%d tokens retrieved out of %d expected",
- len(registerVMReturn.IO.Tokens),
- len(pod.containers))
- }
-
- for _, token := range registerVMReturn.IO.Tokens {
- proxyInfo := ProxyInfo{
- Token: token,
- }
-
- proxyInfos = append(proxyInfos, proxyInfo)
- }
-
- return proxyInfos, url, nil
-}
-
-// unregister is the proxy unregister implementation for ccProxy.
-func (p *ccProxy) unregister(pod Pod) error {
- if p.client == nil {
- return fmt.Errorf("unregister: Client is nil, we can't interact with cc-proxy")
- }
-
- return p.client.UnregisterVM(pod.id)
-}
-
-// connect is the proxy connect implementation for ccProxy.
-func (p *ccProxy) connect(pod Pod, createToken bool) (ProxyInfo, string, error) {
- var err error
-
- ccConfig, ok := newProxyConfig(*(pod.config)).(CCProxyConfig)
- if !ok {
- return ProxyInfo{}, "", fmt.Errorf("Wrong proxy config type, should be CCProxyConfig type")
- }
-
- p.client, err = p.connectProxy(ccConfig.URL)
- if err != nil {
- return ProxyInfo{}, "", err
- }
-
- // In case we are asked to create a token, this means the caller
- // expects only one token to be generated.
- numTokens := 0
- if createToken {
- numTokens = 1
- }
-
- attachVMOptions := &client.AttachVMOptions{
- NumIOStreams: numTokens,
- }
-
- attachVMReturn, err := p.client.AttachVM(pod.id, attachVMOptions)
- if err != nil {
- return ProxyInfo{}, "", err
- }
-
- url := attachVMReturn.IO.URL
- if url == "" {
- url = defaultCCProxyURL
- }
-
- if len(attachVMReturn.IO.Tokens) != numTokens {
- return ProxyInfo{}, "", fmt.Errorf("%d tokens retrieved out of %d expected",
- len(attachVMReturn.IO.Tokens), numTokens)
- }
-
- if !createToken {
- return ProxyInfo{}, url, nil
- }
-
- proxyInfo := ProxyInfo{
- Token: attachVMReturn.IO.Tokens[0],
- }
-
- return proxyInfo, url, nil
-}
-
-// disconnect is the proxy disconnect implementation for ccProxy.
-func (p *ccProxy) disconnect() error {
- if p.client == nil {
- return fmt.Errorf("disconnect: Client is nil, we can't interact with cc-proxy")
- }
-
- p.client.Close()
-
- return nil
-}
-
-// sendCmd is the proxy sendCmd implementation for ccProxy.
-func (p *ccProxy) sendCmd(cmd interface{}) (interface{}, error) {
- if p.client == nil {
- return nil, fmt.Errorf("sendCmd: Client is nil, we can't interact with cc-proxy")
- }
-
- proxyCmd, ok := cmd.(hyperstartProxyCmd)
- if !ok {
- return nil, fmt.Errorf("Wrong command type, should be hyperstartProxyCmd type")
- }
-
- var tokens []string
- if proxyCmd.token != "" {
- tokens = append(tokens, proxyCmd.token)
- }
-
- return nil, p.client.HyperWithTokens(proxyCmd.cmd, tokens, proxyCmd.message)
-}
diff --git a/vendor/github.com/containers/virtcontainers/cc_shim.go b/vendor/github.com/containers/virtcontainers/cc_shim.go
deleted file mode 100644
index 679e562..0000000
--- a/vendor/github.com/containers/virtcontainers/cc_shim.go
+++ /dev/null
@@ -1,90 +0,0 @@
-//
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
- "os"
- "os/exec"
-)
-
-type ccShim struct{}
-
-// CCShimConfig is the structure providing specific configuration
-// for ccShim implementation.
-type CCShimConfig struct {
- Path string
-}
-
-var consoleFileMode = os.FileMode(0660)
-
-// start is the ccShim start implementation.
-// It starts the cc-shim binary with URL and token flags provided by
-// the proxy.
-func (s *ccShim) start(pod Pod, params ShimParams) (int, error) {
- if pod.config == nil {
- return -1, fmt.Errorf("Pod config cannot be nil")
- }
-
- config, ok := newShimConfig(*(pod.config)).(CCShimConfig)
- if !ok {
- return -1, fmt.Errorf("Wrong shim config type, should be CCShimConfig type")
- }
-
- if config.Path == "" {
- return -1, fmt.Errorf("Shim path cannot be empty")
- }
-
- if params.Token == "" {
- return -1, fmt.Errorf("Token cannot be empty")
- }
-
- if params.URL == "" {
- return -1, fmt.Errorf("URL cannot be empty")
- }
-
- cmd := exec.Command(config.Path, "-t", params.Token, "-u", params.URL)
- cmd.Env = os.Environ()
-
- cmd.Stdin = os.Stdin
- cmd.Stdout = os.Stdout
- cmd.Stderr = os.Stderr
-
- var f *os.File
- var err error
- if params.Console != "" {
- f, err = os.OpenFile(params.Console, os.O_RDWR, consoleFileMode)
- if err != nil {
- return -1, err
- }
-
- cmd.Stdin = f
- cmd.Stdout = f
- cmd.Stderr = f
- }
- defer func() {
- if f != nil {
- f.Close()
- }
- }()
-
- if err := cmd.Start(); err != nil {
- return -1, err
- }
-
- return cmd.Process.Pid, nil
-}
diff --git a/vendor/github.com/containers/virtcontainers/cc_shim_test.go b/vendor/github.com/containers/virtcontainers/cc_shim_test.go
deleted file mode 100644
index 141c75f..0000000
--- a/vendor/github.com/containers/virtcontainers/cc_shim_test.go
+++ /dev/null
@@ -1,168 +0,0 @@
-//
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "os"
- "path/filepath"
- "testing"
-)
-
-var testShimPath = "/tmp/bin/cc-shim-mock"
-var testProxyURL = "foo:///foo/clear-containers/proxy.sock"
-var testWrongConsolePath = "/foo/wrong-console"
-var testConsolePath = "tty-console"
-
-func testCCShimStart(t *testing.T, pod Pod, params ShimParams, expectFail bool) {
- s := &ccShim{}
-
- pid, err := s.start(pod, params)
- if expectFail {
- if err == nil || pid != -1 {
- t.Fatalf("This test should fail (pod %+v, params %+v, expectFail %t)",
- pod, params, expectFail)
- }
- } else {
- if err != nil {
- t.Fatalf("This test should pass (pod %+v, params %+v, expectFail %t): %s",
- pod, params, expectFail, err)
- }
-
- if pid == -1 {
- t.Fatalf("This test should pass (pod %+v, params %+v, expectFail %t)",
- pod, params, expectFail)
- }
- }
-}
-
-func TestCCShimStartNilPodConfigFailure(t *testing.T) {
- testCCShimStart(t, Pod{}, ShimParams{}, true)
-}
-
-func TestCCShimStartNilShimConfigFailure(t *testing.T) {
- pod := Pod{
- config: &PodConfig{},
- }
-
- testCCShimStart(t, pod, ShimParams{}, true)
-}
-
-func TestCCShimStartShimPathEmptyFailure(t *testing.T) {
- pod := Pod{
- config: &PodConfig{
- ShimType: CCShimType,
- ShimConfig: CCShimConfig{},
- },
- }
-
- testCCShimStart(t, pod, ShimParams{}, true)
-}
-
-func TestCCShimStartParamsTokenEmptyFailure(t *testing.T) {
- pod := Pod{
- config: &PodConfig{
- ShimType: CCShimType,
- ShimConfig: CCShimConfig{
- Path: testShimPath,
- },
- },
- }
-
- testCCShimStart(t, pod, ShimParams{}, true)
-}
-
-func TestCCShimStartParamsURLEmptyFailure(t *testing.T) {
- pod := Pod{
- config: &PodConfig{
- ShimType: CCShimType,
- ShimConfig: CCShimConfig{
- Path: testShimPath,
- },
- },
- }
-
- params := ShimParams{
- Token: "testToken",
- }
-
- testCCShimStart(t, pod, params, true)
-}
-
-func TestCCShimStartSuccessful(t *testing.T) {
- pod := Pod{
- config: &PodConfig{
- ShimType: CCShimType,
- ShimConfig: CCShimConfig{
- Path: testShimPath,
- },
- },
- }
-
- params := ShimParams{
- Token: "testToken",
- URL: testProxyURL,
- }
-
- testCCShimStart(t, pod, params, false)
-}
-
-func TestCCShimStartWithConsoleNonExistingFailure(t *testing.T) {
- pod := Pod{
- config: &PodConfig{
- ShimType: CCShimType,
- ShimConfig: CCShimConfig{
- Path: testShimPath,
- },
- },
- }
-
- params := ShimParams{
- Token: "testToken",
- URL: testProxyURL,
- Console: testWrongConsolePath,
- }
-
- testCCShimStart(t, pod, params, true)
-}
-
-func TestCCShimStartWithConsoleSuccessful(t *testing.T) {
- cleanUp()
-
- consolePath := filepath.Join(testDir, testConsolePath)
- f, err := os.Create(consolePath)
- if err != nil {
- t.Fatal(err)
- }
- f.Close()
-
- pod := Pod{
- config: &PodConfig{
- ShimType: CCShimType,
- ShimConfig: CCShimConfig{
- Path: testShimPath,
- },
- },
- }
-
- params := ShimParams{
- Token: "testToken",
- URL: testProxyURL,
- Console: consolePath,
- }
-
- testCCShimStart(t, pod, params, false)
-}
diff --git a/vendor/github.com/containers/virtcontainers/cni.go b/vendor/github.com/containers/virtcontainers/cni.go
deleted file mode 100644
index d94ffed..0000000
--- a/vendor/github.com/containers/virtcontainers/cni.go
+++ /dev/null
@@ -1,154 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "github.com/containernetworking/cni/pkg/ns"
- cniPlugin "github.com/containers/virtcontainers/pkg/cni"
-)
-
-// cni is a network implementation for the CNI plugin.
-type cni struct{}
-
-func (n *cni) addVirtInterfaces(networkNS *NetworkNamespace) error {
- netPlugin, err := cniPlugin.NewNetworkPlugin()
- if err != nil {
- return err
- }
-
- for idx, endpoint := range networkNS.Endpoints {
- result, err := netPlugin.AddNetwork(endpoint.NetPair.ID, networkNS.NetNsPath, endpoint.NetPair.VirtIface.Name)
- if err != nil {
- return err
- }
-
- networkNS.Endpoints[idx].Properties = *result
-
- virtLog.Infof("AddNetwork results %v", *result)
- }
-
- return nil
-}
-
-func (n *cni) deleteVirtInterfaces(networkNS NetworkNamespace) error {
- netPlugin, err := cniPlugin.NewNetworkPlugin()
- if err != nil {
- return err
- }
-
- for _, endpoint := range networkNS.Endpoints {
- err := netPlugin.RemoveNetwork(endpoint.NetPair.ID, networkNS.NetNsPath, endpoint.NetPair.VirtIface.Name)
- if err != nil {
- return err
- }
- }
-
- return nil
-}
-
-// init initializes the network, setting a new network namespace for the CNI network.
-func (n *cni) init(config *NetworkConfig) error {
- if config.NetNSPath == "" {
- path, err := createNetNS()
- if err != nil {
- return err
- }
-
- config.NetNSPath = path
- }
-
- return nil
-}
-
-// run runs a callback in the specified network namespace.
-// run does not switch the current process to the specified network namespace
-// for the CNI network. Indeed, the switch will occur in the add() and remove()
-// functions instead.
-func (n *cni) run(networkNSPath string, cb func() error) error {
- return doNetNS(networkNSPath, func(_ ns.NetNS) error {
- return cb()
- })
-}
-
-// add adds all needed interfaces inside the network namespace for the CNI network.
-func (n *cni) add(pod Pod, config NetworkConfig) (NetworkNamespace, error) {
- endpoints, err := createNetworkEndpoints(config.NumInterfaces)
- if err != nil {
- return NetworkNamespace{}, err
- }
-
- networkNS := NetworkNamespace{
- NetNsPath: config.NetNSPath,
- Endpoints: endpoints,
- }
-
- err = n.addVirtInterfaces(&networkNS)
- if err != nil {
- return NetworkNamespace{}, err
- }
-
- err = doNetNS(networkNS.NetNsPath, func(_ ns.NetNS) error {
- for _, endpoint := range networkNS.Endpoints {
- err = bridgeNetworkPair(endpoint.NetPair)
- if err != nil {
- return err
- }
- }
-
- return nil
- })
- if err != nil {
- return NetworkNamespace{}, err
- }
-
- err = addNetDevHypervisor(pod, networkNS.Endpoints)
- if err != nil {
- return NetworkNamespace{}, err
- }
-
- return networkNS, nil
-}
-
-// remove unbridges and deletes TAP interfaces. It also removes virtual network
-// interfaces and deletes the network namespace for the CNI network.
-func (n *cni) remove(pod Pod, networkNS NetworkNamespace) error {
- err := doNetNS(networkNS.NetNsPath, func(_ ns.NetNS) error {
- for _, endpoint := range networkNS.Endpoints {
- err := unBridgeNetworkPair(endpoint.NetPair)
- if err != nil {
- return err
- }
- }
-
- return nil
- })
- if err != nil {
- return err
- }
-
- err = n.deleteVirtInterfaces(networkNS)
- if err != nil {
- return err
- }
-
- err = deleteNetNS(networkNS.NetNsPath, true)
- if err != nil {
- return err
- }
-
- return nil
-}
diff --git a/vendor/github.com/containers/virtcontainers/cnm.go b/vendor/github.com/containers/virtcontainers/cnm.go
deleted file mode 100644
index 4c735db..0000000
--- a/vendor/github.com/containers/virtcontainers/cnm.go
+++ /dev/null
@@ -1,246 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
- "net"
-
- "github.com/01org/ciao/ssntp/uuid"
- "github.com/containernetworking/cni/pkg/ns"
- cniTypes "github.com/containernetworking/cni/pkg/types"
- types "github.com/containernetworking/cni/pkg/types/current"
- "github.com/vishvananda/netlink"
- "github.com/vishvananda/netns"
-)
-
-// cnm is a network implementation for the CNM plugin.
-type cnm struct {
- config NetworkConfig
-}
-
-func (n *cnm) getNetIfaceRoutesWithinNetNs(networkNSPath string, ifaceName string) ([]netlink.Route, error) {
- if networkNSPath == "" {
- return []netlink.Route{}, fmt.Errorf("Network namespace path cannot be empty")
- }
-
- netnsHandle, err := netns.GetFromPath(networkNSPath)
- if err != nil {
- return []netlink.Route{}, err
- }
- defer netnsHandle.Close()
-
- netHandle, err := netlink.NewHandleAt(netnsHandle)
- if err != nil {
- return []netlink.Route{}, err
- }
- defer netHandle.Delete()
-
- link, err := netHandle.LinkByName(ifaceName)
- if err != nil {
- return []netlink.Route{}, err
- }
-
- routes, err := netHandle.RouteList(link, netlink.FAMILY_ALL)
- if err != nil {
- return []netlink.Route{}, err
- }
-
- return routes, nil
-}
-
-func (n *cnm) createResult(iface net.Interface, addrs []net.Addr, routes []netlink.Route) (types.Result, error) {
- var ipConfigs []*types.IPConfig
- for _, addr := range addrs {
- ip, ipNet, err := net.ParseCIDR(addr.String())
- if err != nil {
- return types.Result{}, err
- }
-
- version := "6"
- if ip.To4() != nil {
- version = "4"
- }
- ipNet.IP = ip
-
- ipConfig := &types.IPConfig{
- Version: version,
- Interface: iface.Index,
- Address: *ipNet,
- }
-
- ipConfigs = append(ipConfigs, ipConfig)
- }
-
- ifaceList := []*types.Interface{
- {
- Name: iface.Name,
- Mac: iface.HardwareAddr.String(),
- },
- }
-
- var resultRoutes []*cniTypes.Route
- for _, route := range routes {
- if route.Dst == nil {
- continue
- }
-
- r := &cniTypes.Route{
- Dst: *(route.Dst),
- GW: route.Gw,
- }
-
- resultRoutes = append(resultRoutes, r)
- }
-
- res := types.Result{
- Interfaces: ifaceList,
- IPs: ipConfigs,
- Routes: resultRoutes,
- }
-
- return res, nil
-}
-
-func (n *cnm) createEndpointsFromScan(networkNSPath string) ([]Endpoint, error) {
- var endpoints []Endpoint
-
- netIfaces, err := getIfacesFromNetNs(networkNSPath)
- if err != nil {
- return []Endpoint{}, err
- }
-
- uniqueID := uuid.Generate().String()
-
- idx := 0
- for _, netIface := range netIfaces {
- var endpoint Endpoint
-
- if netIface.iface.Name == "lo" {
- continue
- } else {
- endpoint, err = createNetworkEndpoint(idx, uniqueID, netIface.iface.Name)
- if err != nil {
- return []Endpoint{}, err
- }
- }
-
- routes, err := n.getNetIfaceRoutesWithinNetNs(networkNSPath, netIface.iface.Name)
- if err != nil {
- return []Endpoint{}, err
- }
-
- endpoint.Properties, err = n.createResult(netIface.iface, netIface.addrs, routes)
- if err != nil {
- return []Endpoint{}, err
- }
-
- endpoints = append(endpoints, endpoint)
-
- idx++
- }
-
- return endpoints, nil
-}
-
-// init initializes the network, setting a new network namespace for the CNM network.
-func (n *cnm) init(config *NetworkConfig) error {
- if config == nil {
- return fmt.Errorf("config cannot be empty")
- }
-
- if config.NetNSPath == "" {
- path, err := createNetNS()
- if err != nil {
- return err
- }
-
- config.NetNSPath = path
- }
-
- return nil
-}
-
-// run runs a callback in the specified network namespace.
-func (n *cnm) run(networkNSPath string, cb func() error) error {
- if networkNSPath == "" {
- return fmt.Errorf("networkNSPath cannot be empty")
- }
-
- return safeDoNetNS(networkNSPath, func(_ ns.NetNS) error {
- return cb()
- })
-}
-
-// add adds all needed interfaces inside the network namespace for the CNM network.
-func (n *cnm) add(pod Pod, config NetworkConfig) (NetworkNamespace, error) {
- endpoints, err := n.createEndpointsFromScan(config.NetNSPath)
- if err != nil {
- return NetworkNamespace{}, err
- }
-
- networkNS := NetworkNamespace{
- NetNsPath: config.NetNSPath,
- Endpoints: endpoints,
- }
-
- err = doNetNS(networkNS.NetNsPath, func(_ ns.NetNS) error {
- for _, endpoint := range networkNS.Endpoints {
- err := bridgeNetworkPair(endpoint.NetPair)
- if err != nil {
- return err
- }
- }
-
- return nil
- })
- if err != nil {
- return NetworkNamespace{}, err
- }
-
- err = addNetDevHypervisor(pod, networkNS.Endpoints)
- if err != nil {
- return NetworkNamespace{}, err
- }
-
- return networkNS, nil
-}
-
-// remove unbridges and deletes TAP interfaces. It also removes virtual network
-// interfaces and deletes the network namespace for the CNM network.
-func (n *cnm) remove(pod Pod, networkNS NetworkNamespace) error {
- err := doNetNS(networkNS.NetNsPath, func(_ ns.NetNS) error {
- for _, endpoint := range networkNS.Endpoints {
- err := unBridgeNetworkPair(endpoint.NetPair)
- if err != nil {
- return err
- }
- }
-
- return nil
- })
- if err != nil {
- return err
- }
-
- err = deleteNetNS(networkNS.NetNsPath, true)
- if err != nil {
- return err
- }
-
- return nil
-}
diff --git a/vendor/github.com/containers/virtcontainers/cnm_test.go b/vendor/github.com/containers/virtcontainers/cnm_test.go
deleted file mode 100644
index f9ccddb..0000000
--- a/vendor/github.com/containers/virtcontainers/cnm_test.go
+++ /dev/null
@@ -1,103 +0,0 @@
-//
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "net"
- "reflect"
- "testing"
-
- cniTypes "github.com/containernetworking/cni/pkg/types"
- types "github.com/containernetworking/cni/pkg/types/current"
- "github.com/vishvananda/netlink"
-)
-
-type mockAddr struct {
- network string
- ipAddr string
-}
-
-func (m mockAddr) Network() string {
- return m.network
-}
-
-func (m mockAddr) String() string {
- return m.ipAddr
-}
-
-func TestCNMCreateResults(t *testing.T) {
- plugin := &cnm{}
-
- macAddr := net.HardwareAddr{0x00, 0x00, 0x00, 0x00, 0x00, 0x00}
-
- ip, ipNet, err := net.ParseCIDR("192.168.0.1/8")
- if err != nil {
- t.Fatal()
- }
- ipNet.IP = ip
-
- expected := types.Result{
- Interfaces: []*types.Interface{
- {
- Name: "eth0",
- Mac: macAddr.String(),
- },
- },
- IPs: []*types.IPConfig{
- {
- Version: "4",
- Interface: 0,
- Address: *ipNet,
- },
- },
- Routes: []*cniTypes.Route{
- {
- Dst: *ipNet,
- GW: ipNet.IP,
- },
- },
- }
-
- iface := net.Interface{
- Index: 0,
- Name: "eth0",
- HardwareAddr: macAddr,
- }
-
- addr := mockAddr{
- network: "test-network",
- ipAddr: "192.168.0.1/8",
- }
-
- addrs := []net.Addr{net.Addr(addr)}
-
- routes := []netlink.Route{
- {
- Dst: ipNet,
- Gw: ipNet.IP,
- },
- }
-
- result, err := plugin.createResult(iface, addrs, routes)
- if err != nil {
- t.Fatal(err)
- }
-
- if reflect.DeepEqual(result, expected) == false {
- t.Fatal()
- }
-}
diff --git a/vendor/github.com/containers/virtcontainers/container.go b/vendor/github.com/containers/virtcontainers/container.go
deleted file mode 100644
index 32664c4..0000000
--- a/vendor/github.com/containers/virtcontainers/container.go
+++ /dev/null
@@ -1,506 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "syscall"
-)
-
-// Process gathers data related to a container process.
-type Process struct {
- Token string
- Pid int
-}
-
-// ContainerStatus describes a container status.
-type ContainerStatus struct {
- ID string
- State State
- PID int
- RootFs string
-}
-
-// ContainerConfig describes one container runtime configuration.
-type ContainerConfig struct {
- ID string
-
- // RootFs is the container workload image on the host.
- RootFs string
-
- // Cmd specifies the command to run on a container
- Cmd Cmd
-}
-
-// valid checks that the container configuration is valid.
-func (containerConfig *ContainerConfig) valid() bool {
- if containerConfig == nil {
- return false
- }
-
- if containerConfig.ID == "" {
- return false
- }
-
- return true
-}
-
-// Container is composed of a set of containers and a runtime environment.
-// A Container can be created, deleted, started, stopped, listed, entered, paused and restored.
-type Container struct {
- id string
- podID string
-
- rootFs string
-
- config *ContainerConfig
-
- pod *Pod
-
- runPath string
- configPath string
- containerPath string
-
- state State
-
- process Process
-}
-
-// ID returns the container identifier string.
-func (c *Container) ID() string {
- return c.id
-}
-
-// Process returns the container process.
-func (c *Container) Process() Process {
- return c.process
-}
-
-// GetToken returns the token related to this container's process.
-func (c *Container) GetToken() string {
- return c.process.Token
-}
-
-// GetPid returns the pid related to this container's process.
-func (c *Container) GetPid() int {
- return c.process.Pid
-}
-
-// SetPid sets and stores the given pid as the pid of container's process.
-func (c *Container) SetPid(pid int) error {
- c.process.Pid = pid
-
- return c.storeProcess()
-}
-
-// URL returns the URL related to the pod.
-func (c *Container) URL() string {
- return c.pod.URL()
-}
-
-func (c *Container) startShim() error {
- proxyInfo, url, err := c.pod.proxy.connect(*(c.pod), true)
- if err != nil {
- return err
- }
-
- if err := c.pod.proxy.disconnect(); err != nil {
- return err
- }
-
- if c.pod.state.URL != url {
- return fmt.Errorf("Pod URL %s and URL from proxy %s MUST be identical", c.pod.state.URL, url)
- }
-
- shimParams := ShimParams{
- Token: proxyInfo.Token,
- URL: url,
- Console: c.config.Cmd.Console,
- }
-
- pid, err := c.pod.shim.start(*(c.pod), shimParams)
- if err != nil {
- return err
- }
-
- c.process = Process{
- Token: proxyInfo.Token,
- Pid: pid,
- }
-
- if err := c.storeProcess(); err != nil {
- return err
- }
-
- return nil
-}
-
-func (c *Container) storeProcess() error {
- return c.pod.storage.storeContainerProcess(c.podID, c.id, c.process)
-}
-
-func (c *Container) fetchProcess() (Process, error) {
- return c.pod.storage.fetchContainerProcess(c.podID, c.id)
-}
-
-// fetchContainer fetches a container config from a pod ID and returns a Container.
-func fetchContainer(pod *Pod, containerID string) (*Container, error) {
- if pod == nil {
- return nil, errNeedPod
- }
-
- if containerID == "" {
- return nil, errNeedContainerID
- }
-
- fs := filesystem{}
- config, err := fs.fetchContainerConfig(pod.id, containerID)
- if err != nil {
- return nil, err
- }
-
- virtLog.Infof("Info structure: %+v", config)
-
- return createContainer(pod, config)
-}
-
-// storeContainer stores a container config.
-func (c *Container) storeContainer() error {
- fs := filesystem{}
- err := fs.storeContainerResource(c.pod.id, c.id, configFileType, *(c.config))
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func (c *Container) setContainerState(state stateString) error {
- if state == "" {
- return errNeedState
- }
-
- c.state = State{
- State: state,
- }
-
- err := c.pod.storage.storeContainerResource(c.podID, c.id, stateFileType, c.state)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func (c *Container) createContainersDirs() error {
- err := os.MkdirAll(c.runPath, dirMode)
- if err != nil {
- return err
- }
-
- err = os.MkdirAll(c.configPath, dirMode)
- if err != nil {
- c.pod.storage.deleteContainerResources(c.podID, c.id, nil)
- return err
- }
-
- return nil
-}
-
-func createContainers(pod *Pod, contConfigs []ContainerConfig) ([]*Container, error) {
- if pod == nil {
- return nil, errNeedPod
- }
-
- var containers []*Container
-
- for idx, contConfig := range contConfigs {
- if contConfig.valid() == false {
- return containers, fmt.Errorf("Invalid container configuration")
- }
-
- c := &Container{
- id: contConfig.ID,
- podID: pod.id,
- rootFs: contConfig.RootFs,
- config: &contConfigs[idx],
- pod: pod,
- runPath: filepath.Join(runStoragePath, pod.id, contConfig.ID),
- configPath: filepath.Join(configStoragePath, pod.id, contConfig.ID),
- containerPath: filepath.Join(pod.id, contConfig.ID),
- state: State{},
- process: Process{},
- }
-
- state, err := c.pod.storage.fetchContainerState(c.podID, c.id)
- if err == nil {
- c.state.State = state.State
- }
-
- process, err := c.pod.storage.fetchContainerProcess(c.podID, c.id)
- if err == nil {
- c.process = process
- }
-
- containers = append(containers, c)
- }
-
- return containers, nil
-}
-
-func createContainer(pod *Pod, contConfig ContainerConfig) (*Container, error) {
- if pod == nil {
- return nil, errNeedPod
- }
-
- if contConfig.valid() == false {
- return nil, fmt.Errorf("Invalid container configuration")
- }
-
- c := &Container{
- id: contConfig.ID,
- podID: pod.id,
- rootFs: contConfig.RootFs,
- config: &contConfig,
- pod: pod,
- runPath: filepath.Join(runStoragePath, pod.id, contConfig.ID),
- configPath: filepath.Join(configStoragePath, pod.id, contConfig.ID),
- containerPath: filepath.Join(pod.id, contConfig.ID),
- state: State{},
- process: Process{},
- }
-
- err := c.createContainersDirs()
- if err != nil {
- return nil, err
- }
-
- process, err := c.fetchProcess()
- if err == nil {
- c.process = process
- }
-
- state, err := c.pod.storage.fetchContainerState(c.podID, c.id)
- if err == nil && state.State != "" {
- c.state.State = state.State
- return c, nil
- }
-
- // If we reached that point, this means that no state file has been
- // found and that we are in the first creation of this container.
- // We don't want the following code to be executed outside of this
- // specific case.
- pod.containers = append(pod.containers, c)
-
- if err := c.startShim(); err != nil {
- return nil, err
- }
-
- if err := c.pod.setContainerState(c.id, StateReady); err != nil {
- return nil, err
- }
-
- return c, nil
-}
-
-func (c *Container) delete() error {
- state, err := c.pod.storage.fetchContainerState(c.podID, c.id)
- if err != nil {
- return err
- }
-
- if state.State != StateReady && state.State != StateStopped {
- return fmt.Errorf("Container not ready or stopped, impossible to delete")
- }
-
- err = c.pod.storage.deleteContainerResources(c.podID, c.id, nil)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-// fetchState retrieves the container state.
-//
-// cmd specifies the operation (or verb) that the retieval is destined
-// for and is only used to make the returned error as descriptive as
-// possible.
-func (c *Container) fetchState(cmd string) (State, error) {
- if cmd == "" {
- return State{}, fmt.Errorf("Cmd cannot be empty")
- }
-
- state, err := c.pod.storage.fetchPodState(c.pod.id)
- if err != nil {
- return State{}, err
- }
-
- if state.State != StateRunning {
- return State{}, fmt.Errorf("Pod not running, impossible to %s the container", cmd)
- }
-
- state, err = c.pod.storage.fetchContainerState(c.podID, c.id)
- if err != nil {
- return State{}, err
- }
-
- return state, nil
-}
-
-func (c *Container) start() error {
- state, err := c.fetchState("start")
- if err != nil {
- return err
- }
-
- if state.State != StateReady && state.State != StateStopped {
- return fmt.Errorf("Container not ready or stopped, impossible to start")
- }
-
- err = state.validTransition(StateReady, StateRunning)
- if err != nil {
- err = state.validTransition(StateStopped, StateRunning)
- if err != nil {
- return err
- }
- }
-
- if _, _, err := c.pod.proxy.connect(*(c.pod), false); err != nil {
- return err
- }
- defer c.pod.proxy.disconnect()
-
- err = c.pod.agent.startContainer(*(c.pod), *c)
- if err != nil {
- c.stop()
- return err
- }
-
- err = c.setContainerState(StateRunning)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func (c *Container) stop() error {
- state, err := c.fetchState("stop")
- if err != nil {
- return err
- }
-
- if state.State != StateRunning {
- return fmt.Errorf("Container not running, impossible to stop")
- }
-
- err = state.validTransition(StateRunning, StateStopped)
- if err != nil {
- return err
- }
-
- if _, _, err := c.pod.proxy.connect(*(c.pod), false); err != nil {
- return err
- }
- defer c.pod.proxy.disconnect()
-
- err = c.pod.agent.killContainer(*(c.pod), *c, syscall.SIGTERM)
- if err != nil {
- return err
- }
-
- err = c.pod.agent.stopContainer(*(c.pod), *c)
- if err != nil {
- return err
- }
-
- err = c.setContainerState(StateStopped)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func (c *Container) enter(cmd Cmd) (*Process, error) {
- state, err := c.fetchState("enter")
- if err != nil {
- return nil, err
- }
-
- if state.State != StateRunning {
- return nil, fmt.Errorf("Container not running, impossible to enter")
- }
-
- proxyInfo, url, err := c.pod.proxy.connect(*(c.pod), true)
- if err != nil {
- return nil, err
- }
- defer c.pod.proxy.disconnect()
-
- if c.pod.state.URL != url {
- return nil, fmt.Errorf("Pod URL %s and URL from proxy %s MUST be identical", c.pod.state.URL, url)
- }
-
- shimParams := ShimParams{
- Token: proxyInfo.Token,
- URL: url,
- Console: cmd.Console,
- }
-
- pid, err := c.pod.shim.start(*(c.pod), shimParams)
- if err != nil {
- return nil, err
- }
-
- process := &Process{
- Token: proxyInfo.Token,
- Pid: pid,
- }
-
- if err := c.pod.agent.exec(c.pod, *c, *process, cmd); err != nil {
- return nil, err
- }
-
- return process, nil
-}
-
-func (c *Container) kill(signal syscall.Signal) error {
- state, err := c.fetchState("signal")
- if err != nil {
- return err
- }
-
- if state.State != StateRunning {
- return fmt.Errorf("Container not running, impossible to signal the container")
- }
-
- if _, _, err := c.pod.proxy.connect(*(c.pod), false); err != nil {
- return err
- }
- defer c.pod.proxy.disconnect()
-
- err = c.pod.agent.killContainer(*(c.pod), *c, signal)
- if err != nil {
- return err
- }
-
- return nil
-}
diff --git a/vendor/github.com/containers/virtcontainers/doc.go b/vendor/github.com/containers/virtcontainers/doc.go
deleted file mode 100644
index 457eb87..0000000
--- a/vendor/github.com/containers/virtcontainers/doc.go
+++ /dev/null
@@ -1,28 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-/*
-Package virtcontainers manages hardware virtualized containers.
-Each container belongs to a set of containers sharing the same networking
-namespace and storage, also known as a pod.
-
-Virtcontainers pods are hardware virtualized, i.e. they run on virtual machines.
-Virtcontainers will create one VM per pod, and containers will be created as
-processes within the pod VM.
-
-The virtcontainers package manages both pods and containers lifecycles.
-*/
-package virtcontainers
diff --git a/vendor/github.com/containers/virtcontainers/errors.go b/vendor/github.com/containers/virtcontainers/errors.go
deleted file mode 100644
index c9f3bed..0000000
--- a/vendor/github.com/containers/virtcontainers/errors.go
+++ /dev/null
@@ -1,30 +0,0 @@
-//
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "errors"
-)
-
-// common error objects used for argument checking
-var (
- errNeedPod = errors.New("Pod must be specified")
- errNeedPodID = errors.New("Pod ID cannot be empty")
- errNeedContainerID = errors.New("Container ID cannot be empty")
- errNeedFile = errors.New("File cannot be empty")
- errNeedState = errors.New("State cannot be empty")
-)
diff --git a/vendor/github.com/containers/virtcontainers/example_pod_run_test.go b/vendor/github.com/containers/virtcontainers/example_pod_run_test.go
deleted file mode 100644
index dfc7fa8..0000000
--- a/vendor/github.com/containers/virtcontainers/example_pod_run_test.go
+++ /dev/null
@@ -1,89 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers_test
-
-import (
- "fmt"
- "strings"
-
- vc "github.com/containers/virtcontainers"
-)
-
-const containerRootfs = "/var/lib/container/bundle/"
-
-// This example creates and starts a single container pod,
-// using qemu as the hypervisor and hyperstart as the VM agent.
-func Example_createAndStartPod() {
- envs := []vc.EnvVar{
- {
- Var: "PATH",
- Value: "/bin:/usr/bin:/sbin:/usr/sbin",
- },
- }
-
- cmd := vc.Cmd{
- Args: strings.Split("/bin/sh", " "),
- Envs: envs,
- WorkDir: "/",
- }
-
- // Define the container command and bundle.
- container := vc.ContainerConfig{
- ID: "1",
- RootFs: containerRootfs,
- Cmd: cmd,
- }
-
- // Sets the hypervisor configuration.
- hypervisorConfig := vc.HypervisorConfig{
- KernelPath: "/usr/share/clear-containers/vmlinux.container",
- ImagePath: "/usr/share/clear-containers/clear-containers.img",
- HypervisorPath: "/usr/bin/qemu-lite-system-x86_64",
- }
-
- // Use hyperstart default values for the agent.
- agConfig := vc.HyperConfig{}
-
- // VM resources
- vmConfig := vc.Resources{
- VCPUs: 4,
- Memory: 1024,
- }
-
- // The pod configuration:
- // - One container
- // - Hypervisor is QEMU
- // - Agent is hyperstart
- podConfig := vc.PodConfig{
- VMConfig: vmConfig,
-
- HypervisorType: vc.QemuHypervisor,
- HypervisorConfig: hypervisorConfig,
-
- AgentType: vc.HyperstartAgent,
- AgentConfig: agConfig,
-
- Containers: []vc.ContainerConfig{container},
- }
-
- _, err := vc.RunPod(podConfig)
- if err != nil {
- fmt.Printf("Could not run pod: %s", err)
- }
-
- return
-}
diff --git a/vendor/github.com/containers/virtcontainers/filesystem.go b/vendor/github.com/containers/virtcontainers/filesystem.go
deleted file mode 100644
index ae7d86e..0000000
--- a/vendor/github.com/containers/virtcontainers/filesystem.go
+++ /dev/null
@@ -1,593 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "encoding/json"
- "fmt"
- "io/ioutil"
- "os"
- "path/filepath"
-)
-
-// podResource is an int representing a pod resource type.
-//
-// Note that some are specific to the pod itself and others can apply to
-// pods and containers.
-type podResource int
-
-const (
- // configFileType represents a configuration file type
- configFileType podResource = iota
-
- // stateFileType represents a state file type
- stateFileType
-
- // networkFileType represents a network file type (pod only)
- networkFileType
-
- // processFileType represents a process file type
- processFileType
-
- // lockFileType represents a lock file type (pod only)
- lockFileType
-)
-
-// configFile is the file name used for every JSON pod configuration.
-const configFile = "config.json"
-
-// stateFile is the file name storing a pod state.
-const stateFile = "state.json"
-
-// networkFile is the file name storing a pod network.
-const networkFile = "network.json"
-
-// processFile is the file name storing a container process.
-const processFile = "process.json"
-
-// lockFile is the file name locking the usage of a pod.
-const lockFileName = "lock"
-
-// dirMode is the permission bits used for creating a directory
-const dirMode = os.FileMode(0750)
-
-// storagePathSuffix is the suffix used for all storage paths
-const storagePathSuffix = "/virtcontainers/pods"
-
-// configStoragePath is the pod configuration directory.
-// It will contain one config.json file for each created pod.
-var configStoragePath = filepath.Join("/var/lib", storagePathSuffix)
-
-// runStoragePath is the pod runtime directory.
-// It will contain one state.json and one lock file for each created pod.
-var runStoragePath = filepath.Join("/run", storagePathSuffix)
-
-// resourceStorage is the virtcontainers resources (configuration, state, etc...)
-// storage interface.
-// The default resource storage implementation is filesystem.
-type resourceStorage interface {
- // Create all resources for a pod
- createAllResources(pod Pod) error
-
- // Resources URIs functions return both the URI
- // for the actual resource and the URI base.
- containerURI(podID, containerID string, resource podResource) (string, string, error)
- podURI(podID string, resource podResource) (string, string, error)
-
- // Pod resources
- storePodResource(podID string, resource podResource, data interface{}) error
- deletePodResources(podID string, resources []podResource) error
- fetchPodConfig(podID string) (PodConfig, error)
- fetchPodState(podID string) (State, error)
- fetchPodNetwork(podID string) (NetworkNamespace, error)
- storePodNetwork(podID string, networkNS NetworkNamespace) error
-
- // Container resources
- storeContainerResource(podID, containerID string, resource podResource, data interface{}) error
- deleteContainerResources(podID, containerID string, resources []podResource) error
- fetchContainerConfig(podID, containerID string) (ContainerConfig, error)
- fetchContainerState(podID, containerID string) (State, error)
- fetchContainerProcess(podID, containerID string) (Process, error)
- storeContainerProcess(podID, containerID string, process Process) error
-}
-
-// filesystem is a resourceStorage interface implementation for a local filesystem.
-type filesystem struct {
-}
-
-func (fs *filesystem) createAllResources(pod Pod) (err error) {
- for _, resource := range []podResource{stateFileType, configFileType} {
- _, path, _ := fs.podURI(pod.id, resource)
- err = os.MkdirAll(path, os.ModeDir)
- if err != nil {
- return err
- }
- }
-
- for _, container := range pod.containers {
- for _, resource := range []podResource{stateFileType, configFileType} {
- _, path, _ := fs.containerURI(pod.id, container.id, resource)
- err = os.MkdirAll(path, os.ModeDir)
- if err != nil {
- fs.deletePodResources(pod.id, nil)
- return err
- }
- }
- }
-
- podlockFile, _, err := fs.podURI(pod.id, lockFileType)
- if err != nil {
- fs.deletePodResources(pod.id, nil)
- return err
- }
-
- _, err = os.Stat(podlockFile)
- if err != nil {
- lockFile, err := os.Create(podlockFile)
- if err != nil {
- fs.deletePodResources(pod.id, nil)
- return err
- }
- lockFile.Close()
- }
-
- return nil
-}
-
-func (fs *filesystem) storeFile(file string, data interface{}) error {
- if file == "" {
- return errNeedFile
- }
-
- f, err := os.Create(file)
- if err != nil {
- return err
- }
- defer f.Close()
-
- jsonOut, err := json.Marshal(data)
- if err != nil {
- return fmt.Errorf("Could not marshall data: %s", err)
- }
- f.Write(jsonOut)
-
- return nil
-}
-
-func (fs *filesystem) fetchFile(file string, data interface{}) error {
- if file == "" {
- return errNeedFile
- }
-
- fileData, err := ioutil.ReadFile(file)
- if err != nil {
- return err
- }
-
- err = json.Unmarshal([]byte(string(fileData)), data)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-// resourceNeedsContainerID determines if the specified
-// podResource needs a containerID. Since some podResources can
-// be used for both pods and containers, it is necessary to specify
-// whether the resource is being used in a pod-specific context using
-// the podSpecific parameter.
-func resourceNeedsContainerID(podSpecific bool, resource podResource) bool {
-
- switch resource {
- case lockFileType, networkFileType:
- // pod-specific resources
- return false
- default:
- return !podSpecific
- }
-}
-
-func resourceDir(podSpecific bool, podID, containerID string, resource podResource) (string, error) {
- if podID == "" {
- return "", errNeedPodID
- }
-
- if resourceNeedsContainerID(podSpecific, resource) == true && containerID == "" {
- return "", errNeedContainerID
- }
-
- var path string
-
- switch resource {
- case configFileType:
- path = configStoragePath
- break
- case stateFileType, networkFileType, processFileType, lockFileType:
- path = runStoragePath
- break
- default:
- return "", fmt.Errorf("Invalid pod resource")
- }
-
- dirPath := filepath.Join(path, podID, containerID)
-
- return dirPath, nil
-}
-
-// If podSpecific is true, the resource is being applied for an empty
-// pod (meaning containerID may be blank).
-// Note that this function defers determining if containerID can be
-// blank to resourceDIR()
-func (fs *filesystem) resourceURI(podSpecific bool, podID, containerID string, resource podResource) (string, string, error) {
- if podID == "" {
- return "", "", errNeedPodID
- }
-
- var filename string
-
- dirPath, err := resourceDir(podSpecific, podID, containerID, resource)
- if err != nil {
- return "", "", err
- }
-
- switch resource {
- case configFileType:
- filename = configFile
- break
- case stateFileType:
- filename = stateFile
- case networkFileType:
- filename = networkFile
- case processFileType:
- filename = processFile
- case lockFileType:
- filename = lockFileName
- break
- default:
- return "", "", fmt.Errorf("Invalid pod resource")
- }
-
- filePath := filepath.Join(dirPath, filename)
-
- return filePath, dirPath, nil
-}
-
-func (fs *filesystem) containerURI(podID, containerID string, resource podResource) (string, string, error) {
- if podID == "" {
- return "", "", errNeedPodID
- }
-
- if containerID == "" {
- return "", "", errNeedContainerID
- }
-
- return fs.resourceURI(false, podID, containerID, resource)
-}
-
-func (fs *filesystem) podURI(podID string, resource podResource) (string, string, error) {
- return fs.resourceURI(true, podID, "", resource)
-}
-
-// commonResourceChecks performs basic checks common to both setting and
-// getting a podResource.
-func (fs *filesystem) commonResourceChecks(podSpecific bool, podID, containerID string, resource podResource) error {
- if podID == "" {
- return errNeedPodID
- }
-
- if resourceNeedsContainerID(podSpecific, resource) == true && containerID == "" {
- return errNeedContainerID
- }
-
- return nil
-}
-
-func (fs *filesystem) storeResource(podSpecific bool, podID, containerID string, resource podResource, data interface{}) error {
- if err := fs.commonResourceChecks(podSpecific, podID, containerID, resource); err != nil {
- return err
- }
-
- switch file := data.(type) {
- case PodConfig, ContainerConfig:
- if resource != configFileType {
- return fmt.Errorf("Invalid pod resource")
- }
-
- configFile, _, err := fs.resourceURI(podSpecific, podID, containerID, configFileType)
- if err != nil {
- return err
- }
-
- return fs.storeFile(configFile, file)
-
- case State:
- if resource != stateFileType {
- return fmt.Errorf("Invalid pod resource")
- }
-
- stateFile, _, err := fs.resourceURI(podSpecific, podID, containerID, stateFileType)
- if err != nil {
- return err
- }
-
- return fs.storeFile(stateFile, file)
-
- case NetworkNamespace:
- if resource != networkFileType {
- return fmt.Errorf("Invalid pod resource")
- }
-
- // pod only resource
- networkFile, _, err := fs.resourceURI(true, podID, containerID, networkFileType)
- if err != nil {
- return err
- }
-
- return fs.storeFile(networkFile, file)
-
- case Process:
- if resource != processFileType {
- return fmt.Errorf("Invalid pod resource")
- }
-
- processFile, _, err := fs.resourceURI(podSpecific, podID, containerID, processFileType)
- if err != nil {
- return err
- }
-
- return fs.storeFile(processFile, file)
-
- default:
- return fmt.Errorf("Invalid resource data type")
- }
-}
-
-func (fs *filesystem) fetchResource(podSpecific bool, podID, containerID string, resource podResource) (interface{}, error) {
- if err := fs.commonResourceChecks(podSpecific, podID, containerID, resource); err != nil {
- return nil, err
- }
-
- path, _, err := fs.resourceURI(podSpecific, podID, containerID, resource)
- if err != nil {
- return nil, err
- }
-
- switch resource {
- case configFileType:
- if containerID == "" {
- config := PodConfig{}
- err = fs.fetchFile(path, &config)
- if err != nil {
- return nil, err
- }
-
- return config, nil
- }
-
- config := ContainerConfig{}
- err = fs.fetchFile(path, &config)
- if err != nil {
- return nil, err
- }
-
- return config, nil
-
- case stateFileType:
- state := State{}
- err = fs.fetchFile(path, &state)
- if err != nil {
- return nil, err
- }
-
- return state, nil
-
- case networkFileType:
- networkNS := NetworkNamespace{}
- err = fs.fetchFile(path, &networkNS)
- if err != nil {
- return nil, err
- }
-
- return networkNS, nil
-
- case processFileType:
- process := Process{}
- err = fs.fetchFile(path, &process)
- if err != nil {
- return nil, err
- }
-
- return process, nil
- }
-
- return nil, fmt.Errorf("Invalid pod resource")
-}
-
-func (fs *filesystem) storePodResource(podID string, resource podResource, data interface{}) error {
- return fs.storeResource(true, podID, "", resource, data)
-}
-
-func (fs *filesystem) fetchPodConfig(podID string) (PodConfig, error) {
- data, err := fs.fetchResource(true, podID, "", configFileType)
- if err != nil {
- return PodConfig{}, err
- }
-
- switch config := data.(type) {
- case PodConfig:
- return config, nil
- }
-
- return PodConfig{}, fmt.Errorf("Unknown config type")
-}
-
-func (fs *filesystem) fetchPodState(podID string) (State, error) {
- data, err := fs.fetchResource(true, podID, "", stateFileType)
- if err != nil {
- return State{}, err
- }
-
- switch state := data.(type) {
- case State:
- return state, nil
- }
-
- return State{}, fmt.Errorf("Unknown state type")
-}
-
-func (fs *filesystem) fetchPodNetwork(podID string) (NetworkNamespace, error) {
- data, err := fs.fetchResource(true, podID, "", networkFileType)
- if err != nil {
- return NetworkNamespace{}, err
- }
-
- switch networkNS := data.(type) {
- case NetworkNamespace:
- return networkNS, nil
- }
-
- return NetworkNamespace{}, fmt.Errorf("Unknown network type")
-}
-
-func (fs *filesystem) storePodNetwork(podID string, networkNS NetworkNamespace) error {
- return fs.storePodResource(podID, networkFileType, networkNS)
-}
-
-func (fs *filesystem) deletePodResources(podID string, resources []podResource) error {
- if resources == nil {
- resources = []podResource{configFileType, stateFileType}
- }
-
- for _, resource := range resources {
- _, dir, err := fs.podURI(podID, resource)
- if err != nil {
- return err
- }
-
- err = os.RemoveAll(dir)
- if err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (fs *filesystem) storeContainerResource(podID, containerID string, resource podResource, data interface{}) error {
- if podID == "" {
- return errNeedPodID
- }
-
- if containerID == "" {
- return errNeedContainerID
- }
-
- return fs.storeResource(false, podID, containerID, resource, data)
-}
-
-func (fs *filesystem) fetchContainerConfig(podID, containerID string) (ContainerConfig, error) {
- if podID == "" {
- return ContainerConfig{}, errNeedPodID
- }
-
- if containerID == "" {
- return ContainerConfig{}, errNeedContainerID
- }
-
- data, err := fs.fetchResource(false, podID, containerID, configFileType)
- if err != nil {
- return ContainerConfig{}, err
- }
-
- switch config := data.(type) {
- case ContainerConfig:
- return config, nil
- }
-
- return ContainerConfig{}, fmt.Errorf("Unknown config type")
-}
-
-func (fs *filesystem) fetchContainerState(podID, containerID string) (State, error) {
- if podID == "" {
- return State{}, errNeedPodID
- }
-
- if containerID == "" {
- return State{}, errNeedContainerID
- }
-
- data, err := fs.fetchResource(false, podID, containerID, stateFileType)
- if err != nil {
- return State{}, err
- }
-
- switch state := data.(type) {
- case State:
- return state, nil
- }
-
- return State{}, fmt.Errorf("Unknown state type")
-}
-
-func (fs *filesystem) fetchContainerProcess(podID, containerID string) (Process, error) {
- if podID == "" {
- return Process{}, errNeedPodID
- }
-
- if containerID == "" {
- return Process{}, errNeedContainerID
- }
-
- data, err := fs.fetchResource(false, podID, containerID, processFileType)
- if err != nil {
- return Process{}, err
- }
-
- switch process := data.(type) {
- case Process:
- return process, nil
- }
-
- return Process{}, fmt.Errorf("Unknown process type")
-}
-
-func (fs *filesystem) storeContainerProcess(podID, containerID string, process Process) error {
- return fs.storeContainerResource(podID, containerID, processFileType, process)
-}
-
-func (fs *filesystem) deleteContainerResources(podID, containerID string, resources []podResource) error {
- if resources == nil {
- resources = []podResource{configFileType, stateFileType}
- }
-
- for _, resource := range resources {
- _, dir, err := fs.podURI(podID, resource)
- if err != nil {
- return err
- }
-
- containerDir := filepath.Join(dir, containerID, "/")
-
- err = os.RemoveAll(containerDir)
- if err != nil {
- return err
- }
- }
-
- return nil
-}
diff --git a/vendor/github.com/containers/virtcontainers/filesystem_test.go b/vendor/github.com/containers/virtcontainers/filesystem_test.go
deleted file mode 100644
index 2dbd45d..0000000
--- a/vendor/github.com/containers/virtcontainers/filesystem_test.go
+++ /dev/null
@@ -1,450 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
- "io/ioutil"
- "os"
- "path/filepath"
- "reflect"
- "testing"
-)
-
-func TestFilesystemCreateAllResourcesSuccessful(t *testing.T) {
- fs := &filesystem{}
-
- contConfigs := []ContainerConfig{
- {ID: "1"},
- {ID: "10"},
- {ID: "100"},
- }
-
- pod := Pod{
- id: testPodID,
- storage: fs,
- }
-
- containers, err := createContainers(&pod, contConfigs)
- if err != nil {
- t.Fatal(err)
- }
-
- pod.containers = containers
-
- podConfigPath := filepath.Join(configStoragePath, testPodID)
- podRunPath := filepath.Join(runStoragePath, testPodID)
-
- os.RemoveAll(podConfigPath)
- os.RemoveAll(podRunPath)
-
- for _, container := range contConfigs {
- configPath := filepath.Join(configStoragePath, testPodID, container.ID)
- os.RemoveAll(configPath)
-
- runPath := filepath.Join(runStoragePath, testPodID, container.ID)
- os.RemoveAll(runPath)
- }
-
- err = fs.createAllResources(pod)
- if err != nil {
- t.Fatal(err)
- }
-
- // Check resources
- _, err = os.Stat(podConfigPath)
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = os.Stat(podRunPath)
- if err != nil {
- t.Fatal(err)
- }
-
- for _, container := range contConfigs {
- configPath := filepath.Join(configStoragePath, testPodID, container.ID)
- _, err = os.Stat(configPath)
- if err != nil {
- t.Fatal(err)
- }
-
- runPath := filepath.Join(runStoragePath, testPodID, container.ID)
- _, err = os.Stat(runPath)
- if err != nil {
- t.Fatal(err)
- }
- }
-}
-
-func TestFilesystemCreateAllResourcesFailingPodIDEmpty(t *testing.T) {
- fs := &filesystem{}
-
- pod := Pod{}
-
- err := fs.createAllResources(pod)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestFilesystemCreateAllResourcesFailingContainerIDEmpty(t *testing.T) {
- fs := &filesystem{}
-
- containers := []*Container{
- {id: ""},
- }
-
- pod := Pod{
- id: testPodID,
- containers: containers,
- }
-
- err := fs.createAllResources(pod)
- if err == nil {
- t.Fatal()
- }
-}
-
-type TestNoopStructure struct {
- Field1 string
- Field2 string
-}
-
-func TestFilesystemStoreFileSuccessfulNotExisting(t *testing.T) {
- fs := &filesystem{}
-
- path := filepath.Join(testDir, "testFilesystem")
- os.Remove(path)
-
- data := TestNoopStructure{
- Field1: "value1",
- Field2: "value2",
- }
-
- expected := "{\"Field1\":\"value1\",\"Field2\":\"value2\"}"
-
- err := fs.storeFile(path, data)
- if err != nil {
- t.Fatal(err)
- }
-
- fileData, err := ioutil.ReadFile(path)
- if err != nil {
- t.Fatal(err)
- }
-
- if string(fileData) != expected {
- t.Fatal()
- }
-}
-
-func TestFilesystemStoreFileSuccessfulExisting(t *testing.T) {
- fs := &filesystem{}
-
- path := filepath.Join(testDir, "testFilesystem")
- os.Remove(path)
-
- f, err := os.Create(path)
- if err != nil {
- t.Fatal(err)
- }
- f.Close()
-
- data := TestNoopStructure{
- Field1: "value1",
- Field2: "value2",
- }
-
- expected := "{\"Field1\":\"value1\",\"Field2\":\"value2\"}"
-
- err = fs.storeFile(path, data)
- if err != nil {
- t.Fatal(err)
- }
-
- fileData, err := ioutil.ReadFile(path)
- if err != nil {
- t.Fatal(err)
- }
-
- if string(fileData) != expected {
- t.Fatal()
- }
-}
-
-func TestFilesystemStoreFileFailingMarshalling(t *testing.T) {
- fs := &filesystem{}
-
- path := filepath.Join(testDir, "testFilesystem")
- os.Remove(path)
-
- data := make(chan bool)
-
- err := fs.storeFile(path, data)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestFilesystemFetchFileSuccessful(t *testing.T) {
- fs := &filesystem{}
- data := TestNoopStructure{}
-
- path := filepath.Join(testDir, "testFilesystem")
- os.Remove(path)
-
- f, err := os.Create(path)
- if err != nil {
- t.Fatal(err)
- }
-
- dataToWrite := "{\"Field1\":\"value1\",\"Field2\":\"value2\"}"
- n, err := f.WriteString(dataToWrite)
- if err != nil || n != len(dataToWrite) {
- f.Close()
- t.Fatal(err)
- }
- f.Close()
-
- err = fs.fetchFile(path, &data)
- if err != nil {
- t.Fatal(err)
- }
-
- expected := TestNoopStructure{
- Field1: "value1",
- Field2: "value2",
- }
-
- if reflect.DeepEqual(data, expected) == false {
- t.Fatal()
- }
-}
-
-func TestFilesystemFetchFileFailingNoFile(t *testing.T) {
- fs := &filesystem{}
- data := TestNoopStructure{}
-
- path := filepath.Join(testDir, "testFilesystem")
- os.Remove(path)
-
- err := fs.fetchFile(path, &data)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestFilesystemFetchFileFailingUnMarshalling(t *testing.T) {
- fs := &filesystem{}
- data := TestNoopStructure{}
-
- path := filepath.Join(testDir, "testFilesystem")
- os.Remove(path)
-
- f, err := os.Create(path)
- if err != nil {
- t.Fatal(err)
- }
- f.Close()
-
- err = fs.fetchFile(path, data)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestFilesystemFetchContainerConfigSuccessful(t *testing.T) {
- fs := &filesystem{}
- contID := "100"
- rootFs := "rootfs"
-
- contConfigDir := filepath.Join(configStoragePath, testPodID, contID)
- os.MkdirAll(contConfigDir, dirMode)
-
- path := filepath.Join(contConfigDir, configFile)
- os.Remove(path)
-
- f, err := os.Create(path)
- if err != nil {
- t.Fatal(err)
- }
-
- configData := fmt.Sprintf("{\"ID\":\"%s\",\"RootFs\":\"%s\"}", contID, rootFs)
- n, err := f.WriteString(configData)
- if err != nil || n != len(configData) {
- f.Close()
- t.Fatal(err)
- }
- f.Close()
-
- data, err := fs.fetchContainerConfig(testPodID, contID)
- if err != nil {
- t.Fatal(err)
- }
-
- expected := ContainerConfig{
- ID: contID,
- RootFs: rootFs,
- }
-
- if reflect.DeepEqual(data, expected) == false {
- t.Fatal()
- }
-}
-
-func TestFilesystemFetchContainerConfigFailingContIDEmpty(t *testing.T) {
- fs := &filesystem{}
-
- _, err := fs.fetchContainerConfig(testPodID, "")
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestFilesystemFetchContainerConfigFailingPodIDEmpty(t *testing.T) {
- fs := &filesystem{}
-
- _, err := fs.fetchContainerConfig("", "100")
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestFilesystemResourceDirFailingPodIDEmpty(t *testing.T) {
- for _, b := range []bool{true, false} {
- _, err := resourceDir(b, "", "", configFileType)
- if err == nil {
- t.Fatal()
- }
- }
-}
-
-func TestFilesystemResourceDirFailingInvalidResource(t *testing.T) {
- for _, b := range []bool{true, false} {
- _, err := resourceDir(b, testPodID, "100", podResource(-1))
- if err == nil {
- t.Fatal()
- }
- }
-}
-
-func TestFilesystemResourceURIFailingResourceDir(t *testing.T) {
- fs := &filesystem{}
-
- for _, b := range []bool{true, false} {
- _, _, err := fs.resourceURI(b, testPodID, "100", podResource(-1))
- if err == nil {
- t.Fatal()
- }
- }
-}
-
-func TestFilesystemStoreResourceFailingPodConfigStateFileType(t *testing.T) {
- fs := &filesystem{}
- data := PodConfig{}
-
- for _, b := range []bool{true, false} {
- err := fs.storeResource(b, testPodID, "100", stateFileType, data)
- if err == nil {
- t.Fatal()
- }
- }
-}
-
-func TestFilesystemStoreResourceFailingContainerConfigStateFileType(t *testing.T) {
- fs := &filesystem{}
- data := ContainerConfig{}
-
- for _, b := range []bool{true, false} {
- err := fs.storeResource(b, testPodID, "100", stateFileType, data)
- if err == nil {
- t.Fatal()
- }
- }
-}
-
-func TestFilesystemStoreResourceFailingPodConfigResourceURI(t *testing.T) {
- fs := &filesystem{}
- data := PodConfig{}
-
- for _, b := range []bool{true, false} {
- err := fs.storeResource(b, "", "100", configFileType, data)
- if err == nil {
- t.Fatal()
- }
- }
-}
-
-func TestFilesystemStoreResourceFailingContainerConfigResourceURI(t *testing.T) {
- fs := &filesystem{}
- data := ContainerConfig{}
-
- for _, b := range []bool{true, false} {
- err := fs.storeResource(b, "", "100", configFileType, data)
- if err == nil {
- t.Fatal()
- }
- }
-}
-
-func TestFilesystemStoreResourceFailingStateConfigFileType(t *testing.T) {
- fs := &filesystem{}
- data := State{}
-
- for _, b := range []bool{true, false} {
- err := fs.storeResource(b, testPodID, "100", configFileType, data)
- if err == nil {
- t.Fatal()
- }
- }
-}
-
-func TestFilesystemStoreResourceFailingStateResourceURI(t *testing.T) {
- fs := &filesystem{}
- data := State{}
-
- for _, b := range []bool{true, false} {
- err := fs.storeResource(b, "", "100", stateFileType, data)
- if err == nil {
- t.Fatal()
- }
- }
-}
-
-func TestFilesystemStoreResourceFailingWrongDataType(t *testing.T) {
- fs := &filesystem{}
- data := TestNoopStructure{}
-
- for _, b := range []bool{true, false} {
- err := fs.storeResource(b, testPodID, "100", configFileType, data)
- if err == nil {
- t.Fatal()
- }
- }
-}
-
-func TestFilesystemFetchResourceFailingWrongResourceType(t *testing.T) {
- fs := &filesystem{}
-
- for _, b := range []bool{true, false} {
- _, err := fs.fetchResource(b, testPodID, "100", lockFileType)
- if err == nil {
- t.Fatal()
- }
- }
-}
diff --git a/vendor/github.com/containers/virtcontainers/hook.go b/vendor/github.com/containers/virtcontainers/hook.go
deleted file mode 100644
index 4112b23..0000000
--- a/vendor/github.com/containers/virtcontainers/hook.go
+++ /dev/null
@@ -1,144 +0,0 @@
-//
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "os"
- "os/exec"
- "time"
-
- specs "github.com/opencontainers/runtime-spec/specs-go"
-)
-
-// Hook represents an OCI hook, including its required parameters.
-type Hook struct {
- Path string
- Args []string
- Env []string
- Timeout int
-}
-
-// Hooks gathers all existing OCI hooks list.
-type Hooks struct {
- PreStartHooks []Hook
- PostStartHooks []Hook
- PostStopHooks []Hook
-}
-
-func buildHookState(processID int) specs.State {
- return specs.State{
- Pid: processID,
- }
-}
-
-func (h *Hook) runHook() error {
- state := buildHookState(os.Getpid())
- stateJSON, err := json.Marshal(state)
- if err != nil {
- return err
- }
-
- var stdout, stderr bytes.Buffer
- cmd := &exec.Cmd{
- Path: h.Path,
- Args: h.Args,
- Env: h.Env,
- Stdin: bytes.NewReader(stateJSON),
- Stdout: &stdout,
- Stderr: &stderr,
- }
-
- err = cmd.Start()
- if err != nil {
- return err
- }
-
- if h.Timeout == 0 {
- err = cmd.Wait()
- if err != nil {
- return fmt.Errorf("%s: stdout: %s, stderr: %s", err, stdout.String(), stderr.String())
- }
- } else {
- done := make(chan error)
-
- go func() { done <- cmd.Wait() }()
-
- select {
- case err := <-done:
- if err != nil {
- return fmt.Errorf("%s: stdout: %s, stderr: %s", err, stdout.String(), stderr.String())
- }
- case <-time.After(time.Duration(h.Timeout) * time.Second):
- return fmt.Errorf("Hook timeout")
- }
- }
-
- return nil
-}
-
-func (h *Hooks) preStartHooks() error {
- if len(h.PreStartHooks) == 0 {
- return nil
- }
-
- for _, hook := range h.PreStartHooks {
- err := hook.runHook()
- if err != nil {
- virtLog.Errorf("PreStartHook error: %s", err)
- return err
- }
- }
-
- return nil
-}
-
-func (h *Hooks) postStartHooks() error {
- if len(h.PostStartHooks) == 0 {
- return nil
- }
-
- for _, hook := range h.PostStartHooks {
- err := hook.runHook()
- if err != nil {
- // In case of post start hook, the error is not fatal,
- // just need to be logged.
- virtLog.Infof("PostStartHook error: %s", err)
- }
- }
-
- return nil
-}
-
-func (h *Hooks) postStopHooks() error {
- if len(h.PostStopHooks) == 0 {
- return nil
- }
-
- for _, hook := range h.PostStopHooks {
- err := hook.runHook()
- if err != nil {
- // In case of post stop hook, the error is not fatal,
- // just need to be logged.
- virtLog.Infof("PostStopHook error: %s", err)
- }
- }
-
- return nil
-}
diff --git a/vendor/github.com/containers/virtcontainers/hook_test.go b/vendor/github.com/containers/virtcontainers/hook_test.go
deleted file mode 100644
index 56b974d..0000000
--- a/vendor/github.com/containers/virtcontainers/hook_test.go
+++ /dev/null
@@ -1,177 +0,0 @@
-//
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "os"
- "reflect"
- "testing"
-
- specs "github.com/opencontainers/runtime-spec/specs-go"
-)
-
-// Important to keep these values in sync with hook test binary
-var testKeyHook = "test-key"
-var testContainerIDHook = "test-container-id"
-var testControllerIDHook = "test-controller-id"
-var testProcessIDHook = 12345
-var testBinHookPath = "/tmp/bin/hook"
-
-func TestBuildHookState(t *testing.T) {
- expected := specs.State{
- Pid: testProcessIDHook,
- }
-
- hookState := buildHookState(testProcessIDHook)
-
- if reflect.DeepEqual(hookState, expected) == false {
- t.Fatal()
- }
-}
-
-func createHook(timeout int) *Hook {
- return &Hook{
- Path: testBinHookPath,
- Args: []string{testKeyHook, testContainerIDHook, testControllerIDHook},
- Env: os.Environ(),
- Timeout: timeout,
- }
-}
-
-func createWrongHook() *Hook {
- return &Hook{
- Path: testBinHookPath,
- Args: []string{"wrong-args"},
- Env: os.Environ(),
- }
-}
-
-func testRunHook(t *testing.T, timeout int) {
- hook := createHook(timeout)
-
- err := hook.runHook()
- if err != nil {
- t.Fatal()
- }
-}
-
-func TestRunHook(t *testing.T) {
- cleanUp()
-
- testRunHook(t, 0)
-}
-
-func TestRunHookTimeout(t *testing.T) {
- testRunHook(t, 1)
-}
-
-func TestRunHookExitFailure(t *testing.T) {
- hook := createWrongHook()
-
- err := hook.runHook()
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestRunHookTimeoutFailure(t *testing.T) {
- hook := createHook(1)
-
- hook.Args = append(hook.Args, "2")
-
- err := hook.runHook()
- if err == nil {
- t.Fatal()
- }
-}
-
-func testHooks(t *testing.T, hook *Hook) {
- hooks := &Hooks{
- PreStartHooks: []Hook{*hook},
- PostStartHooks: []Hook{*hook},
- PostStopHooks: []Hook{*hook},
- }
-
- err := hooks.preStartHooks()
- if err != nil {
- t.Fatal(err)
- }
-
- err = hooks.postStartHooks()
- if err != nil {
- t.Fatal(err)
- }
-
- err = hooks.postStopHooks()
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func testFailingHooks(t *testing.T, hook *Hook) {
- hooks := &Hooks{
- PreStartHooks: []Hook{*hook},
- PostStartHooks: []Hook{*hook},
- PostStopHooks: []Hook{*hook},
- }
-
- err := hooks.preStartHooks()
- if err == nil {
- t.Fatal(err)
- }
-
- err = hooks.postStartHooks()
- if err != nil {
- t.Fatal(err)
- }
-
- err = hooks.postStopHooks()
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestHooks(t *testing.T) {
- testHooks(t, createHook(0))
-}
-
-func TestHooksTimeout(t *testing.T) {
- testHooks(t, createHook(1))
-}
-
-func TestFailingHooks(t *testing.T) {
- testFailingHooks(t, createWrongHook())
-}
-
-func TestEmptyHooks(t *testing.T) {
- hooks := &Hooks{}
-
- err := hooks.preStartHooks()
- if err != nil {
- t.Fatal(err)
- }
-
- err = hooks.postStartHooks()
- if err != nil {
- t.Fatal(err)
- }
-
- err = hooks.postStopHooks()
- if err != nil {
- t.Fatal(err)
- }
-}
diff --git a/vendor/github.com/containers/virtcontainers/hyperstart.go b/vendor/github.com/containers/virtcontainers/hyperstart.go
deleted file mode 100644
index 1877e48..0000000
--- a/vendor/github.com/containers/virtcontainers/hyperstart.go
+++ /dev/null
@@ -1,511 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "syscall"
-
- "github.com/containers/virtcontainers/pkg/hyperstart"
-)
-
-var defaultSockPathTemplates = []string{"/tmp/hyper-pod-%s.sock", "/tmp/tty-pod%s.sock"}
-var defaultChannelTemplate = "sh.hyper.channel.%d"
-var defaultDeviceIDTemplate = "channel%d"
-var defaultIDTemplate = "charch%d"
-var defaultSharedDir = "/tmp/hyper/shared/pods/"
-var defaultPauseBinDir = "/usr/bin/"
-var mountTag = "hyperShared"
-var rootfsDir = "rootfs"
-var pauseBinName = "pause"
-var pauseContainerName = "pause-container"
-
-const (
- unixSocket = "unix"
-)
-
-// HyperConfig is a structure storing information needed for
-// hyperstart agent initialization.
-type HyperConfig struct {
- SockCtlName string
- SockTtyName string
- Volumes []Volume
- Sockets []Socket
- PauseBinPath string
-}
-
-func (c *HyperConfig) validate(pod Pod) bool {
- if len(c.Sockets) == 0 {
- virtLog.Infof("No sockets from configuration")
-
- podSocketPaths := []string{
- fmt.Sprintf(defaultSockPathTemplates[0], pod.id),
- fmt.Sprintf(defaultSockPathTemplates[1], pod.id),
- }
-
- c.SockCtlName = podSocketPaths[0]
- c.SockTtyName = podSocketPaths[1]
-
- for i := 0; i < len(podSocketPaths); i++ {
- s := Socket{
- DeviceID: fmt.Sprintf(defaultDeviceIDTemplate, i),
- ID: fmt.Sprintf(defaultIDTemplate, i),
- HostPath: podSocketPaths[i],
- Name: fmt.Sprintf(defaultChannelTemplate, i),
- }
- c.Sockets = append(c.Sockets, s)
- }
- }
-
- if len(c.Sockets) != 2 {
- return false
- }
-
- if c.PauseBinPath == "" {
- c.PauseBinPath = filepath.Join(defaultPauseBinDir, pauseBinName)
- }
-
- virtLog.Infof("Hyperstart config %v", c)
-
- return true
-}
-
-// hyper is the Agent interface implementation for hyperstart.
-type hyper struct {
- config HyperConfig
- proxy proxy
-}
-
-type hyperstartProxyCmd struct {
- cmd string
- message interface{}
- token string
-}
-
-func (h *hyper) buildHyperContainerProcess(cmd Cmd) (*hyperstart.Process, error) {
- var envVars []hyperstart.EnvironmentVar
-
- for _, e := range cmd.Envs {
- envVar := hyperstart.EnvironmentVar{
- Env: e.Var,
- Value: e.Value,
- }
-
- envVars = append(envVars, envVar)
- }
-
- process := &hyperstart.Process{
- User: cmd.User,
- Group: cmd.Group,
- Terminal: cmd.Interactive,
- Args: cmd.Args,
- Envs: envVars,
- Workdir: cmd.WorkDir,
- }
-
- return process, nil
-}
-
-func (h *hyper) buildNetworkInterfacesAndRoutes(pod Pod) ([]hyperstart.NetworkIface, []hyperstart.Route, error) {
- networkNS, err := pod.storage.fetchPodNetwork(pod.id)
- if err != nil {
- return []hyperstart.NetworkIface{}, []hyperstart.Route{}, err
- }
-
- if networkNS.NetNsPath == "" {
- return []hyperstart.NetworkIface{}, []hyperstart.Route{}, nil
- }
-
- netIfaces, err := getIfacesFromNetNs(networkNS.NetNsPath)
- if err != nil {
- return []hyperstart.NetworkIface{}, []hyperstart.Route{}, err
- }
-
- var ifaces []hyperstart.NetworkIface
- var routes []hyperstart.Route
- for _, endpoint := range networkNS.Endpoints {
- netIface, err := getNetIfaceByName(endpoint.NetPair.VirtIface.Name, netIfaces)
- if err != nil {
- return []hyperstart.NetworkIface{}, []hyperstart.Route{}, err
- }
-
- var ipAddrs []hyperstart.IPAddress
- for _, ipConfig := range endpoint.Properties.IPs {
- // Skip IPv6 because not supported by hyperstart
- if ipConfig.Version == "6" || ipConfig.Address.IP.To4() == nil {
- continue
- }
-
- netMask, _ := ipConfig.Address.Mask.Size()
-
- ipAddr := hyperstart.IPAddress{
- IPAddress: ipConfig.Address.IP.String(),
- NetMask: fmt.Sprintf("%d", netMask),
- }
-
- ipAddrs = append(ipAddrs, ipAddr)
- }
-
- iface := hyperstart.NetworkIface{
- NewDevice: endpoint.NetPair.VirtIface.Name,
- IPAddresses: ipAddrs,
- MTU: fmt.Sprintf("%d", netIface.MTU),
- MACAddr: endpoint.NetPair.VirtIface.HardAddr,
- }
-
- ifaces = append(ifaces, iface)
-
- for _, r := range endpoint.Properties.Routes {
- // Skip IPv6 because not supported by hyperstart
- if r.Dst.IP.To4() == nil {
- continue
- }
-
- gateway := r.GW.String()
- if gateway == "" {
- gateway = ""
- }
-
- route := hyperstart.Route{
- Dest: r.Dst.String(),
- Gateway: gateway,
- Device: endpoint.NetPair.VirtIface.Name,
- }
-
- routes = append(routes, route)
- }
- }
-
- return ifaces, routes, nil
-}
-
-func (h *hyper) linkPauseBinary(podID string) error {
- pauseDir := filepath.Join(defaultSharedDir, podID, pauseContainerName, rootfsDir)
-
- if err := os.MkdirAll(pauseDir, dirMode); err != nil {
- return err
- }
-
- pausePath := filepath.Join(pauseDir, pauseBinName)
-
- return os.Link(h.config.PauseBinPath, pausePath)
-}
-
-func (h *hyper) unlinkPauseBinary(podID string) error {
- pauseDir := filepath.Join(defaultSharedDir, podID, pauseContainerName)
-
- return os.RemoveAll(pauseDir)
-}
-
-func (h *hyper) bindMountContainerRootfs(podID, cID, cRootFs string) error {
- rootfsDest := filepath.Join(defaultSharedDir, podID, cID, rootfsDir)
-
- return bindMount(cRootFs, rootfsDest)
-}
-
-func (h *hyper) bindUnmountContainerRootfs(podID, cID string) error {
- rootfsDest := filepath.Join(defaultSharedDir, podID, cID, rootfsDir)
- syscall.Unmount(rootfsDest, 0)
-
- return nil
-}
-
-func (h *hyper) bindUnmountAllRootfs(pod Pod) {
- for _, c := range pod.containers {
- h.bindUnmountContainerRootfs(pod.id, c.id)
- }
-}
-
-// init is the agent initialization implementation for hyperstart.
-func (h *hyper) init(pod *Pod, config interface{}) (err error) {
- switch c := config.(type) {
- case HyperConfig:
- if c.validate(*pod) == false {
- return fmt.Errorf("Invalid configuration")
- }
- h.config = c
- default:
- return fmt.Errorf("Invalid config type")
- }
-
- // Override pod agent configuration
- pod.config.AgentConfig = h.config
-
- for _, volume := range h.config.Volumes {
- err := pod.hypervisor.addDevice(volume, fsDev)
- if err != nil {
- return err
- }
- }
-
- for _, socket := range h.config.Sockets {
- err := pod.hypervisor.addDevice(socket, serialPortDev)
- if err != nil {
- return err
- }
- }
-
- // Adding the hyper shared volume.
- // This volume contains all bind mounted container bundles.
- sharedVolume := Volume{
- MountTag: mountTag,
- HostPath: filepath.Join(defaultSharedDir, pod.id),
- }
-
- if err := os.MkdirAll(sharedVolume.HostPath, dirMode); err != nil {
- return err
- }
-
- if err := pod.hypervisor.addDevice(sharedVolume, fsDev); err != nil {
- return err
- }
-
- h.proxy = pod.proxy
-
- return nil
-}
-
-// exec is the agent command execution implementation for hyperstart.
-func (h *hyper) exec(pod *Pod, c Container, process Process, cmd Cmd) error {
- hyperProcess, err := h.buildHyperContainerProcess(cmd)
- if err != nil {
- return err
- }
-
- execCommand := hyperstart.ExecCommand{
- Container: c.id,
- Process: *hyperProcess,
- }
-
- proxyCmd := hyperstartProxyCmd{
- cmd: hyperstart.ExecCmd,
- message: execCommand,
- token: process.Token,
- }
-
- if _, err := h.proxy.sendCmd(proxyCmd); err != nil {
- return err
- }
-
- return nil
-}
-
-// startPod is the agent Pod starting implementation for hyperstart.
-func (h *hyper) startPod(pod Pod) error {
- ifaces, routes, err := h.buildNetworkInterfacesAndRoutes(pod)
- if err != nil {
- return err
- }
-
- hyperPod := hyperstart.Pod{
- Hostname: pod.id,
- Containers: []hyperstart.Container{},
- Interfaces: ifaces,
- Routes: routes,
- ShareDir: mountTag,
- }
-
- proxyCmd := hyperstartProxyCmd{
- cmd: hyperstart.StartPod,
- message: hyperPod,
- }
-
- if _, err := h.proxy.sendCmd(proxyCmd); err != nil {
- return err
- }
-
- if err := h.startPauseContainer(pod.id); err != nil {
- return err
- }
-
- for _, c := range pod.containers {
- if err := h.startOneContainer(pod, *c); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-// stopPod is the agent Pod stopping implementation for hyperstart.
-func (h *hyper) stopPod(pod Pod) error {
- for _, c := range pod.containers {
- state, err := pod.storage.fetchContainerState(pod.id, c.id)
- if err != nil {
- return err
- }
-
- if state.State != StateRunning {
- continue
- }
-
- if err := h.killOneContainer(c.id, syscall.SIGTERM); err != nil {
- return err
- }
-
- if err := h.stopOneContainer(pod.id, c.id); err != nil {
- return err
- }
- }
-
- if err := h.stopPauseContainer(pod.id); err != nil {
- return err
- }
-
- return nil
-}
-
-// startPauseContainer starts a specific container running the pause binary provided.
-func (h *hyper) startPauseContainer(podID string) error {
- cmd := Cmd{
- Args: []string{fmt.Sprintf("./%s", pauseBinName)},
- Envs: []EnvVar{},
- WorkDir: "/",
- Interactive: false,
- }
-
- process, err := h.buildHyperContainerProcess(cmd)
- if err != nil {
- return err
- }
-
- container := hyperstart.Container{
- ID: pauseContainerName,
- Image: pauseContainerName,
- Rootfs: rootfsDir,
- Process: process,
- }
-
- if err := h.linkPauseBinary(podID); err != nil {
- return err
- }
-
- proxyCmd := hyperstartProxyCmd{
- cmd: hyperstart.NewContainer,
- message: container,
- }
-
- if _, err := h.proxy.sendCmd(proxyCmd); err != nil {
- return err
- }
-
- return nil
-}
-
-func (h *hyper) startOneContainer(pod Pod, c Container) error {
- process, err := h.buildHyperContainerProcess(c.config.Cmd)
- if err != nil {
- return err
- }
-
- container := hyperstart.Container{
- ID: c.id,
- Image: c.id,
- Rootfs: rootfsDir,
- Process: process,
- }
-
- if err := h.bindMountContainerRootfs(pod.id, c.id, c.rootFs); err != nil {
- h.bindUnmountAllRootfs(pod)
- return err
- }
-
- proxyCmd := hyperstartProxyCmd{
- cmd: hyperstart.NewContainer,
- message: container,
- token: c.process.Token,
- }
-
- if _, err := h.proxy.sendCmd(proxyCmd); err != nil {
- return err
- }
-
- return nil
-}
-
-// createContainer is the agent Container creation implementation for hyperstart.
-func (h *hyper) createContainer(pod *Pod, c *Container) error {
- return nil
-}
-
-// startContainer is the agent Container starting implementation for hyperstart.
-func (h *hyper) startContainer(pod Pod, c Container) error {
- return h.startOneContainer(pod, c)
-}
-
-func (h *hyper) stopPauseContainer(podID string) error {
- if err := h.killOneContainer(pauseContainerName, syscall.SIGKILL); err != nil {
- return err
- }
-
- if err := h.unlinkPauseBinary(podID); err != nil {
- return err
- }
-
- return nil
-}
-
-// stopContainer is the agent Container stopping implementation for hyperstart.
-func (h *hyper) stopContainer(pod Pod, c Container) error {
- return h.stopOneContainer(pod.id, c.id)
-}
-
-func (h *hyper) stopOneContainer(podID, cID string) error {
- removeCommand := hyperstart.RemoveCommand{
- Container: cID,
- }
-
- proxyCmd := hyperstartProxyCmd{
- cmd: hyperstart.RemoveContainer,
- message: removeCommand,
- }
-
- if _, err := h.proxy.sendCmd(proxyCmd); err != nil {
- return err
- }
-
- if err := h.bindUnmountContainerRootfs(podID, cID); err != nil {
- return err
- }
-
- return nil
-}
-
-// killContainer is the agent process signal implementation for hyperstart.
-func (h *hyper) killContainer(pod Pod, c Container, signal syscall.Signal) error {
- return h.killOneContainer(c.id, signal)
-}
-
-func (h *hyper) killOneContainer(cID string, signal syscall.Signal) error {
- killCmd := hyperstart.KillCommand{
- Container: cID,
- Signal: signal,
- }
-
- proxyCmd := hyperstartProxyCmd{
- cmd: hyperstart.KillContainer,
- message: killCmd,
- }
-
- if _, err := h.proxy.sendCmd(proxyCmd); err != nil {
- return err
- }
-
- return nil
-}
diff --git a/vendor/github.com/containers/virtcontainers/hyperstart_test.go b/vendor/github.com/containers/virtcontainers/hyperstart_test.go
deleted file mode 100644
index 5d40b48..0000000
--- a/vendor/github.com/containers/virtcontainers/hyperstart_test.go
+++ /dev/null
@@ -1,69 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "testing"
-)
-
-func TestHyperstartValidateNoSocketsSuccessful(t *testing.T) {
- config := &HyperConfig{
- SockCtlName: "ctlSock",
- SockTtyName: "ttySock",
- }
-
- pod := Pod{
- id: testPodID,
- }
-
- ok := config.validate(pod)
- if ok != true {
- t.Fatal()
- }
-}
-
-func testHyperstartValidateNSocket(t *testing.T, socketAmount int, expected bool) {
- sockets := make([]Socket, socketAmount)
-
- config := &HyperConfig{
- SockCtlName: "ctlSock",
- SockTtyName: "ttySock",
- Sockets: sockets,
- }
-
- pod := Pod{
- id: testPodID,
- }
-
- ok := config.validate(pod)
- if ok != expected {
- t.Fatal()
- }
-}
-
-func TestHyperstartValidateOneSocketFailing(t *testing.T) {
- testHyperstartValidateNSocket(t, 1, false)
-
- for i := 3; i < 1000; i++ {
- testHyperstartValidateNSocket(t, i, false)
- }
-}
-
-func TestHyperstartValidateNSocketSuccessful(t *testing.T) {
- testHyperstartValidateNSocket(t, 0, true)
- testHyperstartValidateNSocket(t, 2, true)
-}
diff --git a/vendor/github.com/containers/virtcontainers/hypervisor.go b/vendor/github.com/containers/virtcontainers/hypervisor.go
deleted file mode 100644
index 4fe0957..0000000
--- a/vendor/github.com/containers/virtcontainers/hypervisor.go
+++ /dev/null
@@ -1,176 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
-)
-
-// HypervisorType describes an hypervisor type.
-type HypervisorType string
-
-const (
- // QemuHypervisor is the QEMU hypervisor.
- QemuHypervisor HypervisorType = "qemu"
-
- // MockHypervisor is a mock hypervisor for testing purposes
- MockHypervisor HypervisorType = "mock"
-)
-
-// deviceType describes a virtualized device type.
-type deviceType int
-
-const (
- // ImgDev is the image device type.
- imgDev deviceType = iota
-
- // FsDev is the filesystem device type.
- fsDev
-
- // NetDev is the network device type.
- netDev
-
- // SerialDev is the serial device type.
- serialDev
-
- // BlockDev is the block device type.
- blockDev
-
- // ConsoleDev is the console device type.
- consoleDev
-
- // SerialPortDev is the serial port device type.
- serialPortDev
-)
-
-// Set sets an hypervisor type based on the input string.
-func (hType *HypervisorType) Set(value string) error {
- switch value {
- case "qemu":
- *hType = QemuHypervisor
- return nil
- case "mock":
- *hType = MockHypervisor
- return nil
- default:
- return fmt.Errorf("Unknown hypervisor type %s", value)
- }
-}
-
-// String converts an hypervisor type to a string.
-func (hType *HypervisorType) String() string {
- switch *hType {
- case QemuHypervisor:
- return string(QemuHypervisor)
- case MockHypervisor:
- return string(MockHypervisor)
- default:
- return ""
- }
-}
-
-// newHypervisor returns an hypervisor from and hypervisor type.
-func newHypervisor(hType HypervisorType) (hypervisor, error) {
- switch hType {
- case QemuHypervisor:
- return &qemu{}, nil
- case MockHypervisor:
- return &mockHypervisor{}, nil
- default:
- return nil, fmt.Errorf("Unknown hypervisor type %s", hType)
- }
-}
-
-// Param is a key/value representation for hypervisor and kernel parameters.
-type Param struct {
- parameter string
- value string
-}
-
-// HypervisorConfig is the hypervisor configuration.
-type HypervisorConfig struct {
- // KernelPath is the guest kernel host path.
- KernelPath string
-
- // ImagePath is the guest image host path.
- ImagePath string
-
- // HypervisorPath is the hypervisor executable host path.
- HypervisorPath string
-
- // KernelParams are additional guest kernel parameters.
- KernelParams []Param
-
- // HypervisorParams are additional hypervisor parameters.
- HypervisorParams []Param
-
- // Debug changes the default hypervisor and kernel parameters to
- // enable debug output where available.
- Debug bool
-}
-
-func (conf *HypervisorConfig) valid() (bool, error) {
- if conf.KernelPath == "" {
- return false, fmt.Errorf("Missing kernel path")
- }
-
- if conf.ImagePath == "" {
- return false, fmt.Errorf("Missing image path")
- }
-
- if conf.HypervisorPath == "" {
- return false, fmt.Errorf("Missing hypervisor path")
- }
-
- return true, nil
-}
-
-func appendParam(params []Param, parameter string, value string) []Param {
- return append(params, Param{parameter, value})
-}
-
-func serializeParams(params []Param, delim string) []string {
- var parameters []string
-
- for _, p := range params {
- if p.parameter == "" && p.value == "" {
- continue
- } else if p.parameter == "" {
- parameters = append(parameters, fmt.Sprintf("%s", p.value))
- } else if p.value == "" {
- parameters = append(parameters, fmt.Sprintf("%s", p.parameter))
- } else if delim == "" {
- parameters = append(parameters, fmt.Sprintf("%s", p.parameter))
- parameters = append(parameters, fmt.Sprintf("%s", p.value))
- } else {
- parameters = append(parameters, fmt.Sprintf("%s%s%s", p.parameter, delim, p.value))
- }
- }
-
- return parameters
-}
-
-// hypervisor is the virtcontainers hypervisor interface.
-// The default hypervisor implementation is Qemu.
-type hypervisor interface {
- init(config HypervisorConfig) error
- createPod(podConfig PodConfig) error
- startPod(startCh, stopCh chan struct{}) error
- stopPod() error
- addDevice(devInfo interface{}, devType deviceType) error
- getPodConsole(podID string) string
-}
diff --git a/vendor/github.com/containers/virtcontainers/hypervisor_test.go b/vendor/github.com/containers/virtcontainers/hypervisor_test.go
deleted file mode 100644
index 155c87b..0000000
--- a/vendor/github.com/containers/virtcontainers/hypervisor_test.go
+++ /dev/null
@@ -1,257 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
- "reflect"
- "testing"
-)
-
-func testSetHypervisorType(t *testing.T, value string, expected HypervisorType) {
- var hypervisorType HypervisorType
-
- err := (&hypervisorType).Set(value)
- if err != nil {
- t.Fatal(err)
- }
-
- if hypervisorType != expected {
- t.Fatal()
- }
-}
-
-func TestSetQemuHypervisorType(t *testing.T) {
- testSetHypervisorType(t, "qemu", QemuHypervisor)
-}
-
-func TestSetMockHypervisorType(t *testing.T) {
- testSetHypervisorType(t, "mock", MockHypervisor)
-}
-
-func TestSetUnknownHypervisorType(t *testing.T) {
- var hypervisorType HypervisorType
-
- err := (&hypervisorType).Set("unknown")
- if err == nil {
- t.Fatal()
- }
-
- if hypervisorType == QemuHypervisor ||
- hypervisorType == MockHypervisor {
- t.Fatal()
- }
-}
-
-func testStringFromHypervisorType(t *testing.T, hypervisorType HypervisorType, expected string) {
- hypervisorTypeStr := (&hypervisorType).String()
- if hypervisorTypeStr != expected {
- t.Fatal()
- }
-}
-
-func TestStringFromQemuHypervisorType(t *testing.T) {
- hypervisorType := QemuHypervisor
- testStringFromHypervisorType(t, hypervisorType, "qemu")
-}
-
-func TestStringFromMockHypervisorType(t *testing.T) {
- hypervisorType := MockHypervisor
- testStringFromHypervisorType(t, hypervisorType, "mock")
-}
-
-func TestStringFromUnknownHypervisorType(t *testing.T) {
- var hypervisorType HypervisorType
- testStringFromHypervisorType(t, hypervisorType, "")
-}
-
-func testNewHypervisorFromHypervisorType(t *testing.T, hypervisorType HypervisorType, expected hypervisor) {
- hy, err := newHypervisor(hypervisorType)
- if err != nil {
- t.Fatal(err)
- }
-
- if reflect.DeepEqual(hy, expected) == false {
- t.Fatal()
- }
-}
-
-func TestNewHypervisorFromQemuHypervisorType(t *testing.T) {
- hypervisorType := QemuHypervisor
- expectedHypervisor := &qemu{}
- testNewHypervisorFromHypervisorType(t, hypervisorType, expectedHypervisor)
-}
-
-func TestNewHypervisorFromMockHypervisorType(t *testing.T) {
- hypervisorType := MockHypervisor
- expectedHypervisor := &mockHypervisor{}
- testNewHypervisorFromHypervisorType(t, hypervisorType, expectedHypervisor)
-}
-
-func TestNewHypervisorFromUnknownHypervisorType(t *testing.T) {
- var hypervisorType HypervisorType
-
- hy, err := newHypervisor(hypervisorType)
- if err == nil {
- t.Fatal()
- }
-
- if hy != nil {
- t.Fatal()
- }
-}
-
-func testHypervisorConfigValid(t *testing.T, hypervisorConfig *HypervisorConfig, expected bool) {
- ret, _ := hypervisorConfig.valid()
- if ret != expected {
- t.Fatal()
- }
-}
-
-func TestHypervisorConfigNoKernelPath(t *testing.T) {
- hypervisorConfig := &HypervisorConfig{
- KernelPath: "",
- ImagePath: fmt.Sprintf("%s/%s", testDir, testImage),
- HypervisorPath: fmt.Sprintf("%s/%s", testDir, testHypervisor),
- }
-
- testHypervisorConfigValid(t, hypervisorConfig, false)
-}
-
-func TestHypervisorConfigNoImagePath(t *testing.T) {
- hypervisorConfig := &HypervisorConfig{
- KernelPath: fmt.Sprintf("%s/%s", testDir, testKernel),
- ImagePath: "",
- HypervisorPath: fmt.Sprintf("%s/%s", testDir, testHypervisor),
- }
-
- testHypervisorConfigValid(t, hypervisorConfig, false)
-}
-
-func TestHypervisorConfigNoHypervisorPath(t *testing.T) {
- hypervisorConfig := &HypervisorConfig{
- KernelPath: fmt.Sprintf("%s/%s", testDir, testKernel),
- ImagePath: fmt.Sprintf("%s/%s", testDir, testImage),
- HypervisorPath: "",
- }
-
- testHypervisorConfigValid(t, hypervisorConfig, false)
-}
-
-func TestHypervisorConfigIsValid(t *testing.T) {
- hypervisorConfig := &HypervisorConfig{
- KernelPath: fmt.Sprintf("%s/%s", testDir, testKernel),
- ImagePath: fmt.Sprintf("%s/%s", testDir, testImage),
- HypervisorPath: fmt.Sprintf("%s/%s", testDir, testHypervisor),
- }
-
- testHypervisorConfigValid(t, hypervisorConfig, true)
-}
-
-func TestAppendParams(t *testing.T) {
- paramList := []Param{
- {
- parameter: "param1",
- value: "value1",
- },
- }
-
- expectedParams := []Param{
- {
- parameter: "param1",
- value: "value1",
- },
- {
- parameter: "param2",
- value: "value2",
- },
- }
-
- paramList = appendParam(paramList, "param2", "value2")
- if reflect.DeepEqual(paramList, expectedParams) == false {
- t.Fatal()
- }
-}
-
-func testSerializeParams(t *testing.T, params []Param, delim string, expected []string) {
- result := serializeParams(params, delim)
- if reflect.DeepEqual(result, expected) == false {
- t.Fatal()
- }
-}
-
-func TestSerializeParamsNoParamNoValue(t *testing.T) {
- params := []Param{
- {
- parameter: "",
- value: "",
- },
- }
- var expected []string
-
- testSerializeParams(t, params, "", expected)
-}
-
-func TestSerializeParamsNoParam(t *testing.T) {
- params := []Param{
- {
- value: "value1",
- },
- }
-
- expected := []string{"value1"}
-
- testSerializeParams(t, params, "", expected)
-}
-
-func TestSerializeParamsNoValue(t *testing.T) {
- params := []Param{
- {
- parameter: "param1",
- },
- }
-
- expected := []string{"param1"}
-
- testSerializeParams(t, params, "", expected)
-}
-
-func TestSerializeParamsNoDelim(t *testing.T) {
- params := []Param{
- {
- parameter: "param1",
- value: "value1",
- },
- }
-
- expected := []string{"param1", "value1"}
-
- testSerializeParams(t, params, "", expected)
-}
-
-func TestSerializeParams(t *testing.T) {
- params := []Param{
- {
- parameter: "param1",
- value: "value1",
- },
- }
-
- expected := []string{"param1=value1"}
-
- testSerializeParams(t, params, "=", expected)
-}
diff --git a/vendor/github.com/containers/virtcontainers/lock.json b/vendor/github.com/containers/virtcontainers/lock.json
deleted file mode 100644
index d688a36..0000000
--- a/vendor/github.com/containers/virtcontainers/lock.json
+++ /dev/null
@@ -1,126 +0,0 @@
-{
- "memo": "4c76a118baef92b9fb5a98916d713b34f82809485387e5e398bbdef152b74a71",
- "projects": [
- {
- "name": "github.com/01org/ciao",
- "branch": "master",
- "revision": "dda37852a178ecdc435c50efbe9a8e12ce705acb",
- "packages": [
- "qemu",
- "ssntp/uuid"
- ]
- },
- {
- "name": "github.com/Sirupsen/logrus",
- "branch": "master",
- "revision": "1deb2db2a6fff8a35532079061b903c3a25eed52",
- "packages": [
- "."
- ]
- },
- {
- "name": "github.com/clearcontainers/proxy",
- "revision": "1cbbed5d3de4749739234570641fc7afac2acc07",
- "packages": [
- "client"
- ]
- },
- {
- "name": "github.com/containernetworking/cni",
- "branch": "master",
- "revision": "0799f5732f2a11b329d9e3d51b9c8f2e3759f2ff",
- "packages": [
- "libcni",
- "pkg/ns",
- "pkg/types",
- "pkg/types/current"
- ]
- },
- {
- "name": "github.com/davecgh/go-spew",
- "branch": "master",
- "revision": "346938d642f2ec3594ed81d874461961cd0faa76",
- "packages": [
- "spew"
- ]
- },
- {
- "name": "github.com/mitchellh/mapstructure",
- "branch": "master",
- "revision": "53818660ed4955e899c0bcafa97299a388bd7c8e",
- "packages": [
- "."
- ]
- },
- {
- "name": "github.com/opencontainers/runc",
- "revision": "dcbcdf2470421e911211604c61ea3e8ca740d346",
- "packages": [
- "libcontainer/configs"
- ]
- },
- {
- "name": "github.com/opencontainers/runtime-spec",
- "revision": "a5c4e91dae9533c46a98f122b5085c0b3fe27ee4",
- "packages": [
- "specs-go"
- ]
- },
- {
- "name": "github.com/pmezard/go-difflib",
- "version": "v1.0.0",
- "revision": "792786c7400a136282c1664665ae0a8db921c6c2",
- "packages": [
- "difflib"
- ]
- },
- {
- "name": "github.com/stretchr/testify",
- "branch": "master",
- "revision": "4d4bfba8f1d1027c4fdbe371823030df51419987",
- "packages": [
- "assert"
- ]
- },
- {
- "name": "github.com/urfave/cli",
- "branch": "master",
- "revision": "9e5b04886c4bfee2ceba1465b8121057355c4e53",
- "packages": [
- "."
- ]
- },
- {
- "name": "github.com/vishvananda/netlink",
- "branch": "master",
- "revision": "fe3b5664d23a11b52ba59bece4ff29c52772a56b",
- "packages": [
- "."
- ]
- },
- {
- "name": "github.com/vishvananda/netns",
- "branch": "master",
- "revision": "54f0e4339ce73702a0607f49922aaa1e749b418d",
- "packages": [
- "."
- ]
- },
- {
- "name": "golang.org/x/crypto",
- "branch": "master",
- "revision": "728b753d0135da6801d45a38e6f43ff55779c5c2",
- "packages": [
- "ssh"
- ]
- },
- {
- "name": "golang.org/x/sys",
- "branch": "master",
- "revision": "99f16d856c9836c42d24e7ab64ea72916925fa97",
- "packages": [
- "unix"
- ]
- }
- ]
-}
diff --git a/vendor/github.com/containers/virtcontainers/manifest.json b/vendor/github.com/containers/virtcontainers/manifest.json
deleted file mode 100644
index a4b601f..0000000
--- a/vendor/github.com/containers/virtcontainers/manifest.json
+++ /dev/null
@@ -1,43 +0,0 @@
-{
- "dependencies": {
- "github.com/01org/ciao": {
- "branch": "master"
- },
- "github.com/Sirupsen/logrus": {
- "branch": "master"
- },
- "github.com/clearcontainers/proxy": {
- "revision": "1cbbed5d3de4749739234570641fc7afac2acc07"
- },
- "github.com/containernetworking/cni": {
- "branch": "master"
- },
- "github.com/mitchellh/mapstructure": {
- "branch": "master"
- },
- "github.com/opencontainers/runc": {
- "revision": "dcbcdf2470421e911211604c61ea3e8ca740d346"
- },
- "github.com/opencontainers/runtime-spec": {
- "revision": "a5c4e91dae9533c46a98f122b5085c0b3fe27ee4"
- },
- "github.com/stretchr/testify": {
- "branch": "master"
- },
- "github.com/urfave/cli": {
- "branch": "master"
- },
- "github.com/vishvananda/netlink": {
- "branch": "master"
- },
- "github.com/vishvananda/netns": {
- "branch": "master"
- },
- "golang.org/x/crypto": {
- "branch": "master"
- },
- "golang.org/x/sys": {
- "branch": "master"
- }
- }
-}
diff --git a/vendor/github.com/containers/virtcontainers/mock_hypervisor.go b/vendor/github.com/containers/virtcontainers/mock_hypervisor.go
deleted file mode 100644
index 6648c7a..0000000
--- a/vendor/github.com/containers/virtcontainers/mock_hypervisor.go
+++ /dev/null
@@ -1,51 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-type mockHypervisor struct {
-}
-
-func (m *mockHypervisor) init(config HypervisorConfig) error {
- valid, err := config.valid()
- if valid == false || err != nil {
- return err
- }
-
- return nil
-}
-
-func (m *mockHypervisor) createPod(podConfig PodConfig) error {
- return nil
-}
-
-func (m *mockHypervisor) startPod(startCh, stopCh chan struct{}) error {
- var msg struct{}
- startCh <- msg
- return nil
-}
-
-func (m *mockHypervisor) stopPod() error {
- return nil
-}
-
-func (m *mockHypervisor) addDevice(devInfo interface{}, devType deviceType) error {
- return nil
-}
-
-func (m *mockHypervisor) getPodConsole(podID string) string {
- return ""
-}
diff --git a/vendor/github.com/containers/virtcontainers/mock_hypervisor_test.go b/vendor/github.com/containers/virtcontainers/mock_hypervisor_test.go
deleted file mode 100644
index f155c4d..0000000
--- a/vendor/github.com/containers/virtcontainers/mock_hypervisor_test.go
+++ /dev/null
@@ -1,104 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
- "testing"
- "time"
-)
-
-func TestMockHypervisorInit(t *testing.T) {
- var m *mockHypervisor
-
- wrongConfig := HypervisorConfig{
- KernelPath: "",
- ImagePath: "",
- HypervisorPath: "",
- }
-
- err := m.init(wrongConfig)
- if err == nil {
- t.Fatal()
- }
-
- rightConfig := HypervisorConfig{
- KernelPath: fmt.Sprintf("%s/%s", testDir, testKernel),
- ImagePath: fmt.Sprintf("%s/%s", testDir, testImage),
- HypervisorPath: fmt.Sprintf("%s/%s", testDir, testHypervisor),
- }
-
- err = m.init(rightConfig)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestMockHypervisorCreatePod(t *testing.T) {
- var m *mockHypervisor
-
- config := PodConfig{}
-
- err := m.createPod(config)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestMockHypervisorStartPod(t *testing.T) {
- var m *mockHypervisor
-
- startCh := make(chan struct{})
- stopCh := make(chan struct{})
-
- go m.startPod(startCh, stopCh)
-
- select {
- case <-startCh:
- break
- case <-time.After(time.Second):
- t.Fatal("Timeout waiting for start notification")
- }
-}
-
-func TestMockHypervisorStopPod(t *testing.T) {
- var m *mockHypervisor
-
- err := m.stopPod()
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestMockHypervisorAddDevice(t *testing.T) {
- var m *mockHypervisor
-
- err := m.addDevice(nil, imgDev)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestMockHypervisorGetPodConsole(t *testing.T) {
- var m *mockHypervisor
-
- expected := ""
-
- if result := m.getPodConsole("testPodID"); result != expected {
- t.Fatalf("Got %s\nExpecting %s", result, expected)
- }
-}
diff --git a/vendor/github.com/containers/virtcontainers/network.go b/vendor/github.com/containers/virtcontainers/network.go
deleted file mode 100644
index b2363df..0000000
--- a/vendor/github.com/containers/virtcontainers/network.go
+++ /dev/null
@@ -1,482 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "errors"
- "fmt"
- "net"
- "os"
-
- "github.com/01org/ciao/ssntp/uuid"
- "github.com/containernetworking/cni/pkg/ns"
- types "github.com/containernetworking/cni/pkg/types/current"
- "github.com/vishvananda/netlink"
- "golang.org/x/sys/unix"
-)
-
-type netIfaceAddrs struct {
- iface net.Interface
- addrs []net.Addr
-}
-
-// NetworkInterface defines a network interface.
-type NetworkInterface struct {
- Name string
- HardAddr string
-}
-
-// NetworkInterfacePair defines a pair between TAP and virtual network interfaces.
-type NetworkInterfacePair struct {
- ID string
- Name string
- VirtIface NetworkInterface
- TAPIface NetworkInterface
-}
-
-// NetworkConfig is the network configuration related to a network.
-type NetworkConfig struct {
- NetNSPath string
- NumInterfaces int
-}
-
-// Endpoint gathers a network pair and its properties.
-type Endpoint struct {
- NetPair NetworkInterfacePair
- Properties types.Result
-}
-
-// NetworkNamespace contains all data related to its network namespace.
-type NetworkNamespace struct {
- NetNsPath string
- Endpoints []Endpoint
-}
-
-// NetworkModel describes the type of network specification.
-type NetworkModel string
-
-const (
- // NoopNetworkModel is the No-Op network.
- NoopNetworkModel NetworkModel = "noop"
-
- // CNINetworkModel is the CNI network.
- CNINetworkModel NetworkModel = "CNI"
-
- // CNMNetworkModel is the CNM network.
- CNMNetworkModel NetworkModel = "CNM"
-)
-
-// Set sets a network type based on the input string.
-func (networkType *NetworkModel) Set(value string) error {
- switch value {
- case "noop":
- *networkType = NoopNetworkModel
- return nil
- case "CNI":
- *networkType = CNINetworkModel
- return nil
- case "CNM":
- *networkType = CNMNetworkModel
- return nil
- default:
- return fmt.Errorf("Unknown network type %s", value)
- }
-}
-
-// String converts a network type to a string.
-func (networkType *NetworkModel) String() string {
- switch *networkType {
- case NoopNetworkModel:
- return string(NoopNetworkModel)
- case CNINetworkModel:
- return string(CNINetworkModel)
- case CNMNetworkModel:
- return string(CNMNetworkModel)
- default:
- return ""
- }
-}
-
-// newNetwork returns a network from a network type.
-func newNetwork(networkType NetworkModel) network {
- switch networkType {
- case NoopNetworkModel:
- return &noopNetwork{}
- case CNINetworkModel:
- return &cni{}
- case CNMNetworkModel:
- return &cnm{}
- default:
- return &noopNetwork{}
- }
-}
-
-func createLink(netHandle *netlink.Handle, name string, expectedLink netlink.Link) (netlink.Link, error) {
- var newLink netlink.Link
-
- switch expectedLink.Type() {
- case (&netlink.Bridge{}).Type():
- newLink = &netlink.Bridge{
- LinkAttrs: netlink.LinkAttrs{Name: name},
- }
- case (&netlink.Tuntap{}).Type():
- newLink = &netlink.Tuntap{
- LinkAttrs: netlink.LinkAttrs{Name: name},
- Mode: netlink.TUNTAP_MODE_TAP,
- }
- default:
- return nil, fmt.Errorf("Unsupported link type %s", expectedLink.Type())
- }
-
- if err := netHandle.LinkAdd(newLink); err != nil {
- return nil, fmt.Errorf("LinkAdd() failed for %s name %s: %s", expectedLink.Type(), name, err)
- }
-
- return getLinkByName(netHandle, name, expectedLink)
-}
-
-func getLinkByName(netHandle *netlink.Handle, name string, expectedLink netlink.Link) (netlink.Link, error) {
- link, err := netHandle.LinkByName(name)
- if err != nil {
- return nil, fmt.Errorf("LinkByName() failed for %s name %s: %s", expectedLink.Type(), name, err)
- }
-
- switch expectedLink.Type() {
- case (&netlink.Bridge{}).Type():
- if l, ok := link.(*netlink.Bridge); ok {
- return l, nil
- }
- case (&netlink.Tuntap{}).Type():
- if l, ok := link.(*netlink.GenericLink); ok {
- return l, nil
- }
- case (&netlink.Veth{}).Type():
- if l, ok := link.(*netlink.Veth); ok {
- return l, nil
- }
- default:
- return nil, fmt.Errorf("Unsupported link type %s", expectedLink.Type())
- }
-
- return nil, fmt.Errorf("Incorrect link type %s, expecting %s", link.Type(), expectedLink.Type())
-}
-
-func bridgeNetworkPair(netPair NetworkInterfacePair) error {
- netHandle, err := netlink.NewHandle()
- if err != nil {
- return err
- }
- defer netHandle.Delete()
-
- tapLink, err := createLink(netHandle, netPair.TAPIface.Name, &netlink.Tuntap{})
- if err != nil {
- return fmt.Errorf("Could not create TAP interface: %s", err)
- }
-
- vethLink, err := getLinkByName(netHandle, netPair.VirtIface.Name, &netlink.Veth{})
- if err != nil {
- return fmt.Errorf("Could not get veth interface: %s", err)
- }
-
- hardAddr, err := net.ParseMAC(netPair.VirtIface.HardAddr)
- if err != nil {
- return err
- }
- if err := netHandle.LinkSetHardwareAddr(vethLink, hardAddr); err != nil {
- return fmt.Errorf("Could not set MAC address %s for veth interface %s: %s",
- netPair.VirtIface.HardAddr, netPair.VirtIface.Name, err)
- }
-
- bridgeLink, err := createLink(netHandle, netPair.Name, &netlink.Bridge{})
- if err != nil {
- return fmt.Errorf("Could not create bridge: %s", err)
- }
-
- if err := netHandle.LinkSetMaster(tapLink, bridgeLink.(*netlink.Bridge)); err != nil {
- return fmt.Errorf("Could not attach TAP %s to the bridge %s: %s",
- netPair.TAPIface.Name, netPair.Name, err)
- }
-
- if err := netHandle.LinkSetUp(tapLink); err != nil {
- return fmt.Errorf("Could not enable TAP %s: %s", netPair.TAPIface.Name, err)
- }
-
- if err := netHandle.LinkSetMaster(vethLink, bridgeLink.(*netlink.Bridge)); err != nil {
- return fmt.Errorf("Could not attach veth %s to the bridge %s: %s",
- netPair.VirtIface.Name, netPair.Name, err)
- }
-
- if err := netHandle.LinkSetUp(vethLink); err != nil {
- return fmt.Errorf("Could not enable veth %s: %s", netPair.VirtIface.Name, err)
- }
-
- if err := netHandle.LinkSetUp(bridgeLink); err != nil {
- return fmt.Errorf("Could not enable bridge %s: %s", netPair.Name, err)
- }
-
- return nil
-}
-
-func unBridgeNetworkPair(netPair NetworkInterfacePair) error {
- netHandle, err := netlink.NewHandle()
- if err != nil {
- return err
- }
- defer netHandle.Delete()
-
- tapLink, err := getLinkByName(netHandle, netPair.TAPIface.Name, &netlink.Tuntap{})
- if err != nil {
- return fmt.Errorf("Could not get TAP interface: %s", err)
- }
-
- vethLink, err := getLinkByName(netHandle, netPair.VirtIface.Name, &netlink.Veth{})
- if err != nil {
- return fmt.Errorf("Could not get veth interface: %s", err)
- }
-
- bridgeLink, err := getLinkByName(netHandle, netPair.Name, &netlink.Bridge{})
- if err != nil {
- return fmt.Errorf("Could not get bridge interface: %s", err)
- }
-
- if err := netHandle.LinkSetDown(bridgeLink); err != nil {
- return fmt.Errorf("Could not disable bridge %s: %s", netPair.Name, err)
- }
-
- if err := netHandle.LinkSetDown(vethLink); err != nil {
- return fmt.Errorf("Could not disable veth %s: %s", netPair.VirtIface.Name, err)
- }
-
- if err := netHandle.LinkSetNoMaster(vethLink); err != nil {
- return fmt.Errorf("Could not detach veth %s: %s", netPair.VirtIface.Name, err)
- }
-
- if err := netHandle.LinkSetDown(tapLink); err != nil {
- return fmt.Errorf("Could not disable TAP %s: %s", netPair.TAPIface.Name, err)
- }
-
- if err := netHandle.LinkSetNoMaster(tapLink); err != nil {
- return fmt.Errorf("Could not detach TAP %s: %s", netPair.TAPIface.Name, err)
- }
-
- if err := netHandle.LinkDel(bridgeLink); err != nil {
- return fmt.Errorf("Could not remove bridge %s: %s", netPair.Name, err)
- }
-
- if err := netHandle.LinkDel(tapLink); err != nil {
- return fmt.Errorf("Could not remove TAP %s: %s", netPair.TAPIface.Name, err)
- }
-
- return nil
-}
-
-func createNetNS() (string, error) {
- n, err := ns.NewNS()
- if err != nil {
- return "", err
- }
-
- return n.Path(), nil
-}
-
-func setNetNS(netNSPath string) error {
- n, err := ns.GetNS(netNSPath)
- if err != nil {
- return err
- }
-
- return n.Set()
-}
-
-// doNetNS makes some subsequent calls to a go routine and LockOSThread
-// in order to protect the current process from other thread switching
-// to different netns. Unless we have to make sure the thread ID has to
-// stay the same, this function should be used by default.
-func doNetNS(netNSPath string, cb func(ns.NetNS) error) error {
- n, err := ns.GetNS(netNSPath)
- if err != nil {
- return err
- }
-
- return n.Do(cb)
-}
-
-// safeDoNetNS is free from any call to a go routine, meaning it will
-// not be executed in a different thread than the one expected by the
-// caller. This is used in case of CNM network, because we need to
-// make sure the process switched to the given netns has PID == TID.
-func safeDoNetNS(netNSPath string, cb func(ns.NetNS) error) error {
- currentNS, err := ns.GetCurrentNS()
- if err != nil {
- return err
- }
- defer currentNS.Close()
-
- targetNS, err := ns.GetNS(netNSPath)
- if err != nil {
- return err
- }
-
- if err := targetNS.Set(); err != nil {
- return err
- }
- defer currentNS.Set()
-
- return cb(targetNS)
-}
-
-func deleteNetNS(netNSPath string, mounted bool) error {
- n, err := ns.GetNS(netNSPath)
- if err != nil {
- return err
- }
-
- err = n.Close()
- if err != nil {
- return err
- }
-
- // This unmount part is supposed to be done in the cni/ns package, but the "mounted"
- // flag is not updated when retrieving NetNs handler from GetNS().
- if mounted {
- if err = unix.Unmount(netNSPath, unix.MNT_DETACH); err != nil {
- return fmt.Errorf("Failed to unmount namespace %s: %v", netNSPath, err)
- }
- if err := os.RemoveAll(netNSPath); err != nil {
- return fmt.Errorf("Failed to clean up namespace %s: %v", netNSPath, err)
- }
- }
-
- return nil
-}
-
-func createNetworkEndpoint(idx int, uniqueID string, ifName string) (Endpoint, error) {
- if idx < 0 {
- return Endpoint{}, fmt.Errorf("invalid network endpoint index: %d", idx)
- }
- if uniqueID == "" {
- return Endpoint{}, errors.New("uniqueID cannot be blank")
- }
-
- hardAddr := net.HardwareAddr{0x02, 0x00, 0xCA, 0xFE, byte(idx >> 8), byte(idx)}
-
- endpoint := Endpoint{
- NetPair: NetworkInterfacePair{
- ID: fmt.Sprintf("%s-%d", uniqueID, idx),
- Name: fmt.Sprintf("br%d", idx),
- VirtIface: NetworkInterface{
- Name: fmt.Sprintf("eth%d", idx),
- HardAddr: hardAddr.String(),
- },
- TAPIface: NetworkInterface{
- Name: fmt.Sprintf("tap%d", idx),
- },
- },
- }
-
- if ifName != "" {
- endpoint.NetPair.VirtIface.Name = ifName
- }
-
- return endpoint, nil
-}
-
-func createNetworkEndpoints(numOfEndpoints int) (endpoints []Endpoint, err error) {
- if numOfEndpoints < 1 {
- return endpoints, fmt.Errorf("Invalid number of network endpoints")
- }
-
- uniqueID := uuid.Generate().String()
-
- for i := 0; i < numOfEndpoints; i++ {
- endpoint, err := createNetworkEndpoint(i, uniqueID, "")
- if err != nil {
- return nil, err
- }
- endpoints = append(endpoints, endpoint)
- }
-
- return endpoints, nil
-}
-
-func getIfacesFromNetNs(networkNSPath string) ([]netIfaceAddrs, error) {
- var netIfaces []netIfaceAddrs
-
- if networkNSPath == "" {
- return []netIfaceAddrs{}, fmt.Errorf("Network namespace path cannot be empty")
- }
-
- err := doNetNS(networkNSPath, func(_ ns.NetNS) error {
- ifaces, err := net.Interfaces()
- if err != nil {
- return err
- }
-
- for _, iface := range ifaces {
- addrs, err := iface.Addrs()
- if err != nil {
- return err
- }
-
- netIface := netIfaceAddrs{
- iface: iface,
- addrs: addrs,
- }
-
- netIfaces = append(netIfaces, netIface)
- }
-
- return nil
- })
- if err != nil {
- return []netIfaceAddrs{}, err
- }
-
- return netIfaces, nil
-}
-
-func getNetIfaceByName(name string, netIfaces []netIfaceAddrs) (net.Interface, error) {
- for _, netIface := range netIfaces {
- if netIface.iface.Name == name {
- return netIface.iface, nil
- }
- }
-
- return net.Interface{}, fmt.Errorf("Could not find the interface %s in the list", name)
-}
-
-func addNetDevHypervisor(pod Pod, endpoints []Endpoint) error {
- return pod.hypervisor.addDevice(endpoints, netDev)
-}
-
-// network is the virtcontainers network interface.
-// Container network plugins are used to setup virtual network
-// between VM netns and the host network physical interface.
-type network interface {
- // init initializes the network, setting a new network namespace.
- init(config *NetworkConfig) error
-
- // run runs a callback function in a specified network namespace.
- run(networkNSPath string, cb func() error) error
-
- // add adds all needed interfaces inside the network namespace.
- add(pod Pod, config NetworkConfig) (NetworkNamespace, error)
-
- // remove unbridges and deletes TAP interfaces. It also removes virtual network
- // interfaces and deletes the network namespace.
- remove(pod Pod, networkNS NetworkNamespace) error
-}
diff --git a/vendor/github.com/containers/virtcontainers/network_test.go b/vendor/github.com/containers/virtcontainers/network_test.go
deleted file mode 100644
index 5298da1..0000000
--- a/vendor/github.com/containers/virtcontainers/network_test.go
+++ /dev/null
@@ -1,362 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "net"
- "os"
- "reflect"
- "testing"
-
- "github.com/containernetworking/cni/pkg/ns"
- "github.com/vishvananda/netlink"
- "github.com/vishvananda/netns"
-)
-
-func testNetworkModelSet(t *testing.T, value string, expected NetworkModel) {
- var netModel NetworkModel
-
- err := netModel.Set(value)
- if err != nil {
- t.Fatal(err)
- }
-
- if netModel != expected {
- t.Fatal()
- }
-}
-
-func TestNoopNetworkModelSet(t *testing.T) {
- testNetworkModelSet(t, "noop", NoopNetworkModel)
-}
-
-func TestCNINetworkModelSet(t *testing.T) {
- testNetworkModelSet(t, "CNI", CNINetworkModel)
-}
-
-func TestCNMNetworkModelSet(t *testing.T) {
- testNetworkModelSet(t, "CNM", CNMNetworkModel)
-}
-
-func TestNetworkModelSetFailure(t *testing.T) {
- var netModel NetworkModel
-
- err := netModel.Set("wrong-value")
- if err == nil {
- t.Fatal(err)
- }
-}
-
-func testNetworkModelString(t *testing.T, netModel *NetworkModel, expected string) {
- result := netModel.String()
-
- if result != expected {
- t.Fatal()
- }
-}
-
-func TestNoopNetworkModelString(t *testing.T) {
- netModel := NoopNetworkModel
- testNetworkModelString(t, &netModel, string(NoopNetworkModel))
-}
-
-func TestCNINetworkModelString(t *testing.T) {
- netModel := CNINetworkModel
- testNetworkModelString(t, &netModel, string(CNINetworkModel))
-}
-
-func TestCNMNetworkModelString(t *testing.T) {
- netModel := CNMNetworkModel
- testNetworkModelString(t, &netModel, string(CNMNetworkModel))
-}
-
-func TestWrongNetworkModelString(t *testing.T) {
- var netModel NetworkModel
- testNetworkModelString(t, &netModel, "")
-}
-
-func testNewNetworkFromNetworkModel(t *testing.T, netModel NetworkModel, expected interface{}) {
- result := newNetwork(netModel)
-
- if reflect.DeepEqual(result, expected) == false {
- t.Fatal()
- }
-}
-
-func TestNewNoopNetworkFromNetworkModel(t *testing.T) {
- testNewNetworkFromNetworkModel(t, NoopNetworkModel, &noopNetwork{})
-}
-
-func TestNewCNINetworkFromNetworkModel(t *testing.T) {
- testNewNetworkFromNetworkModel(t, CNINetworkModel, &cni{})
-}
-
-func TestNewCNMNetworkFromNetworkModel(t *testing.T) {
- testNewNetworkFromNetworkModel(t, CNMNetworkModel, &cnm{})
-}
-
-func TestNewUnknownNetworkFromNetworkModel(t *testing.T) {
- var netModel NetworkModel
- testNewNetworkFromNetworkModel(t, netModel, &noopNetwork{})
-}
-
-func TestCreateDeleteNetNS(t *testing.T) {
- if os.Geteuid() != 0 {
- t.Skip(testDisabledAsNonRoot)
- }
-
- netNSPath, err := createNetNS()
- if err != nil {
- t.Fatal(err)
- }
-
- if netNSPath == "" {
- t.Fatal()
- }
-
- _, err = os.Stat(netNSPath)
- if err != nil {
- t.Fatal(err)
- }
-
- err = deleteNetNS(netNSPath, true)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestCreateNetworkEndpoint(t *testing.T) {
- macAddr := net.HardwareAddr{0x02, 0x00, 0xCA, 0xFE, 0x00, 0x04}
-
- expected := Endpoint{
- NetPair: NetworkInterfacePair{
- ID: "uniqueTestID-4",
- Name: "br4",
- VirtIface: NetworkInterface{
- Name: "eth4",
- HardAddr: macAddr.String(),
- },
- TAPIface: NetworkInterface{
- Name: "tap4",
- },
- },
- }
-
- result, err := createNetworkEndpoint(4, "uniqueTestID", "")
- if err != nil {
- t.Fatal(err)
- }
-
- if reflect.DeepEqual(result, expected) == false {
- t.Fatal()
- }
-}
-
-func TestCreateNetworkEndpointChooseIfaceName(t *testing.T) {
- macAddr := net.HardwareAddr{0x02, 0x00, 0xCA, 0xFE, 0x00, 0x04}
-
- expected := Endpoint{
- NetPair: NetworkInterfacePair{
- ID: "uniqueTestID-4",
- Name: "br4",
- VirtIface: NetworkInterface{
- Name: "eth1",
- HardAddr: macAddr.String(),
- },
- TAPIface: NetworkInterface{
- Name: "tap4",
- },
- },
- }
-
- result, err := createNetworkEndpoint(4, "uniqueTestID", "eth1")
- if err != nil {
- t.Fatal(err)
- }
-
- if reflect.DeepEqual(result, expected) == false {
- t.Fatal()
- }
-}
-
-func TestCreateNetworkEndpointInvalidArgs(t *testing.T) {
- type endpointValues struct {
- idx int
- uniqueID string
- ifName string
- }
-
- // all elements are expected to result in failure
- failingValues := []endpointValues{
- {-1, "foo", "bar"},
- {-1, "foo", ""},
- {-3, "foo", "bar"},
- {-3, "foo", ""},
- {0, "", "bar"},
- {0, "", ""},
- {1, "", "bar"},
- {1, "", ""},
- }
-
- for _, d := range failingValues {
- result, err := createNetworkEndpoint(d.idx, d.uniqueID, d.ifName)
- if err == nil {
- t.Fatalf("expected invalid endpoint for %v, got %v", d, result)
- }
- }
-}
-
-func TestCreateNetworkEndpoints(t *testing.T) {
- numOfEndpoints := 3
-
- endpoints, err := createNetworkEndpoints(numOfEndpoints)
- if err != nil {
- t.Fatal(err)
- }
-
- if len(endpoints) != numOfEndpoints {
- t.Fatal()
- }
-}
-
-func TestCreateNetworkEndpointsFailure(t *testing.T) {
- numOfEndpoints := 0
-
- _, err := createNetworkEndpoints(numOfEndpoints)
- if err == nil {
- t.Fatalf("Should fail because %d endpoints is invalid",
- numOfEndpoints)
- }
-}
-
-func TestGetIfacesFromNetNsFailureEmptyNetNsPath(t *testing.T) {
- if _, err := getIfacesFromNetNs(""); err == nil {
- t.Fatal("Should fail because network namespace is empty")
- }
-}
-
-func testGetIfacesFromNetNsSuccessful(t *testing.T, link netlink.Link, expected []netIfaceAddrs) {
- lAttrs := link.Attrs()
-
- n, err := ns.NewNS()
- if err != nil {
- t.Fatal(err)
- }
- defer n.Close()
-
- netnsHandle, err := netns.GetFromPath(n.Path())
- if err != nil {
- t.Fatal(err)
- }
- defer netnsHandle.Close()
-
- netlinkHandle, err := netlink.NewHandleAt(netnsHandle)
- if err != nil {
- t.Fatal(err)
- }
- defer netlinkHandle.Delete()
-
- if err := netlinkHandle.LinkAdd(link); err != nil {
- t.Fatal(err)
- }
-
- if err := netlinkHandle.LinkSetHardwareAddr(link, lAttrs.HardwareAddr); err != nil {
- t.Fatal(err)
- }
-
- result, err := getIfacesFromNetNs(n.Path())
- if err != nil {
- t.Fatal(err)
- }
-
- if reflect.DeepEqual(result, expected) == false {
- t.Fatalf("Got %+v\nExpecting %+v", result, expected)
- }
-}
-
-func TestGetIfacesFromNetNsSuccessfulBridge(t *testing.T) {
- testNetIface := "testIface0"
- testMTU := 1500
- testMACAddr := "00:00:00:00:00:01"
-
- hwAddr, err := net.ParseMAC(testMACAddr)
- if err != nil {
- t.Fatal(err)
- }
-
- link := &netlink.Bridge{
- LinkAttrs: netlink.LinkAttrs{
- Name: testNetIface,
- MTU: testMTU,
- HardwareAddr: hwAddr,
- TxQLen: -1,
- },
- }
-
- expected := []netIfaceAddrs{
- {
- iface: net.Interface{
- Index: 1,
- MTU: 65536,
- Name: "lo",
- Flags: net.FlagLoopback,
- },
- },
- {
- iface: net.Interface{
- Index: 2,
- MTU: testMTU,
- Name: testNetIface,
- HardwareAddr: hwAddr,
- Flags: net.FlagBroadcast | net.FlagMulticast,
- },
- },
- }
-
- testGetIfacesFromNetNsSuccessful(t, link, expected)
-}
-
-func TestGetNetIfaceByNameFailureEmptyList(t *testing.T) {
- if _, err := getNetIfaceByName("testIface", []netIfaceAddrs{}); err == nil {
- t.Fatal("Should fail because network interface list is empty")
- }
-}
-
-func TestGetNetIfaceByNameSuccessful(t *testing.T) {
- testIfaceName := "testIfaceName"
-
- expected := net.Interface{
- Name: testIfaceName,
- }
-
- netIfaces := []netIfaceAddrs{
- {
- iface: net.Interface{
- Name: testIfaceName,
- },
- },
- }
-
- result, err := getNetIfaceByName(testIfaceName, netIfaces)
- if err != nil {
- t.Fatal(err)
- }
-
- if reflect.DeepEqual(result, expected) == false {
- t.Fatalf("Got %+v\nExpecting %+v", result, expected)
- }
-}
diff --git a/vendor/github.com/containers/virtcontainers/noop_agent.go b/vendor/github.com/containers/virtcontainers/noop_agent.go
deleted file mode 100644
index 2d2ec64..0000000
--- a/vendor/github.com/containers/virtcontainers/noop_agent.go
+++ /dev/null
@@ -1,66 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "syscall"
-)
-
-// noopAgent a.k.a. NO-OP Agent is an empty Agent implementation, for testing and
-// mocking purposes.
-type noopAgent struct {
-}
-
-// init initializes the Noop agent, i.e. it does nothing.
-func (n *noopAgent) init(pod *Pod, config interface{}) error {
- return nil
-}
-
-// exec is the Noop agent command execution implementation. It does nothing.
-func (n *noopAgent) exec(pod *Pod, c Container, process Process, cmd Cmd) error {
- return nil
-}
-
-// startPod is the Noop agent Pod starting implementation. It does nothing.
-func (n *noopAgent) startPod(pod Pod) error {
- return nil
-}
-
-// stopPod is the Noop agent Pod stopping implementation. It does nothing.
-func (n *noopAgent) stopPod(pod Pod) error {
- return nil
-}
-
-// createContainer is the Noop agent Container creation implementation. It does nothing.
-func (n *noopAgent) createContainer(pod *Pod, c *Container) error {
- return nil
-}
-
-// startContainer is the Noop agent Container starting implementation. It does nothing.
-func (n *noopAgent) startContainer(pod Pod, c Container) error {
- return nil
-}
-
-// stopContainer is the Noop agent Container stopping implementation. It does nothing.
-func (n *noopAgent) stopContainer(pod Pod, c Container) error {
- return nil
-}
-
-// killContainer is the Noop agent Container signaling implementation. It does nothing.
-func (n *noopAgent) killContainer(pod Pod, c Container, signal syscall.Signal) error {
- return nil
-}
diff --git a/vendor/github.com/containers/virtcontainers/noop_agent_test.go b/vendor/github.com/containers/virtcontainers/noop_agent_test.go
deleted file mode 100644
index 0d680e5..0000000
--- a/vendor/github.com/containers/virtcontainers/noop_agent_test.go
+++ /dev/null
@@ -1,96 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "testing"
-)
-
-func TestNoopAgentInit(t *testing.T) {
- n := &noopAgent{}
- pod := &Pod{}
-
- err := n.init(pod, nil)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestNoopAgentExec(t *testing.T) {
- n := &noopAgent{}
- pod := &Pod{}
- container := Container{}
- process := Process{}
- cmd := Cmd{}
-
- if err := n.exec(pod, container, process, cmd); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestNoopAgentStartPod(t *testing.T) {
- n := &noopAgent{}
- pod := Pod{}
-
- err := n.startPod(pod)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestNoopAgentStopPod(t *testing.T) {
- n := &noopAgent{}
- pod := Pod{}
-
- err := n.stopPod(pod)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestNoopAgentCreateContainer(t *testing.T) {
- n := &noopAgent{}
- pod := &Pod{}
- container := &Container{}
-
- err := n.createContainer(pod, container)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestNoopAgentStartContainer(t *testing.T) {
- n := &noopAgent{}
- pod := Pod{}
- container := Container{}
-
- err := n.startContainer(pod, container)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestNoopAgentStopContainer(t *testing.T) {
- n := &noopAgent{}
- pod := Pod{}
- container := Container{}
-
- err := n.stopContainer(pod, container)
- if err != nil {
- t.Fatal(err)
- }
-}
diff --git a/vendor/github.com/containers/virtcontainers/noop_network.go b/vendor/github.com/containers/virtcontainers/noop_network.go
deleted file mode 100644
index 250fa8b..0000000
--- a/vendor/github.com/containers/virtcontainers/noop_network.go
+++ /dev/null
@@ -1,48 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-// noopNetwork a.k.a. NO-OP Network is an empty network implementation, for
-// testing and mocking purposes.
-type noopNetwork struct {
-}
-
-// init initializes the network, setting a new network namespace for the Noop network.
-// It does nothing.
-func (n *noopNetwork) init(config *NetworkConfig) error {
- return nil
-}
-
-// run runs a callback in the specified network namespace for
-// the Noop network.
-// It does nothing.
-func (n *noopNetwork) run(networkNSPath string, cb func() error) error {
- return cb()
-}
-
-// add adds all needed interfaces inside the network namespace the Noop network.
-// It does nothing.
-func (n *noopNetwork) add(pod Pod, config NetworkConfig) (NetworkNamespace, error) {
- return NetworkNamespace{}, nil
-}
-
-// remove unbridges and deletes TAP interfaces. It also removes virtual network
-// interfaces and deletes the network namespace for the Noop network.
-// It does nothing.
-func (n *noopNetwork) remove(pod Pod, networkNS NetworkNamespace) error {
- return nil
-}
diff --git a/vendor/github.com/containers/virtcontainers/noop_proxy.go b/vendor/github.com/containers/virtcontainers/noop_proxy.go
deleted file mode 100644
index d9c790f..0000000
--- a/vendor/github.com/containers/virtcontainers/noop_proxy.go
+++ /dev/null
@@ -1,59 +0,0 @@
-//
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-type noopProxy struct{}
-
-var noopProxyURL = "noopProxyURL"
-
-// register is the proxy register implementation for testing purpose.
-// It does nothing.
-func (p *noopProxy) register(pod Pod) ([]ProxyInfo, string, error) {
- var proxyInfos []ProxyInfo
-
- for i := 0; i < len(pod.containers); i++ {
- proxyInfo := ProxyInfo{}
-
- proxyInfos = append(proxyInfos, proxyInfo)
- }
-
- return proxyInfos, noopProxyURL, nil
-}
-
-// unregister is the proxy unregister implementation for testing purpose.
-// It does nothing.
-func (p *noopProxy) unregister(pod Pod) error {
- return nil
-}
-
-// connect is the proxy connect implementation for testing purpose.
-// It does nothing.
-func (p *noopProxy) connect(pod Pod, createToken bool) (ProxyInfo, string, error) {
- return ProxyInfo{}, noopProxyURL, nil
-}
-
-// disconnect is the proxy disconnect implementation for testing purpose.
-// It does nothing.
-func (p *noopProxy) disconnect() error {
- return nil
-}
-
-// sendCmd is the proxy sendCmd implementation for testing purpose.
-// It does nothing.
-func (p *noopProxy) sendCmd(cmd interface{}) (interface{}, error) {
- return nil, nil
-}
diff --git a/vendor/github.com/containers/virtcontainers/noop_shim.go b/vendor/github.com/containers/virtcontainers/noop_shim.go
deleted file mode 100644
index 432e994..0000000
--- a/vendor/github.com/containers/virtcontainers/noop_shim.go
+++ /dev/null
@@ -1,25 +0,0 @@
-//
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-type noopShim struct{}
-
-// start is the noopShim start implementation for testing purpose.
-// It does nothing.
-func (s *noopShim) start(pod Pod, params ShimParams) (int, error) {
- return 0, nil
-}
diff --git a/vendor/github.com/containers/virtcontainers/noop_shim_test.go b/vendor/github.com/containers/virtcontainers/noop_shim_test.go
deleted file mode 100644
index 5742902..0000000
--- a/vendor/github.com/containers/virtcontainers/noop_shim_test.go
+++ /dev/null
@@ -1,37 +0,0 @@
-//
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "testing"
-)
-
-func TestNoopShimStart(t *testing.T) {
- s := &noopShim{}
- pod := Pod{}
- params := ShimParams{}
- expected := 0
-
- pid, err := s.start(pod, params)
- if err != nil {
- t.Fatal(err)
- }
-
- if pid != expected {
- t.Fatalf("PID should be %d", expected)
- }
-}
diff --git a/vendor/github.com/containers/virtcontainers/nsenter.go b/vendor/github.com/containers/virtcontainers/nsenter.go
deleted file mode 100644
index 9c9f648..0000000
--- a/vendor/github.com/containers/virtcontainers/nsenter.go
+++ /dev/null
@@ -1,40 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-// nsenter is a spawner implementation for the nsenter util-linux command.
-type nsenter struct {
- ContConfig ContainerConfig
-}
-
-const (
- // NsenterCmd is the command used to start nsenter.
- nsenterCmd = "nsenter"
-)
-
-// formatArgs is the spawner command formatting implementation for nsenter.
-func (n *nsenter) formatArgs(args []string) ([]string, error) {
- var newArgs []string
- pid := "-1"
-
- // TODO: Retrieve container PID from container ID
-
- newArgs = append(newArgs, nsenterCmd+" --target "+pid+" --mount --uts --ipc --net --pid")
- newArgs = append(newArgs, args...)
-
- return newArgs, nil
-}
diff --git a/vendor/github.com/containers/virtcontainers/nsenter_test.go b/vendor/github.com/containers/virtcontainers/nsenter_test.go
deleted file mode 100644
index 6061dc7..0000000
--- a/vendor/github.com/containers/virtcontainers/nsenter_test.go
+++ /dev/null
@@ -1,43 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "strings"
- "testing"
-)
-
-func testNsEnterFormatArgs(t *testing.T, args []string, expected string) {
- nsenter := &nsenter{}
-
- cmd, err := nsenter.formatArgs(args)
- if err != nil {
- t.Fatal(err)
- }
-
- if strings.Join(cmd, " ") != expected {
- t.Fatal()
- }
-}
-
-func TestNsEnterFormatArgsHello(t *testing.T) {
- expectedCmd := "nsenter --target -1 --mount --uts --ipc --net --pid echo hello"
-
- args := []string{"echo", "hello"}
-
- testNsEnterFormatArgs(t, args, expectedCmd)
-}
diff --git a/vendor/github.com/containers/virtcontainers/pkg/hyperstart/hyperstart.go b/vendor/github.com/containers/virtcontainers/pkg/hyperstart/hyperstart.go
deleted file mode 100644
index e3cea47..0000000
--- a/vendor/github.com/containers/virtcontainers/pkg/hyperstart/hyperstart.go
+++ /dev/null
@@ -1,543 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package hyperstart
-
-import (
- "encoding/binary"
- "encoding/json"
- "fmt"
- "math"
- "net"
- "sync"
- "time"
-
- "github.com/Sirupsen/logrus"
-)
-
-// Control command IDs
-// Need to be in sync with hyperstart/src/api.h
-const (
- Version = "version"
- StartPod = "startpod"
- DestroyPod = "destroypod"
- ExecCmd = "execcmd"
- Ready = "ready"
- Ack = "ack"
- Error = "error"
- WinSize = "winsize"
- Ping = "ping"
- FinishPod = "finishpod"
- Next = "next"
- WriteFile = "writefile"
- ReadFile = "readfile"
- NewContainer = "newcontainer"
- KillContainer = "killcontainer"
- OnlineCPUMem = "onlinecpumem"
- SetupInterface = "setupinterface"
- SetupRoute = "setuproute"
- RemoveContainer = "removecontainer"
-)
-
-// CodeList is the map making the relation between a string command
-// and its corresponding code.
-var CodeList = map[string]uint32{
- Version: VersionCode,
- StartPod: StartPodCode,
- DestroyPod: DestroyPodCode,
- ExecCmd: ExecCmdCode,
- Ready: ReadyCode,
- Ack: AckCode,
- Error: ErrorCode,
- WinSize: WinsizeCode,
- Ping: PingCode,
- Next: NextCode,
- WriteFile: WriteFileCode,
- ReadFile: ReadFileCode,
- NewContainer: NewContainerCode,
- KillContainer: KillContainerCode,
- OnlineCPUMem: OnlineCPUMemCode,
- SetupInterface: SetupInterfaceCode,
- SetupRoute: SetupRouteCode,
- RemoveContainer: RemoveContainerCode,
-}
-
-// Values related to the communication on control channel.
-const (
- CtlHdrSize = 8
- CtlHdrLenOffset = 4
-)
-
-// Values related to the communication on tty channel.
-const (
- TtyHdrSize = 12
- TtyHdrLenOffset = 8
-)
-
-type connState struct {
- sync.Mutex
- opened bool
-}
-
-func (c *connState) close() {
- c.Lock()
- defer c.Unlock()
-
- c.opened = false
-}
-
-func (c *connState) open() {
- c.Lock()
- defer c.Unlock()
-
- c.opened = true
-}
-
-func (c *connState) closed() bool {
- c.Lock()
- defer c.Unlock()
-
- return !c.opened
-}
-
-// Hyperstart is the base structure for hyperstart.
-type Hyperstart struct {
- ctlSerial, ioSerial string
- sockType string
- ctl, io net.Conn
- ctlState, ioState connState
-
- // ctl access is arbitrated by ctlMutex. We can only allow a single
- // "transaction" (write command + read answer) at a time
- ctlMutex sync.Mutex
-
- ctlMulticast *multicast
-
- ctlChDone chan interface{}
-}
-
-var hyperLog = logrus.New()
-
-// SetLog sets the logger for hyperstart package.
-func SetLog(logger *logrus.Logger) {
- hyperLog = logger
-}
-
-// NewHyperstart returns a new hyperstart structure.
-func NewHyperstart(ctlSerial, ioSerial, sockType string) *Hyperstart {
- return &Hyperstart{
- ctlSerial: ctlSerial,
- ioSerial: ioSerial,
- sockType: sockType,
- }
-}
-
-// GetCtlSock returns the internal CTL sock.
-func (h *Hyperstart) GetCtlSock() net.Conn {
- return h.ctl
-}
-
-// GetIoSock returns the internal IO sock.
-func (h *Hyperstart) GetIoSock() net.Conn {
- return h.io
-}
-
-// GetCtlSockPath returns the internal CTL sock path.
-func (h *Hyperstart) GetCtlSockPath() string {
- return h.ctlSerial
-}
-
-// GetIoSockPath returns the internal IO sock path.
-func (h *Hyperstart) GetIoSockPath() string {
- return h.ioSerial
-}
-
-// GetSockType returns the internal sock type.
-func (h *Hyperstart) GetSockType() string {
- return h.sockType
-}
-
-// OpenSocketsNoMulticast opens both CTL and IO sockets, without
-// starting the multicast.
-func (h *Hyperstart) OpenSocketsNoMulticast() error {
- var err error
-
- h.ctl, err = net.Dial(h.sockType, h.ctlSerial)
- if err != nil {
- return err
- }
- h.ctlState.open()
-
- h.io, err = net.Dial(h.sockType, h.ioSerial)
- if err != nil {
- h.ctl.Close()
- return err
- }
- h.ioState.open()
-
- return nil
-}
-
-// OpenSockets opens both CTL and IO sockets.
-func (h *Hyperstart) OpenSockets() error {
- if err := h.OpenSocketsNoMulticast(); err != nil {
- return err
- }
-
- h.ctlChDone = make(chan interface{})
- h.ctlMulticast = startCtlMonitor(h.ctl, h.ctlChDone)
-
- return nil
-}
-
-// CloseSockets closes both CTL and IO sockets.
-func (h *Hyperstart) CloseSockets() error {
- if !h.ctlState.closed() {
- if h.ctlChDone != nil {
- // Wait for the CTL channel to be terminated.
- select {
- case <-h.ctlChDone:
- break
- case <-time.After(time.Duration(3) * time.Second):
- return fmt.Errorf("CTL channel did not end as expected")
- }
- }
-
- err := h.ctl.Close()
- if err != nil {
- return err
- }
-
- h.ctlState.close()
- }
-
- if !h.ioState.closed() {
- err := h.io.Close()
- if err != nil {
- return err
- }
-
- h.ioState.close()
- }
-
- h.ctlMulticast = nil
-
- return nil
-}
-
-// SetDeadline sets a timeout for CTL connection.
-func (h *Hyperstart) SetDeadline(t time.Time) error {
- err := h.ctl.SetDeadline(t)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-// IsStarted returns about connection status.
-func (h *Hyperstart) IsStarted() bool {
- ret := false
- timeoutDuration := 1 * time.Second
-
- if h.ctlState.closed() {
- return ret
- }
-
- h.SetDeadline(time.Now().Add(timeoutDuration))
-
- _, err := h.SendCtlMessage(Ping, nil)
- if err == nil {
- ret = true
- }
-
- h.SetDeadline(time.Time{})
-
- if ret == false {
- h.CloseSockets()
- }
-
- return ret
-}
-
-// FormatMessage formats hyperstart messages.
-func FormatMessage(payload interface{}) ([]byte, error) {
- var payloadSlice []byte
- var err error
-
- if payload != nil {
- switch p := payload.(type) {
- case string:
- payloadSlice = []byte(p)
- default:
- payloadSlice, err = json.Marshal(p)
- if err != nil {
- return nil, err
- }
- }
- }
-
- return payloadSlice, nil
-}
-
-// ReadCtlMessage reads an hyperstart message from conn and returns a decoded message.
-//
-// This is a low level function, for a full and safe transaction on the
-// hyperstart control serial link, use SendCtlMessage.
-func ReadCtlMessage(conn net.Conn) (*DecodedMessage, error) {
- needRead := CtlHdrSize
- length := 0
- read := 0
- buf := make([]byte, 512)
- res := []byte{}
- for read < needRead {
- want := needRead - read
- if want > 512 {
- want = 512
- }
- nr, err := conn.Read(buf[:want])
- if err != nil {
- return nil, err
- }
-
- res = append(res, buf[:nr]...)
- read = read + nr
-
- if length == 0 && read >= CtlHdrSize {
- length = int(binary.BigEndian.Uint32(res[CtlHdrLenOffset:CtlHdrSize]))
- if length > CtlHdrSize {
- needRead = length
- }
- }
- }
-
- return &DecodedMessage{
- Code: binary.BigEndian.Uint32(res[:CtlHdrLenOffset]),
- Message: res[CtlHdrSize:],
- }, nil
-}
-
-// WriteCtlMessage writes an hyperstart message to conn.
-//
-// This is a low level function, for a full and safe transaction on the
-// hyperstart control serial link, use SendCtlMessage.
-func (h *Hyperstart) WriteCtlMessage(conn net.Conn, m *DecodedMessage) error {
- length := len(m.Message) + CtlHdrSize
- // XXX: Support sending messages by chunks to support messages over
- // 10240 bytes. That limit is from hyperstart src/init.c,
- // hyper_channel_ops, rbuf_size.
- if length > 10240 {
- return fmt.Errorf("message too long %d", length)
- }
- msg := make([]byte, length)
- binary.BigEndian.PutUint32(msg[:], uint32(m.Code))
- binary.BigEndian.PutUint32(msg[CtlHdrLenOffset:], uint32(length))
- copy(msg[CtlHdrSize:], m.Message)
-
- _, err := conn.Write(msg)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-// ReadIoMessageWithConn returns data coming from the specified IO channel.
-func ReadIoMessageWithConn(conn net.Conn) (*TtyMessage, error) {
- needRead := TtyHdrSize
- length := 0
- read := 0
- buf := make([]byte, 512)
- res := []byte{}
- for read < needRead {
- want := needRead - read
- if want > 512 {
- want = 512
- }
- nr, err := conn.Read(buf[:want])
- if err != nil {
- return nil, err
- }
-
- res = append(res, buf[:nr]...)
- read = read + nr
-
- if length == 0 && read >= TtyHdrSize {
- length = int(binary.BigEndian.Uint32(res[TtyHdrLenOffset:TtyHdrSize]))
- if length > TtyHdrSize {
- needRead = length
- }
- }
- }
-
- return &TtyMessage{
- Session: binary.BigEndian.Uint64(res[:TtyHdrLenOffset]),
- Message: res[TtyHdrSize:],
- }, nil
-}
-
-// ReadIoMessage returns data coming from the IO channel.
-func (h *Hyperstart) ReadIoMessage() (*TtyMessage, error) {
- return ReadIoMessageWithConn(h.io)
-}
-
-// SendIoMessageWithConn sends data to the specified IO channel.
-func SendIoMessageWithConn(conn net.Conn, ttyMsg *TtyMessage) error {
- length := len(ttyMsg.Message) + TtyHdrSize
- // XXX: Support sending messages by chunks to support messages over
- // 10240 bytes. That limit is from hyperstart src/init.c,
- // hyper_channel_ops, rbuf_size.
- if length > 10240 {
- return fmt.Errorf("message too long %d", length)
- }
- msg := make([]byte, length)
- binary.BigEndian.PutUint64(msg[:], ttyMsg.Session)
- binary.BigEndian.PutUint32(msg[TtyHdrLenOffset:], uint32(length))
- copy(msg[TtyHdrSize:], ttyMsg.Message)
-
- n, err := conn.Write(msg)
- if err != nil {
- return err
- }
-
- if n != length {
- return fmt.Errorf("%d bytes written out of %d expected", n, length)
- }
-
- return nil
-}
-
-// SendIoMessage sends data to the IO channel.
-func (h *Hyperstart) SendIoMessage(ttyMsg *TtyMessage) error {
- return SendIoMessageWithConn(h.io, ttyMsg)
-}
-
-// CodeFromCmd translates a string command to its corresponding code.
-func (h *Hyperstart) CodeFromCmd(cmd string) (uint32, error) {
- _, ok := CodeList[cmd]
- if ok == false {
- return math.MaxUint32, fmt.Errorf("unknown command '%s'", cmd)
- }
-
- return CodeList[cmd], nil
-}
-
-// CheckReturnedCode ensures we did not receive an ERROR code.
-func (h *Hyperstart) CheckReturnedCode(recvCode, expectedCode uint32) error {
- if recvCode != expectedCode {
- if recvCode == ErrorCode {
- return fmt.Errorf("ERROR received from Hyperstart")
- }
-
- return fmt.Errorf("CMD ID received %d not matching expected %d", recvCode, expectedCode)
- }
-
- return nil
-}
-
-// WaitForReady waits for a READY message on CTL channel.
-func (h *Hyperstart) WaitForReady() error {
- if h.ctlMulticast == nil {
- return fmt.Errorf("No multicast available for CTL channel")
- }
-
- channel, err := h.ctlMulticast.listen("", "", replyType)
- if err != nil {
- return err
- }
-
- msg := <-channel
-
- err = h.CheckReturnedCode(msg.Code, ReadyCode)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-// WaitForPAE waits for a PROCESSASYNCEVENT message on CTL channel.
-func (h *Hyperstart) WaitForPAE(containerID, processID string) (*PAECommand, error) {
- if h.ctlMulticast == nil {
- return nil, fmt.Errorf("No multicast available for CTL channel")
- }
-
- channel, err := h.ctlMulticast.listen(containerID, processID, eventType)
- if err != nil {
- return nil, err
- }
-
- msg := <-channel
-
- var paeData PAECommand
- err = json.Unmarshal(msg.Message, paeData)
- if err != nil {
- return nil, err
- }
-
- return &paeData, nil
-}
-
-// SendCtlMessage sends a message to the CTL channel.
-//
-// This function does a full transaction over the CTL channel: it will rely on the
-// multicaster to register a listener reading over the CTL channel. Then it writes
-// a command and waits for the multicaster to send hyperstart's answer back before
-// it can return.
-// Several concurrent calls to SendCtlMessage are allowed, the function ensuring
-// proper serialization of the communication by making the listener registration
-// and the command writing an atomic operation protected by a mutex.
-// Waiting for the reply from multicaster doesn't need to be protected by this mutex.
-func (h *Hyperstart) SendCtlMessage(cmd string, data []byte) (*DecodedMessage, error) {
- if h.ctlMulticast == nil {
- return nil, fmt.Errorf("No multicast available for CTL channel")
- }
-
- h.ctlMutex.Lock()
-
- channel, err := h.ctlMulticast.listen("", "", replyType)
- if err != nil {
- h.ctlMutex.Unlock()
- return nil, err
- }
-
- code, err := h.CodeFromCmd(cmd)
- if err != nil {
- h.ctlMutex.Unlock()
- return nil, err
- }
-
- msgSend := &DecodedMessage{
- Code: code,
- Message: data,
- }
- err = h.WriteCtlMessage(h.ctl, msgSend)
- if err != nil {
- h.ctlMutex.Unlock()
- return nil, err
- }
-
- h.ctlMutex.Unlock()
-
- msgRecv := <-channel
-
- err = h.CheckReturnedCode(msgRecv.Code, AckCode)
- if err != nil {
- return nil, err
- }
-
- return msgRecv, nil
-}
diff --git a/vendor/github.com/containers/virtcontainers/pkg/hyperstart/hyperstart_test.go b/vendor/github.com/containers/virtcontainers/pkg/hyperstart/hyperstart_test.go
deleted file mode 100644
index 06eabfe..0000000
--- a/vendor/github.com/containers/virtcontainers/pkg/hyperstart/hyperstart_test.go
+++ /dev/null
@@ -1,581 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package hyperstart_test
-
-import (
- "math"
- "net"
- "reflect"
- "testing"
- "time"
-
- . "github.com/containers/virtcontainers/pkg/hyperstart"
- "github.com/containers/virtcontainers/pkg/hyperstart/mock"
-)
-
-const (
- testSockType = "unix"
- testSequence = uint64(100)
- testMessage = "test_message"
-)
-
-func connectHyperstartNoMulticast(h *Hyperstart) error {
- return h.OpenSocketsNoMulticast()
-}
-
-func connectHyperstart(h *Hyperstart) error {
- return h.OpenSockets()
-}
-
-func disconnectHyperstart(h *Hyperstart) {
- h.CloseSockets()
-}
-
-func connectMockHyperstart(t *testing.T, multiCast bool) (*mock.Hyperstart, *Hyperstart, error) {
- mockHyper := mock.NewHyperstart(t)
-
- mockHyper.Start()
-
- ctlSock, ioSock := mockHyper.GetSocketPaths()
-
- h := NewHyperstart(ctlSock, ioSock, testSockType)
-
- var err error
- if multiCast {
- err = connectHyperstart(h)
- } else {
- err = connectHyperstartNoMulticast(h)
- }
- if err != nil {
- mockHyper.Stop()
- return nil, nil, err
- }
-
- return mockHyper, h, nil
-}
-
-func TestNewHyperstart(t *testing.T) {
- ctlSock := "/tmp/test_hyper.sock"
- ioSock := "/tmp/test_tty.sock"
- sockType := "test_unix"
-
- h := NewHyperstart(ctlSock, ioSock, sockType)
-
- resultCtlSockPath := h.GetCtlSockPath()
- resultIoSockPath := h.GetIoSockPath()
- resultSockType := h.GetSockType()
-
- if resultCtlSockPath != ctlSock {
- t.Fatalf("CTL sock result %s should be the same than %s", resultCtlSockPath, ctlSock)
- }
-
- if resultIoSockPath != ioSock {
- t.Fatalf("IO sock result %s should be the same than %s", resultIoSockPath, ioSock)
- }
-
- if resultSockType != sockType {
- t.Fatalf("Sock type result %s should be the same than %s", resultSockType, sockType)
- }
-}
-
-func TestOpenSockets(t *testing.T) {
- mockHyper := mock.NewHyperstart(t)
-
- mockHyper.Start()
-
- ctlSock, ioSock := mockHyper.GetSocketPaths()
-
- h := NewHyperstart(ctlSock, ioSock, testSockType)
-
- err := h.OpenSockets()
- if err != nil {
- mockHyper.Stop()
- t.Fatal()
- }
-
- mockHyper.Stop()
-
- disconnectHyperstart(h)
-}
-
-func TestCloseSockets(t *testing.T) {
- mockHyper, h, err := connectMockHyperstart(t, true)
- if err != nil {
- t.Fatal()
- }
-
- mockHyper.Stop()
-
- err = h.CloseSockets()
- if err != nil {
- t.Fatal()
- }
-}
-
-func TestSetDeadline(t *testing.T) {
- mockHyper, h, err := connectMockHyperstart(t, false)
- if err != nil {
- t.Fatal()
- }
- defer disconnectHyperstart(h)
- defer mockHyper.Stop()
-
- timeoutDuration := 1 * time.Second
-
- err = h.SetDeadline(time.Now().Add(timeoutDuration))
- if err != nil {
- t.Fatal()
- }
-
- mockHyper.SendMessage(ReadyCode, []byte{})
-
- buf := make([]byte, 512)
- _, err = h.GetCtlSock().Read(buf)
- if err != nil {
- t.Fatal()
- }
-
- err = h.SetDeadline(time.Now().Add(timeoutDuration))
- if err != nil {
- t.Fatal()
- }
-
- time.Sleep(timeoutDuration)
-
- _, err = h.GetCtlSock().Read(buf)
- netErr, ok := err.(net.Error)
- if ok && netErr.Timeout() == false {
- t.Fatal()
- }
-}
-
-func TestIsStartedFalse(t *testing.T) {
- h := &Hyperstart{}
-
- if h.IsStarted() == true {
- t.Fatal()
- }
-}
-
-func TestIsStartedTrue(t *testing.T) {
- mockHyper, h, err := connectMockHyperstart(t, true)
- if err != nil {
- t.Fatal()
- }
- defer disconnectHyperstart(h)
- defer mockHyper.Stop()
-
- if h.IsStarted() == false {
- t.Fatal()
- }
-}
-
-func testFormatMessage(t *testing.T, payload interface{}, expected []byte) {
- res, err := FormatMessage(payload)
- if err != nil {
- t.Fatal()
- }
-
- if reflect.DeepEqual(res, expected) == false {
- t.Fatal()
- }
-}
-
-func TestFormatMessageFromString(t *testing.T) {
- payload := testMessage
- expectedOut := []byte(payload)
-
- testFormatMessage(t, payload, expectedOut)
-}
-
-type TestStruct struct {
- FieldString string `json:"fieldString"`
- FieldInt int `json:"fieldInt"`
-}
-
-func TestFormatMessageFromStruct(t *testing.T) {
- payload := TestStruct{
- FieldString: "test_string",
- FieldInt: 100,
- }
-
- expectedOut := []byte("{\"fieldString\":\"test_string\",\"fieldInt\":100}")
-
- testFormatMessage(t, payload, expectedOut)
-}
-
-func TestReadCtlMessage(t *testing.T) {
- mockHyper, h, err := connectMockHyperstart(t, false)
- if err != nil {
- t.Fatal()
- }
- defer disconnectHyperstart(h)
- defer mockHyper.Stop()
-
- expected := &DecodedMessage{
- Code: ReadyCode,
- Message: []byte{},
- }
-
- mockHyper.SendMessage(int(expected.Code), expected.Message)
-
- reply, err := ReadCtlMessage(h.GetCtlSock())
- if err != nil {
- t.Fatal()
- }
-
- if reflect.DeepEqual(reply, expected) == false {
- t.Fatal()
- }
-}
-
-func TestWriteCtlMessage(t *testing.T) {
- mockHyper, h, err := connectMockHyperstart(t, false)
- if err != nil {
- t.Fatal()
- }
- defer disconnectHyperstart(h)
- defer mockHyper.Stop()
-
- msg := DecodedMessage{
- Code: PingCode,
- Message: []byte{},
- }
-
- err = h.WriteCtlMessage(h.GetCtlSock(), &msg)
- if err != nil {
- t.Fatal()
- }
-
- for {
- reply, err := ReadCtlMessage(h.GetCtlSock())
- if err != nil {
- t.Fatal()
- }
-
- if reply.Code == NextCode {
- continue
- }
-
- err = h.CheckReturnedCode(reply.Code, AckCode)
- if err != nil {
- t.Fatal()
- }
-
- break
- }
-
- msgs := mockHyper.GetLastMessages()
- if msgs == nil {
- t.Fatal()
- }
-
- if msgs[0].Code != msg.Code || string(msgs[0].Message) != string(msg.Message) {
- t.Fatal()
- }
-}
-
-func TestReadIoMessage(t *testing.T) {
- mockHyper, h, err := connectMockHyperstart(t, true)
- if err != nil {
- t.Fatal()
- }
- defer disconnectHyperstart(h)
- defer mockHyper.Stop()
-
- mockHyper.SendIo(testSequence, []byte(testMessage))
-
- msg, err := h.ReadIoMessage()
- if err != nil {
- t.Fatal()
- }
-
- if msg.Session != testSequence || string(msg.Message) != testMessage {
- t.Fatal()
- }
-}
-
-func TestReadIoMessageWithConn(t *testing.T) {
- mockHyper, h, err := connectMockHyperstart(t, true)
- if err != nil {
- t.Fatal()
- }
- defer disconnectHyperstart(h)
- defer mockHyper.Stop()
-
- mockHyper.SendIo(testSequence, []byte(testMessage))
-
- msg, err := ReadIoMessageWithConn(h.GetIoSock())
- if err != nil {
- t.Fatal()
- }
-
- if msg.Session != testSequence || string(msg.Message) != testMessage {
- t.Fatal()
- }
-}
-
-func TestSendIoMessage(t *testing.T) {
- mockHyper, h, err := connectMockHyperstart(t, true)
- if err != nil {
- t.Fatal()
- }
- defer disconnectHyperstart(h)
- defer mockHyper.Stop()
-
- msg := &TtyMessage{
- Session: testSequence,
- Message: []byte(testMessage),
- }
-
- err = h.SendIoMessage(msg)
- if err != nil {
- t.Fatal()
- }
-
- buf := make([]byte, 512)
- n, seqRecv := mockHyper.ReadIo(buf)
-
- if seqRecv != testSequence || string(buf[TtyHdrSize:n]) != testMessage {
- t.Fatal()
- }
-}
-
-func TestSendIoMessageWithConn(t *testing.T) {
- mockHyper, h, err := connectMockHyperstart(t, true)
- if err != nil {
- t.Fatal()
- }
- defer disconnectHyperstart(h)
- defer mockHyper.Stop()
-
- msg := &TtyMessage{
- Session: testSequence,
- Message: []byte(testMessage),
- }
-
- err = SendIoMessageWithConn(h.GetIoSock(), msg)
- if err != nil {
- t.Fatal()
- }
-
- buf := make([]byte, 512)
- n, seqRecv := mockHyper.ReadIo(buf)
-
- if seqRecv != testSequence || string(buf[TtyHdrSize:n]) != testMessage {
- t.Fatal()
- }
-}
-
-func testCodeFromCmd(t *testing.T, cmd string, expected uint32) {
- h := &Hyperstart{}
-
- code, err := h.CodeFromCmd(cmd)
- if err != nil || code != expected {
- t.Fatal()
- }
-}
-
-func TestCodeFromCmdVersion(t *testing.T) {
- testCodeFromCmd(t, Version, VersionCode)
-}
-
-func TestCodeFromCmdStartPod(t *testing.T) {
- testCodeFromCmd(t, StartPod, StartPodCode)
-}
-
-func TestCodeFromCmdDestroyPod(t *testing.T) {
- testCodeFromCmd(t, DestroyPod, DestroyPodCode)
-}
-
-func TestCodeFromCmdExecCmd(t *testing.T) {
- testCodeFromCmd(t, ExecCmd, ExecCmdCode)
-}
-
-func TestCodeFromCmdReady(t *testing.T) {
- testCodeFromCmd(t, Ready, ReadyCode)
-}
-
-func TestCodeFromCmdAck(t *testing.T) {
- testCodeFromCmd(t, Ack, AckCode)
-}
-
-func TestCodeFromCmdError(t *testing.T) {
- testCodeFromCmd(t, Error, ErrorCode)
-}
-
-func TestCodeFromCmdWinSize(t *testing.T) {
- testCodeFromCmd(t, WinSize, WinsizeCode)
-}
-
-func TestCodeFromCmdPing(t *testing.T) {
- testCodeFromCmd(t, Ping, PingCode)
-}
-
-func TestCodeFromCmdNext(t *testing.T) {
- testCodeFromCmd(t, Next, NextCode)
-}
-
-func TestCodeFromCmdWriteFile(t *testing.T) {
- testCodeFromCmd(t, WriteFile, WriteFileCode)
-}
-
-func TestCodeFromCmdReadFile(t *testing.T) {
- testCodeFromCmd(t, ReadFile, ReadFileCode)
-}
-
-func TestCodeFromCmdNewContainer(t *testing.T) {
- testCodeFromCmd(t, NewContainer, NewContainerCode)
-}
-
-func TestCodeFromCmdKillContainer(t *testing.T) {
- testCodeFromCmd(t, KillContainer, KillContainerCode)
-}
-
-func TestCodeFromCmdOnlineCPUMem(t *testing.T) {
- testCodeFromCmd(t, OnlineCPUMem, OnlineCPUMemCode)
-}
-
-func TestCodeFromCmdSetupInterface(t *testing.T) {
- testCodeFromCmd(t, SetupInterface, SetupInterfaceCode)
-}
-
-func TestCodeFromCmdSetupRoute(t *testing.T) {
- testCodeFromCmd(t, SetupRoute, SetupRouteCode)
-}
-
-func TestCodeFromCmdRemoveContainer(t *testing.T) {
- testCodeFromCmd(t, RemoveContainer, RemoveContainerCode)
-}
-
-func TestCodeFromCmdUnknown(t *testing.T) {
- h := &Hyperstart{}
-
- code, err := h.CodeFromCmd("unknown")
- if err == nil || code != math.MaxUint32 {
- t.Fatal()
- }
-}
-
-func testCheckReturnedCode(t *testing.T, code, refCode uint32) {
- h := &Hyperstart{}
-
- err := h.CheckReturnedCode(code, refCode)
- if err != nil {
- t.Fatal()
- }
-}
-
-func TestCheckReturnedCodeList(t *testing.T) {
- for _, code := range CodeList {
- testCheckReturnedCode(t, code, code)
- }
-}
-
-func testCheckReturnedCodeFailure(t *testing.T, code, refCode uint32) {
- h := &Hyperstart{}
-
- err := h.CheckReturnedCode(code, refCode)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestCheckReturnedCodeListWrong(t *testing.T) {
- for _, code := range CodeList {
- if code != ReadyCode {
- testCheckReturnedCodeFailure(t, code, ReadyCode)
- } else {
- testCheckReturnedCodeFailure(t, code, PingCode)
- }
- }
-}
-
-func TestWaitForReady(t *testing.T) {
- mockHyper, h, err := connectMockHyperstart(t, true)
- if err != nil {
- t.Fatal()
- }
- defer disconnectHyperstart(h)
- defer mockHyper.Stop()
-
- mockHyper.SendMessage(int(ReadyCode), []byte{})
-
- err = h.WaitForReady()
- if err != nil {
- t.Fatal()
- }
-}
-
-func TestWaitForReadyError(t *testing.T) {
- mockHyper, h, err := connectMockHyperstart(t, true)
- if err != nil {
- t.Fatal()
- }
- defer disconnectHyperstart(h)
- defer mockHyper.Stop()
-
- mockHyper.SendMessage(int(ErrorCode), []byte{})
-
- err = h.WaitForReady()
- if err == nil {
- t.Fatal()
- }
-}
-
-var cmdList = []string{
- Version,
- StartPod,
- DestroyPod,
- ExecCmd,
- Ready,
- Ack,
- Error,
- WinSize,
- Ping,
- Next,
- NewContainer,
- KillContainer,
- OnlineCPUMem,
- SetupInterface,
- SetupRoute,
- RemoveContainer,
-}
-
-func testSendCtlMessage(t *testing.T, cmd string) {
- mockHyper, h, err := connectMockHyperstart(t, true)
- if err != nil {
- t.Fatal()
- }
- defer disconnectHyperstart(h)
- defer mockHyper.Stop()
-
- msg, err := h.SendCtlMessage(cmd, []byte{})
- if err != nil {
- t.Fatal()
- }
-
- if msg.Code != AckCode {
- t.Fatal()
- }
-}
-
-func TestSendCtlMessage(t *testing.T) {
- for _, cmd := range cmdList {
- testSendCtlMessage(t, cmd)
- }
-}
diff --git a/vendor/github.com/containers/virtcontainers/pkg/hyperstart/mock/hyperstart.go b/vendor/github.com/containers/virtcontainers/pkg/hyperstart/mock/hyperstart.go
deleted file mode 100644
index d1dc8a3..0000000
--- a/vendor/github.com/containers/virtcontainers/pkg/hyperstart/mock/hyperstart.go
+++ /dev/null
@@ -1,408 +0,0 @@
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package mock
-
-import (
- "encoding/binary"
- "encoding/hex"
- "fmt"
- "net"
- "os"
- "path/filepath"
- "sync"
- "testing"
-
- hyper "github.com/containers/virtcontainers/pkg/hyperstart"
- "github.com/stretchr/testify/assert"
-)
-
-// Control command string IDs
-const (
- Version = "version"
- StartPod = "startpod"
- DestroyPod = "destroypod"
- ExecCmd = "execcmd"
- Ready = "ready"
- Ack = "ack"
- Error = "error"
- WinSize = "winsize"
- Ping = "ping"
- FinishPod = "finishpod"
- Next = "next"
- WriteFile = "writefile"
- ReadFile = "readfile"
- NewContainer = "newcontainer"
- KillContainer = "killcontainer"
- RemoveContainer = "removecontainer"
- OnlineCPUMem = "onlinecpumem"
- SetupInterface = "setupinterface"
- SetupRoute = "setuproute"
-)
-
-var codeList = map[int]string{
- hyper.VersionCode: Version,
- hyper.StartPodCode: StartPod,
- hyper.DestroyPodCode: DestroyPod,
- hyper.ExecCmdCode: ExecCmd,
- hyper.ReadyCode: Ready,
- hyper.AckCode: Ack,
- hyper.ErrorCode: Error,
- hyper.WinsizeCode: WinSize,
- hyper.PingCode: Ping,
- hyper.NextCode: Next,
- hyper.WriteFileCode: WriteFile,
- hyper.ReadFileCode: ReadFile,
- hyper.NewContainerCode: NewContainer,
- hyper.KillContainerCode: KillContainer,
- hyper.OnlineCPUMemCode: OnlineCPUMem,
- hyper.SetupInterfaceCode: SetupInterface,
- hyper.SetupRouteCode: SetupRoute,
- hyper.RemoveContainerCode: RemoveContainer,
-}
-
-// Hyperstart is an object mocking the hyperstart agent.
-type Hyperstart struct {
- t *testing.T
- ctlSocketPath, ioSocketPath string
- ctlListener, ioListener *net.UnixListener
- ctl, io net.Conn
-
- // Start() will launch two goroutines to accept connections on the ctl
- // and io sockets. Those goroutine will exit once the first connection
- // is accepted or when the listening socket is closed. wgConnected can
- // be used to make sure we've accepted connections to both sockets
- wgConnected sync.WaitGroup
-
- // We then have two other goroutines to handle communication on those
- // sockets.
- wg sync.WaitGroup
-
- // Keep the list of messages received by hyperstart, older first, for
- // later inspection with GetLastMessages()
- lastMessages []hyper.DecodedMessage
-}
-
-func newMessageList() []hyper.DecodedMessage {
- return make([]hyper.DecodedMessage, 0, 10)
-}
-
-// NewHyperstart creates a new hyperstart instance.
-func NewHyperstart(t *testing.T) *Hyperstart {
- dir := os.TempDir()
- ctlSocketPath := filepath.Join(dir, "mock.hyper."+nextSuffix()+".0.sock")
- ioSocketPath := filepath.Join(dir, "mock.hyper."+nextSuffix()+".1.sock")
-
- return &Hyperstart{
- t: t,
- ctlSocketPath: ctlSocketPath,
- ioSocketPath: ioSocketPath,
- lastMessages: newMessageList(),
- }
-}
-
-// GetSocketPaths returns the ctl and io socket paths, respectively
-func (h *Hyperstart) GetSocketPaths() (string, string) {
- return h.ctlSocketPath, h.ioSocketPath
-
-}
-
-// GetLastMessages returns list of messages received by hyperstart, older
-// first. This function only returns the messages:
-// - since Start on the first invocation
-// - since the last GetLastMessages for subsequent invocations
-func (h *Hyperstart) GetLastMessages() []hyper.DecodedMessage {
- msgs := h.lastMessages
- h.lastMessages = newMessageList()
- return msgs
-}
-
-func (h *Hyperstart) log(s string) {
- h.logf("%s\n", s)
-}
-
-func (h *Hyperstart) logf(format string, args ...interface{}) {
- h.t.Logf("[hyperstart] "+format, args...)
-}
-
-func (h *Hyperstart) logData(data []byte) {
- h.t.Log(hex.Dump(data))
-}
-
-//
-// ctl channel
-//
-
-const ctlHeaderSize = 8
-
-func (h *Hyperstart) writeCtl(data []byte) error {
- h.wgConnected.Wait()
-
- n, err := h.ctl.Write(data)
- if err != nil {
- return fmt.Errorf("Connection broken, cannot send data")
- }
- assert.Equal(h.t, n, len(data))
-
- return nil
-}
-
-// SendMessage makes hyperstart send the hyper command cmd along with optional
-// data on the control channel
-func (h *Hyperstart) SendMessage(cmd int, data []byte) {
- length := ctlHeaderSize + len(data)
- header := make([]byte, ctlHeaderSize)
-
- binary.BigEndian.PutUint32(header[:], uint32(cmd))
- binary.BigEndian.PutUint32(header[4:], uint32(length))
-
- err := h.writeCtl(header)
- if err != nil {
- return
- }
-
- if len(data) == 0 {
- return
- }
-
- h.writeCtl(data)
-}
-
-func (h *Hyperstart) readCtl(data []byte) error {
- h.wgConnected.Wait()
-
- n, err := h.ctl.Read(data)
-
- if err != nil {
- return err
- }
- assert.Equal(h.t, n, len(data))
- return nil
-}
-
-func (h *Hyperstart) ackData(nBytes int) {
- data := make([]byte, 4)
- binary.BigEndian.PutUint32(data[:], uint32(nBytes))
- h.SendMessage(hyper.NextCode, data)
-}
-
-func (h *Hyperstart) readMessage() (int, []byte, error) {
- buf := make([]byte, ctlHeaderSize)
- if err := h.readCtl(buf); err != nil {
- return -1, buf, err
- }
-
- h.ackData(len(buf))
-
- cmd := int(binary.BigEndian.Uint32(buf[:4]))
- length := int(binary.BigEndian.Uint32(buf[4:8]))
- assert.True(h.t, length >= 8)
- length -= 8
- if length == 0 {
- return cmd, nil, nil
- }
-
- data := make([]byte, length)
- if err := h.readCtl(data); err != nil {
- return -1, buf, err
- }
-
- h.ackData(len(data))
-
- return cmd, data, nil
-}
-
-func cmdToString(cmd int) (string, error) {
- _, ok := codeList[cmd]
- if ok == false {
- return "", fmt.Errorf("unknown command '%d'", cmd)
- }
-
- return codeList[cmd], nil
-}
-
-func (h *Hyperstart) handleCtl() {
- for {
- cmd, data, err := h.readMessage()
- if err != nil {
- break
- }
- cmdName, err := cmdToString(cmd)
- assert.Nil(h.t, err)
- h.logf("ctl: --> command %s, payload_len=%d\n", cmdName, len(data))
- if len(data) != 0 {
- h.logData(data)
- }
-
- h.lastMessages = append(h.lastMessages, hyper.DecodedMessage{
- Code: uint32(cmd),
- Message: data,
- })
-
- // answer back with the message exit status
- // XXX: may be interesting to be able to configure the mock
- // hyperstart to fail and test the reaction of proxy/clients
- h.logf("ctl: <-- command %s executed successfully\n", cmdName)
-
- h.SendMessage(hyper.AckCode, nil)
-
- }
-
- h.wg.Done()
-}
-
-//
-// io channel
-//
-
-const ioHeaderSize = 12
-
-func (h *Hyperstart) writeIo(data []byte) {
- h.wgConnected.Wait()
-
- n, err := h.io.Write(data)
- assert.Nil(h.t, err)
- assert.Equal(h.t, n, len(data))
-}
-
-// SendIo sends a packet of I/O data to a client connected the I/O channel.
-// Multiple I/O streams are multiplexed on that channel. seq specifies which
-// steam the data belongs to.
-func (h *Hyperstart) SendIo(seq uint64, data []byte) {
- length := ioHeaderSize + len(data)
- header := make([]byte, ioHeaderSize)
-
- h.logf("io: <-- writing %d bytes for seq %d\n", len(data), seq)
-
- binary.BigEndian.PutUint64(header[:], uint64(seq))
- binary.BigEndian.PutUint32(header[8:], uint32(length))
- h.writeIo(header)
-
- if len(data) == 0 {
- return
- }
-
- h.writeIo(data)
-}
-
-// SendIoString sends a string a client connected the I/O channel.
-// Multiple I/O streams are multiplexed on that channel. seq specifies which
-// steam the data belongs to.
-func (h *Hyperstart) SendIoString(seq uint64, data string) {
- h.SendIo(seq, []byte(data))
-}
-
-// CloseIo closes the I/O stream specified by seq.
-func (h *Hyperstart) CloseIo(seq uint64) {
- h.SendIo(seq, nil)
-}
-
-// SendExitStatus sends the exit status on the I/O streams specified by seq.
-// The exit status should only be sent after the stream has been closed with
-// CloseIo.
-func (h *Hyperstart) SendExitStatus(seq uint64, exitStatus uint8) {
- status := []byte{exitStatus}
- h.SendIo(seq, status)
-}
-
-// ReadIo reads data that has been sent on the I/O channel by a client. It
-// returns the full packet (header & data) as well as the seq number decoded
-// from the header.
-func (h *Hyperstart) ReadIo(buf []byte) (n int, seq uint64) {
- h.wgConnected.Wait()
-
- n, err := h.io.Read(buf)
- assert.Nil(h.t, err)
-
- seq = binary.BigEndian.Uint64(buf[:8])
- return
-}
-
-type acceptCb func(c net.Conn)
-
-func (h *Hyperstart) startListening(path string, cb acceptCb) *net.UnixListener {
-
- addr := &net.UnixAddr{Name: path, Net: "unix"}
- l, err := net.ListenUnix("unix", addr)
- assert.Nil(h.t, err)
-
- go func() {
- h.logf("%s: waiting for connection\n", path)
- c, err := l.Accept()
- if err != nil {
- cb(nil)
- return
- }
-
- cb(c)
- h.logf("%s: accepted connection\n", path)
- }()
-
- return l
-}
-
-// Start will
-// Once finished with the Hyperstart object, Close must be called.
-func (h *Hyperstart) Start() {
- h.log("start")
- h.wgConnected.Add(1)
- h.wgConnected.Add(1)
- h.ctlListener = h.startListening(h.ctlSocketPath, func(s net.Conn) {
- // a client is now connected to the ctl socket
- h.ctl = s
-
- // Close() was called before we had a chance to accept a
- // connection.
- if s == nil {
- h.wgConnected.Done()
- return
- }
-
- // start the goroutine that will handle the ctl socket
- h.wg.Add(1)
- go h.handleCtl()
-
- // we need signal wgConnected late, so wg.Add(1) is done before
- // the wg.Wait() in Close()
- // See https://golang.org/pkg/sync/#WaitGroup.Wait:
- // "Note that calls with a positive delta that occur when the
- // counter is zero must happen before a Wait"
- h.wgConnected.Done()
- })
-
- h.ioListener = h.startListening(h.ioSocketPath, func(s net.Conn) {
- // a client is now connected to the ctl socket
- h.io = s
- h.wgConnected.Done()
- })
-}
-
-// Stop closes all internal resources and waits for goroutines started by Start
-// to finish. Stop shouldn't be called if Start hasn't been called.
-func (h *Hyperstart) Stop() {
- h.wgConnected.Wait()
-
- h.ctl.Close()
- h.io.Close()
-
- h.ctlListener.Close()
- h.ioListener.Close()
-
- h.wg.Wait()
-
- os.Remove(h.ctlSocketPath)
- os.Remove(h.ioSocketPath)
-
- h.log("stopped")
-}
diff --git a/vendor/github.com/containers/virtcontainers/pkg/hyperstart/mock/misc.go b/vendor/github.com/containers/virtcontainers/pkg/hyperstart/mock/misc.go
deleted file mode 100644
index 26ef34d..0000000
--- a/vendor/github.com/containers/virtcontainers/pkg/hyperstart/mock/misc.go
+++ /dev/null
@@ -1,37 +0,0 @@
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package mock
-
-import (
- "fmt"
- "os"
- "path/filepath"
-)
-
-// GetTmpPath will return a filename suitable for a tempory file according to
-// the format string given in argument. The format string must contain a single
-// %s which will be replaced by a random string. Eg.:
-//
-// GetTmpPath("test.foo.%s.sock")
-//
-// will return something like:
-//
-// "/tmp/test.foo.832222621.sock"
-func GetTmpPath(format string) string {
- filename := fmt.Sprintf(format, nextSuffix())
- dir := os.TempDir()
- return filepath.Join(dir, filename)
-
-}
diff --git a/vendor/github.com/containers/virtcontainers/pkg/hyperstart/mock/rand.go b/vendor/github.com/containers/virtcontainers/pkg/hyperstart/mock/rand.go
deleted file mode 100644
index 29193b1..0000000
--- a/vendor/github.com/containers/virtcontainers/pkg/hyperstart/mock/rand.go
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package mock
-
-import (
- "os"
- "strconv"
- "sync"
- "time"
-)
-
-// Taken from https://golang.org/src/io/ioutil/tempfile.go?s=#L19
-var rand uint32
-var randmu sync.Mutex
-
-func reseed() uint32 {
- return uint32(time.Now().UnixNano() + int64(os.Getpid()))
-}
-
-func nextSuffix() string {
- randmu.Lock()
- r := rand
- if r == 0 {
- r = reseed()
- }
- r = r*1664525 + 1013904223 // constants from Numerical Recipes
- rand = r
- randmu.Unlock()
- return strconv.Itoa(int(1e9 + r%1e9))[1:]
-}
diff --git a/vendor/github.com/containers/virtcontainers/pkg/hyperstart/multicast.go b/vendor/github.com/containers/virtcontainers/pkg/hyperstart/multicast.go
deleted file mode 100644
index ddf1c30..0000000
--- a/vendor/github.com/containers/virtcontainers/pkg/hyperstart/multicast.go
+++ /dev/null
@@ -1,175 +0,0 @@
-//
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package hyperstart
-
-import (
- "encoding/json"
- "fmt"
- "net"
- "sync"
-)
-
-type ctlDataType string
-
-const (
- eventType ctlDataType = "ctlEvent"
- replyType ctlDataType = "ctlReply"
-)
-
-type multicast struct {
- bufReplies []*DecodedMessage
- reply []chan *DecodedMessage
- event map[string]chan *DecodedMessage
- ctl net.Conn
- sync.Mutex
-}
-
-func newMulticast(ctlConn net.Conn) *multicast {
- return &multicast{
- bufReplies: []*DecodedMessage{},
- reply: []chan *DecodedMessage{},
- event: make(map[string]chan *DecodedMessage),
- ctl: ctlConn,
- }
-}
-
-func startCtlMonitor(ctlConn net.Conn, done chan<- interface{}) *multicast {
- ctlMulticast := newMulticast(ctlConn)
-
- go func() {
- for {
- msg, err := ReadCtlMessage(ctlMulticast.ctl)
- if err != nil {
- hyperLog.Infof("Read on CTL channel ended: %s", err)
- break
- }
-
- err = ctlMulticast.write(msg)
- if err != nil {
- hyperLog.Errorf("Multicaster write error: %s", err)
- break
- }
- }
-
- close(done)
- }()
-
- return ctlMulticast
-}
-
-func (m *multicast) buildEventID(containerID, processID string) string {
- return fmt.Sprintf("%s-%s", containerID, processID)
-}
-
-func (m *multicast) sendEvent(msg *DecodedMessage) error {
- var paeData PAECommand
-
- err := json.Unmarshal(msg.Message, paeData)
- if err != nil {
- return err
- }
-
- uniqueID := m.buildEventID(paeData.Container, paeData.Process)
- channel, exist := m.event[uniqueID]
- if !exist {
- return nil
- }
-
- channel <- msg
-
- delete(m.event, uniqueID)
-
- return nil
-}
-
-func (m *multicast) sendReply(msg *DecodedMessage) error {
- m.Lock()
- if len(m.reply) == 0 {
- m.bufReplies = append(m.bufReplies, msg)
- m.Unlock()
- return nil
- }
-
- replyChannel := m.reply[0]
- m.reply = m.reply[1:]
-
- m.Unlock()
-
- // The current reply channel has been removed from the list, that's why
- // we can be out of the mutex to send through that channel. Indeed, there
- // is no risk that someone else tries to write on this channel.
- replyChannel <- msg
-
- return nil
-}
-
-func (m *multicast) processBufferedReply(channel chan *DecodedMessage) {
- m.Lock()
-
- if len(m.bufReplies) == 0 {
- m.reply = append(m.reply, channel)
- m.Unlock()
- return
- }
-
- msg := m.bufReplies[0]
- m.bufReplies = m.bufReplies[1:]
-
- m.Unlock()
-
- // The current buffered reply message has been removed from the list, and
- // the channel have not been added to the reply list, that's why we can be
- // out of the mutex to send the buffered message through that channel.
- // There is no risk that someone else tries to write this message on another
- // channel, or another message on this channel.
- channel <- msg
-}
-
-func (m *multicast) write(msg *DecodedMessage) error {
- switch msg.Code {
- case NextCode:
- return nil
- case ProcessAsyncEventCode:
- return m.sendEvent(msg)
- default:
- return m.sendReply(msg)
- }
-}
-
-func (m *multicast) listen(containerID, processID string, dataType ctlDataType) (chan *DecodedMessage, error) {
- switch dataType {
- case replyType:
- newChan := make(chan *DecodedMessage)
-
- go m.processBufferedReply(newChan)
-
- return newChan, nil
- case eventType:
- uniqueID := m.buildEventID(containerID, processID)
-
- _, exist := m.event[uniqueID]
- if exist {
- return nil, fmt.Errorf("Channel already assigned for ID %s", uniqueID)
- }
-
- m.event[uniqueID] = make(chan *DecodedMessage)
-
- return m.event[uniqueID], nil
- default:
- return nil, fmt.Errorf("Unknown data type: %s", dataType)
- }
-}
diff --git a/vendor/github.com/containers/virtcontainers/pkg/hyperstart/types.go b/vendor/github.com/containers/virtcontainers/pkg/hyperstart/types.go
deleted file mode 100644
index aaaceba..0000000
--- a/vendor/github.com/containers/virtcontainers/pkg/hyperstart/types.go
+++ /dev/null
@@ -1,210 +0,0 @@
-//
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package hyperstart
-
-import (
- "syscall"
-)
-
-// Defines all available commands to communicate with hyperstart agent.
-const (
- VersionCode = iota
- StartPodCode
- GetPodDeprecatedCode
- StopPodDeprecatedCode
- DestroyPodCode
- RestartContainerDeprecatedCode
- ExecCmdCode
- FinishCmdDeprecatedCode
- ReadyCode
- AckCode
- ErrorCode
- WinsizeCode
- PingCode
- FinishPodDeprecatedCode
- NextCode
- WriteFileCode
- ReadFileCode
- NewContainerCode
- KillContainerCode
- OnlineCPUMemCode
- SetupInterfaceCode
- SetupRouteCode
- RemoveContainerCode
- ProcessAsyncEventCode
-)
-
-// FileCommand is the structure corresponding to the format expected by
-// hyperstart to interact with files.
-type FileCommand struct {
- Container string `json:"container"`
- File string `json:"file"`
-}
-
-// KillCommand is the structure corresponding to the format expected by
-// hyperstart to kill a container on the guest.
-type KillCommand struct {
- Container string `json:"container"`
- Signal syscall.Signal `json:"signal"`
-}
-
-// ExecCommand is the structure corresponding to the format expected by
-// hyperstart to execute a command on the guest.
-type ExecCommand struct {
- Container string `json:"container,omitempty"`
- Process Process `json:"process"`
-}
-
-// RemoveCommand is the structure corresponding to the format expected by
-// hyperstart to remove a container on the guest.
-type RemoveCommand struct {
- Container string `json:"container"`
-}
-
-// PAECommand is the structure hyperstart can expects to
-// receive after a process has been started/executed on a container.
-type PAECommand struct {
- Container string `json:"container"`
- Process string `json:"process"`
- Event string `json:"event"`
- Info string `json:"info,omitempty"`
- Status int `json:"status,omitempty"`
-}
-
-// DecodedMessage is the structure holding messages coming from CTL channel.
-type DecodedMessage struct {
- Code uint32
- Message []byte
-}
-
-// TtyMessage is the structure holding messages coming from TTY channel.
-type TtyMessage struct {
- Session uint64
- Message []byte
-}
-
-// WindowSizeMessage is the structure corresponding to the format expected by
-// hyperstart to resize a container's window.
-type WindowSizeMessage struct {
- Container string `json:"container"`
- Process string `json:"process"`
- Row uint16 `json:"row"`
- Column uint16 `json:"column"`
-}
-
-// VolumeDescriptor describes a volume related to a container.
-type VolumeDescriptor struct {
- Device string `json:"device"`
- Addr string `json:"addr,omitempty"`
- Mount string `json:"mount"`
- Fstype string `json:"fstype,omitempty"`
- ReadOnly bool `json:"readOnly"`
- DockerVolume bool `json:"dockerVolume"`
-}
-
-// FsmapDescriptor describes a filesystem map related to a container.
-type FsmapDescriptor struct {
- Source string `json:"source"`
- Path string `json:"path"`
- ReadOnly bool `json:"readOnly"`
- DockerVolume bool `json:"dockerVolume"`
-}
-
-// EnvironmentVar holds an environment variable and its value.
-type EnvironmentVar struct {
- Env string `json:"env"`
- Value string `json:"value"`
-}
-
-// Rlimit describes a resource limit.
-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"`
-}
-
-// Process describes a process running on a container inside a pod.
-type Process struct {
- User string `json:"user,omitempty"`
- Group string `json:"group,omitempty"`
- AdditionalGroups []string `json:"additionalGroups,omitempty"`
- // Terminal creates an interactive terminal for the process.
- Terminal bool `json:"terminal"`
- // Sequeue number for stdin and stdout
- Stdio uint64 `json:"stdio,omitempty"`
- // Sequeue number for stderr if it is not shared with stdout
- Stderr uint64 `json:"stderr,omitempty"`
- // Args specifies the binary and arguments for the application to execute.
- Args []string `json:"args"`
- // Envs populates the process environment for the process.
- Envs []EnvironmentVar `json:"envs,omitempty"`
- // Workdir is the current working directory for the process and must be
- // relative to the container's root.
- Workdir string `json:"workdir"`
- // Rlimits specifies rlimit options to apply to the process.
- Rlimits []Rlimit `json:"rlimits,omitempty"`
-}
-
-// Container describes a container running on a pod.
-type Container struct {
- ID string `json:"id"`
- Rootfs string `json:"rootfs"`
- Fstype string `json:"fstype,omitempty"`
- Image string `json:"image"`
- Addr string `json:"addr,omitempty"`
- Volumes []*VolumeDescriptor `json:"volumes,omitempty"`
- Fsmap []*FsmapDescriptor `json:"fsmap,omitempty"`
- Sysctl map[string]string `json:"sysctl,omitempty"`
- Process *Process `json:"process"`
- RestartPolicy string `json:"restartPolicy"`
- Initialize bool `json:"initialize"`
-}
-
-// IPAddress describes an IP address and its network mask.
-type IPAddress struct {
- IPAddress string `json:"ipAddress"`
- NetMask string `json:"netMask"`
-}
-
-// NetworkIface describes a network interface to setup on the host.
-type NetworkIface struct {
- Device string `json:"device,omitempty"`
- NewDevice string `json:"newDeviceName,omitempty"`
- IPAddresses []IPAddress `json:"ipAddresses"`
- MTU string `json:"mtu"`
- MACAddr string `json:"macAddr"`
-}
-
-// Route describes a route to setup on the host.
-type Route struct {
- Dest string `json:"dest"`
- Gateway string `json:"gateway,omitempty"`
- Device string `json:"device,omitempty"`
-}
-
-// Pod describes the pod configuration to start inside the VM.
-type Pod struct {
- Hostname string `json:"hostname"`
- Containers []Container `json:"containers,omitempty"`
- Interfaces []NetworkIface `json:"interfaces,omitempty"`
- DNS []string `json:"dns,omitempty"`
- Routes []Route `json:"routes,omitempty"`
- ShareDir string `json:"shareDir"`
-}
diff --git a/vendor/github.com/containers/virtcontainers/pod.go b/vendor/github.com/containers/virtcontainers/pod.go
deleted file mode 100644
index 1c2378c..0000000
--- a/vendor/github.com/containers/virtcontainers/pod.go
+++ /dev/null
@@ -1,874 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "strings"
- "syscall"
- "time"
-)
-
-// controlSocket is the pod control socket.
-// It is an hypervisor resource, and for example qemu's control
-// socket is the QMP one.
-const controlSocket = "ctrl.sock"
-
-// monitorSocket is the pod monitoring socket.
-// It is an hypervisor resource, and is a qmp socket in the qemu case.
-// This is a socket that any monitoring entity will listen to in order
-// to understand if the VM is still alive or not.
-const monitorSocket = "monitor.sock"
-
-// stateString is a string representing a pod state.
-type stateString string
-
-const (
- // StateReady represents a pod/container that's ready to be run
- StateReady stateString = "ready"
-
- // StateRunning represents a pod/container that's currently running.
- StateRunning stateString = "running"
-
- // StateStopped represents a pod/container that has been stopped.
- StateStopped stateString = "stopped"
-)
-
-// State is a pod state structure.
-type State struct {
- State stateString `json:"state"`
- URL string `json:"url,omitempty"`
-}
-
-// valid checks that the pod state is valid.
-func (state *State) valid() bool {
- for _, validState := range []stateString{StateReady, StateRunning, StateStopped} {
- if state.State == validState {
- return true
- }
- }
-
- return false
-}
-
-// validTransition returns an error if we want to move to
-// an unreachable state.
-func (state *State) validTransition(oldState stateString, newState stateString) error {
- if state.State != oldState {
- return fmt.Errorf("Invalid state %s (Expecting %s)", state.State, oldState)
- }
-
- switch state.State {
- case StateReady:
- if newState == StateRunning {
- return nil
- }
-
- case StateRunning:
- if newState == StateStopped {
- return nil
- }
-
- case StateStopped:
- if newState == StateRunning {
- return nil
- }
- }
-
- return fmt.Errorf("Can not move from %s to %s",
- state.State, newState)
-}
-
-// Volume is a shared volume between the host and the VM,
-// defined by its mount tag and its host path.
-type Volume struct {
- // MountTag is a label used as a hint to the guest.
- MountTag string
-
- // HostPath is the host filesystem path for this volume.
- HostPath string
-}
-
-// Volumes is a Volume list.
-type Volumes []Volume
-
-// Set assigns volume values from string to a Volume.
-func (v *Volumes) Set(volStr string) error {
- if volStr == "" {
- return fmt.Errorf("volStr cannot be empty")
- }
-
- volSlice := strings.Split(volStr, " ")
- const expectedVolLen = 2
- const volDelimiter = ":"
-
- for _, vol := range volSlice {
- volArgs := strings.Split(vol, volDelimiter)
-
- if len(volArgs) != expectedVolLen {
- return fmt.Errorf("Wrong string format: %s, expecting only %v parameters separated with %q",
- vol, expectedVolLen, volDelimiter)
- }
-
- if volArgs[0] == "" || volArgs[1] == "" {
- return fmt.Errorf("Volume parameters cannot be empty")
- }
-
- volume := Volume{
- MountTag: volArgs[0],
- HostPath: volArgs[1],
- }
-
- *v = append(*v, volume)
- }
-
- return nil
-}
-
-// String converts a Volume to a string.
-func (v *Volumes) String() string {
- var volSlice []string
-
- for _, volume := range *v {
- volSlice = append(volSlice, fmt.Sprintf("%s:%s", volume.MountTag, volume.HostPath))
- }
-
- return strings.Join(volSlice, " ")
-}
-
-// Socket defines a socket to communicate between
-// the host and any process inside the VM.
-type Socket struct {
- DeviceID string
- ID string
- HostPath string
- Name string
-}
-
-// Sockets is a Socket list.
-type Sockets []Socket
-
-// Set assigns socket values from string to a Socket.
-func (s *Sockets) Set(sockStr string) error {
- if sockStr == "" {
- return fmt.Errorf("sockStr cannot be empty")
- }
-
- sockSlice := strings.Split(sockStr, " ")
- const expectedSockCount = 4
- const sockDelimiter = ":"
-
- for _, sock := range sockSlice {
- sockArgs := strings.Split(sock, sockDelimiter)
-
- if len(sockArgs) != expectedSockCount {
- return fmt.Errorf("Wrong string format: %s, expecting only %v parameters separated with %q", sock, expectedSockCount, sockDelimiter)
- }
-
- for _, a := range sockArgs {
- if a == "" {
- return fmt.Errorf("Socket parameters cannot be empty")
- }
- }
-
- socket := Socket{
- DeviceID: sockArgs[0],
- ID: sockArgs[1],
- HostPath: sockArgs[2],
- Name: sockArgs[3],
- }
-
- *s = append(*s, socket)
- }
-
- return nil
-}
-
-// String converts a Socket to a string.
-func (s *Sockets) String() string {
- var sockSlice []string
-
- for _, sock := range *s {
- sockSlice = append(sockSlice, fmt.Sprintf("%s:%s:%s:%s", sock.DeviceID, sock.ID, sock.HostPath, sock.Name))
- }
-
- return strings.Join(sockSlice, " ")
-}
-
-// EnvVar is a key/value structure representing a command
-// environment variable.
-type EnvVar struct {
- Var string
- Value string
-}
-
-// Cmd represents a command to execute in a running container.
-type Cmd struct {
- Args []string
- Envs []EnvVar
- WorkDir string
-
- User string
- Group string
-
- Interactive bool
- Console string
-}
-
-// Resources describes VM resources configuration.
-type Resources struct {
- // VCPUs is the number of available virtual CPUs.
- VCPUs uint
-
- // Memory is the amount of available memory in MiB.
- Memory uint
-}
-
-// PodStatus describes a pod status.
-type PodStatus struct {
- ID string
- State State
- Hypervisor HypervisorType
- Agent AgentType
- ContainersStatus []ContainerStatus
-}
-
-// PodConfig is a Pod configuration.
-type PodConfig struct {
- ID string
-
- // Field specific to OCI specs, needed to setup all the hooks
- Hooks Hooks
-
- // VMConfig is the VM configuration to set for this pod.
- VMConfig Resources
-
- HypervisorType HypervisorType
- HypervisorConfig HypervisorConfig
-
- AgentType AgentType
- AgentConfig interface{}
-
- ProxyType ProxyType
- ProxyConfig interface{}
-
- ShimType ShimType
- ShimConfig interface{}
-
- NetworkModel NetworkModel
- NetworkConfig NetworkConfig
-
- // Volumes is a list of shared volumes between the host and the Pod.
- Volumes []Volume
-
- // Containers describe the list of containers within a Pod.
- // This list can be empty and populated by adding containers
- // to the Pod a posteriori.
- Containers []ContainerConfig
-
- // Annotations keys must be unique strings an must be name-spaced
- // with e.g. reverse domain notation (org.clearlinux.key).
- Annotations map[string]string
-}
-
-// valid checks that the pod configuration is valid.
-func (podConfig *PodConfig) valid() bool {
- if podConfig.ID == "" {
- return false
- }
-
- if _, err := newHypervisor(podConfig.HypervisorType); err != nil {
- podConfig.HypervisorType = QemuHypervisor
- }
-
- return true
-}
-
-// lock locks any pod to prevent it from being accessed by other processes.
-func lockPod(podID string) (*os.File, error) {
- if podID == "" {
- return nil, errNeedPodID
- }
-
- fs := filesystem{}
- podlockFile, _, err := fs.podURI(podID, lockFileType)
- if err != nil {
- return nil, err
- }
-
- lockFile, err := os.Open(podlockFile)
- if err != nil {
- return nil, err
- }
-
- err = syscall.Flock(int(lockFile.Fd()), syscall.LOCK_EX)
- if err != nil {
- return nil, err
- }
-
- return lockFile, nil
-}
-
-// unlock unlocks any pod to allow it being accessed by other processes.
-func unlockPod(lockFile *os.File) error {
- if lockFile == nil {
- return fmt.Errorf("lockFile cannot be empty")
- }
-
- err := syscall.Flock(int(lockFile.Fd()), syscall.LOCK_UN)
- if err != nil {
- return err
- }
-
- lockFile.Close()
-
- return nil
-}
-
-// Pod is composed of a set of containers and a runtime environment.
-// A Pod can be created, deleted, started, stopped, listed, entered, paused and restored.
-type Pod struct {
- id string
-
- hypervisor hypervisor
- agent agent
- proxy proxy
- shim shim
- storage resourceStorage
- network network
-
- config *PodConfig
-
- volumes []Volume
-
- containers []*Container
-
- runPath string
- configPath string
-
- state State
-
- lockFile *os.File
-}
-
-// ID returns the pod identifier string.
-func (p *Pod) ID() string {
- return p.id
-}
-
-// Annotations returns any annotation that a user could have stored through the pod.
-func (p *Pod) Annotations(key string) (string, error) {
- value, exist := p.config.Annotations[key]
- if exist == false {
- return "", fmt.Errorf("Annotations key %s does not exist", key)
- }
-
- return value, nil
-}
-
-// URL returns the pod URL for any runtime to connect to the proxy.
-func (p *Pod) URL() string {
- return p.state.URL
-}
-
-// GetContainers returns a container config list.
-func (p *Pod) GetContainers() []*Container {
- return p.containers
-}
-
-func (p *Pod) createSetStates() error {
- p.state.State = StateReady
- err := p.setPodState(p.state)
- if err != nil {
- return err
- }
-
- err = p.setContainersState(StateReady)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-// createPod creates a pod from a pod description, the containers list, the hypervisor
-// and the agent passed through the Config structure.
-// It will create and store the pod structure, and then ask the hypervisor
-// to physically create that pod i.e. starts a VM for that pod to eventually
-// be started.
-func createPod(podConfig PodConfig) (*Pod, error) {
- if podConfig.valid() == false {
- return nil, fmt.Errorf("Invalid pod configuration")
- }
-
- agent := newAgent(podConfig.AgentType)
-
- hypervisor, err := newHypervisor(podConfig.HypervisorType)
- if err != nil {
- return nil, err
- }
-
- if err := hypervisor.init(podConfig.HypervisorConfig); err != nil {
- return nil, err
- }
-
- proxy, err := newProxy(podConfig.ProxyType)
- if err != nil {
- return nil, err
- }
-
- shim, err := newShim(podConfig.ShimType)
- if err != nil {
- return nil, err
- }
-
- network := newNetwork(podConfig.NetworkModel)
-
- p := &Pod{
- id: podConfig.ID,
- hypervisor: hypervisor,
- agent: agent,
- proxy: proxy,
- shim: shim,
- storage: &filesystem{},
- network: network,
- config: &podConfig,
- volumes: podConfig.Volumes,
- runPath: filepath.Join(runStoragePath, podConfig.ID),
- configPath: filepath.Join(configStoragePath, podConfig.ID),
- state: State{},
- }
-
- containers, err := createContainers(p, podConfig.Containers)
- if err != nil {
- return nil, err
- }
-
- p.containers = containers
-
- if err := p.storage.createAllResources(*p); err != nil {
- return nil, err
- }
-
- if err := p.hypervisor.createPod(podConfig); err != nil {
- p.storage.deletePodResources(p.id, nil)
- return nil, err
- }
-
- agentConfig := newAgentConfig(podConfig)
- if err := p.agent.init(p, agentConfig); err != nil {
- p.storage.deletePodResources(p.id, nil)
- return nil, err
- }
-
- state, err := p.storage.fetchPodState(p.id)
- if err == nil && state.State != "" {
- p.state = state
- return p, nil
- }
-
- if err := p.createSetStates(); err != nil {
- p.storage.deletePodResources(p.id, nil)
- return nil, err
- }
-
- return p, nil
-}
-
-// storePod stores a pod config.
-func (p *Pod) storePod() error {
- err := p.storage.storePodResource(p.id, configFileType, *(p.config))
- if err != nil {
- return err
- }
-
- for _, container := range p.containers {
- err = p.storage.storeContainerResource(p.id, container.id, configFileType, *(container.config))
- if err != nil {
- return err
- }
- }
-
- return nil
-}
-
-// fetchPod fetches a pod config from a pod ID and returns a pod.
-func fetchPod(podID string) (*Pod, error) {
- if podID == "" {
- return nil, errNeedPodID
- }
-
- fs := filesystem{}
- config, err := fs.fetchPodConfig(podID)
- if err != nil {
- return nil, err
- }
-
- virtLog.Infof("Info structure: %+v", config)
-
- return createPod(config)
-}
-
-// delete deletes an already created pod.
-// The VM in which the pod is running will be shut down.
-func (p *Pod) delete() error {
- state, err := p.storage.fetchPodState(p.id)
- if err != nil {
- return err
- }
-
- if state.State != StateReady && state.State != StateStopped {
- return fmt.Errorf("Pod not ready or stopped, impossible to delete")
- }
-
- err = p.storage.deletePodResources(p.id, nil)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func (p *Pod) startCheckStates() error {
- state, err := p.storage.fetchPodState(p.id)
- if err != nil {
- return err
- }
-
- err = state.validTransition(StateReady, StateRunning)
- if err != nil {
- err = state.validTransition(StateStopped, StateRunning)
- if err != nil {
- return err
- }
- }
-
- err = p.checkContainersState(StateReady)
- if err != nil {
- err = p.checkContainersState(StateStopped)
- if err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (p *Pod) startSetStates() error {
- p.state.State = StateRunning
- err := p.setPodState(p.state)
- if err != nil {
- return err
- }
-
- err = p.setContainersState(StateRunning)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-// startVM starts the VM, ensuring it is started before it returns or issuing
-// an error in case of timeout. Then it connects to the agent inside the VM.
-func (p *Pod) startVM() error {
- vmStartedCh := make(chan struct{})
- vmStoppedCh := make(chan struct{})
-
- go func() {
- p.network.run(p.config.NetworkConfig.NetNSPath, func() error {
- err := p.hypervisor.startPod(vmStartedCh, vmStoppedCh)
- return err
- })
- }()
-
- // Wait for the pod started notification
- select {
- case <-vmStartedCh:
- break
- case <-time.After(time.Second):
- return fmt.Errorf("Did not receive the pod started notification")
- }
-
- virtLog.Infof("VM started")
-
- return nil
-}
-
-// startShims registers all containers to the proxy and starts one
-// shim per container.
-func (p *Pod) startShims() error {
- proxyInfos, url, err := p.proxy.register(*p)
- if err != nil {
- return err
- }
-
- if err := p.proxy.disconnect(); err != nil {
- return err
- }
-
- if len(proxyInfos) != len(p.containers) {
- return fmt.Errorf("Retrieved %d proxy infos, expecting %d", len(proxyInfos), len(p.containers))
- }
-
- p.state.URL = url
- if err := p.setPodState(p.state); err != nil {
- return err
- }
-
- for idx := range p.containers {
- shimParams := ShimParams{
- Token: proxyInfos[idx].Token,
- URL: url,
- Console: p.containers[idx].config.Cmd.Console,
- }
-
- pid, err := p.shim.start(*p, shimParams)
- if err != nil {
- return err
- }
-
- p.containers[idx].process = Process{
- Token: proxyInfos[idx].Token,
- Pid: pid,
- }
-
- if err := p.containers[idx].storeProcess(); err != nil {
- return err
- }
- }
-
- virtLog.Infof("Shim(s) started")
-
- return nil
-}
-
-// start starts a pod. The containers that are making the pod
-// will be started.
-func (p *Pod) start() error {
- if err := p.startCheckStates(); err != nil {
- return err
- }
-
- if _, _, err := p.proxy.connect(*p, false); err != nil {
- return err
- }
- defer p.proxy.disconnect()
-
- if err := p.agent.startPod(*p); err != nil {
- return err
- }
-
- if err := p.startSetStates(); err != nil {
- return err
- }
-
- virtLog.Infof("Started Pod %s", p.ID())
-
- return nil
-}
-
-func (p *Pod) stopCheckStates() error {
- state, err := p.storage.fetchPodState(p.id)
- if err != nil {
- return err
- }
-
- err = state.validTransition(StateRunning, StateStopped)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func (p *Pod) stopSetStates() error {
- err := p.setContainersState(StateStopped)
- if err != nil {
- return err
- }
-
- p.state.State = StateStopped
- err = p.setPodState(p.state)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-// stopVM stops the agent inside the VM and shut down the VM itself.
-func (p *Pod) stopVM() error {
- if _, _, err := p.proxy.connect(*p, false); err != nil {
- return err
- }
-
- if err := p.proxy.unregister(*p); err != nil {
- return err
- }
-
- if err := p.proxy.disconnect(); err != nil {
- return err
- }
-
- if err := p.hypervisor.stopPod(); err != nil {
- return err
- }
-
- return nil
-}
-
-// stop stops a pod. The containers that are making the pod
-// will be destroyed.
-func (p *Pod) stop() error {
- if err := p.stopCheckStates(); err != nil {
- return err
- }
-
- if _, _, err := p.proxy.connect(*p, false); err != nil {
- return err
- }
- defer p.proxy.disconnect()
-
- if err := p.agent.stopPod(*p); err != nil {
- return err
- }
-
- if err := p.stopSetStates(); err != nil {
- return err
- }
-
- return nil
-}
-
-// list lists all pod running on the host.
-func (p *Pod) list() ([]Pod, error) {
- return nil, nil
-}
-
-// enter runs an executable within a pod.
-func (p *Pod) enter(args []string) error {
- return nil
-}
-
-func (p *Pod) setPodState(state State) error {
- err := p.storage.storePodResource(p.id, stateFileType, state)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-// endSession makes sure to end the session properly.
-func (p *Pod) endSession() error {
- return nil
-}
-
-func (p *Pod) setContainerState(containerID string, state stateString) error {
- if containerID == "" {
- return errNeedContainerID
- }
-
- contState := State{
- State: state,
- }
-
- err := p.storage.storeContainerResource(p.id, containerID, stateFileType, contState)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func (p *Pod) setContainersState(state stateString) error {
- if state == "" {
- return errNeedState
- }
-
- for _, container := range p.config.Containers {
- err := p.setContainerState(container.ID, state)
- if err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (p *Pod) deleteContainerState(containerID string) error {
- if containerID == "" {
- return errNeedContainerID
- }
-
- err := p.storage.deleteContainerResources(p.id, containerID, []podResource{stateFileType})
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func (p *Pod) deleteContainersState() error {
- for _, container := range p.config.Containers {
- err := p.deleteContainerState(container.ID)
- if err != nil {
- return err
- }
- }
-
- return nil
-}
-
-func (p *Pod) checkContainerState(containerID string, expectedState stateString) error {
- if containerID == "" {
- return errNeedContainerID
- }
-
- if expectedState == "" {
- return fmt.Errorf("expectedState cannot be empty")
- }
-
- state, err := p.storage.fetchContainerState(p.id, containerID)
- if err != nil {
- return err
- }
-
- if state.State != expectedState {
- return fmt.Errorf("Container %s not %s", containerID, expectedState)
- }
-
- return nil
-}
-
-func (p *Pod) checkContainersState(state stateString) error {
- if state == "" {
- return errNeedState
- }
-
- for _, container := range p.config.Containers {
- err := p.checkContainerState(container.ID, state)
- if err != nil {
- return err
- }
- }
-
- return nil
-}
diff --git a/vendor/github.com/containers/virtcontainers/pod_test.go b/vendor/github.com/containers/virtcontainers/pod_test.go
deleted file mode 100644
index e95780a..0000000
--- a/vendor/github.com/containers/virtcontainers/pod_test.go
+++ /dev/null
@@ -1,711 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "reflect"
- "testing"
-)
-
-func newHypervisorConfig(kernelParams []Param, hParams []Param) HypervisorConfig {
- return HypervisorConfig{
- KernelPath: filepath.Join(testDir, testKernel),
- ImagePath: filepath.Join(testDir, testImage),
- HypervisorPath: filepath.Join(testDir, testHypervisor),
- KernelParams: kernelParams,
- HypervisorParams: hParams,
- }
-
-}
-
-func testCreatePod(t *testing.T, id string,
- htype HypervisorType, hconfig HypervisorConfig, atype AgentType,
- nmodel NetworkModel, nconfig NetworkConfig, containers []ContainerConfig,
- volumes []Volume) (*Pod, error) {
-
- config := PodConfig{
- ID: id,
- HypervisorType: htype,
- HypervisorConfig: hconfig,
- AgentType: atype,
- NetworkModel: nmodel,
- NetworkConfig: nconfig,
- Volumes: volumes,
- Containers: containers,
- }
-
- pod, err := createPod(config)
- if err != nil {
- return nil, fmt.Errorf("Could not create pod: %s", err)
- }
-
- if pod.id == "" {
- return pod, fmt.Errorf("Invalid empty pod ID")
- }
-
- if id != "" && pod.id != id {
- return pod, fmt.Errorf("Invalid ID %s vs %s", id, pod.id)
- }
-
- return pod, nil
-}
-
-func TestCreateEmtpyPod(t *testing.T) {
- _, err := testCreatePod(t, testPodID, MockHypervisor, HypervisorConfig{}, NoopAgentType, NoopNetworkModel, NetworkConfig{}, nil, nil)
- if err == nil {
- t.Fatalf("VirtContainers should not allow empty pods")
- }
-}
-
-func TestCreateEmtpyHypervisorPod(t *testing.T) {
- _, err := testCreatePod(t, testPodID, QemuHypervisor, HypervisorConfig{}, NoopAgentType, NoopNetworkModel, NetworkConfig{}, nil, nil)
- if err == nil {
- t.Fatalf("VirtContainers should not allow pods with empty hypervisors")
- }
-}
-
-func TestCreateMockPod(t *testing.T) {
- hConfig := newHypervisorConfig(nil, nil)
-
- _, err := testCreatePod(t, testPodID, MockHypervisor, hConfig, NoopAgentType, NoopNetworkModel, NetworkConfig{}, nil, nil)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestCreatePodEmtpyID(t *testing.T) {
- hConfig := newHypervisorConfig(nil, nil)
-
- p, err := testCreatePod(t, "", MockHypervisor, hConfig, NoopAgentType, NoopNetworkModel, NetworkConfig{}, nil, nil)
- if err == nil {
- t.Fatalf("Expected pod with empty ID to fail, but got pod %v", p)
- }
-}
-
-func testPodStateTransition(t *testing.T, state stateString, newState stateString) error {
- hConfig := newHypervisorConfig(nil, nil)
-
- p, err := testCreatePod(t, testPodID, MockHypervisor, hConfig, NoopAgentType, NoopNetworkModel, NetworkConfig{}, nil, nil)
- if err != nil {
- return err
- }
-
- p.state = State{
- State: state,
- }
-
- return p.state.validTransition(state, newState)
-}
-
-func TestPodStateReadyRunning(t *testing.T) {
- err := testPodStateTransition(t, StateReady, StateRunning)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestPodStateRunningPaused(t *testing.T) {
- err := testPodStateTransition(t, StateRunning, StateStopped)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestPodStatePausedRunning(t *testing.T) {
- err := testPodStateTransition(t, StateStopped, StateRunning)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestPodStateRunningStopped(t *testing.T) {
- err := testPodStateTransition(t, StateRunning, StateStopped)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestPodStateReadyPaused(t *testing.T) {
- err := testPodStateTransition(t, StateReady, StateStopped)
- if err == nil {
- t.Fatal("Invalid transition from Ready to Paused")
- }
-}
-
-func TestPodStatePausedReady(t *testing.T) {
- err := testPodStateTransition(t, StateStopped, StateReady)
- if err == nil {
- t.Fatal("Invalid transition from Ready to Paused")
- }
-}
-
-func testPodDir(t *testing.T, resource podResource, expected string) error {
- fs := filesystem{}
- _, dir, err := fs.podURI(testPodID, resource)
- if err != nil {
- return err
- }
-
- if dir != expected {
- return fmt.Errorf("Unexpected pod directory %s vs %s", dir, expected)
- }
-
- return nil
-}
-
-func testPodFile(t *testing.T, resource podResource, expected string) error {
- fs := filesystem{}
- file, _, err := fs.podURI(testPodID, resource)
- if err != nil {
- return err
- }
-
- if file != expected {
- return fmt.Errorf("Unexpected pod file %s vs %s", file, expected)
- }
-
- return nil
-}
-
-func TestPodDirConfig(t *testing.T) {
- err := testPodDir(t, configFileType, podDirConfig)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestPodDirState(t *testing.T) {
- err := testPodDir(t, stateFileType, podDirState)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestPodDirLock(t *testing.T) {
- err := testPodDir(t, lockFileType, podDirLock)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestPodDirNegative(t *testing.T) {
- fs := filesystem{}
- _, _, err := fs.podURI("", lockFileType)
- if err == nil {
- t.Fatal("Empty pod IDs should not be allowed")
- }
-}
-
-func TestPodFileConfig(t *testing.T) {
- err := testPodFile(t, configFileType, podFileConfig)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestPodFileState(t *testing.T) {
- err := testPodFile(t, stateFileType, podFileState)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestPodFileLock(t *testing.T) {
- err := testPodFile(t, lockFileType, podFileLock)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestPodFileNegative(t *testing.T) {
- fs := filesystem{}
- _, _, err := fs.podURI("", lockFileType)
- if err == nil {
- t.Fatal("Empty pod IDs should not be allowed")
- }
-}
-
-func testStateValid(t *testing.T, stateStr stateString, expected bool) {
- state := &State{
- State: stateStr,
- }
-
- ok := state.valid()
- if ok != expected {
- t.Fatal()
- }
-}
-
-func TestStateValidSuccessful(t *testing.T) {
- testStateValid(t, StateReady, true)
- testStateValid(t, StateRunning, true)
- testStateValid(t, StateStopped, true)
-}
-
-func TestStateValidFailing(t *testing.T) {
- testStateValid(t, "", false)
-}
-
-func TestValidTransitionFailingOldStateMismatch(t *testing.T) {
- state := &State{
- State: StateReady,
- }
-
- err := state.validTransition(StateRunning, StateStopped)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestVolumesSetSuccessful(t *testing.T) {
- volumes := &Volumes{}
-
- volStr := "mountTag1:hostPath1 mountTag2:hostPath2"
-
- expected := Volumes{
- {
- MountTag: "mountTag1",
- HostPath: "hostPath1",
- },
- {
- MountTag: "mountTag2",
- HostPath: "hostPath2",
- },
- }
-
- err := volumes.Set(volStr)
- if err != nil {
- t.Fatal(err)
- }
-
- if reflect.DeepEqual(*volumes, expected) == false {
- t.Fatal()
- }
-}
-
-func TestVolumesSetFailingTooFewArguments(t *testing.T) {
- volumes := &Volumes{}
-
- volStr := "mountTag1 mountTag2"
-
- err := volumes.Set(volStr)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestVolumesSetFailingTooManyArguments(t *testing.T) {
- volumes := &Volumes{}
-
- volStr := "mountTag1:hostPath1:Foo1 mountTag2:hostPath2:Foo2"
-
- err := volumes.Set(volStr)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestVolumesSetFailingVoidArguments(t *testing.T) {
- volumes := &Volumes{}
-
- volStr := ": : :"
-
- err := volumes.Set(volStr)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestVolumesStringSuccessful(t *testing.T) {
- volumes := &Volumes{
- {
- MountTag: "mountTag1",
- HostPath: "hostPath1",
- },
- {
- MountTag: "mountTag2",
- HostPath: "hostPath2",
- },
- }
-
- expected := "mountTag1:hostPath1 mountTag2:hostPath2"
-
- result := volumes.String()
- if result != expected {
- t.Fatal()
- }
-}
-
-func TestSocketsSetSuccessful(t *testing.T) {
- sockets := &Sockets{}
-
- sockStr := "devID1:id1:hostPath1:Name1 devID2:id2:hostPath2:Name2"
-
- expected := Sockets{
- {
- DeviceID: "devID1",
- ID: "id1",
- HostPath: "hostPath1",
- Name: "Name1",
- },
- {
- DeviceID: "devID2",
- ID: "id2",
- HostPath: "hostPath2",
- Name: "Name2",
- },
- }
-
- err := sockets.Set(sockStr)
- if err != nil {
- t.Fatal(err)
- }
-
- if reflect.DeepEqual(*sockets, expected) == false {
- t.Fatal()
- }
-}
-
-func TestSocketsSetFailingWrongArgsAmount(t *testing.T) {
- sockets := &Sockets{}
-
- sockStr := "devID1:id1:hostPath1"
-
- err := sockets.Set(sockStr)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestSocketsSetFailingVoidArguments(t *testing.T) {
- sockets := &Sockets{}
-
- sockStr := ":::"
-
- err := sockets.Set(sockStr)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestSocketsStringSuccessful(t *testing.T) {
- sockets := &Sockets{
- {
- DeviceID: "devID1",
- ID: "id1",
- HostPath: "hostPath1",
- Name: "Name1",
- },
- {
- DeviceID: "devID2",
- ID: "id2",
- HostPath: "hostPath2",
- Name: "Name2",
- },
- }
-
- expected := "devID1:id1:hostPath1:Name1 devID2:id2:hostPath2:Name2"
-
- result := sockets.String()
- if result != expected {
- t.Fatal()
- }
-}
-
-func TestPodListSuccessful(t *testing.T) {
- pod := &Pod{}
-
- podList, err := pod.list()
- if podList != nil || err != nil {
- t.Fatal()
- }
-}
-
-func TestPodEnterSuccessful(t *testing.T) {
- pod := &Pod{}
-
- err := pod.enter([]string{})
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestPodSetPodStateFailingStorePodResource(t *testing.T) {
- fs := &filesystem{}
- pod := &Pod{
- storage: fs,
- }
-
- pod.state.State = StateReady
- err := pod.setPodState(pod.state)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestPodSetContainerStateFailingStoreContainerResource(t *testing.T) {
- fs := &filesystem{}
- pod := &Pod{
- storage: fs,
- }
-
- err := pod.setContainerState("100", StateReady)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestPodSetContainersStateFailingEmptyPodID(t *testing.T) {
- containers := []ContainerConfig{
- {
- ID: "100",
- },
- }
-
- podConfig := &PodConfig{
- Containers: containers,
- }
-
- fs := &filesystem{}
- pod := &Pod{
- config: podConfig,
- storage: fs,
- }
-
- err := pod.setContainersState(StateReady)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestPodDeleteContainerStateSuccessful(t *testing.T) {
- contID := "100"
-
- fs := &filesystem{}
- pod := &Pod{
- id: testPodID,
- storage: fs,
- }
-
- path := filepath.Join(runStoragePath, testPodID, contID)
- err := os.MkdirAll(path, dirMode)
- if err != nil {
- t.Fatal(err)
- }
-
- stateFilePath := filepath.Join(path, stateFile)
-
- os.Remove(stateFilePath)
-
- _, err = os.Create(stateFilePath)
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = os.Stat(stateFilePath)
- if err != nil {
- t.Fatal(err)
- }
-
- err = pod.deleteContainerState(contID)
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = os.Stat(stateFilePath)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestPodDeleteContainerStateFailingEmptyPodID(t *testing.T) {
- contID := "100"
-
- fs := &filesystem{}
- pod := &Pod{
- storage: fs,
- }
-
- err := pod.deleteContainerState(contID)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestPodDeleteContainersStateSuccessful(t *testing.T) {
- var err error
-
- containers := []ContainerConfig{
- {
- ID: "100",
- },
- {
- ID: "200",
- },
- }
-
- podConfig := &PodConfig{
- Containers: containers,
- }
-
- fs := &filesystem{}
- pod := &Pod{
- id: testPodID,
- config: podConfig,
- storage: fs,
- }
-
- for _, c := range containers {
- path := filepath.Join(runStoragePath, testPodID, c.ID)
- err = os.MkdirAll(path, dirMode)
- if err != nil {
- t.Fatal(err)
- }
-
- stateFilePath := filepath.Join(path, stateFile)
-
- os.Remove(stateFilePath)
-
- _, err = os.Create(stateFilePath)
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = os.Stat(stateFilePath)
- if err != nil {
- t.Fatal(err)
- }
- }
-
- err = pod.deleteContainersState()
- if err != nil {
- t.Fatal(err)
- }
-
- for _, c := range containers {
- stateFilePath := filepath.Join(runStoragePath, testPodID, c.ID, stateFile)
- _, err = os.Stat(stateFilePath)
- if err == nil {
- t.Fatal()
- }
- }
-}
-
-func TestPodDeleteContainersStateFailingEmptyPodID(t *testing.T) {
- containers := []ContainerConfig{
- {
- ID: "100",
- },
- }
-
- podConfig := &PodConfig{
- Containers: containers,
- }
-
- fs := &filesystem{}
- pod := &Pod{
- config: podConfig,
- storage: fs,
- }
-
- err := pod.deleteContainersState()
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestPodCheckContainerStateFailingEmptyPodID(t *testing.T) {
- contID := "100"
- fs := &filesystem{}
- pod := &Pod{
- storage: fs,
- }
-
- err := pod.checkContainerState(contID, StateReady)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestPodCheckContainerStateFailingNotExpectedState(t *testing.T) {
- contID := "100"
-
- fs := &filesystem{}
- pod := &Pod{
- id: testPodID,
- storage: fs,
- }
-
- path := filepath.Join(runStoragePath, testPodID, contID)
- err := os.MkdirAll(path, dirMode)
- if err != nil {
- t.Fatal(err)
- }
-
- stateFilePath := filepath.Join(path, stateFile)
-
- os.Remove(stateFilePath)
-
- f, err := os.Create(stateFilePath)
- if err != nil {
- t.Fatal(err)
- }
-
- stateData := "{\"state\":\"ready\"}"
- n, err := f.WriteString(stateData)
- if err != nil || n != len(stateData) {
- f.Close()
- t.Fatal()
- }
- f.Close()
-
- _, err = os.Stat(stateFilePath)
- if err != nil {
- t.Fatal(err)
- }
-
- err = pod.checkContainerState(contID, StateStopped)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestPodCheckContainersStateFailingEmptyPodID(t *testing.T) {
- containers := []ContainerConfig{
- {
- ID: "100",
- },
- }
-
- podConfig := &PodConfig{
- Containers: containers,
- }
-
- fs := &filesystem{}
- pod := &Pod{
- config: podConfig,
- storage: fs,
- }
-
- err := pod.checkContainersState(StateReady)
- if err == nil {
- t.Fatal()
- }
-}
diff --git a/vendor/github.com/containers/virtcontainers/proxy.go b/vendor/github.com/containers/virtcontainers/proxy.go
deleted file mode 100644
index bdcc4e6..0000000
--- a/vendor/github.com/containers/virtcontainers/proxy.go
+++ /dev/null
@@ -1,127 +0,0 @@
-//
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
-
- "github.com/mitchellh/mapstructure"
-)
-
-// ProxyType describes a proxy type.
-type ProxyType string
-
-const (
- // CCProxyType is the ccProxy.
- CCProxyType ProxyType = "ccProxy"
-
- // NoopProxyType is the noopProxy.
- NoopProxyType ProxyType = "noopProxy"
-)
-
-// Set sets a proxy type based on the input string.
-func (pType *ProxyType) Set(value string) error {
- switch value {
- case "noopProxy":
- *pType = NoopProxyType
- return nil
- case "ccProxy":
- *pType = CCProxyType
- return nil
- default:
- return fmt.Errorf("Unknown proxy type %s", value)
- }
-}
-
-// String converts a proxy type to a string.
-func (pType *ProxyType) String() string {
- switch *pType {
- case NoopProxyType:
- return string(NoopProxyType)
- case CCProxyType:
- return string(CCProxyType)
- default:
- return ""
- }
-}
-
-// newProxy returns a proxy from a proxy type.
-func newProxy(pType ProxyType) (proxy, error) {
- switch pType {
- case NoopProxyType:
- return &noopProxy{}, nil
- case CCProxyType:
- return &ccProxy{}, nil
- default:
- return &noopProxy{}, nil
- }
-}
-
-// newProxyConfig returns a proxy config from a generic PodConfig interface.
-func newProxyConfig(config PodConfig) interface{} {
- switch config.ProxyType {
- case NoopProxyType:
- return nil
- case CCProxyType:
- var ccConfig CCProxyConfig
- err := mapstructure.Decode(config.ProxyConfig, &ccConfig)
- if err != nil {
- return err
- }
- return ccConfig
- default:
- return nil
- }
-}
-
-// ProxyInfo holds the token and url returned by the proxy.
-// Each ProxyInfo relates to a process running inside a container.
-type ProxyInfo struct {
- Token string
-}
-
-// proxy is the virtcontainers proxy interface.
-type proxy interface {
- // register connects and registers the proxy to the given VM.
- // It also returns information related to containers workloads.
- register(pod Pod) ([]ProxyInfo, string, error)
-
- // unregister unregisters and disconnects the proxy from the given VM.
- unregister(pod Pod) error
-
- // connect gets the proxy a handle to a previously registered VM.
- // It also returns information related to containers workloads.
- //
- // createToken is intended to be true in case we don't want
- // the proxy to create a new token, but instead only get a handle
- // to be able to communicate with the agent inside the VM.
- connect(pod Pod, createToken bool) (ProxyInfo, string, error)
-
- // disconnect disconnects from the proxy.
- disconnect() error
-
- // sendCmd sends a command to the agent inside the VM through the
- // proxy.
- // This function will always be used from a specific agent
- // implementation because a proxy type is always tied to an agent
- // type. That's the reason why it takes an interface as parameter
- // and it returns another interface.
- // Those interfaces allows consumers (agent implementations) of this
- // proxy interface to be able to use specific structures that can only
- // be understood by a specific agent<=>proxy pair.
- sendCmd(cmd interface{}) (interface{}, error)
-}
diff --git a/vendor/github.com/containers/virtcontainers/proxy_test.go b/vendor/github.com/containers/virtcontainers/proxy_test.go
deleted file mode 100644
index fa31974..0000000
--- a/vendor/github.com/containers/virtcontainers/proxy_test.go
+++ /dev/null
@@ -1,149 +0,0 @@
-//
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "reflect"
- "testing"
-)
-
-func testSetProxyType(t *testing.T, value string, expected ProxyType) {
- var proxyType ProxyType
-
- err := (&proxyType).Set(value)
- if err != nil {
- t.Fatal(err)
- }
-
- if proxyType != expected {
- t.Fatalf("Got %s\nExpecting %s", proxyType, expected)
- }
-}
-
-func TestSetCCProxyType(t *testing.T) {
- testSetProxyType(t, "ccProxy", CCProxyType)
-}
-
-func TestSetNoopProxyType(t *testing.T) {
- testSetProxyType(t, "noopProxy", NoopProxyType)
-}
-
-func TestSetUnknownProxyType(t *testing.T) {
- var proxyType ProxyType
-
- unknownType := "unknown"
-
- err := (&proxyType).Set(unknownType)
- if err == nil {
- t.Fatalf("Should fail because %s type used", unknownType)
- }
-
- if proxyType == CCProxyType || proxyType == NoopProxyType {
- t.Fatalf("%s proxy type was not expected", proxyType)
- }
-}
-
-func testStringFromProxyType(t *testing.T, proxyType ProxyType, expected string) {
- proxyTypeStr := (&proxyType).String()
- if proxyTypeStr != expected {
- t.Fatalf("Got %s\nExpecting %s", proxyTypeStr, expected)
- }
-}
-
-func TestStringFromCCProxyType(t *testing.T) {
- proxyType := CCProxyType
- testStringFromProxyType(t, proxyType, "ccProxy")
-}
-
-func TestStringFromNoopProxyType(t *testing.T) {
- proxyType := NoopProxyType
- testStringFromProxyType(t, proxyType, "noopProxy")
-}
-
-func TestStringFromUnknownProxyType(t *testing.T) {
- var proxyType ProxyType
- testStringFromProxyType(t, proxyType, "")
-}
-
-func testNewProxyFromProxyType(t *testing.T, proxyType ProxyType, expected proxy) {
- result, err := newProxy(proxyType)
- if err != nil {
- t.Fatal(err)
- }
-
- if reflect.DeepEqual(result, expected) == false {
- t.Fatalf("Got %+v\nExpecting %+v", result, expected)
- }
-}
-
-func TestNewProxyFromCCProxyType(t *testing.T) {
- proxyType := CCProxyType
- expectedProxy := &ccProxy{}
- testNewProxyFromProxyType(t, proxyType, expectedProxy)
-}
-
-func TestNewProxyFromNoopProxyType(t *testing.T) {
- proxyType := NoopProxyType
- expectedProxy := &noopProxy{}
- testNewProxyFromProxyType(t, proxyType, expectedProxy)
-}
-
-func TestNewProxyFromUnknownProxyType(t *testing.T) {
- var proxyType ProxyType
-
- _, err := newProxy(proxyType)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func testNewProxyConfigFromPodConfig(t *testing.T, podConfig PodConfig, expected interface{}) {
- result := newProxyConfig(podConfig)
-
- if reflect.DeepEqual(result, expected) == false {
- t.Fatalf("Got %+v\nExpecting %+v", result, expected)
- }
-}
-
-func TestNewProxyConfigFromCCProxyPodConfig(t *testing.T) {
- proxyConfig := CCProxyConfig{}
-
- podConfig := PodConfig{
- ProxyType: CCProxyType,
- ProxyConfig: proxyConfig,
- }
-
- testNewProxyConfigFromPodConfig(t, podConfig, proxyConfig)
-}
-
-func TestNewProxyConfigFromNoopProxyPodConfig(t *testing.T) {
- podConfig := PodConfig{
- ProxyType: NoopProxyType,
- }
-
- testNewProxyConfigFromPodConfig(t, podConfig, nil)
-}
-
-func TestNewProxyConfigFromUnknownProxyPodConfig(t *testing.T) {
- var proxyType ProxyType
-
- podConfig := PodConfig{
- ProxyType: proxyType,
- }
-
- testNewProxyConfigFromPodConfig(t, podConfig, nil)
-}
diff --git a/vendor/github.com/containers/virtcontainers/qemu.go b/vendor/github.com/containers/virtcontainers/qemu.go
deleted file mode 100644
index 7163b01..0000000
--- a/vendor/github.com/containers/virtcontainers/qemu.go
+++ /dev/null
@@ -1,541 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "context"
- "fmt"
- "os"
- "path/filepath"
- "regexp"
- "runtime"
- "strings"
- "sync"
-
- ciaoQemu "github.com/01org/ciao/qemu"
- "github.com/01org/ciao/ssntp/uuid"
-)
-
-type qmpChannel struct {
- ctx context.Context
- path string
- disconnectCh chan struct{}
- wg sync.WaitGroup
- qmp *ciaoQemu.QMP
-}
-
-// qemu is an Hypervisor interface implementation for the Linux qemu hypervisor.
-type qemu struct {
- path string
- config HypervisorConfig
-
- hypervisorParams []string
- kernelParams []string
-
- qmpMonitorCh qmpChannel
- qmpControlCh qmpChannel
-
- qemuConfig ciaoQemu.Config
-}
-
-const defaultQemuPath = "/usr/bin/qemu-system-x86_64"
-
-const (
- defaultSockets uint32 = 1
- defaultThreads uint32 = 1
-)
-
-const (
- defaultMemSize = "2G"
- defaultMemMax = "3G"
- defaultMemSlots uint8 = 2
-)
-
-const (
- defaultConsole = "console.sock"
-)
-
-const (
- maxDevIDSize = 31
-)
-
-type qmpLogger struct{}
-
-func (l qmpLogger) V(level int32) bool {
- if level != 0 {
- return true
- }
-
- return false
-}
-
-func (l qmpLogger) Infof(format string, v ...interface{}) {
- virtLog.Infof(format, v...)
-}
-
-func (l qmpLogger) Warningf(format string, v ...interface{}) {
- virtLog.Warnf(format, v...)
-}
-
-func (l qmpLogger) Errorf(format string, v ...interface{}) {
- virtLog.Errorf(format, v...)
-}
-
-var kernelDefaultParams = []Param{
- {"root", "/dev/pmem0p1"},
- {"rootflags", "dax,data=ordered,errors=remount-ro rw"},
- {"rootfstype", "ext4"},
- {"tsc", "reliable"},
- {"no_timer_check", ""},
- {"rcupdate.rcu_expedited", "1"},
- {"i8042.direct", "1"},
- {"i8042.dumbkbd", "1"},
- {"i8042.nopnp", "1"},
- {"i8042.noaux", "1"},
- {"noreplace-smp", ""},
- {"reboot", "k"},
- {"panic", "1"},
- {"console", "hvc0"},
- {"console", "hvc1"},
- {"initcall_debug", ""},
- {"init", "/usr/lib/systemd/systemd"},
- {"systemd.unit", "cc-agent.target"},
- {"iommu", "off"},
- {"systemd.mask", "systemd-networkd.service"},
- {"systemd.mask", "systemd-networkd.socket"},
- {"cryptomgr.notests", ""},
- {"net.ifnames", "0"},
-}
-
-// kernelDefaultParamsNonDebug is a list of the default kernel
-// parameters that will be used in standard (non-debug) mode.
-var kernelDefaultParamsNonDebug = []Param{
- {"quiet", ""},
- {"systemd.show_status", "false"},
-}
-
-// kernelDefaultParamsDebug is a list of the default kernel
-// parameters that will be used in debug mode (as much boot output as
-// possible).
-var kernelDefaultParamsDebug = []Param{
- {"debug", ""},
- {"systemd.show_status", "true"},
- {"systemd.log_level", "debug"},
-}
-
-func (q *qemu) buildKernelParams(config HypervisorConfig) error {
- params := kernelDefaultParams
-
- if config.Debug == true {
- params = append(params, kernelDefaultParamsDebug...)
- } else {
- params = append(params, kernelDefaultParamsNonDebug...)
- }
-
- params = append(params, config.KernelParams...)
-
- q.kernelParams = serializeParams(params, "=")
-
- return nil
-}
-
-func (q *qemu) appendVolume(devices []ciaoQemu.Device, volume Volume) []ciaoQemu.Device {
- if volume.MountTag == "" || volume.HostPath == "" {
- return devices
- }
-
- devID := fmt.Sprintf("extra-9p-%s", volume.MountTag)
- if len(devID) > maxDevIDSize {
- devID = string(devID[:maxDevIDSize])
- }
-
- devices = append(devices,
- ciaoQemu.FSDevice{
- Driver: ciaoQemu.Virtio9P,
- FSDriver: ciaoQemu.Local,
- ID: devID,
- Path: volume.HostPath,
- MountTag: volume.MountTag,
- SecurityModel: ciaoQemu.None,
- },
- )
-
- return devices
-}
-
-func (q *qemu) appendSocket(devices []ciaoQemu.Device, socket Socket) []ciaoQemu.Device {
- devID := socket.ID
- if len(devID) > maxDevIDSize {
- devID = string(devID[:maxDevIDSize])
- }
-
- devices = append(devices,
- ciaoQemu.CharDevice{
- Driver: ciaoQemu.VirtioSerialPort,
- Backend: ciaoQemu.Socket,
- DeviceID: socket.DeviceID,
- ID: devID,
- Path: socket.HostPath,
- Name: socket.Name,
- },
- )
-
- return devices
-}
-
-func (q *qemu) appendNetworks(devices []ciaoQemu.Device, endpoints []Endpoint) []ciaoQemu.Device {
- for idx, endpoint := range endpoints {
- devices = append(devices,
- ciaoQemu.NetDevice{
- Type: ciaoQemu.TAP,
- Driver: ciaoQemu.VirtioNet,
- ID: fmt.Sprintf("network-%d", idx),
- IFName: endpoint.NetPair.TAPIface.Name,
- MACAddress: endpoint.NetPair.VirtIface.HardAddr,
- },
- )
- }
-
- return devices
-}
-
-func (q *qemu) appendFSDevices(devices []ciaoQemu.Device, podConfig PodConfig) []ciaoQemu.Device {
- // Add the containers rootfs
- for idx, c := range podConfig.Containers {
- if c.RootFs == "" || c.ID == "" {
- continue
- }
-
- devices = append(devices,
- ciaoQemu.FSDevice{
- Driver: ciaoQemu.Virtio9P,
- FSDriver: ciaoQemu.Local,
- ID: fmt.Sprintf("ctr-9p-%d", idx),
- Path: c.RootFs,
- MountTag: fmt.Sprintf("ctr-rootfs-%d", idx),
- SecurityModel: ciaoQemu.None,
- },
- )
- }
-
- // Add the shared volumes
- for _, v := range podConfig.Volumes {
- devices = q.appendVolume(devices, v)
- }
-
- return devices
-}
-
-func (q *qemu) appendConsoles(devices []ciaoQemu.Device, podConfig PodConfig) []ciaoQemu.Device {
- serial := ciaoQemu.SerialDevice{
- Driver: ciaoQemu.VirtioSerial,
- ID: "serial0",
- }
-
- devices = append(devices, serial)
-
- var console ciaoQemu.CharDevice
-
- console = ciaoQemu.CharDevice{
- Driver: ciaoQemu.Console,
- Backend: ciaoQemu.Socket,
- DeviceID: "console0",
- ID: "charconsole0",
- Path: q.getPodConsole(podConfig.ID),
- }
-
- devices = append(devices, console)
-
- return devices
-}
-
-func (q *qemu) appendImage(devices []ciaoQemu.Device, podConfig PodConfig) ([]ciaoQemu.Device, error) {
- imageFile, err := os.Open(q.config.ImagePath)
- if err != nil {
- return nil, err
- }
- defer imageFile.Close()
-
- imageStat, err := imageFile.Stat()
- if err != nil {
- return nil, err
- }
-
- object := ciaoQemu.Object{
- Driver: ciaoQemu.NVDIMM,
- Type: ciaoQemu.MemoryBackendFile,
- DeviceID: "nv0",
- ID: "mem0",
- MemPath: q.config.ImagePath,
- Size: (uint64)(imageStat.Size()),
- }
-
- devices = append(devices, object)
-
- return devices, nil
-}
-
-func (q *qemu) forceUUIDFormat(str string) string {
- re := regexp.MustCompile(`[^[0-9,a-f,A-F]]*`)
- hexStr := re.ReplaceAllLiteralString(str, ``)
-
- slice := []byte(hexStr)
- sliceLen := len(slice)
-
- var uuidSlice uuid.UUID
- uuidLen := len(uuidSlice)
-
- if sliceLen > uuidLen {
- copy(uuidSlice[:], slice[:uuidLen])
- } else {
- copy(uuidSlice[:], slice)
- }
-
- return uuidSlice.String()
-}
-
-// init intializes the Qemu structure.
-func (q *qemu) init(config HypervisorConfig) error {
- valid, err := config.valid()
- if valid == false || err != nil {
- return err
- }
-
- p := config.HypervisorPath
- if p == "" {
- p = defaultQemuPath
- }
-
- q.config = config
- q.path = p
-
- err = q.buildKernelParams(config)
- if err != nil {
- return err
- }
-
- return nil
-}
-
-func (q *qemu) qmpMonitor(connectedCh chan struct{}) {
- defer func(qemu *qemu) {
- if q.qmpMonitorCh.qmp != nil {
- q.qmpMonitorCh.qmp.Shutdown()
- }
-
- q.qmpMonitorCh.wg.Done()
- }(q)
-
- cfg := ciaoQemu.QMPConfig{Logger: qmpLogger{}}
- qmp, ver, err := ciaoQemu.QMPStart(q.qmpMonitorCh.ctx, q.qmpMonitorCh.path, cfg, q.qmpMonitorCh.disconnectCh)
- if err != nil {
- virtLog.Errorf("Failed to connect to QEMU instance %v", err)
- return
- }
-
- q.qmpMonitorCh.qmp = qmp
-
- virtLog.Infof("QMP version %d.%d.%d", ver.Major, ver.Minor, ver.Micro)
- virtLog.Infof("QMP capabilities %s", ver.Capabilities)
-
- err = q.qmpMonitorCh.qmp.ExecuteQMPCapabilities(q.qmpMonitorCh.ctx)
- if err != nil {
- virtLog.Errorf("Unable to send qmp_capabilities command: %v", err)
- return
- }
-
- close(connectedCh)
-}
-
-func (q *qemu) setCPUResources(podConfig PodConfig) ciaoQemu.SMP {
- vcpus := uint(runtime.NumCPU())
- if podConfig.VMConfig.VCPUs > 0 {
- vcpus = podConfig.VMConfig.VCPUs
- }
-
- smp := ciaoQemu.SMP{
- CPUs: uint32(vcpus),
- Cores: uint32(vcpus),
- Sockets: defaultSockets,
- Threads: defaultThreads,
- }
-
- return smp
-}
-
-func (q *qemu) setMemoryResources(podConfig PodConfig) ciaoQemu.Memory {
- mem := defaultMemSize
- memMax := defaultMemMax
- if podConfig.VMConfig.Memory > 0 {
- mem = fmt.Sprintf("%dM", podConfig.VMConfig.Memory)
- intMemMax := int(float64(podConfig.VMConfig.Memory) * 1.5)
- memMax = fmt.Sprintf("%dM", intMemMax)
- }
-
- memory := ciaoQemu.Memory{
- Size: mem,
- Slots: defaultMemSlots,
- MaxMem: memMax,
- }
-
- return memory
-}
-
-// createPod is the Hypervisor pod creation implementation for ciaoQemu.
-func (q *qemu) createPod(podConfig PodConfig) error {
- var devices []ciaoQemu.Device
-
- machine := ciaoQemu.Machine{
- Type: "pc-lite",
- Acceleration: "kvm,kernel_irqchip,nvdimm",
- }
-
- smp := q.setCPUResources(podConfig)
-
- memory := q.setMemoryResources(podConfig)
-
- knobs := ciaoQemu.Knobs{
- NoUserConfig: true,
- NoDefaults: true,
- NoGraphic: true,
- Daemonize: true,
- }
-
- kernel := ciaoQemu.Kernel{
- Path: q.config.KernelPath,
- Params: strings.Join(q.kernelParams, " "),
- }
-
- rtc := ciaoQemu.RTC{
- Base: "utc",
- DriftFix: "slew",
- }
-
- q.qmpMonitorCh = qmpChannel{
- ctx: context.Background(),
- path: fmt.Sprintf("%s/%s/%s", runStoragePath, podConfig.ID, monitorSocket),
- }
-
- q.qmpControlCh = qmpChannel{
- ctx: context.Background(),
- path: fmt.Sprintf("%s/%s/%s", runStoragePath, podConfig.ID, controlSocket),
- }
-
- qmpSockets := []ciaoQemu.QMPSocket{
- {
- Type: "unix",
- Name: q.qmpMonitorCh.path,
- Server: true,
- NoWait: true,
- },
- {
- Type: "unix",
- Name: q.qmpControlCh.path,
- Server: true,
- NoWait: true,
- },
- }
-
- devices = q.appendFSDevices(devices, podConfig)
- devices = q.appendConsoles(devices, podConfig)
- devices, err := q.appendImage(devices, podConfig)
- if err != nil {
- return err
- }
-
- qemuConfig := ciaoQemu.Config{
- Name: fmt.Sprintf("pod-%s", podConfig.ID),
- UUID: q.forceUUIDFormat(podConfig.ID),
- Path: q.path,
- Ctx: q.qmpMonitorCh.ctx,
- Machine: machine,
- SMP: smp,
- Memory: memory,
- Devices: devices,
- CPUModel: "host",
- Kernel: kernel,
- RTC: rtc,
- QMPSockets: qmpSockets,
- Knobs: knobs,
- VGA: "none",
- GlobalParam: "kvm-pit.lost_tick_policy=discard",
- }
-
- q.qemuConfig = qemuConfig
-
- return nil
-}
-
-// startPod will start the Pod's VM.
-func (q *qemu) startPod(startCh, stopCh chan struct{}) error {
- strErr, err := ciaoQemu.LaunchQemu(q.qemuConfig, qmpLogger{})
- if err != nil {
- return fmt.Errorf("%s", strErr)
- }
-
- // Start the QMP monitoring thread
- q.qmpMonitorCh.disconnectCh = stopCh
- q.qmpMonitorCh.wg.Add(1)
- q.qmpMonitor(startCh)
-
- return nil
-}
-
-// stopPod will stop the Pod's VM.
-func (q *qemu) stopPod() error {
- cfg := ciaoQemu.QMPConfig{Logger: qmpLogger{}}
- q.qmpControlCh.disconnectCh = make(chan struct{})
-
- qmp, _, err := ciaoQemu.QMPStart(q.qmpControlCh.ctx, q.qmpControlCh.path, cfg, q.qmpControlCh.disconnectCh)
- if err != nil {
- virtLog.Errorf("Failed to connect to QEMU instance %v", err)
- return err
- }
-
- err = qmp.ExecuteQMPCapabilities(q.qmpMonitorCh.ctx)
- if err != nil {
- virtLog.Errorf("Failed to negotiate capabilities with QEMU %v", err)
- return err
- }
-
- return qmp.ExecuteQuit(q.qmpMonitorCh.ctx)
-}
-
-// addDevice will add extra devices to Qemu command line.
-func (q *qemu) addDevice(devInfo interface{}, devType deviceType) error {
- switch devType {
- case fsDev:
- volume := devInfo.(Volume)
- q.qemuConfig.Devices = q.appendVolume(q.qemuConfig.Devices, volume)
- case serialPortDev:
- socket := devInfo.(Socket)
- q.qemuConfig.Devices = q.appendSocket(q.qemuConfig.Devices, socket)
- case netDev:
- endpoints := devInfo.([]Endpoint)
- q.qemuConfig.Devices = q.appendNetworks(q.qemuConfig.Devices, endpoints)
- default:
- break
- }
-
- return nil
-}
-
-// getPodConsole builds the path of the console where we can read
-// logs coming from the pod.
-func (q *qemu) getPodConsole(podID string) string {
- return filepath.Join(runStoragePath, podID, defaultConsole)
-}
diff --git a/vendor/github.com/containers/virtcontainers/qemu_test.go b/vendor/github.com/containers/virtcontainers/qemu_test.go
deleted file mode 100644
index a446710..0000000
--- a/vendor/github.com/containers/virtcontainers/qemu_test.go
+++ /dev/null
@@ -1,461 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "reflect"
- "strings"
- "testing"
-
- ciaoQemu "github.com/01org/ciao/qemu"
-)
-
-func newQemuConfig() HypervisorConfig {
- return HypervisorConfig{
- KernelPath: testQemuKernelPath,
- ImagePath: testQemuImagePath,
- HypervisorPath: testQemuPath,
- }
-}
-
-func testQemuBuildKernelParams(t *testing.T, kernelParams []Param, expected string, debug bool) {
- qemuConfig := newQemuConfig()
- qemuConfig.KernelParams = kernelParams
-
- if debug == true {
- qemuConfig.Debug = true
- }
-
- q := &qemu{}
-
- err := q.buildKernelParams(qemuConfig)
- if err != nil {
- t.Fatal(err)
- }
-
- if strings.Join(q.kernelParams, " ") != expected {
- t.Fatal()
- }
-}
-
-var testQemuKernelParamsBase = "root=/dev/pmem0p1 rootflags=dax,data=ordered,errors=remount-ro rw rootfstype=ext4 tsc=reliable no_timer_check rcupdate.rcu_expedited=1 i8042.direct=1 i8042.dumbkbd=1 i8042.nopnp=1 i8042.noaux=1 noreplace-smp reboot=k panic=1 console=hvc0 console=hvc1 initcall_debug init=/usr/lib/systemd/systemd systemd.unit=cc-agent.target iommu=off systemd.mask=systemd-networkd.service systemd.mask=systemd-networkd.socket cryptomgr.notests net.ifnames=0"
-var testQemuKernelParamsNonDebug = "quiet systemd.show_status=false"
-var testQemuKernelParamsDebug = "debug systemd.show_status=true systemd.log_level=debug"
-
-func TestQemuBuildKernelParamsFoo(t *testing.T) {
- // two representations of the same kernel parameters
- suffixStr := "foo=foo bar=bar"
- suffixParams := []Param{
- {
- parameter: "foo",
- value: "foo",
- },
- {
- parameter: "bar",
- value: "bar",
- },
- }
-
- type testData struct {
- debugParams string
- debugValue bool
- }
-
- data := []testData{
- {testQemuKernelParamsNonDebug, false},
- {testQemuKernelParamsDebug, true},
- }
-
- for _, d := range data {
- // kernel params consist of a default set of params,
- // followed by a set of params that depend on whether
- // debug mode is enabled and end with any user-supplied
- // params.
- expected := []string{testQemuKernelParamsBase, d.debugParams, suffixStr}
-
- expectedOut := strings.Join(expected, " ")
-
- testQemuBuildKernelParams(t, suffixParams, expectedOut, d.debugValue)
- }
-}
-
-func testQemuAppend(t *testing.T, structure interface{}, expected []ciaoQemu.Device, devType deviceType) {
- var devices []ciaoQemu.Device
- q := &qemu{}
-
- switch s := structure.(type) {
- case Volume:
- devices = q.appendVolume(devices, s)
- case Socket:
- devices = q.appendSocket(devices, s)
- case PodConfig:
- switch devType {
- case fsDev:
- devices = q.appendFSDevices(devices, s)
- case consoleDev:
- devices = q.appendConsoles(devices, s)
- }
- }
-
- if reflect.DeepEqual(devices, expected) == false {
- t.Fatalf("Got %v\nExpecting %v", devices, expected)
- }
-}
-
-func TestQemuAppendVolume(t *testing.T) {
- mountTag := "testMountTag"
- hostPath := "testHostPath"
-
- expectedOut := []ciaoQemu.Device{
- ciaoQemu.FSDevice{
- Driver: ciaoQemu.Virtio9P,
- FSDriver: ciaoQemu.Local,
- ID: fmt.Sprintf("extra-9p-%s", mountTag),
- Path: hostPath,
- MountTag: mountTag,
- SecurityModel: ciaoQemu.None,
- },
- }
-
- volume := Volume{
- MountTag: mountTag,
- HostPath: hostPath,
- }
-
- testQemuAppend(t, volume, expectedOut, -1)
-}
-
-func TestQemuAppendSocket(t *testing.T) {
- deviceID := "channelTest"
- id := "charchTest"
- hostPath := "/tmp/hyper_test.sock"
- name := "sh.hyper.channel.test"
-
- expectedOut := []ciaoQemu.Device{
- ciaoQemu.CharDevice{
- Driver: ciaoQemu.VirtioSerialPort,
- Backend: ciaoQemu.Socket,
- DeviceID: deviceID,
- ID: id,
- Path: hostPath,
- Name: name,
- },
- }
-
- socket := Socket{
- DeviceID: deviceID,
- ID: id,
- HostPath: hostPath,
- Name: name,
- }
-
- testQemuAppend(t, socket, expectedOut, -1)
-}
-
-func TestQemuAppendFSDevices(t *testing.T) {
- podID := "testPodID"
- contID := "testContID"
- contRootFs := "testContRootFs"
- volMountTag := "testVolMountTag"
- volHostPath := "testVolHostPath"
-
- expectedOut := []ciaoQemu.Device{
- ciaoQemu.FSDevice{
- Driver: ciaoQemu.Virtio9P,
- FSDriver: ciaoQemu.Local,
- ID: "ctr-9p-0",
- Path: fmt.Sprintf("%s.1", contRootFs),
- MountTag: "ctr-rootfs-0",
- SecurityModel: ciaoQemu.None,
- },
- ciaoQemu.FSDevice{
- Driver: ciaoQemu.Virtio9P,
- FSDriver: ciaoQemu.Local,
- ID: "ctr-9p-1",
- Path: fmt.Sprintf("%s.2", contRootFs),
- MountTag: "ctr-rootfs-1",
- SecurityModel: ciaoQemu.None,
- },
- ciaoQemu.FSDevice{
- Driver: ciaoQemu.Virtio9P,
- FSDriver: ciaoQemu.Local,
- ID: fmt.Sprintf("extra-9p-%s", fmt.Sprintf("%s.1", volMountTag)),
- Path: fmt.Sprintf("%s.1", volHostPath),
- MountTag: fmt.Sprintf("%s.1", volMountTag),
- SecurityModel: ciaoQemu.None,
- },
- ciaoQemu.FSDevice{
- Driver: ciaoQemu.Virtio9P,
- FSDriver: ciaoQemu.Local,
- ID: fmt.Sprintf("extra-9p-%s", fmt.Sprintf("%s.2", volMountTag)),
- Path: fmt.Sprintf("%s.2", volHostPath),
- MountTag: fmt.Sprintf("%s.2", volMountTag),
- SecurityModel: ciaoQemu.None,
- },
- }
-
- volumes := []Volume{
- {
- MountTag: fmt.Sprintf("%s.1", volMountTag),
- HostPath: fmt.Sprintf("%s.1", volHostPath),
- },
- {
- MountTag: fmt.Sprintf("%s.2", volMountTag),
- HostPath: fmt.Sprintf("%s.2", volHostPath),
- },
- }
-
- containers := []ContainerConfig{
- {
- ID: fmt.Sprintf("%s.1", contID),
- RootFs: fmt.Sprintf("%s.1", contRootFs),
- },
- {
- ID: fmt.Sprintf("%s.2", contID),
- RootFs: fmt.Sprintf("%s.2", contRootFs),
- },
- }
-
- podConfig := PodConfig{
- ID: podID,
- Volumes: volumes,
- Containers: containers,
- }
-
- testQemuAppend(t, podConfig, expectedOut, fsDev)
-}
-
-func TestQemuAppendConsoles(t *testing.T) {
- podID := "testPodID"
-
- expectedOut := []ciaoQemu.Device{
- ciaoQemu.SerialDevice{
- Driver: ciaoQemu.VirtioSerial,
- ID: "serial0",
- },
- ciaoQemu.CharDevice{
- Driver: ciaoQemu.Console,
- Backend: ciaoQemu.Socket,
- DeviceID: "console0",
- ID: "charconsole0",
- Path: filepath.Join(runStoragePath, podID, defaultConsole),
- },
- }
-
- podConfig := PodConfig{
- ID: podID,
- Containers: []ContainerConfig{},
- }
-
- testQemuAppend(t, podConfig, expectedOut, consoleDev)
-}
-
-func TestQemuAppendImage(t *testing.T) {
- var devices []ciaoQemu.Device
-
- qemuConfig := newQemuConfig()
- q := &qemu{
- config: qemuConfig,
- }
-
- imageFile, err := os.Open(q.config.ImagePath)
- if err != nil {
- t.Fatal(err)
- }
- defer imageFile.Close()
-
- imageStat, err := imageFile.Stat()
- if err != nil {
- t.Fatal(err)
- }
-
- expectedOut := []ciaoQemu.Device{
- ciaoQemu.Object{
- Driver: ciaoQemu.NVDIMM,
- Type: ciaoQemu.MemoryBackendFile,
- DeviceID: "nv0",
- ID: "mem0",
- MemPath: q.config.ImagePath,
- Size: (uint64)(imageStat.Size()),
- },
- }
-
- podConfig := PodConfig{}
-
- devices, err = q.appendImage(devices, podConfig)
- if err != nil {
- t.Fatal(err)
- }
-
- if reflect.DeepEqual(devices, expectedOut) == false {
- t.Fatalf("Got %v\nExpecting %v", devices, expectedOut)
- }
-}
-
-func TestQemuInit(t *testing.T) {
- qemuConfig := newQemuConfig()
- q := &qemu{}
-
- err := q.init(qemuConfig)
- if err != nil {
- t.Fatal(err)
- }
-
- if reflect.DeepEqual(qemuConfig, q.config) == false {
- t.Fatalf("Got %v\nExpecting %v", q.config, qemuConfig)
- }
-
- if reflect.DeepEqual(qemuConfig.HypervisorPath, q.path) == false {
- t.Fatalf("Got %v\nExpecting %v", q.path, qemuConfig.HypervisorPath)
- }
-
- // non-debug is the default
- var testQemuKernelParamsDefault = testQemuKernelParamsBase + " " + testQemuKernelParamsNonDebug
-
- if strings.Join(q.kernelParams, " ") != testQemuKernelParamsDefault {
- t.Fatal()
- }
-}
-
-func TestQemuSetCPUResources(t *testing.T) {
- vcpus := 1
-
- q := &qemu{}
-
- expectedOut := ciaoQemu.SMP{
- CPUs: uint32(vcpus),
- Cores: uint32(vcpus),
- Sockets: uint32(1),
- Threads: uint32(1),
- }
-
- vmConfig := Resources{
- VCPUs: uint(vcpus),
- }
-
- podConfig := PodConfig{
- VMConfig: vmConfig,
- }
-
- smp := q.setCPUResources(podConfig)
-
- if reflect.DeepEqual(smp, expectedOut) == false {
- t.Fatalf("Got %v\nExpecting %v", smp, expectedOut)
- }
-}
-
-func TestQemuSetMemoryResources(t *testing.T) {
- mem := 1000
-
- q := &qemu{}
-
- expectedOut := ciaoQemu.Memory{
- Size: "1000M",
- Slots: uint8(2),
- MaxMem: "1500M",
- }
-
- vmConfig := Resources{
- Memory: uint(mem),
- }
-
- podConfig := PodConfig{
- VMConfig: vmConfig,
- }
-
- memory := q.setMemoryResources(podConfig)
-
- if reflect.DeepEqual(memory, expectedOut) == false {
- t.Fatalf("Got %v\nExpecting %v", memory, expectedOut)
- }
-}
-
-func testQemuAddDevice(t *testing.T, devInfo interface{}, devType deviceType, expected []ciaoQemu.Device) {
- q := &qemu{}
-
- err := q.addDevice(devInfo, devType)
- if err != nil {
- t.Fatal(err)
- }
-
- if reflect.DeepEqual(q.qemuConfig.Devices, expected) == false {
- t.Fatalf("Got %v\nExpecting %v", q.qemuConfig.Devices, expected)
- }
-}
-
-func TestQemuAddDeviceFsDev(t *testing.T) {
- mountTag := "testMountTag"
- hostPath := "testHostPath"
-
- expectedOut := []ciaoQemu.Device{
- ciaoQemu.FSDevice{
- Driver: ciaoQemu.Virtio9P,
- FSDriver: ciaoQemu.Local,
- ID: fmt.Sprintf("extra-9p-%s", mountTag),
- Path: hostPath,
- MountTag: mountTag,
- SecurityModel: ciaoQemu.None,
- },
- }
-
- volume := Volume{
- MountTag: mountTag,
- HostPath: hostPath,
- }
-
- testQemuAddDevice(t, volume, fsDev, expectedOut)
-}
-
-func TestQemuAddDeviceSerialPordDev(t *testing.T) {
- deviceID := "channelTest"
- id := "charchTest"
- hostPath := "/tmp/hyper_test.sock"
- name := "sh.hyper.channel.test"
-
- expectedOut := []ciaoQemu.Device{
- ciaoQemu.CharDevice{
- Driver: ciaoQemu.VirtioSerialPort,
- Backend: ciaoQemu.Socket,
- DeviceID: deviceID,
- ID: id,
- Path: hostPath,
- Name: name,
- },
- }
-
- socket := Socket{
- DeviceID: deviceID,
- ID: id,
- HostPath: hostPath,
- Name: name,
- }
-
- testQemuAddDevice(t, socket, serialPortDev, expectedOut)
-}
-
-func TestQemuGetPodConsole(t *testing.T) {
- q := &qemu{}
- podID := "testPodID"
- expected := filepath.Join(runStoragePath, podID, defaultConsole)
-
- if result := q.getPodConsole(podID); result != expected {
- t.Fatalf("Got %s\nExpecting %s", result, expected)
- }
-}
diff --git a/vendor/github.com/containers/virtcontainers/shim.go b/vendor/github.com/containers/virtcontainers/shim.go
deleted file mode 100644
index d67b690..0000000
--- a/vendor/github.com/containers/virtcontainers/shim.go
+++ /dev/null
@@ -1,104 +0,0 @@
-//
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
-
- "github.com/mitchellh/mapstructure"
-)
-
-// ShimType describes a shim type.
-type ShimType string
-
-const (
- // CCShimType is the ccShim.
- CCShimType ShimType = "ccShim"
-
- // NoopShimType is the noopShim.
- NoopShimType ShimType = "noopShim"
-)
-
-// ShimParams is the structure providing specific parameters needed
-// for the execution of the shim binary.
-type ShimParams struct {
- Token string
- URL string
- Console string
-}
-
-// Set sets a shim type based on the input string.
-func (pType *ShimType) Set(value string) error {
- switch value {
- case "noopShim":
- *pType = NoopShimType
- return nil
- case "ccShim":
- *pType = CCShimType
- return nil
- default:
- return fmt.Errorf("Unknown shim type %s", value)
- }
-}
-
-// String converts a shim type to a string.
-func (pType *ShimType) String() string {
- switch *pType {
- case NoopShimType:
- return string(NoopShimType)
- case CCShimType:
- return string(CCShimType)
- default:
- return ""
- }
-}
-
-// newShim returns a shim from a shim type.
-func newShim(pType ShimType) (shim, error) {
- switch pType {
- case NoopShimType:
- return &noopShim{}, nil
- case CCShimType:
- return &ccShim{}, nil
- default:
- return &noopShim{}, nil
- }
-}
-
-// newShimConfig returns a shim config from a generic PodConfig interface.
-func newShimConfig(config PodConfig) interface{} {
- switch config.ShimType {
- case NoopShimType:
- return nil
- case CCShimType:
- var ccConfig CCShimConfig
- err := mapstructure.Decode(config.ShimConfig, &ccConfig)
- if err != nil {
- return err
- }
- return ccConfig
- default:
- return nil
- }
-}
-
-// shim is the virtcontainers shim interface.
-type shim interface {
- // start starts the shim relying on its configuration and on
- // parameters provided.
- start(pod Pod, params ShimParams) (int, error)
-}
diff --git a/vendor/github.com/containers/virtcontainers/shim_test.go b/vendor/github.com/containers/virtcontainers/shim_test.go
deleted file mode 100644
index f814c9d..0000000
--- a/vendor/github.com/containers/virtcontainers/shim_test.go
+++ /dev/null
@@ -1,149 +0,0 @@
-//
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "reflect"
- "testing"
-)
-
-func testSetShimType(t *testing.T, value string, expected ShimType) {
- var shimType ShimType
-
- err := (&shimType).Set(value)
- if err != nil {
- t.Fatal(err)
- }
-
- if shimType != expected {
- t.Fatalf("Got %s\nExpecting %s", shimType, expected)
- }
-}
-
-func TestSetCCShimType(t *testing.T) {
- testSetShimType(t, "ccShim", CCShimType)
-}
-
-func TestSetNoopShimType(t *testing.T) {
- testSetShimType(t, "noopShim", NoopShimType)
-}
-
-func TestSetUnknownShimType(t *testing.T) {
- var shimType ShimType
-
- unknownType := "unknown"
-
- err := (&shimType).Set(unknownType)
- if err == nil {
- t.Fatalf("Should fail because %s type used", unknownType)
- }
-
- if shimType == CCShimType || shimType == NoopShimType {
- t.Fatalf("%s shim type was not expected", shimType)
- }
-}
-
-func testStringFromShimType(t *testing.T, shimType ShimType, expected string) {
- shimTypeStr := (&shimType).String()
- if shimTypeStr != expected {
- t.Fatalf("Got %s\nExpecting %s", shimTypeStr, expected)
- }
-}
-
-func TestStringFromCCShimType(t *testing.T) {
- shimType := CCShimType
- testStringFromShimType(t, shimType, "ccShim")
-}
-
-func TestStringFromNoopShimType(t *testing.T) {
- shimType := NoopShimType
- testStringFromShimType(t, shimType, "noopShim")
-}
-
-func TestStringFromUnknownShimType(t *testing.T) {
- var shimType ShimType
- testStringFromShimType(t, shimType, "")
-}
-
-func testNewShimFromShimType(t *testing.T, shimType ShimType, expected shim) {
- result, err := newShim(shimType)
- if err != nil {
- t.Fatal(err)
- }
-
- if reflect.DeepEqual(result, expected) == false {
- t.Fatalf("Got %+v\nExpecting %+v", result, expected)
- }
-}
-
-func TestNewShimFromCCShimType(t *testing.T) {
- shimType := CCShimType
- expectedShim := &ccShim{}
- testNewShimFromShimType(t, shimType, expectedShim)
-}
-
-func TestNewShimFromNoopShimType(t *testing.T) {
- shimType := NoopShimType
- expectedShim := &noopShim{}
- testNewShimFromShimType(t, shimType, expectedShim)
-}
-
-func TestNewShimFromUnknownShimType(t *testing.T) {
- var shimType ShimType
-
- _, err := newShim(shimType)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func testNewShimConfigFromPodConfig(t *testing.T, podConfig PodConfig, expected interface{}) {
- result := newShimConfig(podConfig)
-
- if reflect.DeepEqual(result, expected) == false {
- t.Fatalf("Got %+v\nExpecting %+v", result, expected)
- }
-}
-
-func TestNewShimConfigFromCCShimPodConfig(t *testing.T) {
- shimConfig := CCShimConfig{}
-
- podConfig := PodConfig{
- ShimType: CCShimType,
- ShimConfig: shimConfig,
- }
-
- testNewShimConfigFromPodConfig(t, podConfig, shimConfig)
-}
-
-func TestNewShimConfigFromNoopShimPodConfig(t *testing.T) {
- podConfig := PodConfig{
- ShimType: NoopShimType,
- }
-
- testNewShimConfigFromPodConfig(t, podConfig, nil)
-}
-
-func TestNewShimConfigFromUnknownShimPodConfig(t *testing.T) {
- var shimType ShimType
-
- podConfig := PodConfig{
- ShimType: shimType,
- }
-
- testNewShimConfigFromPodConfig(t, podConfig, nil)
-}
diff --git a/vendor/github.com/containers/virtcontainers/spawner.go b/vendor/github.com/containers/virtcontainers/spawner.go
deleted file mode 100644
index 84e8e31..0000000
--- a/vendor/github.com/containers/virtcontainers/spawner.go
+++ /dev/null
@@ -1,65 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
-)
-
-// SpawnerType describes the type of guest agent a Pod should run.
-type SpawnerType string
-
-const (
- // NsEnter is the nsenter spawner type
- NsEnter SpawnerType = "nsenter"
-)
-
-// Set sets an agent type based on the input string.
-func (spawnerType *SpawnerType) Set(value string) error {
- switch value {
- case "nsenter":
- *spawnerType = NsEnter
- return nil
- default:
- return fmt.Errorf("Unknown spawner type %s", value)
- }
-}
-
-// String converts an agent type to a string.
-func (spawnerType *SpawnerType) String() string {
- switch *spawnerType {
- case NsEnter:
- return string(NsEnter)
- default:
- return ""
- }
-}
-
-// newSpawner returns an agent from and agent type.
-func newSpawner(spawnerType SpawnerType) spawner {
- switch spawnerType {
- case NsEnter:
- return &nsenter{}
- default:
- return nil
- }
-}
-
-// spawner is the virtcontainers spawner interface.
-type spawner interface {
- formatArgs(args []string) ([]string, error)
-}
diff --git a/vendor/github.com/containers/virtcontainers/spawner_test.go b/vendor/github.com/containers/virtcontainers/spawner_test.go
deleted file mode 100644
index 0ba8635..0000000
--- a/vendor/github.com/containers/virtcontainers/spawner_test.go
+++ /dev/null
@@ -1,97 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "reflect"
- "testing"
-)
-
-var testSpawnerTypeList = []SpawnerType{
- NsEnter,
-}
-
-func TestSpawnerTypeSet(t *testing.T) {
- var s SpawnerType
- var err error
-
- for _, sType := range testSpawnerTypeList {
- err = (&s).Set(string(sType))
- if err != nil {
- t.Fatal(err)
- }
-
- if s != sType {
- t.Fatal()
- }
- }
-}
-
-func TestWrongSpawnerTypeSet(t *testing.T) {
- var s SpawnerType
-
- err := (&s).Set("noType")
- if err == nil || s != "" {
- t.Fatal()
- }
-}
-
-func TestSpawnerTypeString(t *testing.T) {
- for _, sType := range testSpawnerTypeList {
- s := sType
-
- result := (&s).String()
- if result != string(NsEnter) {
- t.Fatal()
- }
- }
-}
-
-func TestWrongSpawnerTypeString(t *testing.T) {
- var s = SpawnerType("noType")
-
- result := (&s).String()
- if result != "" {
- t.Fatal()
- }
-}
-
-func testSpawnerNewSpawner(t *testing.T, sType SpawnerType, expected interface{}) {
- spawner := newSpawner(sType)
-
- if spawner == nil {
- t.Fatal()
- }
-
- if reflect.DeepEqual(spawner, expected) == false {
- t.Fatal()
- }
-}
-
-func TestSpawnerNsEnterNewSpawner(t *testing.T) {
- expectedOut := &nsenter{}
-
- testSpawnerNewSpawner(t, NsEnter, expectedOut)
-}
-
-func TestWrongSpawnerNewSpawner(t *testing.T) {
- spawner := newSpawner(SpawnerType("noType"))
-
- if spawner != nil {
- t.Fatal()
- }
-}
diff --git a/vendor/github.com/containers/virtcontainers/sshd.go b/vendor/github.com/containers/virtcontainers/sshd.go
deleted file mode 100644
index 27ca7b8..0000000
--- a/vendor/github.com/containers/virtcontainers/sshd.go
+++ /dev/null
@@ -1,196 +0,0 @@
-//
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
- "io/ioutil"
- "strings"
- "syscall"
- "time"
-
- "golang.org/x/crypto/ssh"
-)
-
-// SshdConfig is a structure storing information needed for
-// sshd agent initialization.
-type SshdConfig struct {
- Username string
- PrivKeyFile string
- Server string
- Port string
- Protocol string
-
- Spawner SpawnerType
-}
-
-// sshd is an Agent interface implementation for the sshd agent.
-type sshd struct {
- config SshdConfig
- client *ssh.Client
-
- spawner spawner
-}
-
-func (c SshdConfig) validate() bool {
- return true
-}
-
-func publicKeyAuth(file string) (ssh.AuthMethod, error) {
- if file == "" {
- return nil, errNeedFile
- }
-
- privateBytes, err := ioutil.ReadFile(file)
- if err != nil {
- return nil, fmt.Errorf("Failed to load private key")
- }
-
- private, err := ssh.ParsePrivateKey(privateBytes)
- if err != nil {
- return nil, fmt.Errorf("Failed to parse private key")
- }
-
- return ssh.PublicKeys(private), nil
-}
-
-func execCmd(session *ssh.Session, cmd string) error {
- if session == nil {
- return fmt.Errorf("session cannot be empty")
- }
-
- stdout, err := session.CombinedOutput(cmd)
-
- if err != nil {
- return fmt.Errorf("Failed to run %s", cmd)
- }
-
- fmt.Printf("%s\n", stdout)
-
- return nil
-}
-
-// init is the agent initialization implementation for sshd.
-func (s *sshd) init(pod *Pod, config interface{}) error {
- if pod == nil {
- return errNeedPod
- }
-
- if config == nil {
- return fmt.Errorf("config cannot be empty")
- }
-
- c := config.(SshdConfig)
- if c.validate() == false {
- return fmt.Errorf("Invalid configuration")
- }
- s.config = c
-
- s.spawner = newSpawner(c.Spawner)
-
- return nil
-}
-
-// exec is the agent command execution implementation for sshd.
-func (s *sshd) exec(pod *Pod, c Container, process Process, cmd Cmd) error {
- if pod == nil {
- return errNeedPod
- }
-
- session, err := s.client.NewSession()
- if err != nil {
- return fmt.Errorf("Failed to create session (Pod ID %s, Container ID %s)",
- pod.id, c.id)
- }
- defer session.Close()
-
- if s.spawner != nil {
- cmd.Args, err = s.spawner.formatArgs(cmd.Args)
- if err != nil {
- return err
- }
- }
-
- strCmd := strings.Join(cmd.Args, " ")
-
- return execCmd(session, strCmd)
-}
-
-// startPod is the agent Pod starting implementation for sshd.
-func (s *sshd) startPod(pod Pod) error {
- if s.client != nil {
- session, err := s.client.NewSession()
- if err == nil {
- session.Close()
- return nil
- }
- }
-
- sshAuthMethod, err := publicKeyAuth(s.config.PrivKeyFile)
- if err != nil {
- return err
- }
- sshConfig := &ssh.ClientConfig{
- User: s.config.Username,
- Auth: []ssh.AuthMethod{
- sshAuthMethod,
- },
- }
-
- for i := 0; i < 1000; i++ {
- s.client, err = ssh.Dial(s.config.Protocol, s.config.Server+":"+s.config.Port, sshConfig)
- if err == nil {
- break
- }
-
- select {
- case <-time.After(100 * time.Millisecond):
- break
- }
- }
-
- if err != nil {
- return fmt.Errorf("Failed to dial: %s", err)
- }
-
- return nil
-}
-
-// stopPod is the agent Pod stopping implementation for sshd.
-func (s *sshd) stopPod(pod Pod) error {
- return nil
-}
-
-// createContainer is the agent Container creation implementation for sshd.
-func (s *sshd) createContainer(pod *Pod, c *Container) error {
- return nil
-}
-
-// startContainer is the agent Container starting implementation for sshd.
-func (s *sshd) startContainer(pod Pod, c Container) error {
- return nil
-}
-
-// stopContainer is the agent Container stopping implementation for sshd.
-func (s *sshd) stopContainer(pod Pod, c Container) error {
- return nil
-}
-
-// killContainer is the agent Container signaling implementation for sshd.
-func (s *sshd) killContainer(pod Pod, c Container, signal syscall.Signal) error {
- return nil
-}
diff --git a/vendor/github.com/containers/virtcontainers/syscall.go b/vendor/github.com/containers/virtcontainers/syscall.go
deleted file mode 100644
index f1c12e7..0000000
--- a/vendor/github.com/containers/virtcontainers/syscall.go
+++ /dev/null
@@ -1,82 +0,0 @@
-//
-// Copyright 2015 The rkt Authors
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "syscall"
-)
-
-const mountPerm = os.FileMode(0755)
-
-// bindMount bind mounts a source in to a destination. This will
-// do some bookkeeping:
-// * evaluate all symlinks
-// * ensure the source exists
-// * recursively create the destination
-func bindMount(source, destination string) error {
- if source == "" {
- return fmt.Errorf("source must be specified")
- }
- if destination == "" {
- return fmt.Errorf("destination must be specified")
- }
-
- absSource, err := filepath.EvalSymlinks(source)
- if err != nil {
- return fmt.Errorf("Could not resolve symlink for source %v", source)
- }
-
- if err := ensureDestinationExists(absSource, destination); err != nil {
- return fmt.Errorf("Could not create destination mount point %v: %v", destination, err)
- } else if err := syscall.Mount(absSource, destination, "bind", syscall.MS_BIND, ""); err != nil {
- return fmt.Errorf("Could not bind mount %v to %v: %v", absSource, destination, err)
- }
-
- return nil
-}
-
-// ensureDestinationExists will recursively create a given mountpoint. If directories
-// are created, their permissions are initialized to mountPerm
-func ensureDestinationExists(source, destination string) error {
- fileInfo, err := os.Stat(source)
- if err != nil {
- return fmt.Errorf("could not stat source location %v: %v", source, err)
- }
-
- targetPathParent, _ := filepath.Split(destination)
- if err := os.MkdirAll(targetPathParent, mountPerm); err != nil {
- return fmt.Errorf("could not create parent directory %v: %v", targetPathParent, err)
- }
-
- if fileInfo.IsDir() {
- if err := os.Mkdir(destination, mountPerm); !os.IsExist(err) {
- return err
- }
- } else {
- file, err := os.OpenFile(destination, os.O_CREATE, mountPerm)
- if err != nil {
- return err
- }
-
- file.Close()
- }
- return nil
-}
diff --git a/vendor/github.com/containers/virtcontainers/syscall_test.go b/vendor/github.com/containers/virtcontainers/syscall_test.go
deleted file mode 100644
index 323db24..0000000
--- a/vendor/github.com/containers/virtcontainers/syscall_test.go
+++ /dev/null
@@ -1,144 +0,0 @@
-//
-// Copyright 2015 The rkt Authors
-// Copyright (c) 2016 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "os"
- "path/filepath"
- "syscall"
- "testing"
-)
-
-func TestBindMountInvalidSourceSymlink(t *testing.T) {
- source := filepath.Join(testDir, "fooFile")
- os.Remove(source)
-
- err := bindMount(source, "")
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestBindMountFailingMount(t *testing.T) {
- source := filepath.Join(testDir, "fooLink")
- fakeSource := filepath.Join(testDir, "fooFile")
- os.Remove(source)
- os.Remove(fakeSource)
-
- _, err := os.OpenFile(fakeSource, os.O_CREATE, mountPerm)
- if err != nil {
- t.Fatal(err)
- }
-
- err = os.Symlink(fakeSource, source)
- if err != nil {
- t.Fatal(err)
- }
-
- err = bindMount(source, "")
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestBindMountSuccessful(t *testing.T) {
- if os.Geteuid() != 0 {
- t.Skip(testDisabledAsNonRoot)
- }
-
- source := filepath.Join(testDir, "fooDirSrc")
- dest := filepath.Join(testDir, "fooDirDest")
- syscall.Unmount(dest, 0)
- os.Remove(source)
- os.Remove(dest)
-
- err := os.MkdirAll(source, mountPerm)
- if err != nil {
- t.Fatal(err)
- }
-
- err = os.MkdirAll(dest, mountPerm)
- if err != nil {
- t.Fatal(err)
- }
-
- err = bindMount(source, dest)
- if err != nil {
- t.Fatal(err)
- }
-
- syscall.Unmount(dest, 0)
-}
-
-func TestEnsureDestinationExistsNonExistingSource(t *testing.T) {
- err := ensureDestinationExists("", "")
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestEnsureDestinationExistsWrongParentDir(t *testing.T) {
- source := filepath.Join(testDir, "fooFile")
- dest := filepath.Join(source, "fooDest")
- os.Remove(source)
- os.Remove(dest)
-
- _, err := os.OpenFile(source, os.O_CREATE, mountPerm)
- if err != nil {
- t.Fatal(err)
- }
-
- err = ensureDestinationExists(source, dest)
- if err == nil {
- t.Fatal()
- }
-}
-
-func TestEnsureDestinationExistsSuccessfulSrcDir(t *testing.T) {
- source := filepath.Join(testDir, "fooDirSrc")
- dest := filepath.Join(testDir, "fooDirDest")
- os.Remove(source)
- os.Remove(dest)
-
- err := os.MkdirAll(source, mountPerm)
- if err != nil {
- t.Fatal(err)
- }
-
- err = ensureDestinationExists(source, dest)
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestEnsureDestinationExistsSuccessfulSrcFile(t *testing.T) {
- source := filepath.Join(testDir, "fooDirSrc")
- dest := filepath.Join(testDir, "fooDirDest")
- os.Remove(source)
- os.Remove(dest)
-
- _, err := os.OpenFile(source, os.O_CREATE, mountPerm)
- if err != nil {
- t.Fatal(err)
- }
-
- err = ensureDestinationExists(source, dest)
- if err != nil {
- t.Fatal(err)
- }
-}
diff --git a/vendor/github.com/containers/virtcontainers/virtcontainers_test.go b/vendor/github.com/containers/virtcontainers/virtcontainers_test.go
deleted file mode 100644
index 767cc99..0000000
--- a/vendor/github.com/containers/virtcontainers/virtcontainers_test.go
+++ /dev/null
@@ -1,146 +0,0 @@
-//
-// Copyright (c) 2017 Intel Corporation
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-package virtcontainers
-
-import (
- "flag"
- "fmt"
- "io/ioutil"
- "os"
- "path/filepath"
- "testing"
-
- "github.com/Sirupsen/logrus"
-)
-
-const testPodID = "7f49d00d-1995-4156-8c79-5f5ab24ce138"
-const testKernel = "kernel"
-const testImage = "image"
-const testHypervisor = "hypervisor"
-const testBundle = "bundle"
-
-const testDisabledAsNonRoot = "Test disabled as requires root privileges"
-
-// package variables set in TestMain
-var testDir = ""
-var podDirConfig = ""
-var podFileConfig = ""
-var podDirState = ""
-var podDirLock = ""
-var podFileState = ""
-var podFileLock = ""
-var testQemuKernelPath = ""
-var testQemuImagePath = ""
-var testQemuPath = ""
-var testHyperstartCtlSocket = ""
-var testHyperstartTtySocket = ""
-
-// cleanUp Removes any stale pod/container state that can affect
-// the next test to run.
-func cleanUp() {
- for _, dir := range []string{testDir, defaultSharedDir} {
- os.RemoveAll(dir)
- os.MkdirAll(dir, dirMode)
- }
-
- os.Mkdir(filepath.Join(testDir, testBundle), dirMode)
-
- _, err := os.Create(filepath.Join(testDir, testImage))
- if err != nil {
- fmt.Println("Could not recreate test image:", err)
- os.Exit(1)
- }
-}
-
-// TestMain is the common main function used by ALL the test functions
-// for this package.
-func TestMain(m *testing.M) {
- var err error
-
- flag.Parse()
-
- virtLog.Level = logrus.ErrorLevel
- for _, arg := range flag.Args() {
- if arg == "debug-logs" {
- virtLog.Level = logrus.DebugLevel
- }
- }
-
- testDir, err = ioutil.TempDir("", "virtcontainers-tmp-")
- if err != nil {
- panic(err)
- }
-
- err = os.MkdirAll(testDir, dirMode)
- if err != nil {
- fmt.Println("Could not create test directories:", err)
- os.Exit(1)
- }
-
- _, err = os.Create(filepath.Join(testDir, testKernel))
- if err != nil {
- fmt.Println("Could not create test kernel:", err)
- os.RemoveAll(testDir)
- os.Exit(1)
- }
-
- _, err = os.Create(filepath.Join(testDir, testImage))
- if err != nil {
- fmt.Println("Could not create test image:", err)
- os.RemoveAll(testDir)
- os.Exit(1)
- }
-
- _, err = os.Create(filepath.Join(testDir, testHypervisor))
- if err != nil {
- fmt.Println("Could not create test hypervisor:", err)
- os.RemoveAll(testDir)
- os.Exit(1)
- }
-
- err = os.Mkdir(filepath.Join(testDir, testBundle), dirMode)
- if err != nil {
- fmt.Println("Could not create test bundle directory:", err)
- os.RemoveAll(testDir)
- os.Exit(1)
- }
-
- // allow the tests to run without affecting the host system.
- configStoragePath = filepath.Join(testDir, storagePathSuffix, "config")
- runStoragePath = filepath.Join(testDir, storagePathSuffix, "run")
-
- // set now that configStoragePath has been overridden.
- podDirConfig = filepath.Join(configStoragePath, testPodID)
- podFileConfig = filepath.Join(configStoragePath, testPodID, configFile)
- podDirState = filepath.Join(runStoragePath, testPodID)
- podDirLock = filepath.Join(runStoragePath, testPodID)
- podFileState = filepath.Join(runStoragePath, testPodID, stateFile)
- podFileLock = filepath.Join(runStoragePath, testPodID, lockFileName)
-
- testQemuKernelPath = filepath.Join(testDir, testKernel)
- testQemuImagePath = filepath.Join(testDir, testImage)
- testQemuPath = filepath.Join(testDir, testHypervisor)
-
- testHyperstartCtlSocket = filepath.Join(testDir, "test_hyper.sock")
- testHyperstartTtySocket = filepath.Join(testDir, "test_tty.sock")
-
- ret := m.Run()
-
- os.RemoveAll(testDir)
-
- os.Exit(ret)
-}
diff --git a/vendor/github.com/davecgh/go-spew/.gitignore b/vendor/github.com/davecgh/go-spew/.gitignore
deleted file mode 100644
index 0026861..0000000
--- a/vendor/github.com/davecgh/go-spew/.gitignore
+++ /dev/null
@@ -1,22 +0,0 @@
-# Compiled Object files, Static and Dynamic libs (Shared Objects)
-*.o
-*.a
-*.so
-
-# Folders
-_obj
-_test
-
-# Architecture specific extensions/prefixes
-*.[568vq]
-[568vq].out
-
-*.cgo1.go
-*.cgo2.c
-_cgo_defun.c
-_cgo_gotypes.go
-_cgo_export.*
-
-_testmain.go
-
-*.exe
diff --git a/vendor/github.com/davecgh/go-spew/.travis.yml b/vendor/github.com/davecgh/go-spew/.travis.yml
deleted file mode 100644
index 984e073..0000000
--- a/vendor/github.com/davecgh/go-spew/.travis.yml
+++ /dev/null
@@ -1,14 +0,0 @@
-language: go
-go:
- - 1.5.4
- - 1.6.3
- - 1.7
-install:
- - go get -v golang.org/x/tools/cmd/cover
-script:
- - go test -v -tags=safe ./spew
- - go test -v -tags=testcgo ./spew -covermode=count -coverprofile=profile.cov
-after_success:
- - go get -v github.com/mattn/goveralls
- - export PATH=$PATH:$HOME/gopath/bin
- - goveralls -coverprofile=profile.cov -service=travis-ci
diff --git a/vendor/github.com/davecgh/go-spew/LICENSE b/vendor/github.com/davecgh/go-spew/LICENSE
deleted file mode 100644
index c836416..0000000
--- a/vendor/github.com/davecgh/go-spew/LICENSE
+++ /dev/null
@@ -1,15 +0,0 @@
-ISC License
-
-Copyright (c) 2012-2016 Dave Collins
-
-Permission to use, copy, modify, and distribute this software for any
-purpose with or without fee is hereby granted, provided that the above
-copyright notice and this permission notice appear in all copies.
-
-THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/vendor/github.com/davecgh/go-spew/README.md b/vendor/github.com/davecgh/go-spew/README.md
deleted file mode 100644
index 2624304..0000000
--- a/vendor/github.com/davecgh/go-spew/README.md
+++ /dev/null
@@ -1,205 +0,0 @@
-go-spew
-=======
-
-[![Build Status](https://img.shields.io/travis/davecgh/go-spew.svg)]
-(https://travis-ci.org/davecgh/go-spew) [![ISC License]
-(http://img.shields.io/badge/license-ISC-blue.svg)](http://copyfree.org) [![Coverage Status]
-(https://img.shields.io/coveralls/davecgh/go-spew.svg)]
-(https://coveralls.io/r/davecgh/go-spew?branch=master)
-
-
-Go-spew implements a deep pretty printer for Go data structures to aid in
-debugging. A comprehensive suite of tests with 100% test coverage is provided
-to ensure proper functionality. See `test_coverage.txt` for the gocov coverage
-report. Go-spew is licensed under the liberal ISC license, so it may be used in
-open source or commercial projects.
-
-If you're interested in reading about how this package came to life and some
-of the challenges involved in providing a deep pretty printer, there is a blog
-post about it
-[here](https://web.archive.org/web/20160304013555/https://blog.cyphertite.com/go-spew-a-journey-into-dumping-go-data-structures/).
-
-## Documentation
-
-[![GoDoc](https://img.shields.io/badge/godoc-reference-blue.svg)]
-(http://godoc.org/github.com/davecgh/go-spew/spew)
-
-Full `go doc` style documentation for the project can be viewed online without
-installing this package by using the excellent GoDoc site here:
-http://godoc.org/github.com/davecgh/go-spew/spew
-
-You can also view the documentation locally once the package is installed with
-the `godoc` tool by running `godoc -http=":6060"` and pointing your browser to
-http://localhost:6060/pkg/github.com/davecgh/go-spew/spew
-
-## Installation
-
-```bash
-$ go get -u github.com/davecgh/go-spew/spew
-```
-
-## Quick Start
-
-Add this import line to the file you're working in:
-
-```Go
-import "github.com/davecgh/go-spew/spew"
-```
-
-To dump a variable with full newlines, indentation, type, and pointer
-information use Dump, Fdump, or Sdump:
-
-```Go
-spew.Dump(myVar1, myVar2, ...)
-spew.Fdump(someWriter, myVar1, myVar2, ...)
-str := spew.Sdump(myVar1, myVar2, ...)
-```
-
-Alternatively, if you would prefer to use format strings with a compacted inline
-printing style, use the convenience wrappers Printf, Fprintf, etc with %v (most
-compact), %+v (adds pointer addresses), %#v (adds types), or %#+v (adds types
-and pointer addresses):
-
-```Go
-spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2)
-spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
-spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2)
-spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
-```
-
-## Debugging a Web Application Example
-
-Here is an example of how you can use `spew.Sdump()` to help debug a web application. Please be sure to wrap your output using the `html.EscapeString()` function for safety reasons. You should also only use this debugging technique in a development environment, never in production.
-
-```Go
-package main
-
-import (
- "fmt"
- "html"
- "net/http"
-
- "github.com/davecgh/go-spew/spew"
-)
-
-func handler(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "text/html")
- fmt.Fprintf(w, "Hi there, %s!", r.URL.Path[1:])
- fmt.Fprintf(w, "")
-}
-
-func main() {
- http.HandleFunc("/", handler)
- http.ListenAndServe(":8080", nil)
-}
-```
-
-## Sample Dump Output
-
-```
-(main.Foo) {
- unexportedField: (*main.Bar)(0xf84002e210)({
- flag: (main.Flag) flagTwo,
- data: (uintptr)
- }),
- ExportedField: (map[interface {}]interface {}) {
- (string) "one": (bool) true
- }
-}
-([]uint8) {
- 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... |
- 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0|
- 00000020 31 32 |12|
-}
-```
-
-## Sample Formatter Output
-
-Double pointer to a uint8:
-```
- %v: <**>5
- %+v: <**>(0xf8400420d0->0xf8400420c8)5
- %#v: (**uint8)5
- %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5
-```
-
-Pointer to circular struct with a uint8 field and a pointer to itself:
-```
- %v: <*>{1 <*>}
- %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)}
- %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)}
- %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)}
-```
-
-## Configuration Options
-
-Configuration of spew is handled by fields in the ConfigState type. For
-convenience, all of the top-level functions use a global state available via the
-spew.Config global.
-
-It is also possible to create a ConfigState instance that provides methods
-equivalent to the top-level functions. This allows concurrent configuration
-options. See the ConfigState documentation for more details.
-
-```
-* Indent
- String to use for each indentation level for Dump functions.
- It is a single space by default. A popular alternative is "\t".
-
-* MaxDepth
- Maximum number of levels to descend into nested data structures.
- There is no limit by default.
-
-* DisableMethods
- Disables invocation of error and Stringer interface methods.
- Method invocation is enabled by default.
-
-* DisablePointerMethods
- Disables invocation of error and Stringer interface methods on types
- which only accept pointer receivers from non-pointer variables. This option
- relies on access to the unsafe package, so it will not have any effect when
- running in environments without access to the unsafe package such as Google
- App Engine or with the "safe" build tag specified.
- Pointer method invocation is enabled by default.
-
-* DisablePointerAddresses
- DisablePointerAddresses specifies whether to disable the printing of
- pointer addresses. This is useful when diffing data structures in tests.
-
-* DisableCapacities
- DisableCapacities specifies whether to disable the printing of capacities
- for arrays, slices, maps and channels. This is useful when diffing data
- structures in tests.
-
-* ContinueOnMethod
- Enables recursion into types after invoking error and Stringer interface
- methods. Recursion after method invocation is disabled by default.
-
-* SortKeys
- Specifies map keys should be sorted before being printed. Use
- this to have a more deterministic, diffable output. Note that
- only native types (bool, int, uint, floats, uintptr and string)
- and types which implement error or Stringer interfaces are supported,
- with other types sorted according to the reflect.Value.String() output
- which guarantees display stability. Natural map order is used by
- default.
-
-* SpewKeys
- SpewKeys specifies that, as a last resort attempt, map keys should be
- spewed to strings and sorted by those strings. This is only considered
- if SortKeys is true.
-
-```
-
-## Unsafe Package Dependency
-
-This package relies on the unsafe package to perform some of the more advanced
-features, however it also supports a "limited" mode which allows it to work in
-environments where the unsafe package is not available. By default, it will
-operate in this mode on Google App Engine and when compiled with GopherJS. The
-"safe" build tag may also be specified to force the package to build without
-using the unsafe package.
-
-## License
-
-Go-spew is licensed under the [copyfree](http://copyfree.org) ISC License.
diff --git a/vendor/github.com/davecgh/go-spew/cov_report.sh b/vendor/github.com/davecgh/go-spew/cov_report.sh
deleted file mode 100644
index 9579497..0000000
--- a/vendor/github.com/davecgh/go-spew/cov_report.sh
+++ /dev/null
@@ -1,22 +0,0 @@
-#!/bin/sh
-
-# This script uses gocov to generate a test coverage report.
-# The gocov tool my be obtained with the following command:
-# go get github.com/axw/gocov/gocov
-#
-# It will be installed to $GOPATH/bin, so ensure that location is in your $PATH.
-
-# Check for gocov.
-if ! type gocov >/dev/null 2>&1; then
- echo >&2 "This script requires the gocov tool."
- echo >&2 "You may obtain it with the following command:"
- echo >&2 "go get github.com/axw/gocov/gocov"
- exit 1
-fi
-
-# Only run the cgo tests if gcc is installed.
-if type gcc >/dev/null 2>&1; then
- (cd spew && gocov test -tags testcgo | gocov report)
-else
- (cd spew && gocov test | gocov report)
-fi
diff --git a/vendor/github.com/davecgh/go-spew/spew/bypass.go b/vendor/github.com/davecgh/go-spew/spew/bypass.go
deleted file mode 100644
index 8a4a658..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/bypass.go
+++ /dev/null
@@ -1,152 +0,0 @@
-// Copyright (c) 2015-2016 Dave Collins
-//
-// Permission to use, copy, modify, and distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-// NOTE: Due to the following build constraints, this file will only be compiled
-// when the code is not running on Google App Engine, compiled by GopherJS, and
-// "-tags safe" is not added to the go build command line. The "disableunsafe"
-// tag is deprecated and thus should not be used.
-// +build !js,!appengine,!safe,!disableunsafe
-
-package spew
-
-import (
- "reflect"
- "unsafe"
-)
-
-const (
- // UnsafeDisabled is a build-time constant which specifies whether or
- // not access to the unsafe package is available.
- UnsafeDisabled = false
-
- // ptrSize is the size of a pointer on the current arch.
- ptrSize = unsafe.Sizeof((*byte)(nil))
-)
-
-var (
- // offsetPtr, offsetScalar, and offsetFlag are the offsets for the
- // internal reflect.Value fields. These values are valid before golang
- // commit ecccf07e7f9d which changed the format. The are also valid
- // after commit 82f48826c6c7 which changed the format again to mirror
- // the original format. Code in the init function updates these offsets
- // as necessary.
- offsetPtr = uintptr(ptrSize)
- offsetScalar = uintptr(0)
- offsetFlag = uintptr(ptrSize * 2)
-
- // flagKindWidth and flagKindShift indicate various bits that the
- // reflect package uses internally to track kind information.
- //
- // flagRO indicates whether or not the value field of a reflect.Value is
- // read-only.
- //
- // flagIndir indicates whether the value field of a reflect.Value is
- // the actual data or a pointer to the data.
- //
- // These values are valid before golang commit 90a7c3c86944 which
- // changed their positions. Code in the init function updates these
- // flags as necessary.
- flagKindWidth = uintptr(5)
- flagKindShift = uintptr(flagKindWidth - 1)
- flagRO = uintptr(1 << 0)
- flagIndir = uintptr(1 << 1)
-)
-
-func init() {
- // Older versions of reflect.Value stored small integers directly in the
- // ptr field (which is named val in the older versions). Versions
- // between commits ecccf07e7f9d and 82f48826c6c7 added a new field named
- // scalar for this purpose which unfortunately came before the flag
- // field, so the offset of the flag field is different for those
- // versions.
- //
- // This code constructs a new reflect.Value from a known small integer
- // and checks if the size of the reflect.Value struct indicates it has
- // the scalar field. When it does, the offsets are updated accordingly.
- vv := reflect.ValueOf(0xf00)
- if unsafe.Sizeof(vv) == (ptrSize * 4) {
- offsetScalar = ptrSize * 2
- offsetFlag = ptrSize * 3
- }
-
- // Commit 90a7c3c86944 changed the flag positions such that the low
- // order bits are the kind. This code extracts the kind from the flags
- // field and ensures it's the correct type. When it's not, the flag
- // order has been changed to the newer format, so the flags are updated
- // accordingly.
- upf := unsafe.Pointer(uintptr(unsafe.Pointer(&vv)) + offsetFlag)
- upfv := *(*uintptr)(upf)
- flagKindMask := uintptr((1<>flagKindShift != uintptr(reflect.Int) {
- flagKindShift = 0
- flagRO = 1 << 5
- flagIndir = 1 << 6
-
- // Commit adf9b30e5594 modified the flags to separate the
- // flagRO flag into two bits which specifies whether or not the
- // field is embedded. This causes flagIndir to move over a bit
- // and means that flagRO is the combination of either of the
- // original flagRO bit and the new bit.
- //
- // This code detects the change by extracting what used to be
- // the indirect bit to ensure it's set. When it's not, the flag
- // order has been changed to the newer format, so the flags are
- // updated accordingly.
- if upfv&flagIndir == 0 {
- flagRO = 3 << 5
- flagIndir = 1 << 7
- }
- }
-}
-
-// unsafeReflectValue converts the passed reflect.Value into a one that bypasses
-// the typical safety restrictions preventing access to unaddressable and
-// unexported data. It works by digging the raw pointer to the underlying
-// value out of the protected value and generating a new unprotected (unsafe)
-// reflect.Value to it.
-//
-// This allows us to check for implementations of the Stringer and error
-// interfaces to be used for pretty printing ordinarily unaddressable and
-// inaccessible values such as unexported struct fields.
-func unsafeReflectValue(v reflect.Value) (rv reflect.Value) {
- indirects := 1
- vt := v.Type()
- upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr)
- rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag))
- if rvf&flagIndir != 0 {
- vt = reflect.PtrTo(v.Type())
- indirects++
- } else if offsetScalar != 0 {
- // The value is in the scalar field when it's not one of the
- // reference types.
- switch vt.Kind() {
- case reflect.Uintptr:
- case reflect.Chan:
- case reflect.Func:
- case reflect.Map:
- case reflect.Ptr:
- case reflect.UnsafePointer:
- default:
- upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) +
- offsetScalar)
- }
- }
-
- pv := reflect.NewAt(vt, upv)
- rv = pv
- for i := 0; i < indirects; i++ {
- rv = rv.Elem()
- }
- return rv
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go
deleted file mode 100644
index 1fe3cf3..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright (c) 2015-2016 Dave Collins
-//
-// Permission to use, copy, modify, and distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-// NOTE: Due to the following build constraints, this file will only be compiled
-// when the code is running on Google App Engine, compiled by GopherJS, or
-// "-tags safe" is added to the go build command line. The "disableunsafe"
-// tag is deprecated and thus should not be used.
-// +build js appengine safe disableunsafe
-
-package spew
-
-import "reflect"
-
-const (
- // UnsafeDisabled is a build-time constant which specifies whether or
- // not access to the unsafe package is available.
- UnsafeDisabled = true
-)
-
-// unsafeReflectValue typically converts the passed reflect.Value into a one
-// that bypasses the typical safety restrictions preventing access to
-// unaddressable and unexported data. However, doing this relies on access to
-// the unsafe package. This is a stub version which simply returns the passed
-// reflect.Value when the unsafe package is not available.
-func unsafeReflectValue(v reflect.Value) reflect.Value {
- return v
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/common.go b/vendor/github.com/davecgh/go-spew/spew/common.go
deleted file mode 100644
index 7c519ff..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/common.go
+++ /dev/null
@@ -1,341 +0,0 @@
-/*
- * Copyright (c) 2013-2016 Dave Collins
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-package spew
-
-import (
- "bytes"
- "fmt"
- "io"
- "reflect"
- "sort"
- "strconv"
-)
-
-// Some constants in the form of bytes to avoid string overhead. This mirrors
-// the technique used in the fmt package.
-var (
- panicBytes = []byte("(PANIC=")
- plusBytes = []byte("+")
- iBytes = []byte("i")
- trueBytes = []byte("true")
- falseBytes = []byte("false")
- interfaceBytes = []byte("(interface {})")
- commaNewlineBytes = []byte(",\n")
- newlineBytes = []byte("\n")
- openBraceBytes = []byte("{")
- openBraceNewlineBytes = []byte("{\n")
- closeBraceBytes = []byte("}")
- asteriskBytes = []byte("*")
- colonBytes = []byte(":")
- colonSpaceBytes = []byte(": ")
- openParenBytes = []byte("(")
- closeParenBytes = []byte(")")
- spaceBytes = []byte(" ")
- pointerChainBytes = []byte("->")
- nilAngleBytes = []byte("")
- maxNewlineBytes = []byte("\n")
- maxShortBytes = []byte("")
- circularBytes = []byte("")
- circularShortBytes = []byte("")
- invalidAngleBytes = []byte("")
- openBracketBytes = []byte("[")
- closeBracketBytes = []byte("]")
- percentBytes = []byte("%")
- precisionBytes = []byte(".")
- openAngleBytes = []byte("<")
- closeAngleBytes = []byte(">")
- openMapBytes = []byte("map[")
- closeMapBytes = []byte("]")
- lenEqualsBytes = []byte("len=")
- capEqualsBytes = []byte("cap=")
-)
-
-// hexDigits is used to map a decimal value to a hex digit.
-var hexDigits = "0123456789abcdef"
-
-// catchPanic handles any panics that might occur during the handleMethods
-// calls.
-func catchPanic(w io.Writer, v reflect.Value) {
- if err := recover(); err != nil {
- w.Write(panicBytes)
- fmt.Fprintf(w, "%v", err)
- w.Write(closeParenBytes)
- }
-}
-
-// handleMethods attempts to call the Error and String methods on the underlying
-// type the passed reflect.Value represents and outputes the result to Writer w.
-//
-// It handles panics in any called methods by catching and displaying the error
-// as the formatted value.
-func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) {
- // We need an interface to check if the type implements the error or
- // Stringer interface. However, the reflect package won't give us an
- // interface on certain things like unexported struct fields in order
- // to enforce visibility rules. We use unsafe, when it's available,
- // to bypass these restrictions since this package does not mutate the
- // values.
- if !v.CanInterface() {
- if UnsafeDisabled {
- return false
- }
-
- v = unsafeReflectValue(v)
- }
-
- // Choose whether or not to do error and Stringer interface lookups against
- // the base type or a pointer to the base type depending on settings.
- // Technically calling one of these methods with a pointer receiver can
- // mutate the value, however, types which choose to satisify an error or
- // Stringer interface with a pointer receiver should not be mutating their
- // state inside these interface methods.
- if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() {
- v = unsafeReflectValue(v)
- }
- if v.CanAddr() {
- v = v.Addr()
- }
-
- // Is it an error or Stringer?
- switch iface := v.Interface().(type) {
- case error:
- defer catchPanic(w, v)
- if cs.ContinueOnMethod {
- w.Write(openParenBytes)
- w.Write([]byte(iface.Error()))
- w.Write(closeParenBytes)
- w.Write(spaceBytes)
- return false
- }
-
- w.Write([]byte(iface.Error()))
- return true
-
- case fmt.Stringer:
- defer catchPanic(w, v)
- if cs.ContinueOnMethod {
- w.Write(openParenBytes)
- w.Write([]byte(iface.String()))
- w.Write(closeParenBytes)
- w.Write(spaceBytes)
- return false
- }
- w.Write([]byte(iface.String()))
- return true
- }
- return false
-}
-
-// printBool outputs a boolean value as true or false to Writer w.
-func printBool(w io.Writer, val bool) {
- if val {
- w.Write(trueBytes)
- } else {
- w.Write(falseBytes)
- }
-}
-
-// printInt outputs a signed integer value to Writer w.
-func printInt(w io.Writer, val int64, base int) {
- w.Write([]byte(strconv.FormatInt(val, base)))
-}
-
-// printUint outputs an unsigned integer value to Writer w.
-func printUint(w io.Writer, val uint64, base int) {
- w.Write([]byte(strconv.FormatUint(val, base)))
-}
-
-// printFloat outputs a floating point value using the specified precision,
-// which is expected to be 32 or 64bit, to Writer w.
-func printFloat(w io.Writer, val float64, precision int) {
- w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision)))
-}
-
-// printComplex outputs a complex value using the specified float precision
-// for the real and imaginary parts to Writer w.
-func printComplex(w io.Writer, c complex128, floatPrecision int) {
- r := real(c)
- w.Write(openParenBytes)
- w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision)))
- i := imag(c)
- if i >= 0 {
- w.Write(plusBytes)
- }
- w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision)))
- w.Write(iBytes)
- w.Write(closeParenBytes)
-}
-
-// printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x'
-// prefix to Writer w.
-func printHexPtr(w io.Writer, p uintptr) {
- // Null pointer.
- num := uint64(p)
- if num == 0 {
- w.Write(nilAngleBytes)
- return
- }
-
- // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix
- buf := make([]byte, 18)
-
- // It's simpler to construct the hex string right to left.
- base := uint64(16)
- i := len(buf) - 1
- for num >= base {
- buf[i] = hexDigits[num%base]
- num /= base
- i--
- }
- buf[i] = hexDigits[num]
-
- // Add '0x' prefix.
- i--
- buf[i] = 'x'
- i--
- buf[i] = '0'
-
- // Strip unused leading bytes.
- buf = buf[i:]
- w.Write(buf)
-}
-
-// valuesSorter implements sort.Interface to allow a slice of reflect.Value
-// elements to be sorted.
-type valuesSorter struct {
- values []reflect.Value
- strings []string // either nil or same len and values
- cs *ConfigState
-}
-
-// newValuesSorter initializes a valuesSorter instance, which holds a set of
-// surrogate keys on which the data should be sorted. It uses flags in
-// ConfigState to decide if and how to populate those surrogate keys.
-func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface {
- vs := &valuesSorter{values: values, cs: cs}
- if canSortSimply(vs.values[0].Kind()) {
- return vs
- }
- if !cs.DisableMethods {
- vs.strings = make([]string, len(values))
- for i := range vs.values {
- b := bytes.Buffer{}
- if !handleMethods(cs, &b, vs.values[i]) {
- vs.strings = nil
- break
- }
- vs.strings[i] = b.String()
- }
- }
- if vs.strings == nil && cs.SpewKeys {
- vs.strings = make([]string, len(values))
- for i := range vs.values {
- vs.strings[i] = Sprintf("%#v", vs.values[i].Interface())
- }
- }
- return vs
-}
-
-// canSortSimply tests whether a reflect.Kind is a primitive that can be sorted
-// directly, or whether it should be considered for sorting by surrogate keys
-// (if the ConfigState allows it).
-func canSortSimply(kind reflect.Kind) bool {
- // This switch parallels valueSortLess, except for the default case.
- switch kind {
- case reflect.Bool:
- return true
- case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
- return true
- case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
- return true
- case reflect.Float32, reflect.Float64:
- return true
- case reflect.String:
- return true
- case reflect.Uintptr:
- return true
- case reflect.Array:
- return true
- }
- return false
-}
-
-// Len returns the number of values in the slice. It is part of the
-// sort.Interface implementation.
-func (s *valuesSorter) Len() int {
- return len(s.values)
-}
-
-// Swap swaps the values at the passed indices. It is part of the
-// sort.Interface implementation.
-func (s *valuesSorter) Swap(i, j int) {
- s.values[i], s.values[j] = s.values[j], s.values[i]
- if s.strings != nil {
- s.strings[i], s.strings[j] = s.strings[j], s.strings[i]
- }
-}
-
-// valueSortLess returns whether the first value should sort before the second
-// value. It is used by valueSorter.Less as part of the sort.Interface
-// implementation.
-func valueSortLess(a, b reflect.Value) bool {
- switch a.Kind() {
- case reflect.Bool:
- return !a.Bool() && b.Bool()
- case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
- return a.Int() < b.Int()
- case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
- return a.Uint() < b.Uint()
- case reflect.Float32, reflect.Float64:
- return a.Float() < b.Float()
- case reflect.String:
- return a.String() < b.String()
- case reflect.Uintptr:
- return a.Uint() < b.Uint()
- case reflect.Array:
- // Compare the contents of both arrays.
- l := a.Len()
- for i := 0; i < l; i++ {
- av := a.Index(i)
- bv := b.Index(i)
- if av.Interface() == bv.Interface() {
- continue
- }
- return valueSortLess(av, bv)
- }
- }
- return a.String() < b.String()
-}
-
-// Less returns whether the value at index i should sort before the
-// value at index j. It is part of the sort.Interface implementation.
-func (s *valuesSorter) Less(i, j int) bool {
- if s.strings == nil {
- return valueSortLess(s.values[i], s.values[j])
- }
- return s.strings[i] < s.strings[j]
-}
-
-// sortValues is a sort function that handles both native types and any type that
-// can be converted to error or Stringer. Other inputs are sorted according to
-// their Value.String() value to ensure display stability.
-func sortValues(values []reflect.Value, cs *ConfigState) {
- if len(values) == 0 {
- return
- }
- sort.Sort(newValuesSorter(values, cs))
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/common_test.go b/vendor/github.com/davecgh/go-spew/spew/common_test.go
deleted file mode 100644
index 0f5ce47..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/common_test.go
+++ /dev/null
@@ -1,298 +0,0 @@
-/*
- * Copyright (c) 2013-2016 Dave Collins
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-package spew_test
-
-import (
- "fmt"
- "reflect"
- "testing"
-
- "github.com/davecgh/go-spew/spew"
-)
-
-// custom type to test Stinger interface on non-pointer receiver.
-type stringer string
-
-// String implements the Stringer interface for testing invocation of custom
-// stringers on types with non-pointer receivers.
-func (s stringer) String() string {
- return "stringer " + string(s)
-}
-
-// custom type to test Stinger interface on pointer receiver.
-type pstringer string
-
-// String implements the Stringer interface for testing invocation of custom
-// stringers on types with only pointer receivers.
-func (s *pstringer) String() string {
- return "stringer " + string(*s)
-}
-
-// xref1 and xref2 are cross referencing structs for testing circular reference
-// detection.
-type xref1 struct {
- ps2 *xref2
-}
-type xref2 struct {
- ps1 *xref1
-}
-
-// indirCir1, indirCir2, and indirCir3 are used to generate an indirect circular
-// reference for testing detection.
-type indirCir1 struct {
- ps2 *indirCir2
-}
-type indirCir2 struct {
- ps3 *indirCir3
-}
-type indirCir3 struct {
- ps1 *indirCir1
-}
-
-// embed is used to test embedded structures.
-type embed struct {
- a string
-}
-
-// embedwrap is used to test embedded structures.
-type embedwrap struct {
- *embed
- e *embed
-}
-
-// panicer is used to intentionally cause a panic for testing spew properly
-// handles them
-type panicer int
-
-func (p panicer) String() string {
- panic("test panic")
-}
-
-// customError is used to test custom error interface invocation.
-type customError int
-
-func (e customError) Error() string {
- return fmt.Sprintf("error: %d", int(e))
-}
-
-// stringizeWants converts a slice of wanted test output into a format suitable
-// for a test error message.
-func stringizeWants(wants []string) string {
- s := ""
- for i, want := range wants {
- if i > 0 {
- s += fmt.Sprintf("want%d: %s", i+1, want)
- } else {
- s += "want: " + want
- }
- }
- return s
-}
-
-// testFailed returns whether or not a test failed by checking if the result
-// of the test is in the slice of wanted strings.
-func testFailed(result string, wants []string) bool {
- for _, want := range wants {
- if result == want {
- return false
- }
- }
- return true
-}
-
-type sortableStruct struct {
- x int
-}
-
-func (ss sortableStruct) String() string {
- return fmt.Sprintf("ss.%d", ss.x)
-}
-
-type unsortableStruct struct {
- x int
-}
-
-type sortTestCase struct {
- input []reflect.Value
- expected []reflect.Value
-}
-
-func helpTestSortValues(tests []sortTestCase, cs *spew.ConfigState, t *testing.T) {
- getInterfaces := func(values []reflect.Value) []interface{} {
- interfaces := []interface{}{}
- for _, v := range values {
- interfaces = append(interfaces, v.Interface())
- }
- return interfaces
- }
-
- for _, test := range tests {
- spew.SortValues(test.input, cs)
- // reflect.DeepEqual cannot really make sense of reflect.Value,
- // probably because of all the pointer tricks. For instance,
- // v(2.0) != v(2.0) on a 32-bits system. Turn them into interface{}
- // instead.
- input := getInterfaces(test.input)
- expected := getInterfaces(test.expected)
- if !reflect.DeepEqual(input, expected) {
- t.Errorf("Sort mismatch:\n %v != %v", input, expected)
- }
- }
-}
-
-// TestSortValues ensures the sort functionality for relect.Value based sorting
-// works as intended.
-func TestSortValues(t *testing.T) {
- v := reflect.ValueOf
-
- a := v("a")
- b := v("b")
- c := v("c")
- embedA := v(embed{"a"})
- embedB := v(embed{"b"})
- embedC := v(embed{"c"})
- tests := []sortTestCase{
- // No values.
- {
- []reflect.Value{},
- []reflect.Value{},
- },
- // Bools.
- {
- []reflect.Value{v(false), v(true), v(false)},
- []reflect.Value{v(false), v(false), v(true)},
- },
- // Ints.
- {
- []reflect.Value{v(2), v(1), v(3)},
- []reflect.Value{v(1), v(2), v(3)},
- },
- // Uints.
- {
- []reflect.Value{v(uint8(2)), v(uint8(1)), v(uint8(3))},
- []reflect.Value{v(uint8(1)), v(uint8(2)), v(uint8(3))},
- },
- // Floats.
- {
- []reflect.Value{v(2.0), v(1.0), v(3.0)},
- []reflect.Value{v(1.0), v(2.0), v(3.0)},
- },
- // Strings.
- {
- []reflect.Value{b, a, c},
- []reflect.Value{a, b, c},
- },
- // Array
- {
- []reflect.Value{v([3]int{3, 2, 1}), v([3]int{1, 3, 2}), v([3]int{1, 2, 3})},
- []reflect.Value{v([3]int{1, 2, 3}), v([3]int{1, 3, 2}), v([3]int{3, 2, 1})},
- },
- // Uintptrs.
- {
- []reflect.Value{v(uintptr(2)), v(uintptr(1)), v(uintptr(3))},
- []reflect.Value{v(uintptr(1)), v(uintptr(2)), v(uintptr(3))},
- },
- // SortableStructs.
- {
- // Note: not sorted - DisableMethods is set.
- []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})},
- []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})},
- },
- // UnsortableStructs.
- {
- // Note: not sorted - SpewKeys is false.
- []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
- []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
- },
- // Invalid.
- {
- []reflect.Value{embedB, embedA, embedC},
- []reflect.Value{embedB, embedA, embedC},
- },
- }
- cs := spew.ConfigState{DisableMethods: true, SpewKeys: false}
- helpTestSortValues(tests, &cs, t)
-}
-
-// TestSortValuesWithMethods ensures the sort functionality for relect.Value
-// based sorting works as intended when using string methods.
-func TestSortValuesWithMethods(t *testing.T) {
- v := reflect.ValueOf
-
- a := v("a")
- b := v("b")
- c := v("c")
- tests := []sortTestCase{
- // Ints.
- {
- []reflect.Value{v(2), v(1), v(3)},
- []reflect.Value{v(1), v(2), v(3)},
- },
- // Strings.
- {
- []reflect.Value{b, a, c},
- []reflect.Value{a, b, c},
- },
- // SortableStructs.
- {
- []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})},
- []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})},
- },
- // UnsortableStructs.
- {
- // Note: not sorted - SpewKeys is false.
- []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
- []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
- },
- }
- cs := spew.ConfigState{DisableMethods: false, SpewKeys: false}
- helpTestSortValues(tests, &cs, t)
-}
-
-// TestSortValuesWithSpew ensures the sort functionality for relect.Value
-// based sorting works as intended when using spew to stringify keys.
-func TestSortValuesWithSpew(t *testing.T) {
- v := reflect.ValueOf
-
- a := v("a")
- b := v("b")
- c := v("c")
- tests := []sortTestCase{
- // Ints.
- {
- []reflect.Value{v(2), v(1), v(3)},
- []reflect.Value{v(1), v(2), v(3)},
- },
- // Strings.
- {
- []reflect.Value{b, a, c},
- []reflect.Value{a, b, c},
- },
- // SortableStructs.
- {
- []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})},
- []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})},
- },
- // UnsortableStructs.
- {
- []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
- []reflect.Value{v(unsortableStruct{1}), v(unsortableStruct{2}), v(unsortableStruct{3})},
- },
- }
- cs := spew.ConfigState{DisableMethods: true, SpewKeys: true}
- helpTestSortValues(tests, &cs, t)
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/config.go b/vendor/github.com/davecgh/go-spew/spew/config.go
deleted file mode 100644
index 2e3d22f..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/config.go
+++ /dev/null
@@ -1,306 +0,0 @@
-/*
- * Copyright (c) 2013-2016 Dave Collins
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-package spew
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
-)
-
-// ConfigState houses the configuration options used by spew to format and
-// display values. There is a global instance, Config, that is used to control
-// all top-level Formatter and Dump functionality. Each ConfigState instance
-// provides methods equivalent to the top-level functions.
-//
-// The zero value for ConfigState provides no indentation. You would typically
-// want to set it to a space or a tab.
-//
-// Alternatively, you can use NewDefaultConfig to get a ConfigState instance
-// with default settings. See the documentation of NewDefaultConfig for default
-// values.
-type ConfigState struct {
- // Indent specifies the string to use for each indentation level. The
- // global config instance that all top-level functions use set this to a
- // single space by default. If you would like more indentation, you might
- // set this to a tab with "\t" or perhaps two spaces with " ".
- Indent string
-
- // MaxDepth controls the maximum number of levels to descend into nested
- // data structures. The default, 0, means there is no limit.
- //
- // NOTE: Circular data structures are properly detected, so it is not
- // necessary to set this value unless you specifically want to limit deeply
- // nested data structures.
- MaxDepth int
-
- // DisableMethods specifies whether or not error and Stringer interfaces are
- // invoked for types that implement them.
- DisableMethods bool
-
- // DisablePointerMethods specifies whether or not to check for and invoke
- // error and Stringer interfaces on types which only accept a pointer
- // receiver when the current type is not a pointer.
- //
- // NOTE: This might be an unsafe action since calling one of these methods
- // with a pointer receiver could technically mutate the value, however,
- // in practice, types which choose to satisify an error or Stringer
- // interface with a pointer receiver should not be mutating their state
- // inside these interface methods. As a result, this option relies on
- // access to the unsafe package, so it will not have any effect when
- // running in environments without access to the unsafe package such as
- // Google App Engine or with the "safe" build tag specified.
- DisablePointerMethods bool
-
- // DisablePointerAddresses specifies whether to disable the printing of
- // pointer addresses. This is useful when diffing data structures in tests.
- DisablePointerAddresses bool
-
- // DisableCapacities specifies whether to disable the printing of capacities
- // for arrays, slices, maps and channels. This is useful when diffing
- // data structures in tests.
- DisableCapacities bool
-
- // ContinueOnMethod specifies whether or not recursion should continue once
- // a custom error or Stringer interface is invoked. The default, false,
- // means it will print the results of invoking the custom error or Stringer
- // interface and return immediately instead of continuing to recurse into
- // the internals of the data type.
- //
- // NOTE: This flag does not have any effect if method invocation is disabled
- // via the DisableMethods or DisablePointerMethods options.
- ContinueOnMethod bool
-
- // SortKeys specifies map keys should be sorted before being printed. Use
- // this to have a more deterministic, diffable output. Note that only
- // native types (bool, int, uint, floats, uintptr and string) and types
- // that support the error or Stringer interfaces (if methods are
- // enabled) are supported, with other types sorted according to the
- // reflect.Value.String() output which guarantees display stability.
- SortKeys bool
-
- // SpewKeys specifies that, as a last resort attempt, map keys should
- // be spewed to strings and sorted by those strings. This is only
- // considered if SortKeys is true.
- SpewKeys bool
-}
-
-// Config is the active configuration of the top-level functions.
-// The configuration can be changed by modifying the contents of spew.Config.
-var Config = ConfigState{Indent: " "}
-
-// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were
-// passed with a Formatter interface returned by c.NewFormatter. It returns
-// the formatted string as a value that satisfies error. See NewFormatter
-// for formatting details.
-//
-// This function is shorthand for the following syntax:
-//
-// fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b))
-func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) {
- return fmt.Errorf(format, c.convertArgs(a)...)
-}
-
-// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were
-// passed with a Formatter interface returned by c.NewFormatter. It returns
-// the number of bytes written and any write error encountered. See
-// NewFormatter for formatting details.
-//
-// This function is shorthand for the following syntax:
-//
-// fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b))
-func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) {
- return fmt.Fprint(w, c.convertArgs(a)...)
-}
-
-// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were
-// passed with a Formatter interface returned by c.NewFormatter. It returns
-// the number of bytes written and any write error encountered. See
-// NewFormatter for formatting details.
-//
-// This function is shorthand for the following syntax:
-//
-// fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b))
-func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
- return fmt.Fprintf(w, format, c.convertArgs(a)...)
-}
-
-// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it
-// passed with a Formatter interface returned by c.NewFormatter. See
-// NewFormatter for formatting details.
-//
-// This function is shorthand for the following syntax:
-//
-// fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b))
-func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
- return fmt.Fprintln(w, c.convertArgs(a)...)
-}
-
-// Print is a wrapper for fmt.Print that treats each argument as if it were
-// passed with a Formatter interface returned by c.NewFormatter. It returns
-// the number of bytes written and any write error encountered. See
-// NewFormatter for formatting details.
-//
-// This function is shorthand for the following syntax:
-//
-// fmt.Print(c.NewFormatter(a), c.NewFormatter(b))
-func (c *ConfigState) Print(a ...interface{}) (n int, err error) {
- return fmt.Print(c.convertArgs(a)...)
-}
-
-// Printf is a wrapper for fmt.Printf that treats each argument as if it were
-// passed with a Formatter interface returned by c.NewFormatter. It returns
-// the number of bytes written and any write error encountered. See
-// NewFormatter for formatting details.
-//
-// This function is shorthand for the following syntax:
-//
-// fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b))
-func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) {
- return fmt.Printf(format, c.convertArgs(a)...)
-}
-
-// Println is a wrapper for fmt.Println that treats each argument as if it were
-// passed with a Formatter interface returned by c.NewFormatter. It returns
-// the number of bytes written and any write error encountered. See
-// NewFormatter for formatting details.
-//
-// This function is shorthand for the following syntax:
-//
-// fmt.Println(c.NewFormatter(a), c.NewFormatter(b))
-func (c *ConfigState) Println(a ...interface{}) (n int, err error) {
- return fmt.Println(c.convertArgs(a)...)
-}
-
-// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were
-// passed with a Formatter interface returned by c.NewFormatter. It returns
-// the resulting string. See NewFormatter for formatting details.
-//
-// This function is shorthand for the following syntax:
-//
-// fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b))
-func (c *ConfigState) Sprint(a ...interface{}) string {
- return fmt.Sprint(c.convertArgs(a)...)
-}
-
-// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were
-// passed with a Formatter interface returned by c.NewFormatter. It returns
-// the resulting string. See NewFormatter for formatting details.
-//
-// This function is shorthand for the following syntax:
-//
-// fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b))
-func (c *ConfigState) Sprintf(format string, a ...interface{}) string {
- return fmt.Sprintf(format, c.convertArgs(a)...)
-}
-
-// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it
-// were passed with a Formatter interface returned by c.NewFormatter. It
-// returns the resulting string. See NewFormatter for formatting details.
-//
-// This function is shorthand for the following syntax:
-//
-// fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b))
-func (c *ConfigState) Sprintln(a ...interface{}) string {
- return fmt.Sprintln(c.convertArgs(a)...)
-}
-
-/*
-NewFormatter returns a custom formatter that satisfies the fmt.Formatter
-interface. As a result, it integrates cleanly with standard fmt package
-printing functions. The formatter is useful for inline printing of smaller data
-types similar to the standard %v format specifier.
-
-The custom formatter only responds to the %v (most compact), %+v (adds pointer
-addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb
-combinations. Any other verbs such as %x and %q will be sent to the the
-standard fmt package for formatting. In addition, the custom formatter ignores
-the width and precision arguments (however they will still work on the format
-specifiers not handled by the custom formatter).
-
-Typically this function shouldn't be called directly. It is much easier to make
-use of the custom formatter by calling one of the convenience functions such as
-c.Printf, c.Println, or c.Printf.
-*/
-func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter {
- return newFormatter(c, v)
-}
-
-// Fdump formats and displays the passed arguments to io.Writer w. It formats
-// exactly the same as Dump.
-func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) {
- fdump(c, w, a...)
-}
-
-/*
-Dump displays the passed parameters to standard out with newlines, customizable
-indentation, and additional debug information such as complete types and all
-pointer addresses used to indirect to the final value. It provides the
-following features over the built-in printing facilities provided by the fmt
-package:
-
- * Pointers are dereferenced and followed
- * Circular data structures are detected and handled properly
- * Custom Stringer/error interfaces are optionally invoked, including
- on unexported types
- * Custom types which only implement the Stringer/error interfaces via
- a pointer receiver are optionally invoked when passing non-pointer
- variables
- * Byte arrays and slices are dumped like the hexdump -C command which
- includes offsets, byte values in hex, and ASCII output
-
-The configuration options are controlled by modifying the public members
-of c. See ConfigState for options documentation.
-
-See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to
-get the formatted result as a string.
-*/
-func (c *ConfigState) Dump(a ...interface{}) {
- fdump(c, os.Stdout, a...)
-}
-
-// Sdump returns a string with the passed arguments formatted exactly the same
-// as Dump.
-func (c *ConfigState) Sdump(a ...interface{}) string {
- var buf bytes.Buffer
- fdump(c, &buf, a...)
- return buf.String()
-}
-
-// convertArgs accepts a slice of arguments and returns a slice of the same
-// length with each argument converted to a spew Formatter interface using
-// the ConfigState associated with s.
-func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) {
- formatters = make([]interface{}, len(args))
- for index, arg := range args {
- formatters[index] = newFormatter(c, arg)
- }
- return formatters
-}
-
-// NewDefaultConfig returns a ConfigState with the following default settings.
-//
-// Indent: " "
-// MaxDepth: 0
-// DisableMethods: false
-// DisablePointerMethods: false
-// ContinueOnMethod: false
-// SortKeys: false
-func NewDefaultConfig() *ConfigState {
- return &ConfigState{Indent: " "}
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/doc.go b/vendor/github.com/davecgh/go-spew/spew/doc.go
deleted file mode 100644
index aacaac6..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/doc.go
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Copyright (c) 2013-2016 Dave Collins
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-/*
-Package spew implements a deep pretty printer for Go data structures to aid in
-debugging.
-
-A quick overview of the additional features spew provides over the built-in
-printing facilities for Go data types are as follows:
-
- * Pointers are dereferenced and followed
- * Circular data structures are detected and handled properly
- * Custom Stringer/error interfaces are optionally invoked, including
- on unexported types
- * Custom types which only implement the Stringer/error interfaces via
- a pointer receiver are optionally invoked when passing non-pointer
- variables
- * Byte arrays and slices are dumped like the hexdump -C command which
- includes offsets, byte values in hex, and ASCII output (only when using
- Dump style)
-
-There are two different approaches spew allows for dumping Go data structures:
-
- * Dump style which prints with newlines, customizable indentation,
- and additional debug information such as types and all pointer addresses
- used to indirect to the final value
- * A custom Formatter interface that integrates cleanly with the standard fmt
- package and replaces %v, %+v, %#v, and %#+v to provide inline printing
- similar to the default %v while providing the additional functionality
- outlined above and passing unsupported format verbs such as %x and %q
- along to fmt
-
-Quick Start
-
-This section demonstrates how to quickly get started with spew. See the
-sections below for further details on formatting and configuration options.
-
-To dump a variable with full newlines, indentation, type, and pointer
-information use Dump, Fdump, or Sdump:
- spew.Dump(myVar1, myVar2, ...)
- spew.Fdump(someWriter, myVar1, myVar2, ...)
- str := spew.Sdump(myVar1, myVar2, ...)
-
-Alternatively, if you would prefer to use format strings with a compacted inline
-printing style, use the convenience wrappers Printf, Fprintf, etc with
-%v (most compact), %+v (adds pointer addresses), %#v (adds types), or
-%#+v (adds types and pointer addresses):
- spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2)
- spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
- spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2)
- spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
-
-Configuration Options
-
-Configuration of spew is handled by fields in the ConfigState type. For
-convenience, all of the top-level functions use a global state available
-via the spew.Config global.
-
-It is also possible to create a ConfigState instance that provides methods
-equivalent to the top-level functions. This allows concurrent configuration
-options. See the ConfigState documentation for more details.
-
-The following configuration options are available:
- * Indent
- String to use for each indentation level for Dump functions.
- It is a single space by default. A popular alternative is "\t".
-
- * MaxDepth
- Maximum number of levels to descend into nested data structures.
- There is no limit by default.
-
- * DisableMethods
- Disables invocation of error and Stringer interface methods.
- Method invocation is enabled by default.
-
- * DisablePointerMethods
- Disables invocation of error and Stringer interface methods on types
- which only accept pointer receivers from non-pointer variables.
- Pointer method invocation is enabled by default.
-
- * DisablePointerAddresses
- DisablePointerAddresses specifies whether to disable the printing of
- pointer addresses. This is useful when diffing data structures in tests.
-
- * DisableCapacities
- DisableCapacities specifies whether to disable the printing of
- capacities for arrays, slices, maps and channels. This is useful when
- diffing data structures in tests.
-
- * ContinueOnMethod
- Enables recursion into types after invoking error and Stringer interface
- methods. Recursion after method invocation is disabled by default.
-
- * SortKeys
- Specifies map keys should be sorted before being printed. Use
- this to have a more deterministic, diffable output. Note that
- only native types (bool, int, uint, floats, uintptr and string)
- and types which implement error or Stringer interfaces are
- supported with other types sorted according to the
- reflect.Value.String() output which guarantees display
- stability. Natural map order is used by default.
-
- * SpewKeys
- Specifies that, as a last resort attempt, map keys should be
- spewed to strings and sorted by those strings. This is only
- considered if SortKeys is true.
-
-Dump Usage
-
-Simply call spew.Dump with a list of variables you want to dump:
-
- spew.Dump(myVar1, myVar2, ...)
-
-You may also call spew.Fdump if you would prefer to output to an arbitrary
-io.Writer. For example, to dump to standard error:
-
- spew.Fdump(os.Stderr, myVar1, myVar2, ...)
-
-A third option is to call spew.Sdump to get the formatted output as a string:
-
- str := spew.Sdump(myVar1, myVar2, ...)
-
-Sample Dump Output
-
-See the Dump example for details on the setup of the types and variables being
-shown here.
-
- (main.Foo) {
- unexportedField: (*main.Bar)(0xf84002e210)({
- flag: (main.Flag) flagTwo,
- data: (uintptr)
- }),
- ExportedField: (map[interface {}]interface {}) (len=1) {
- (string) (len=3) "one": (bool) true
- }
- }
-
-Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C
-command as shown.
- ([]uint8) (len=32 cap=32) {
- 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... |
- 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0|
- 00000020 31 32 |12|
- }
-
-Custom Formatter
-
-Spew provides a custom formatter that implements the fmt.Formatter interface
-so that it integrates cleanly with standard fmt package printing functions. The
-formatter is useful for inline printing of smaller data types similar to the
-standard %v format specifier.
-
-The custom formatter only responds to the %v (most compact), %+v (adds pointer
-addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb
-combinations. Any other verbs such as %x and %q will be sent to the the
-standard fmt package for formatting. In addition, the custom formatter ignores
-the width and precision arguments (however they will still work on the format
-specifiers not handled by the custom formatter).
-
-Custom Formatter Usage
-
-The simplest way to make use of the spew custom formatter is to call one of the
-convenience functions such as spew.Printf, spew.Println, or spew.Printf. The
-functions have syntax you are most likely already familiar with:
-
- spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2)
- spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
- spew.Println(myVar, myVar2)
- spew.Fprintf(os.Stderr, "myVar1: %v -- myVar2: %+v", myVar1, myVar2)
- spew.Fprintf(os.Stderr, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4)
-
-See the Index for the full list convenience functions.
-
-Sample Formatter Output
-
-Double pointer to a uint8:
- %v: <**>5
- %+v: <**>(0xf8400420d0->0xf8400420c8)5
- %#v: (**uint8)5
- %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5
-
-Pointer to circular struct with a uint8 field and a pointer to itself:
- %v: <*>{1 <*>}
- %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)}
- %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)}
- %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)}
-
-See the Printf example for details on the setup of variables being shown
-here.
-
-Errors
-
-Since it is possible for custom Stringer/error interfaces to panic, spew
-detects them and handles them internally by printing the panic information
-inline with the output. Since spew is intended to provide deep pretty printing
-capabilities on structures, it intentionally does not return any errors.
-*/
-package spew
diff --git a/vendor/github.com/davecgh/go-spew/spew/dump.go b/vendor/github.com/davecgh/go-spew/spew/dump.go
deleted file mode 100644
index df1d582..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/dump.go
+++ /dev/null
@@ -1,509 +0,0 @@
-/*
- * Copyright (c) 2013-2016 Dave Collins
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-package spew
-
-import (
- "bytes"
- "encoding/hex"
- "fmt"
- "io"
- "os"
- "reflect"
- "regexp"
- "strconv"
- "strings"
-)
-
-var (
- // uint8Type is a reflect.Type representing a uint8. It is used to
- // convert cgo types to uint8 slices for hexdumping.
- uint8Type = reflect.TypeOf(uint8(0))
-
- // cCharRE is a regular expression that matches a cgo char.
- // It is used to detect character arrays to hexdump them.
- cCharRE = regexp.MustCompile("^.*\\._Ctype_char$")
-
- // cUnsignedCharRE is a regular expression that matches a cgo unsigned
- // char. It is used to detect unsigned character arrays to hexdump
- // them.
- cUnsignedCharRE = regexp.MustCompile("^.*\\._Ctype_unsignedchar$")
-
- // cUint8tCharRE is a regular expression that matches a cgo uint8_t.
- // It is used to detect uint8_t arrays to hexdump them.
- cUint8tCharRE = regexp.MustCompile("^.*\\._Ctype_uint8_t$")
-)
-
-// dumpState contains information about the state of a dump operation.
-type dumpState struct {
- w io.Writer
- depth int
- pointers map[uintptr]int
- ignoreNextType bool
- ignoreNextIndent bool
- cs *ConfigState
-}
-
-// indent performs indentation according to the depth level and cs.Indent
-// option.
-func (d *dumpState) indent() {
- if d.ignoreNextIndent {
- d.ignoreNextIndent = false
- return
- }
- d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth))
-}
-
-// unpackValue returns values inside of non-nil interfaces when possible.
-// This is useful for data types like structs, arrays, slices, and maps which
-// can contain varying types packed inside an interface.
-func (d *dumpState) unpackValue(v reflect.Value) reflect.Value {
- if v.Kind() == reflect.Interface && !v.IsNil() {
- v = v.Elem()
- }
- return v
-}
-
-// dumpPtr handles formatting of pointers by indirecting them as necessary.
-func (d *dumpState) dumpPtr(v reflect.Value) {
- // Remove pointers at or below the current depth from map used to detect
- // circular refs.
- for k, depth := range d.pointers {
- if depth >= d.depth {
- delete(d.pointers, k)
- }
- }
-
- // Keep list of all dereferenced pointers to show later.
- pointerChain := make([]uintptr, 0)
-
- // Figure out how many levels of indirection there are by dereferencing
- // pointers and unpacking interfaces down the chain while detecting circular
- // references.
- nilFound := false
- cycleFound := false
- indirects := 0
- ve := v
- for ve.Kind() == reflect.Ptr {
- if ve.IsNil() {
- nilFound = true
- break
- }
- indirects++
- addr := ve.Pointer()
- pointerChain = append(pointerChain, addr)
- if pd, ok := d.pointers[addr]; ok && pd < d.depth {
- cycleFound = true
- indirects--
- break
- }
- d.pointers[addr] = d.depth
-
- ve = ve.Elem()
- if ve.Kind() == reflect.Interface {
- if ve.IsNil() {
- nilFound = true
- break
- }
- ve = ve.Elem()
- }
- }
-
- // Display type information.
- d.w.Write(openParenBytes)
- d.w.Write(bytes.Repeat(asteriskBytes, indirects))
- d.w.Write([]byte(ve.Type().String()))
- d.w.Write(closeParenBytes)
-
- // Display pointer information.
- if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 {
- d.w.Write(openParenBytes)
- for i, addr := range pointerChain {
- if i > 0 {
- d.w.Write(pointerChainBytes)
- }
- printHexPtr(d.w, addr)
- }
- d.w.Write(closeParenBytes)
- }
-
- // Display dereferenced value.
- d.w.Write(openParenBytes)
- switch {
- case nilFound == true:
- d.w.Write(nilAngleBytes)
-
- case cycleFound == true:
- d.w.Write(circularBytes)
-
- default:
- d.ignoreNextType = true
- d.dump(ve)
- }
- d.w.Write(closeParenBytes)
-}
-
-// dumpSlice handles formatting of arrays and slices. Byte (uint8 under
-// reflection) arrays and slices are dumped in hexdump -C fashion.
-func (d *dumpState) dumpSlice(v reflect.Value) {
- // Determine whether this type should be hex dumped or not. Also,
- // for types which should be hexdumped, try to use the underlying data
- // first, then fall back to trying to convert them to a uint8 slice.
- var buf []uint8
- doConvert := false
- doHexDump := false
- numEntries := v.Len()
- if numEntries > 0 {
- vt := v.Index(0).Type()
- vts := vt.String()
- switch {
- // C types that need to be converted.
- case cCharRE.MatchString(vts):
- fallthrough
- case cUnsignedCharRE.MatchString(vts):
- fallthrough
- case cUint8tCharRE.MatchString(vts):
- doConvert = true
-
- // Try to use existing uint8 slices and fall back to converting
- // and copying if that fails.
- case vt.Kind() == reflect.Uint8:
- // We need an addressable interface to convert the type
- // to a byte slice. However, the reflect package won't
- // give us an interface on certain things like
- // unexported struct fields in order to enforce
- // visibility rules. We use unsafe, when available, to
- // bypass these restrictions since this package does not
- // mutate the values.
- vs := v
- if !vs.CanInterface() || !vs.CanAddr() {
- vs = unsafeReflectValue(vs)
- }
- if !UnsafeDisabled {
- vs = vs.Slice(0, numEntries)
-
- // Use the existing uint8 slice if it can be
- // type asserted.
- iface := vs.Interface()
- if slice, ok := iface.([]uint8); ok {
- buf = slice
- doHexDump = true
- break
- }
- }
-
- // The underlying data needs to be converted if it can't
- // be type asserted to a uint8 slice.
- doConvert = true
- }
-
- // Copy and convert the underlying type if needed.
- if doConvert && vt.ConvertibleTo(uint8Type) {
- // Convert and copy each element into a uint8 byte
- // slice.
- buf = make([]uint8, numEntries)
- for i := 0; i < numEntries; i++ {
- vv := v.Index(i)
- buf[i] = uint8(vv.Convert(uint8Type).Uint())
- }
- doHexDump = true
- }
- }
-
- // Hexdump the entire slice as needed.
- if doHexDump {
- indent := strings.Repeat(d.cs.Indent, d.depth)
- str := indent + hex.Dump(buf)
- str = strings.Replace(str, "\n", "\n"+indent, -1)
- str = strings.TrimRight(str, d.cs.Indent)
- d.w.Write([]byte(str))
- return
- }
-
- // Recursively call dump for each item.
- for i := 0; i < numEntries; i++ {
- d.dump(d.unpackValue(v.Index(i)))
- if i < (numEntries - 1) {
- d.w.Write(commaNewlineBytes)
- } else {
- d.w.Write(newlineBytes)
- }
- }
-}
-
-// dump is the main workhorse for dumping a value. It uses the passed reflect
-// value to figure out what kind of object we are dealing with and formats it
-// appropriately. It is a recursive function, however circular data structures
-// are detected and handled properly.
-func (d *dumpState) dump(v reflect.Value) {
- // Handle invalid reflect values immediately.
- kind := v.Kind()
- if kind == reflect.Invalid {
- d.w.Write(invalidAngleBytes)
- return
- }
-
- // Handle pointers specially.
- if kind == reflect.Ptr {
- d.indent()
- d.dumpPtr(v)
- return
- }
-
- // Print type information unless already handled elsewhere.
- if !d.ignoreNextType {
- d.indent()
- d.w.Write(openParenBytes)
- d.w.Write([]byte(v.Type().String()))
- d.w.Write(closeParenBytes)
- d.w.Write(spaceBytes)
- }
- d.ignoreNextType = false
-
- // Display length and capacity if the built-in len and cap functions
- // work with the value's kind and the len/cap itself is non-zero.
- valueLen, valueCap := 0, 0
- switch v.Kind() {
- case reflect.Array, reflect.Slice, reflect.Chan:
- valueLen, valueCap = v.Len(), v.Cap()
- case reflect.Map, reflect.String:
- valueLen = v.Len()
- }
- if valueLen != 0 || !d.cs.DisableCapacities && valueCap != 0 {
- d.w.Write(openParenBytes)
- if valueLen != 0 {
- d.w.Write(lenEqualsBytes)
- printInt(d.w, int64(valueLen), 10)
- }
- if !d.cs.DisableCapacities && valueCap != 0 {
- if valueLen != 0 {
- d.w.Write(spaceBytes)
- }
- d.w.Write(capEqualsBytes)
- printInt(d.w, int64(valueCap), 10)
- }
- d.w.Write(closeParenBytes)
- d.w.Write(spaceBytes)
- }
-
- // Call Stringer/error interfaces if they exist and the handle methods flag
- // is enabled
- if !d.cs.DisableMethods {
- if (kind != reflect.Invalid) && (kind != reflect.Interface) {
- if handled := handleMethods(d.cs, d.w, v); handled {
- return
- }
- }
- }
-
- switch kind {
- case reflect.Invalid:
- // Do nothing. We should never get here since invalid has already
- // been handled above.
-
- case reflect.Bool:
- printBool(d.w, v.Bool())
-
- case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
- printInt(d.w, v.Int(), 10)
-
- case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
- printUint(d.w, v.Uint(), 10)
-
- case reflect.Float32:
- printFloat(d.w, v.Float(), 32)
-
- case reflect.Float64:
- printFloat(d.w, v.Float(), 64)
-
- case reflect.Complex64:
- printComplex(d.w, v.Complex(), 32)
-
- case reflect.Complex128:
- printComplex(d.w, v.Complex(), 64)
-
- case reflect.Slice:
- if v.IsNil() {
- d.w.Write(nilAngleBytes)
- break
- }
- fallthrough
-
- case reflect.Array:
- d.w.Write(openBraceNewlineBytes)
- d.depth++
- if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
- d.indent()
- d.w.Write(maxNewlineBytes)
- } else {
- d.dumpSlice(v)
- }
- d.depth--
- d.indent()
- d.w.Write(closeBraceBytes)
-
- case reflect.String:
- d.w.Write([]byte(strconv.Quote(v.String())))
-
- case reflect.Interface:
- // The only time we should get here is for nil interfaces due to
- // unpackValue calls.
- if v.IsNil() {
- d.w.Write(nilAngleBytes)
- }
-
- case reflect.Ptr:
- // Do nothing. We should never get here since pointers have already
- // been handled above.
-
- case reflect.Map:
- // nil maps should be indicated as different than empty maps
- if v.IsNil() {
- d.w.Write(nilAngleBytes)
- break
- }
-
- d.w.Write(openBraceNewlineBytes)
- d.depth++
- if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
- d.indent()
- d.w.Write(maxNewlineBytes)
- } else {
- numEntries := v.Len()
- keys := v.MapKeys()
- if d.cs.SortKeys {
- sortValues(keys, d.cs)
- }
- for i, key := range keys {
- d.dump(d.unpackValue(key))
- d.w.Write(colonSpaceBytes)
- d.ignoreNextIndent = true
- d.dump(d.unpackValue(v.MapIndex(key)))
- if i < (numEntries - 1) {
- d.w.Write(commaNewlineBytes)
- } else {
- d.w.Write(newlineBytes)
- }
- }
- }
- d.depth--
- d.indent()
- d.w.Write(closeBraceBytes)
-
- case reflect.Struct:
- d.w.Write(openBraceNewlineBytes)
- d.depth++
- if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) {
- d.indent()
- d.w.Write(maxNewlineBytes)
- } else {
- vt := v.Type()
- numFields := v.NumField()
- for i := 0; i < numFields; i++ {
- d.indent()
- vtf := vt.Field(i)
- d.w.Write([]byte(vtf.Name))
- d.w.Write(colonSpaceBytes)
- d.ignoreNextIndent = true
- d.dump(d.unpackValue(v.Field(i)))
- if i < (numFields - 1) {
- d.w.Write(commaNewlineBytes)
- } else {
- d.w.Write(newlineBytes)
- }
- }
- }
- d.depth--
- d.indent()
- d.w.Write(closeBraceBytes)
-
- case reflect.Uintptr:
- printHexPtr(d.w, uintptr(v.Uint()))
-
- case reflect.UnsafePointer, reflect.Chan, reflect.Func:
- printHexPtr(d.w, v.Pointer())
-
- // There were not any other types at the time this code was written, but
- // fall back to letting the default fmt package handle it in case any new
- // types are added.
- default:
- if v.CanInterface() {
- fmt.Fprintf(d.w, "%v", v.Interface())
- } else {
- fmt.Fprintf(d.w, "%v", v.String())
- }
- }
-}
-
-// fdump is a helper function to consolidate the logic from the various public
-// methods which take varying writers and config states.
-func fdump(cs *ConfigState, w io.Writer, a ...interface{}) {
- for _, arg := range a {
- if arg == nil {
- w.Write(interfaceBytes)
- w.Write(spaceBytes)
- w.Write(nilAngleBytes)
- w.Write(newlineBytes)
- continue
- }
-
- d := dumpState{w: w, cs: cs}
- d.pointers = make(map[uintptr]int)
- d.dump(reflect.ValueOf(arg))
- d.w.Write(newlineBytes)
- }
-}
-
-// Fdump formats and displays the passed arguments to io.Writer w. It formats
-// exactly the same as Dump.
-func Fdump(w io.Writer, a ...interface{}) {
- fdump(&Config, w, a...)
-}
-
-// Sdump returns a string with the passed arguments formatted exactly the same
-// as Dump.
-func Sdump(a ...interface{}) string {
- var buf bytes.Buffer
- fdump(&Config, &buf, a...)
- return buf.String()
-}
-
-/*
-Dump displays the passed parameters to standard out with newlines, customizable
-indentation, and additional debug information such as complete types and all
-pointer addresses used to indirect to the final value. It provides the
-following features over the built-in printing facilities provided by the fmt
-package:
-
- * Pointers are dereferenced and followed
- * Circular data structures are detected and handled properly
- * Custom Stringer/error interfaces are optionally invoked, including
- on unexported types
- * Custom types which only implement the Stringer/error interfaces via
- a pointer receiver are optionally invoked when passing non-pointer
- variables
- * Byte arrays and slices are dumped like the hexdump -C command which
- includes offsets, byte values in hex, and ASCII output
-
-The configuration options are controlled by an exported package global,
-spew.Config. See ConfigState for options documentation.
-
-See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to
-get the formatted result as a string.
-*/
-func Dump(a ...interface{}) {
- fdump(&Config, os.Stdout, a...)
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/dump_test.go b/vendor/github.com/davecgh/go-spew/spew/dump_test.go
deleted file mode 100644
index 5aad9c7..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/dump_test.go
+++ /dev/null
@@ -1,1042 +0,0 @@
-/*
- * Copyright (c) 2013-2016 Dave Collins
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-/*
-Test Summary:
-NOTE: For each test, a nil pointer, a single pointer and double pointer to the
-base test element are also tested to ensure proper indirection across all types.
-
-- Max int8, int16, int32, int64, int
-- Max uint8, uint16, uint32, uint64, uint
-- Boolean true and false
-- Standard complex64 and complex128
-- Array containing standard ints
-- Array containing type with custom formatter on pointer receiver only
-- Array containing interfaces
-- Array containing bytes
-- Slice containing standard float32 values
-- Slice containing type with custom formatter on pointer receiver only
-- Slice containing interfaces
-- Slice containing bytes
-- Nil slice
-- Standard string
-- Nil interface
-- Sub-interface
-- Map with string keys and int vals
-- Map with custom formatter type on pointer receiver only keys and vals
-- Map with interface keys and values
-- Map with nil interface value
-- Struct with primitives
-- Struct that contains another struct
-- Struct that contains custom type with Stringer pointer interface via both
- exported and unexported fields
-- Struct that contains embedded struct and field to same struct
-- Uintptr to 0 (null pointer)
-- Uintptr address of real variable
-- Unsafe.Pointer to 0 (null pointer)
-- Unsafe.Pointer to address of real variable
-- Nil channel
-- Standard int channel
-- Function with no params and no returns
-- Function with param and no returns
-- Function with multiple params and multiple returns
-- Struct that is circular through self referencing
-- Structs that are circular through cross referencing
-- Structs that are indirectly circular
-- Type that panics in its Stringer interface
-*/
-
-package spew_test
-
-import (
- "bytes"
- "fmt"
- "testing"
- "unsafe"
-
- "github.com/davecgh/go-spew/spew"
-)
-
-// dumpTest is used to describe a test to be performed against the Dump method.
-type dumpTest struct {
- in interface{}
- wants []string
-}
-
-// dumpTests houses all of the tests to be performed against the Dump method.
-var dumpTests = make([]dumpTest, 0)
-
-// addDumpTest is a helper method to append the passed input and desired result
-// to dumpTests
-func addDumpTest(in interface{}, wants ...string) {
- test := dumpTest{in, wants}
- dumpTests = append(dumpTests, test)
-}
-
-func addIntDumpTests() {
- // Max int8.
- v := int8(127)
- nv := (*int8)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "int8"
- vs := "127"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Max int16.
- v2 := int16(32767)
- nv2 := (*int16)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "int16"
- v2s := "32767"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv2, "(*"+v2t+")()\n")
-
- // Max int32.
- v3 := int32(2147483647)
- nv3 := (*int32)(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "int32"
- v3s := "2147483647"
- addDumpTest(v3, "("+v3t+") "+v3s+"\n")
- addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n")
- addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n")
- addDumpTest(nv3, "(*"+v3t+")()\n")
-
- // Max int64.
- v4 := int64(9223372036854775807)
- nv4 := (*int64)(nil)
- pv4 := &v4
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "int64"
- v4s := "9223372036854775807"
- addDumpTest(v4, "("+v4t+") "+v4s+"\n")
- addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n")
- addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n")
- addDumpTest(nv4, "(*"+v4t+")()\n")
-
- // Max int.
- v5 := int(2147483647)
- nv5 := (*int)(nil)
- pv5 := &v5
- v5Addr := fmt.Sprintf("%p", pv5)
- pv5Addr := fmt.Sprintf("%p", &pv5)
- v5t := "int"
- v5s := "2147483647"
- addDumpTest(v5, "("+v5t+") "+v5s+"\n")
- addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n")
- addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n")
- addDumpTest(nv5, "(*"+v5t+")()\n")
-}
-
-func addUintDumpTests() {
- // Max uint8.
- v := uint8(255)
- nv := (*uint8)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "uint8"
- vs := "255"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Max uint16.
- v2 := uint16(65535)
- nv2 := (*uint16)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "uint16"
- v2s := "65535"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv2, "(*"+v2t+")()\n")
-
- // Max uint32.
- v3 := uint32(4294967295)
- nv3 := (*uint32)(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "uint32"
- v3s := "4294967295"
- addDumpTest(v3, "("+v3t+") "+v3s+"\n")
- addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n")
- addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n")
- addDumpTest(nv3, "(*"+v3t+")()\n")
-
- // Max uint64.
- v4 := uint64(18446744073709551615)
- nv4 := (*uint64)(nil)
- pv4 := &v4
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "uint64"
- v4s := "18446744073709551615"
- addDumpTest(v4, "("+v4t+") "+v4s+"\n")
- addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n")
- addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n")
- addDumpTest(nv4, "(*"+v4t+")()\n")
-
- // Max uint.
- v5 := uint(4294967295)
- nv5 := (*uint)(nil)
- pv5 := &v5
- v5Addr := fmt.Sprintf("%p", pv5)
- pv5Addr := fmt.Sprintf("%p", &pv5)
- v5t := "uint"
- v5s := "4294967295"
- addDumpTest(v5, "("+v5t+") "+v5s+"\n")
- addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n")
- addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n")
- addDumpTest(nv5, "(*"+v5t+")()\n")
-}
-
-func addBoolDumpTests() {
- // Boolean true.
- v := bool(true)
- nv := (*bool)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "bool"
- vs := "true"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Boolean false.
- v2 := bool(false)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "bool"
- v2s := "false"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
-}
-
-func addFloatDumpTests() {
- // Standard float32.
- v := float32(3.1415)
- nv := (*float32)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "float32"
- vs := "3.1415"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Standard float64.
- v2 := float64(3.1415926)
- nv2 := (*float64)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "float64"
- v2s := "3.1415926"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv2, "(*"+v2t+")()\n")
-}
-
-func addComplexDumpTests() {
- // Standard complex64.
- v := complex(float32(6), -2)
- nv := (*complex64)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "complex64"
- vs := "(6-2i)"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Standard complex128.
- v2 := complex(float64(-6), 2)
- nv2 := (*complex128)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "complex128"
- v2s := "(-6+2i)"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv2, "(*"+v2t+")()\n")
-}
-
-func addArrayDumpTests() {
- // Array containing standard ints.
- v := [3]int{1, 2, 3}
- vLen := fmt.Sprintf("%d", len(v))
- vCap := fmt.Sprintf("%d", cap(v))
- nv := (*[3]int)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "int"
- vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 1,\n (" +
- vt + ") 2,\n (" + vt + ") 3\n}"
- addDumpTest(v, "([3]"+vt+") "+vs+"\n")
- addDumpTest(pv, "(*[3]"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**[3]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*[3]"+vt+")()\n")
-
- // Array containing type with custom formatter on pointer receiver only.
- v2i0 := pstringer("1")
- v2i1 := pstringer("2")
- v2i2 := pstringer("3")
- v2 := [3]pstringer{v2i0, v2i1, v2i2}
- v2i0Len := fmt.Sprintf("%d", len(v2i0))
- v2i1Len := fmt.Sprintf("%d", len(v2i1))
- v2i2Len := fmt.Sprintf("%d", len(v2i2))
- v2Len := fmt.Sprintf("%d", len(v2))
- v2Cap := fmt.Sprintf("%d", cap(v2))
- nv2 := (*[3]pstringer)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "spew_test.pstringer"
- v2sp := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t +
- ") (len=" + v2i0Len + ") stringer 1,\n (" + v2t +
- ") (len=" + v2i1Len + ") stringer 2,\n (" + v2t +
- ") (len=" + v2i2Len + ") " + "stringer 3\n}"
- v2s := v2sp
- if spew.UnsafeDisabled {
- v2s = "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t +
- ") (len=" + v2i0Len + ") \"1\",\n (" + v2t + ") (len=" +
- v2i1Len + ") \"2\",\n (" + v2t + ") (len=" + v2i2Len +
- ") " + "\"3\"\n}"
- }
- addDumpTest(v2, "([3]"+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*[3]"+v2t+")("+v2Addr+")("+v2sp+")\n")
- addDumpTest(&pv2, "(**[3]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2sp+")\n")
- addDumpTest(nv2, "(*[3]"+v2t+")()\n")
-
- // Array containing interfaces.
- v3i0 := "one"
- v3 := [3]interface{}{v3i0, int(2), uint(3)}
- v3i0Len := fmt.Sprintf("%d", len(v3i0))
- v3Len := fmt.Sprintf("%d", len(v3))
- v3Cap := fmt.Sprintf("%d", cap(v3))
- nv3 := (*[3]interface{})(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "[3]interface {}"
- v3t2 := "string"
- v3t3 := "int"
- v3t4 := "uint"
- v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " +
- "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" +
- v3t4 + ") 3\n}"
- addDumpTest(v3, "("+v3t+") "+v3s+"\n")
- addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n")
- addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n")
- addDumpTest(nv3, "(*"+v3t+")()\n")
-
- // Array containing bytes.
- v4 := [34]byte{
- 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
- 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
- 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
- 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
- 0x31, 0x32,
- }
- v4Len := fmt.Sprintf("%d", len(v4))
- v4Cap := fmt.Sprintf("%d", cap(v4))
- nv4 := (*[34]byte)(nil)
- pv4 := &v4
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "[34]uint8"
- v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " +
- "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" +
- " |............... |\n" +
- " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" +
- " |!\"#$%&'()*+,-./0|\n" +
- " 00000020 31 32 " +
- " |12|\n}"
- addDumpTest(v4, "("+v4t+") "+v4s+"\n")
- addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n")
- addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n")
- addDumpTest(nv4, "(*"+v4t+")()\n")
-}
-
-func addSliceDumpTests() {
- // Slice containing standard float32 values.
- v := []float32{3.14, 6.28, 12.56}
- vLen := fmt.Sprintf("%d", len(v))
- vCap := fmt.Sprintf("%d", cap(v))
- nv := (*[]float32)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "float32"
- vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 3.14,\n (" +
- vt + ") 6.28,\n (" + vt + ") 12.56\n}"
- addDumpTest(v, "([]"+vt+") "+vs+"\n")
- addDumpTest(pv, "(*[]"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**[]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*[]"+vt+")()\n")
-
- // Slice containing type with custom formatter on pointer receiver only.
- v2i0 := pstringer("1")
- v2i1 := pstringer("2")
- v2i2 := pstringer("3")
- v2 := []pstringer{v2i0, v2i1, v2i2}
- v2i0Len := fmt.Sprintf("%d", len(v2i0))
- v2i1Len := fmt.Sprintf("%d", len(v2i1))
- v2i2Len := fmt.Sprintf("%d", len(v2i2))
- v2Len := fmt.Sprintf("%d", len(v2))
- v2Cap := fmt.Sprintf("%d", cap(v2))
- nv2 := (*[]pstringer)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "spew_test.pstringer"
- v2s := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + ") (len=" +
- v2i0Len + ") stringer 1,\n (" + v2t + ") (len=" + v2i1Len +
- ") stringer 2,\n (" + v2t + ") (len=" + v2i2Len + ") " +
- "stringer 3\n}"
- addDumpTest(v2, "([]"+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*[]"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**[]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv2, "(*[]"+v2t+")()\n")
-
- // Slice containing interfaces.
- v3i0 := "one"
- v3 := []interface{}{v3i0, int(2), uint(3), nil}
- v3i0Len := fmt.Sprintf("%d", len(v3i0))
- v3Len := fmt.Sprintf("%d", len(v3))
- v3Cap := fmt.Sprintf("%d", cap(v3))
- nv3 := (*[]interface{})(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "[]interface {}"
- v3t2 := "string"
- v3t3 := "int"
- v3t4 := "uint"
- v3t5 := "interface {}"
- v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " +
- "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" +
- v3t4 + ") 3,\n (" + v3t5 + ") \n}"
- addDumpTest(v3, "("+v3t+") "+v3s+"\n")
- addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n")
- addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n")
- addDumpTest(nv3, "(*"+v3t+")()\n")
-
- // Slice containing bytes.
- v4 := []byte{
- 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
- 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
- 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
- 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
- 0x31, 0x32,
- }
- v4Len := fmt.Sprintf("%d", len(v4))
- v4Cap := fmt.Sprintf("%d", cap(v4))
- nv4 := (*[]byte)(nil)
- pv4 := &v4
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "[]uint8"
- v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " +
- "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" +
- " |............... |\n" +
- " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" +
- " |!\"#$%&'()*+,-./0|\n" +
- " 00000020 31 32 " +
- " |12|\n}"
- addDumpTest(v4, "("+v4t+") "+v4s+"\n")
- addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n")
- addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n")
- addDumpTest(nv4, "(*"+v4t+")()\n")
-
- // Nil slice.
- v5 := []int(nil)
- nv5 := (*[]int)(nil)
- pv5 := &v5
- v5Addr := fmt.Sprintf("%p", pv5)
- pv5Addr := fmt.Sprintf("%p", &pv5)
- v5t := "[]int"
- v5s := ""
- addDumpTest(v5, "("+v5t+") "+v5s+"\n")
- addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n")
- addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n")
- addDumpTest(nv5, "(*"+v5t+")()\n")
-}
-
-func addStringDumpTests() {
- // Standard string.
- v := "test"
- vLen := fmt.Sprintf("%d", len(v))
- nv := (*string)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "string"
- vs := "(len=" + vLen + ") \"test\""
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-}
-
-func addInterfaceDumpTests() {
- // Nil interface.
- var v interface{}
- nv := (*interface{})(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "interface {}"
- vs := ""
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Sub-interface.
- v2 := interface{}(uint16(65535))
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "uint16"
- v2s := "65535"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
-}
-
-func addMapDumpTests() {
- // Map with string keys and int vals.
- k := "one"
- kk := "two"
- m := map[string]int{k: 1, kk: 2}
- klen := fmt.Sprintf("%d", len(k)) // not kLen to shut golint up
- kkLen := fmt.Sprintf("%d", len(kk))
- mLen := fmt.Sprintf("%d", len(m))
- nilMap := map[string]int(nil)
- nm := (*map[string]int)(nil)
- pm := &m
- mAddr := fmt.Sprintf("%p", pm)
- pmAddr := fmt.Sprintf("%p", &pm)
- mt := "map[string]int"
- mt1 := "string"
- mt2 := "int"
- ms := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + klen + ") " +
- "\"one\": (" + mt2 + ") 1,\n (" + mt1 + ") (len=" + kkLen +
- ") \"two\": (" + mt2 + ") 2\n}"
- ms2 := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + kkLen + ") " +
- "\"two\": (" + mt2 + ") 2,\n (" + mt1 + ") (len=" + klen +
- ") \"one\": (" + mt2 + ") 1\n}"
- addDumpTest(m, "("+mt+") "+ms+"\n", "("+mt+") "+ms2+"\n")
- addDumpTest(pm, "(*"+mt+")("+mAddr+")("+ms+")\n",
- "(*"+mt+")("+mAddr+")("+ms2+")\n")
- addDumpTest(&pm, "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms+")\n",
- "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms2+")\n")
- addDumpTest(nm, "(*"+mt+")()\n")
- addDumpTest(nilMap, "("+mt+") \n")
-
- // Map with custom formatter type on pointer receiver only keys and vals.
- k2 := pstringer("one")
- v2 := pstringer("1")
- m2 := map[pstringer]pstringer{k2: v2}
- k2Len := fmt.Sprintf("%d", len(k2))
- v2Len := fmt.Sprintf("%d", len(v2))
- m2Len := fmt.Sprintf("%d", len(m2))
- nilMap2 := map[pstringer]pstringer(nil)
- nm2 := (*map[pstringer]pstringer)(nil)
- pm2 := &m2
- m2Addr := fmt.Sprintf("%p", pm2)
- pm2Addr := fmt.Sprintf("%p", &pm2)
- m2t := "map[spew_test.pstringer]spew_test.pstringer"
- m2t1 := "spew_test.pstringer"
- m2t2 := "spew_test.pstringer"
- m2s := "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len + ") " +
- "stringer one: (" + m2t2 + ") (len=" + v2Len + ") stringer 1\n}"
- if spew.UnsafeDisabled {
- m2s = "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len +
- ") " + "\"one\": (" + m2t2 + ") (len=" + v2Len +
- ") \"1\"\n}"
- }
- addDumpTest(m2, "("+m2t+") "+m2s+"\n")
- addDumpTest(pm2, "(*"+m2t+")("+m2Addr+")("+m2s+")\n")
- addDumpTest(&pm2, "(**"+m2t+")("+pm2Addr+"->"+m2Addr+")("+m2s+")\n")
- addDumpTest(nm2, "(*"+m2t+")()\n")
- addDumpTest(nilMap2, "("+m2t+") \n")
-
- // Map with interface keys and values.
- k3 := "one"
- k3Len := fmt.Sprintf("%d", len(k3))
- m3 := map[interface{}]interface{}{k3: 1}
- m3Len := fmt.Sprintf("%d", len(m3))
- nilMap3 := map[interface{}]interface{}(nil)
- nm3 := (*map[interface{}]interface{})(nil)
- pm3 := &m3
- m3Addr := fmt.Sprintf("%p", pm3)
- pm3Addr := fmt.Sprintf("%p", &pm3)
- m3t := "map[interface {}]interface {}"
- m3t1 := "string"
- m3t2 := "int"
- m3s := "(len=" + m3Len + ") {\n (" + m3t1 + ") (len=" + k3Len + ") " +
- "\"one\": (" + m3t2 + ") 1\n}"
- addDumpTest(m3, "("+m3t+") "+m3s+"\n")
- addDumpTest(pm3, "(*"+m3t+")("+m3Addr+")("+m3s+")\n")
- addDumpTest(&pm3, "(**"+m3t+")("+pm3Addr+"->"+m3Addr+")("+m3s+")\n")
- addDumpTest(nm3, "(*"+m3t+")()\n")
- addDumpTest(nilMap3, "("+m3t+") \n")
-
- // Map with nil interface value.
- k4 := "nil"
- k4Len := fmt.Sprintf("%d", len(k4))
- m4 := map[string]interface{}{k4: nil}
- m4Len := fmt.Sprintf("%d", len(m4))
- nilMap4 := map[string]interface{}(nil)
- nm4 := (*map[string]interface{})(nil)
- pm4 := &m4
- m4Addr := fmt.Sprintf("%p", pm4)
- pm4Addr := fmt.Sprintf("%p", &pm4)
- m4t := "map[string]interface {}"
- m4t1 := "string"
- m4t2 := "interface {}"
- m4s := "(len=" + m4Len + ") {\n (" + m4t1 + ") (len=" + k4Len + ")" +
- " \"nil\": (" + m4t2 + ") \n}"
- addDumpTest(m4, "("+m4t+") "+m4s+"\n")
- addDumpTest(pm4, "(*"+m4t+")("+m4Addr+")("+m4s+")\n")
- addDumpTest(&pm4, "(**"+m4t+")("+pm4Addr+"->"+m4Addr+")("+m4s+")\n")
- addDumpTest(nm4, "(*"+m4t+")()\n")
- addDumpTest(nilMap4, "("+m4t+") \n")
-}
-
-func addStructDumpTests() {
- // Struct with primitives.
- type s1 struct {
- a int8
- b uint8
- }
- v := s1{127, 255}
- nv := (*s1)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "spew_test.s1"
- vt2 := "int8"
- vt3 := "uint8"
- vs := "{\n a: (" + vt2 + ") 127,\n b: (" + vt3 + ") 255\n}"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Struct that contains another struct.
- type s2 struct {
- s1 s1
- b bool
- }
- v2 := s2{s1{127, 255}, true}
- nv2 := (*s2)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "spew_test.s2"
- v2t2 := "spew_test.s1"
- v2t3 := "int8"
- v2t4 := "uint8"
- v2t5 := "bool"
- v2s := "{\n s1: (" + v2t2 + ") {\n a: (" + v2t3 + ") 127,\n b: (" +
- v2t4 + ") 255\n },\n b: (" + v2t5 + ") true\n}"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv2, "(*"+v2t+")()\n")
-
- // Struct that contains custom type with Stringer pointer interface via both
- // exported and unexported fields.
- type s3 struct {
- s pstringer
- S pstringer
- }
- v3 := s3{"test", "test2"}
- nv3 := (*s3)(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "spew_test.s3"
- v3t2 := "spew_test.pstringer"
- v3s := "{\n s: (" + v3t2 + ") (len=4) stringer test,\n S: (" + v3t2 +
- ") (len=5) stringer test2\n}"
- v3sp := v3s
- if spew.UnsafeDisabled {
- v3s = "{\n s: (" + v3t2 + ") (len=4) \"test\",\n S: (" +
- v3t2 + ") (len=5) \"test2\"\n}"
- v3sp = "{\n s: (" + v3t2 + ") (len=4) \"test\",\n S: (" +
- v3t2 + ") (len=5) stringer test2\n}"
- }
- addDumpTest(v3, "("+v3t+") "+v3s+"\n")
- addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3sp+")\n")
- addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3sp+")\n")
- addDumpTest(nv3, "(*"+v3t+")()\n")
-
- // Struct that contains embedded struct and field to same struct.
- e := embed{"embedstr"}
- eLen := fmt.Sprintf("%d", len("embedstr"))
- v4 := embedwrap{embed: &e, e: &e}
- nv4 := (*embedwrap)(nil)
- pv4 := &v4
- eAddr := fmt.Sprintf("%p", &e)
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "spew_test.embedwrap"
- v4t2 := "spew_test.embed"
- v4t3 := "string"
- v4s := "{\n embed: (*" + v4t2 + ")(" + eAddr + ")({\n a: (" + v4t3 +
- ") (len=" + eLen + ") \"embedstr\"\n }),\n e: (*" + v4t2 +
- ")(" + eAddr + ")({\n a: (" + v4t3 + ") (len=" + eLen + ")" +
- " \"embedstr\"\n })\n}"
- addDumpTest(v4, "("+v4t+") "+v4s+"\n")
- addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n")
- addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n")
- addDumpTest(nv4, "(*"+v4t+")()\n")
-}
-
-func addUintptrDumpTests() {
- // Null pointer.
- v := uintptr(0)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "uintptr"
- vs := ""
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
-
- // Address of real variable.
- i := 1
- v2 := uintptr(unsafe.Pointer(&i))
- nv2 := (*uintptr)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "uintptr"
- v2s := fmt.Sprintf("%p", &i)
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv2, "(*"+v2t+")()\n")
-}
-
-func addUnsafePointerDumpTests() {
- // Null pointer.
- v := unsafe.Pointer(uintptr(0))
- nv := (*unsafe.Pointer)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "unsafe.Pointer"
- vs := ""
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Address of real variable.
- i := 1
- v2 := unsafe.Pointer(&i)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "unsafe.Pointer"
- v2s := fmt.Sprintf("%p", &i)
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-}
-
-func addChanDumpTests() {
- // Nil channel.
- var v chan int
- pv := &v
- nv := (*chan int)(nil)
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "chan int"
- vs := ""
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Real channel.
- v2 := make(chan int)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "chan int"
- v2s := fmt.Sprintf("%p", v2)
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
-}
-
-func addFuncDumpTests() {
- // Function with no params and no returns.
- v := addIntDumpTests
- nv := (*func())(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "func()"
- vs := fmt.Sprintf("%p", v)
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Function with param and no returns.
- v2 := TestDump
- nv2 := (*func(*testing.T))(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "func(*testing.T)"
- v2s := fmt.Sprintf("%p", v2)
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv2, "(*"+v2t+")()\n")
-
- // Function with multiple params and multiple returns.
- var v3 = func(i int, s string) (b bool, err error) {
- return true, nil
- }
- nv3 := (*func(int, string) (bool, error))(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "func(int, string) (bool, error)"
- v3s := fmt.Sprintf("%p", v3)
- addDumpTest(v3, "("+v3t+") "+v3s+"\n")
- addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n")
- addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n")
- addDumpTest(nv3, "(*"+v3t+")()\n")
-}
-
-func addCircularDumpTests() {
- // Struct that is circular through self referencing.
- type circular struct {
- c *circular
- }
- v := circular{nil}
- v.c = &v
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "spew_test.circular"
- vs := "{\n c: (*" + vt + ")(" + vAddr + ")({\n c: (*" + vt + ")(" +
- vAddr + ")()\n })\n}"
- vs2 := "{\n c: (*" + vt + ")(" + vAddr + ")()\n}"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs2+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs2+")\n")
-
- // Structs that are circular through cross referencing.
- v2 := xref1{nil}
- ts2 := xref2{&v2}
- v2.ps2 = &ts2
- pv2 := &v2
- ts2Addr := fmt.Sprintf("%p", &ts2)
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "spew_test.xref1"
- v2t2 := "spew_test.xref2"
- v2s := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t +
- ")(" + v2Addr + ")({\n ps2: (*" + v2t2 + ")(" + ts2Addr +
- ")()\n })\n })\n}"
- v2s2 := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t +
- ")(" + v2Addr + ")()\n })\n}"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s2+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s2+")\n")
-
- // Structs that are indirectly circular.
- v3 := indirCir1{nil}
- tic2 := indirCir2{nil}
- tic3 := indirCir3{&v3}
- tic2.ps3 = &tic3
- v3.ps2 = &tic2
- pv3 := &v3
- tic2Addr := fmt.Sprintf("%p", &tic2)
- tic3Addr := fmt.Sprintf("%p", &tic3)
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "spew_test.indirCir1"
- v3t2 := "spew_test.indirCir2"
- v3t3 := "spew_test.indirCir3"
- v3s := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 +
- ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr +
- ")({\n ps2: (*" + v3t2 + ")(" + tic2Addr +
- ")()\n })\n })\n })\n}"
- v3s2 := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 +
- ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr +
- ")()\n })\n })\n}"
- addDumpTest(v3, "("+v3t+") "+v3s+"\n")
- addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s2+")\n")
- addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s2+")\n")
-}
-
-func addPanicDumpTests() {
- // Type that panics in its Stringer interface.
- v := panicer(127)
- nv := (*panicer)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "spew_test.panicer"
- vs := "(PANIC=test panic)127"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-}
-
-func addErrorDumpTests() {
- // Type that has a custom Error interface.
- v := customError(127)
- nv := (*customError)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "spew_test.customError"
- vs := "error: 127"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-}
-
-// TestDump executes all of the tests described by dumpTests.
-func TestDump(t *testing.T) {
- // Setup tests.
- addIntDumpTests()
- addUintDumpTests()
- addBoolDumpTests()
- addFloatDumpTests()
- addComplexDumpTests()
- addArrayDumpTests()
- addSliceDumpTests()
- addStringDumpTests()
- addInterfaceDumpTests()
- addMapDumpTests()
- addStructDumpTests()
- addUintptrDumpTests()
- addUnsafePointerDumpTests()
- addChanDumpTests()
- addFuncDumpTests()
- addCircularDumpTests()
- addPanicDumpTests()
- addErrorDumpTests()
- addCgoDumpTests()
-
- t.Logf("Running %d tests", len(dumpTests))
- for i, test := range dumpTests {
- buf := new(bytes.Buffer)
- spew.Fdump(buf, test.in)
- s := buf.String()
- if testFailed(s, test.wants) {
- t.Errorf("Dump #%d\n got: %s %s", i, s, stringizeWants(test.wants))
- continue
- }
- }
-}
-
-func TestDumpSortedKeys(t *testing.T) {
- cfg := spew.ConfigState{SortKeys: true}
- s := cfg.Sdump(map[int]string{1: "1", 3: "3", 2: "2"})
- expected := "(map[int]string) (len=3) {\n(int) 1: (string) (len=1) " +
- "\"1\",\n(int) 2: (string) (len=1) \"2\",\n(int) 3: (string) " +
- "(len=1) \"3\"\n" +
- "}\n"
- if s != expected {
- t.Errorf("Sorted keys mismatch:\n %v %v", s, expected)
- }
-
- s = cfg.Sdump(map[stringer]int{"1": 1, "3": 3, "2": 2})
- expected = "(map[spew_test.stringer]int) (len=3) {\n" +
- "(spew_test.stringer) (len=1) stringer 1: (int) 1,\n" +
- "(spew_test.stringer) (len=1) stringer 2: (int) 2,\n" +
- "(spew_test.stringer) (len=1) stringer 3: (int) 3\n" +
- "}\n"
- if s != expected {
- t.Errorf("Sorted keys mismatch:\n %v %v", s, expected)
- }
-
- s = cfg.Sdump(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2})
- expected = "(map[spew_test.pstringer]int) (len=3) {\n" +
- "(spew_test.pstringer) (len=1) stringer 1: (int) 1,\n" +
- "(spew_test.pstringer) (len=1) stringer 2: (int) 2,\n" +
- "(spew_test.pstringer) (len=1) stringer 3: (int) 3\n" +
- "}\n"
- if spew.UnsafeDisabled {
- expected = "(map[spew_test.pstringer]int) (len=3) {\n" +
- "(spew_test.pstringer) (len=1) \"1\": (int) 1,\n" +
- "(spew_test.pstringer) (len=1) \"2\": (int) 2,\n" +
- "(spew_test.pstringer) (len=1) \"3\": (int) 3\n" +
- "}\n"
- }
- if s != expected {
- t.Errorf("Sorted keys mismatch:\n %v %v", s, expected)
- }
-
- s = cfg.Sdump(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2})
- expected = "(map[spew_test.customError]int) (len=3) {\n" +
- "(spew_test.customError) error: 1: (int) 1,\n" +
- "(spew_test.customError) error: 2: (int) 2,\n" +
- "(spew_test.customError) error: 3: (int) 3\n" +
- "}\n"
- if s != expected {
- t.Errorf("Sorted keys mismatch:\n %v %v", s, expected)
- }
-
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go b/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go
deleted file mode 100644
index 6ab1808..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go
+++ /dev/null
@@ -1,99 +0,0 @@
-// Copyright (c) 2013-2016 Dave Collins
-//
-// Permission to use, copy, modify, and distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-// NOTE: Due to the following build constraints, this file will only be compiled
-// when both cgo is supported and "-tags testcgo" is added to the go test
-// command line. This means the cgo tests are only added (and hence run) when
-// specifially requested. This configuration is used because spew itself
-// does not require cgo to run even though it does handle certain cgo types
-// specially. Rather than forcing all clients to require cgo and an external
-// C compiler just to run the tests, this scheme makes them optional.
-// +build cgo,testcgo
-
-package spew_test
-
-import (
- "fmt"
-
- "github.com/davecgh/go-spew/spew/testdata"
-)
-
-func addCgoDumpTests() {
- // C char pointer.
- v := testdata.GetCgoCharPointer()
- nv := testdata.GetCgoNullCharPointer()
- pv := &v
- vcAddr := fmt.Sprintf("%p", v)
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "*testdata._Ctype_char"
- vs := "116"
- addDumpTest(v, "("+vt+")("+vcAddr+")("+vs+")\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+"->"+vcAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+"->"+vcAddr+")("+vs+")\n")
- addDumpTest(nv, "("+vt+")()\n")
-
- // C char array.
- v2, v2l, v2c := testdata.GetCgoCharArray()
- v2Len := fmt.Sprintf("%d", v2l)
- v2Cap := fmt.Sprintf("%d", v2c)
- v2t := "[6]testdata._Ctype_char"
- v2s := "(len=" + v2Len + " cap=" + v2Cap + ") " +
- "{\n 00000000 74 65 73 74 32 00 " +
- " |test2.|\n}"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
-
- // C unsigned char array.
- v3, v3l, v3c := testdata.GetCgoUnsignedCharArray()
- v3Len := fmt.Sprintf("%d", v3l)
- v3Cap := fmt.Sprintf("%d", v3c)
- v3t := "[6]testdata._Ctype_unsignedchar"
- v3t2 := "[6]testdata._Ctype_uchar"
- v3s := "(len=" + v3Len + " cap=" + v3Cap + ") " +
- "{\n 00000000 74 65 73 74 33 00 " +
- " |test3.|\n}"
- addDumpTest(v3, "("+v3t+") "+v3s+"\n", "("+v3t2+") "+v3s+"\n")
-
- // C signed char array.
- v4, v4l, v4c := testdata.GetCgoSignedCharArray()
- v4Len := fmt.Sprintf("%d", v4l)
- v4Cap := fmt.Sprintf("%d", v4c)
- v4t := "[6]testdata._Ctype_schar"
- v4t2 := "testdata._Ctype_schar"
- v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " +
- "{\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 101,\n (" + v4t2 +
- ") 115,\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 52,\n (" + v4t2 +
- ") 0\n}"
- addDumpTest(v4, "("+v4t+") "+v4s+"\n")
-
- // C uint8_t array.
- v5, v5l, v5c := testdata.GetCgoUint8tArray()
- v5Len := fmt.Sprintf("%d", v5l)
- v5Cap := fmt.Sprintf("%d", v5c)
- v5t := "[6]testdata._Ctype_uint8_t"
- v5s := "(len=" + v5Len + " cap=" + v5Cap + ") " +
- "{\n 00000000 74 65 73 74 35 00 " +
- " |test5.|\n}"
- addDumpTest(v5, "("+v5t+") "+v5s+"\n")
-
- // C typedefed unsigned char array.
- v6, v6l, v6c := testdata.GetCgoTypdefedUnsignedCharArray()
- v6Len := fmt.Sprintf("%d", v6l)
- v6Cap := fmt.Sprintf("%d", v6c)
- v6t := "[6]testdata._Ctype_custom_uchar_t"
- v6s := "(len=" + v6Len + " cap=" + v6Cap + ") " +
- "{\n 00000000 74 65 73 74 36 00 " +
- " |test6.|\n}"
- addDumpTest(v6, "("+v6t+") "+v6s+"\n")
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go b/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go
deleted file mode 100644
index 52a0971..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) 2013 Dave Collins
-//
-// Permission to use, copy, modify, and distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-// NOTE: Due to the following build constraints, this file will only be compiled
-// when either cgo is not supported or "-tags testcgo" is not added to the go
-// test command line. This file intentionally does not setup any cgo tests in
-// this scenario.
-// +build !cgo !testcgo
-
-package spew_test
-
-func addCgoDumpTests() {
- // Don't add any tests for cgo since this file is only compiled when
- // there should not be any cgo tests.
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/example_test.go b/vendor/github.com/davecgh/go-spew/spew/example_test.go
deleted file mode 100644
index c6ec8c6..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/example_test.go
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Copyright (c) 2013-2016 Dave Collins
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-package spew_test
-
-import (
- "fmt"
-
- "github.com/davecgh/go-spew/spew"
-)
-
-type Flag int
-
-const (
- flagOne Flag = iota
- flagTwo
-)
-
-var flagStrings = map[Flag]string{
- flagOne: "flagOne",
- flagTwo: "flagTwo",
-}
-
-func (f Flag) String() string {
- if s, ok := flagStrings[f]; ok {
- return s
- }
- return fmt.Sprintf("Unknown flag (%d)", int(f))
-}
-
-type Bar struct {
- data uintptr
-}
-
-type Foo struct {
- unexportedField Bar
- ExportedField map[interface{}]interface{}
-}
-
-// This example demonstrates how to use Dump to dump variables to stdout.
-func ExampleDump() {
- // The following package level declarations are assumed for this example:
- /*
- type Flag int
-
- const (
- flagOne Flag = iota
- flagTwo
- )
-
- var flagStrings = map[Flag]string{
- flagOne: "flagOne",
- flagTwo: "flagTwo",
- }
-
- func (f Flag) String() string {
- if s, ok := flagStrings[f]; ok {
- return s
- }
- return fmt.Sprintf("Unknown flag (%d)", int(f))
- }
-
- type Bar struct {
- data uintptr
- }
-
- type Foo struct {
- unexportedField Bar
- ExportedField map[interface{}]interface{}
- }
- */
-
- // Setup some sample data structures for the example.
- bar := Bar{uintptr(0)}
- s1 := Foo{bar, map[interface{}]interface{}{"one": true}}
- f := Flag(5)
- b := []byte{
- 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
- 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
- 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
- 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
- 0x31, 0x32,
- }
-
- // Dump!
- spew.Dump(s1, f, b)
-
- // Output:
- // (spew_test.Foo) {
- // unexportedField: (spew_test.Bar) {
- // data: (uintptr)
- // },
- // ExportedField: (map[interface {}]interface {}) (len=1) {
- // (string) (len=3) "one": (bool) true
- // }
- // }
- // (spew_test.Flag) Unknown flag (5)
- // ([]uint8) (len=34 cap=34) {
- // 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... |
- // 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0|
- // 00000020 31 32 |12|
- // }
- //
-}
-
-// This example demonstrates how to use Printf to display a variable with a
-// format string and inline formatting.
-func ExamplePrintf() {
- // Create a double pointer to a uint 8.
- ui8 := uint8(5)
- pui8 := &ui8
- ppui8 := &pui8
-
- // Create a circular data type.
- type circular struct {
- ui8 uint8
- c *circular
- }
- c := circular{ui8: 1}
- c.c = &c
-
- // Print!
- spew.Printf("ppui8: %v\n", ppui8)
- spew.Printf("circular: %v\n", c)
-
- // Output:
- // ppui8: <**>5
- // circular: {1 <*>{1 <*>}}
-}
-
-// This example demonstrates how to use a ConfigState.
-func ExampleConfigState() {
- // Modify the indent level of the ConfigState only. The global
- // configuration is not modified.
- scs := spew.ConfigState{Indent: "\t"}
-
- // Output using the ConfigState instance.
- v := map[string]int{"one": 1}
- scs.Printf("v: %v\n", v)
- scs.Dump(v)
-
- // Output:
- // v: map[one:1]
- // (map[string]int) (len=1) {
- // (string) (len=3) "one": (int) 1
- // }
-}
-
-// This example demonstrates how to use ConfigState.Dump to dump variables to
-// stdout
-func ExampleConfigState_Dump() {
- // See the top-level Dump example for details on the types used in this
- // example.
-
- // Create two ConfigState instances with different indentation.
- scs := spew.ConfigState{Indent: "\t"}
- scs2 := spew.ConfigState{Indent: " "}
-
- // Setup some sample data structures for the example.
- bar := Bar{uintptr(0)}
- s1 := Foo{bar, map[interface{}]interface{}{"one": true}}
-
- // Dump using the ConfigState instances.
- scs.Dump(s1)
- scs2.Dump(s1)
-
- // Output:
- // (spew_test.Foo) {
- // unexportedField: (spew_test.Bar) {
- // data: (uintptr)
- // },
- // ExportedField: (map[interface {}]interface {}) (len=1) {
- // (string) (len=3) "one": (bool) true
- // }
- // }
- // (spew_test.Foo) {
- // unexportedField: (spew_test.Bar) {
- // data: (uintptr)
- // },
- // ExportedField: (map[interface {}]interface {}) (len=1) {
- // (string) (len=3) "one": (bool) true
- // }
- // }
- //
-}
-
-// This example demonstrates how to use ConfigState.Printf to display a variable
-// with a format string and inline formatting.
-func ExampleConfigState_Printf() {
- // See the top-level Dump example for details on the types used in this
- // example.
-
- // Create two ConfigState instances and modify the method handling of the
- // first ConfigState only.
- scs := spew.NewDefaultConfig()
- scs2 := spew.NewDefaultConfig()
- scs.DisableMethods = true
-
- // Alternatively
- // scs := spew.ConfigState{Indent: " ", DisableMethods: true}
- // scs2 := spew.ConfigState{Indent: " "}
-
- // This is of type Flag which implements a Stringer and has raw value 1.
- f := flagTwo
-
- // Dump using the ConfigState instances.
- scs.Printf("f: %v\n", f)
- scs2.Printf("f: %v\n", f)
-
- // Output:
- // f: 1
- // f: flagTwo
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/format.go b/vendor/github.com/davecgh/go-spew/spew/format.go
deleted file mode 100644
index c49875b..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/format.go
+++ /dev/null
@@ -1,419 +0,0 @@
-/*
- * Copyright (c) 2013-2016 Dave Collins
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-package spew
-
-import (
- "bytes"
- "fmt"
- "reflect"
- "strconv"
- "strings"
-)
-
-// supportedFlags is a list of all the character flags supported by fmt package.
-const supportedFlags = "0-+# "
-
-// formatState implements the fmt.Formatter interface and contains information
-// about the state of a formatting operation. The NewFormatter function can
-// be used to get a new Formatter which can be used directly as arguments
-// in standard fmt package printing calls.
-type formatState struct {
- value interface{}
- fs fmt.State
- depth int
- pointers map[uintptr]int
- ignoreNextType bool
- cs *ConfigState
-}
-
-// buildDefaultFormat recreates the original format string without precision
-// and width information to pass in to fmt.Sprintf in the case of an
-// unrecognized type. Unless new types are added to the language, this
-// function won't ever be called.
-func (f *formatState) buildDefaultFormat() (format string) {
- buf := bytes.NewBuffer(percentBytes)
-
- for _, flag := range supportedFlags {
- if f.fs.Flag(int(flag)) {
- buf.WriteRune(flag)
- }
- }
-
- buf.WriteRune('v')
-
- format = buf.String()
- return format
-}
-
-// constructOrigFormat recreates the original format string including precision
-// and width information to pass along to the standard fmt package. This allows
-// automatic deferral of all format strings this package doesn't support.
-func (f *formatState) constructOrigFormat(verb rune) (format string) {
- buf := bytes.NewBuffer(percentBytes)
-
- for _, flag := range supportedFlags {
- if f.fs.Flag(int(flag)) {
- buf.WriteRune(flag)
- }
- }
-
- if width, ok := f.fs.Width(); ok {
- buf.WriteString(strconv.Itoa(width))
- }
-
- if precision, ok := f.fs.Precision(); ok {
- buf.Write(precisionBytes)
- buf.WriteString(strconv.Itoa(precision))
- }
-
- buf.WriteRune(verb)
-
- format = buf.String()
- return format
-}
-
-// unpackValue returns values inside of non-nil interfaces when possible and
-// ensures that types for values which have been unpacked from an interface
-// are displayed when the show types flag is also set.
-// This is useful for data types like structs, arrays, slices, and maps which
-// can contain varying types packed inside an interface.
-func (f *formatState) unpackValue(v reflect.Value) reflect.Value {
- if v.Kind() == reflect.Interface {
- f.ignoreNextType = false
- if !v.IsNil() {
- v = v.Elem()
- }
- }
- return v
-}
-
-// formatPtr handles formatting of pointers by indirecting them as necessary.
-func (f *formatState) formatPtr(v reflect.Value) {
- // Display nil if top level pointer is nil.
- showTypes := f.fs.Flag('#')
- if v.IsNil() && (!showTypes || f.ignoreNextType) {
- f.fs.Write(nilAngleBytes)
- return
- }
-
- // Remove pointers at or below the current depth from map used to detect
- // circular refs.
- for k, depth := range f.pointers {
- if depth >= f.depth {
- delete(f.pointers, k)
- }
- }
-
- // Keep list of all dereferenced pointers to possibly show later.
- pointerChain := make([]uintptr, 0)
-
- // Figure out how many levels of indirection there are by derferencing
- // pointers and unpacking interfaces down the chain while detecting circular
- // references.
- nilFound := false
- cycleFound := false
- indirects := 0
- ve := v
- for ve.Kind() == reflect.Ptr {
- if ve.IsNil() {
- nilFound = true
- break
- }
- indirects++
- addr := ve.Pointer()
- pointerChain = append(pointerChain, addr)
- if pd, ok := f.pointers[addr]; ok && pd < f.depth {
- cycleFound = true
- indirects--
- break
- }
- f.pointers[addr] = f.depth
-
- ve = ve.Elem()
- if ve.Kind() == reflect.Interface {
- if ve.IsNil() {
- nilFound = true
- break
- }
- ve = ve.Elem()
- }
- }
-
- // Display type or indirection level depending on flags.
- if showTypes && !f.ignoreNextType {
- f.fs.Write(openParenBytes)
- f.fs.Write(bytes.Repeat(asteriskBytes, indirects))
- f.fs.Write([]byte(ve.Type().String()))
- f.fs.Write(closeParenBytes)
- } else {
- if nilFound || cycleFound {
- indirects += strings.Count(ve.Type().String(), "*")
- }
- f.fs.Write(openAngleBytes)
- f.fs.Write([]byte(strings.Repeat("*", indirects)))
- f.fs.Write(closeAngleBytes)
- }
-
- // Display pointer information depending on flags.
- if f.fs.Flag('+') && (len(pointerChain) > 0) {
- f.fs.Write(openParenBytes)
- for i, addr := range pointerChain {
- if i > 0 {
- f.fs.Write(pointerChainBytes)
- }
- printHexPtr(f.fs, addr)
- }
- f.fs.Write(closeParenBytes)
- }
-
- // Display dereferenced value.
- switch {
- case nilFound == true:
- f.fs.Write(nilAngleBytes)
-
- case cycleFound == true:
- f.fs.Write(circularShortBytes)
-
- default:
- f.ignoreNextType = true
- f.format(ve)
- }
-}
-
-// format is the main workhorse for providing the Formatter interface. It
-// uses the passed reflect value to figure out what kind of object we are
-// dealing with and formats it appropriately. It is a recursive function,
-// however circular data structures are detected and handled properly.
-func (f *formatState) format(v reflect.Value) {
- // Handle invalid reflect values immediately.
- kind := v.Kind()
- if kind == reflect.Invalid {
- f.fs.Write(invalidAngleBytes)
- return
- }
-
- // Handle pointers specially.
- if kind == reflect.Ptr {
- f.formatPtr(v)
- return
- }
-
- // Print type information unless already handled elsewhere.
- if !f.ignoreNextType && f.fs.Flag('#') {
- f.fs.Write(openParenBytes)
- f.fs.Write([]byte(v.Type().String()))
- f.fs.Write(closeParenBytes)
- }
- f.ignoreNextType = false
-
- // Call Stringer/error interfaces if they exist and the handle methods
- // flag is enabled.
- if !f.cs.DisableMethods {
- if (kind != reflect.Invalid) && (kind != reflect.Interface) {
- if handled := handleMethods(f.cs, f.fs, v); handled {
- return
- }
- }
- }
-
- switch kind {
- case reflect.Invalid:
- // Do nothing. We should never get here since invalid has already
- // been handled above.
-
- case reflect.Bool:
- printBool(f.fs, v.Bool())
-
- case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
- printInt(f.fs, v.Int(), 10)
-
- case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint:
- printUint(f.fs, v.Uint(), 10)
-
- case reflect.Float32:
- printFloat(f.fs, v.Float(), 32)
-
- case reflect.Float64:
- printFloat(f.fs, v.Float(), 64)
-
- case reflect.Complex64:
- printComplex(f.fs, v.Complex(), 32)
-
- case reflect.Complex128:
- printComplex(f.fs, v.Complex(), 64)
-
- case reflect.Slice:
- if v.IsNil() {
- f.fs.Write(nilAngleBytes)
- break
- }
- fallthrough
-
- case reflect.Array:
- f.fs.Write(openBracketBytes)
- f.depth++
- if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) {
- f.fs.Write(maxShortBytes)
- } else {
- numEntries := v.Len()
- for i := 0; i < numEntries; i++ {
- if i > 0 {
- f.fs.Write(spaceBytes)
- }
- f.ignoreNextType = true
- f.format(f.unpackValue(v.Index(i)))
- }
- }
- f.depth--
- f.fs.Write(closeBracketBytes)
-
- case reflect.String:
- f.fs.Write([]byte(v.String()))
-
- case reflect.Interface:
- // The only time we should get here is for nil interfaces due to
- // unpackValue calls.
- if v.IsNil() {
- f.fs.Write(nilAngleBytes)
- }
-
- case reflect.Ptr:
- // Do nothing. We should never get here since pointers have already
- // been handled above.
-
- case reflect.Map:
- // nil maps should be indicated as different than empty maps
- if v.IsNil() {
- f.fs.Write(nilAngleBytes)
- break
- }
-
- f.fs.Write(openMapBytes)
- f.depth++
- if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) {
- f.fs.Write(maxShortBytes)
- } else {
- keys := v.MapKeys()
- if f.cs.SortKeys {
- sortValues(keys, f.cs)
- }
- for i, key := range keys {
- if i > 0 {
- f.fs.Write(spaceBytes)
- }
- f.ignoreNextType = true
- f.format(f.unpackValue(key))
- f.fs.Write(colonBytes)
- f.ignoreNextType = true
- f.format(f.unpackValue(v.MapIndex(key)))
- }
- }
- f.depth--
- f.fs.Write(closeMapBytes)
-
- case reflect.Struct:
- numFields := v.NumField()
- f.fs.Write(openBraceBytes)
- f.depth++
- if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) {
- f.fs.Write(maxShortBytes)
- } else {
- vt := v.Type()
- for i := 0; i < numFields; i++ {
- if i > 0 {
- f.fs.Write(spaceBytes)
- }
- vtf := vt.Field(i)
- if f.fs.Flag('+') || f.fs.Flag('#') {
- f.fs.Write([]byte(vtf.Name))
- f.fs.Write(colonBytes)
- }
- f.format(f.unpackValue(v.Field(i)))
- }
- }
- f.depth--
- f.fs.Write(closeBraceBytes)
-
- case reflect.Uintptr:
- printHexPtr(f.fs, uintptr(v.Uint()))
-
- case reflect.UnsafePointer, reflect.Chan, reflect.Func:
- printHexPtr(f.fs, v.Pointer())
-
- // There were not any other types at the time this code was written, but
- // fall back to letting the default fmt package handle it if any get added.
- default:
- format := f.buildDefaultFormat()
- if v.CanInterface() {
- fmt.Fprintf(f.fs, format, v.Interface())
- } else {
- fmt.Fprintf(f.fs, format, v.String())
- }
- }
-}
-
-// Format satisfies the fmt.Formatter interface. See NewFormatter for usage
-// details.
-func (f *formatState) Format(fs fmt.State, verb rune) {
- f.fs = fs
-
- // Use standard formatting for verbs that are not v.
- if verb != 'v' {
- format := f.constructOrigFormat(verb)
- fmt.Fprintf(fs, format, f.value)
- return
- }
-
- if f.value == nil {
- if fs.Flag('#') {
- fs.Write(interfaceBytes)
- }
- fs.Write(nilAngleBytes)
- return
- }
-
- f.format(reflect.ValueOf(f.value))
-}
-
-// newFormatter is a helper function to consolidate the logic from the various
-// public methods which take varying config states.
-func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter {
- fs := &formatState{value: v, cs: cs}
- fs.pointers = make(map[uintptr]int)
- return fs
-}
-
-/*
-NewFormatter returns a custom formatter that satisfies the fmt.Formatter
-interface. As a result, it integrates cleanly with standard fmt package
-printing functions. The formatter is useful for inline printing of smaller data
-types similar to the standard %v format specifier.
-
-The custom formatter only responds to the %v (most compact), %+v (adds pointer
-addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb
-combinations. Any other verbs such as %x and %q will be sent to the the
-standard fmt package for formatting. In addition, the custom formatter ignores
-the width and precision arguments (however they will still work on the format
-specifiers not handled by the custom formatter).
-
-Typically this function shouldn't be called directly. It is much easier to make
-use of the custom formatter by calling one of the convenience functions such as
-Printf, Println, or Fprintf.
-*/
-func NewFormatter(v interface{}) fmt.Formatter {
- return newFormatter(&Config, v)
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/format_test.go b/vendor/github.com/davecgh/go-spew/spew/format_test.go
deleted file mode 100644
index f9b93ab..0000000
--- a/vendor/github.com/davecgh/go-spew/spew/format_test.go
+++ /dev/null
@@ -1,1558 +0,0 @@
-/*
- * Copyright (c) 2013-2016 Dave Collins
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-/*
-Test Summary:
-NOTE: For each test, a nil pointer, a single pointer and double pointer to the
-base test element are also tested to ensure proper indirection across all types.
-
-- Max int8, int16, int32, int64, int
-- Max uint8, uint16, uint32, uint64, uint
-- Boolean true and false
-- Standard complex64 and complex128
-- Array containing standard ints
-- Array containing type with custom formatter on pointer receiver only
-- Array containing interfaces
-- Slice containing standard float32 values
-- Slice containing type with custom formatter on pointer receiver only
-- Slice containing interfaces
-- Nil slice
-- Standard string
-- Nil interface
-- Sub-interface
-- Map with string keys and int vals
-- Map with custom formatter type on pointer receiver only keys and vals
-- Map with interface keys and values
-- Map with nil interface value
-- Struct with primitives
-- Struct that contains another struct
-- Struct that contains custom type with Stringer pointer interface via both
- exported and unexported fields
-- Struct that contains embedded struct and field to same struct
-- Uintptr to 0 (null pointer)
-- Uintptr address of real variable
-- Unsafe.Pointer to 0 (null pointer)
-- Unsafe.Pointer to address of real variable
-- Nil channel
-- Standard int channel
-- Function with no params and no returns
-- Function with param and no returns
-- Function with multiple params and multiple returns
-- Struct that is circular through self referencing
-- Structs that are circular through cross referencing
-- Structs that are indirectly circular
-- Type that panics in its Stringer interface
-- Type that has a custom Error interface
-- %x passthrough with uint
-- %#x passthrough with uint
-- %f passthrough with precision
-- %f passthrough with width and precision
-- %d passthrough with width
-- %q passthrough with string
-*/
-
-package spew_test
-
-import (
- "bytes"
- "fmt"
- "testing"
- "unsafe"
-
- "github.com/davecgh/go-spew/spew"
-)
-
-// formatterTest is used to describe a test to be performed against NewFormatter.
-type formatterTest struct {
- format string
- in interface{}
- wants []string
-}
-
-// formatterTests houses all of the tests to be performed against NewFormatter.
-var formatterTests = make([]formatterTest, 0)
-
-// addFormatterTest is a helper method to append the passed input and desired
-// result to formatterTests.
-func addFormatterTest(format string, in interface{}, wants ...string) {
- test := formatterTest{format, in, wants}
- formatterTests = append(formatterTests, test)
-}
-
-func addIntFormatterTests() {
- // Max int8.
- v := int8(127)
- nv := (*int8)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "int8"
- vs := "127"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Max int16.
- v2 := int16(32767)
- nv2 := (*int16)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "int16"
- v2s := "32767"
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%v", nv2, "")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"")
-
- // Max int32.
- v3 := int32(2147483647)
- nv3 := (*int32)(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "int32"
- v3s := "2147483647"
- addFormatterTest("%v", v3, v3s)
- addFormatterTest("%v", pv3, "<*>"+v3s)
- addFormatterTest("%v", &pv3, "<**>"+v3s)
- addFormatterTest("%v", nv3, "")
- addFormatterTest("%+v", v3, v3s)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"")
-
- // Max int64.
- v4 := int64(9223372036854775807)
- nv4 := (*int64)(nil)
- pv4 := &v4
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "int64"
- v4s := "9223372036854775807"
- addFormatterTest("%v", v4, v4s)
- addFormatterTest("%v", pv4, "<*>"+v4s)
- addFormatterTest("%v", &pv4, "<**>"+v4s)
- addFormatterTest("%v", nv4, "")
- addFormatterTest("%+v", v4, v4s)
- addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s)
- addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%+v", nv4, "")
- addFormatterTest("%#v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s)
- addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s)
- addFormatterTest("%#v", nv4, "(*"+v4t+")"+"")
- addFormatterTest("%#+v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s)
- addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"")
-
- // Max int.
- v5 := int(2147483647)
- nv5 := (*int)(nil)
- pv5 := &v5
- v5Addr := fmt.Sprintf("%p", pv5)
- pv5Addr := fmt.Sprintf("%p", &pv5)
- v5t := "int"
- v5s := "2147483647"
- addFormatterTest("%v", v5, v5s)
- addFormatterTest("%v", pv5, "<*>"+v5s)
- addFormatterTest("%v", &pv5, "<**>"+v5s)
- addFormatterTest("%v", nv5, "")
- addFormatterTest("%+v", v5, v5s)
- addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s)
- addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s)
- addFormatterTest("%+v", nv5, "")
- addFormatterTest("%#v", v5, "("+v5t+")"+v5s)
- addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s)
- addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s)
- addFormatterTest("%#v", nv5, "(*"+v5t+")"+"")
- addFormatterTest("%#+v", v5, "("+v5t+")"+v5s)
- addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s)
- addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s)
- addFormatterTest("%#+v", nv5, "(*"+v5t+")"+"")
-}
-
-func addUintFormatterTests() {
- // Max uint8.
- v := uint8(255)
- nv := (*uint8)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "uint8"
- vs := "255"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Max uint16.
- v2 := uint16(65535)
- nv2 := (*uint16)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "uint16"
- v2s := "65535"
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%v", nv2, "")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"")
-
- // Max uint32.
- v3 := uint32(4294967295)
- nv3 := (*uint32)(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "uint32"
- v3s := "4294967295"
- addFormatterTest("%v", v3, v3s)
- addFormatterTest("%v", pv3, "<*>"+v3s)
- addFormatterTest("%v", &pv3, "<**>"+v3s)
- addFormatterTest("%v", nv3, "")
- addFormatterTest("%+v", v3, v3s)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"")
-
- // Max uint64.
- v4 := uint64(18446744073709551615)
- nv4 := (*uint64)(nil)
- pv4 := &v4
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "uint64"
- v4s := "18446744073709551615"
- addFormatterTest("%v", v4, v4s)
- addFormatterTest("%v", pv4, "<*>"+v4s)
- addFormatterTest("%v", &pv4, "<**>"+v4s)
- addFormatterTest("%v", nv4, "")
- addFormatterTest("%+v", v4, v4s)
- addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s)
- addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%+v", nv4, "")
- addFormatterTest("%#v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s)
- addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s)
- addFormatterTest("%#v", nv4, "(*"+v4t+")"+"")
- addFormatterTest("%#+v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s)
- addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"")
-
- // Max uint.
- v5 := uint(4294967295)
- nv5 := (*uint)(nil)
- pv5 := &v5
- v5Addr := fmt.Sprintf("%p", pv5)
- pv5Addr := fmt.Sprintf("%p", &pv5)
- v5t := "uint"
- v5s := "4294967295"
- addFormatterTest("%v", v5, v5s)
- addFormatterTest("%v", pv5, "<*>"+v5s)
- addFormatterTest("%v", &pv5, "<**>"+v5s)
- addFormatterTest("%v", nv5, "")
- addFormatterTest("%+v", v5, v5s)
- addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s)
- addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s)
- addFormatterTest("%+v", nv5, "")
- addFormatterTest("%#v", v5, "("+v5t+")"+v5s)
- addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s)
- addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s)
- addFormatterTest("%#v", nv5, "(*"+v5t+")"+"")
- addFormatterTest("%#+v", v5, "("+v5t+")"+v5s)
- addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s)
- addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s)
- addFormatterTest("%#v", nv5, "(*"+v5t+")"+"")
-}
-
-func addBoolFormatterTests() {
- // Boolean true.
- v := bool(true)
- nv := (*bool)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "bool"
- vs := "true"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Boolean false.
- v2 := bool(false)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "bool"
- v2s := "false"
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
-}
-
-func addFloatFormatterTests() {
- // Standard float32.
- v := float32(3.1415)
- nv := (*float32)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "float32"
- vs := "3.1415"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Standard float64.
- v2 := float64(3.1415926)
- nv2 := (*float64)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "float64"
- v2s := "3.1415926"
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"")
-}
-
-func addComplexFormatterTests() {
- // Standard complex64.
- v := complex(float32(6), -2)
- nv := (*complex64)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "complex64"
- vs := "(6-2i)"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Standard complex128.
- v2 := complex(float64(-6), 2)
- nv2 := (*complex128)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "complex128"
- v2s := "(-6+2i)"
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"")
-}
-
-func addArrayFormatterTests() {
- // Array containing standard ints.
- v := [3]int{1, 2, 3}
- nv := (*[3]int)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "[3]int"
- vs := "[1 2 3]"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Array containing type with custom formatter on pointer receiver only.
- v2 := [3]pstringer{"1", "2", "3"}
- nv2 := (*[3]pstringer)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "[3]spew_test.pstringer"
- v2sp := "[stringer 1 stringer 2 stringer 3]"
- v2s := v2sp
- if spew.UnsafeDisabled {
- v2s = "[1 2 3]"
- }
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2sp)
- addFormatterTest("%v", &pv2, "<**>"+v2sp)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2sp)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2sp)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2sp)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2sp)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2sp)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2sp)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"")
-
- // Array containing interfaces.
- v3 := [3]interface{}{"one", int(2), uint(3)}
- nv3 := (*[3]interface{})(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "[3]interface {}"
- v3t2 := "string"
- v3t3 := "int"
- v3t4 := "uint"
- v3s := "[one 2 3]"
- v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3]"
- addFormatterTest("%v", v3, v3s)
- addFormatterTest("%v", pv3, "<*>"+v3s)
- addFormatterTest("%v", &pv3, "<**>"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%+v", v3, v3s)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"")
-}
-
-func addSliceFormatterTests() {
- // Slice containing standard float32 values.
- v := []float32{3.14, 6.28, 12.56}
- nv := (*[]float32)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "[]float32"
- vs := "[3.14 6.28 12.56]"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Slice containing type with custom formatter on pointer receiver only.
- v2 := []pstringer{"1", "2", "3"}
- nv2 := (*[]pstringer)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "[]spew_test.pstringer"
- v2s := "[stringer 1 stringer 2 stringer 3]"
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"")
-
- // Slice containing interfaces.
- v3 := []interface{}{"one", int(2), uint(3), nil}
- nv3 := (*[]interface{})(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "[]interface {}"
- v3t2 := "string"
- v3t3 := "int"
- v3t4 := "uint"
- v3t5 := "interface {}"
- v3s := "[one 2 3 ]"
- v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3 (" + v3t5 +
- ")]"
- addFormatterTest("%v", v3, v3s)
- addFormatterTest("%v", pv3, "<*>"+v3s)
- addFormatterTest("%v", &pv3, "<**>"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%+v", v3, v3s)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"")
-
- // Nil slice.
- var v4 []int
- nv4 := (*[]int)(nil)
- pv4 := &v4
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "[]int"
- v4s := ""
- addFormatterTest("%v", v4, v4s)
- addFormatterTest("%v", pv4, "<*>"+v4s)
- addFormatterTest("%v", &pv4, "<**>"+v4s)
- addFormatterTest("%+v", nv4, "")
- addFormatterTest("%+v", v4, v4s)
- addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s)
- addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%+v", nv4, "")
- addFormatterTest("%#v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s)
- addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s)
- addFormatterTest("%#v", nv4, "(*"+v4t+")"+"")
- addFormatterTest("%#+v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s)
- addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"")
-}
-
-func addStringFormatterTests() {
- // Standard string.
- v := "test"
- nv := (*string)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "string"
- vs := "test"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-}
-
-func addInterfaceFormatterTests() {
- // Nil interface.
- var v interface{}
- nv := (*interface{})(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "interface {}"
- vs := ""
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Sub-interface.
- v2 := interface{}(uint16(65535))
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "uint16"
- v2s := "65535"
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
-}
-
-func addMapFormatterTests() {
- // Map with string keys and int vals.
- v := map[string]int{"one": 1, "two": 2}
- nilMap := map[string]int(nil)
- nv := (*map[string]int)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "map[string]int"
- vs := "map[one:1 two:2]"
- vs2 := "map[two:2 one:1]"
- addFormatterTest("%v", v, vs, vs2)
- addFormatterTest("%v", pv, "<*>"+vs, "<*>"+vs2)
- addFormatterTest("%v", &pv, "<**>"+vs, "<**>"+vs2)
- addFormatterTest("%+v", nilMap, "")
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs, vs2)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs, "<*>("+vAddr+")"+vs2)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs,
- "<**>("+pvAddr+"->"+vAddr+")"+vs2)
- addFormatterTest("%+v", nilMap, "")
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs, "("+vt+")"+vs2)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs, "(*"+vt+")"+vs2)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs, "(**"+vt+")"+vs2)
- addFormatterTest("%#v", nilMap, "("+vt+")"+"")
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs, "("+vt+")"+vs2)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs,
- "(*"+vt+")("+vAddr+")"+vs2)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs,
- "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs2)
- addFormatterTest("%#+v", nilMap, "("+vt+")"+"")
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Map with custom formatter type on pointer receiver only keys and vals.
- v2 := map[pstringer]pstringer{"one": "1"}
- nv2 := (*map[pstringer]pstringer)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "map[spew_test.pstringer]spew_test.pstringer"
- v2s := "map[stringer one:stringer 1]"
- if spew.UnsafeDisabled {
- v2s = "map[one:1]"
- }
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"")
-
- // Map with interface keys and values.
- v3 := map[interface{}]interface{}{"one": 1}
- nv3 := (*map[interface{}]interface{})(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "map[interface {}]interface {}"
- v3t1 := "string"
- v3t2 := "int"
- v3s := "map[one:1]"
- v3s2 := "map[(" + v3t1 + ")one:(" + v3t2 + ")1]"
- addFormatterTest("%v", v3, v3s)
- addFormatterTest("%v", pv3, "<*>"+v3s)
- addFormatterTest("%v", &pv3, "<**>"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%+v", v3, v3s)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"")
-
- // Map with nil interface value
- v4 := map[string]interface{}{"nil": nil}
- nv4 := (*map[string]interface{})(nil)
- pv4 := &v4
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "map[string]interface {}"
- v4t1 := "interface {}"
- v4s := "map[nil:]"
- v4s2 := "map[nil:(" + v4t1 + ")]"
- addFormatterTest("%v", v4, v4s)
- addFormatterTest("%v", pv4, "<*>"+v4s)
- addFormatterTest("%v", &pv4, "<**>"+v4s)
- addFormatterTest("%+v", nv4, "")
- addFormatterTest("%+v", v4, v4s)
- addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s)
- addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%+v", nv4, "")
- addFormatterTest("%#v", v4, "("+v4t+")"+v4s2)
- addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s2)
- addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s2)
- addFormatterTest("%#v", nv4, "(*"+v4t+")"+"")
- addFormatterTest("%#+v", v4, "("+v4t+")"+v4s2)
- addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s2)
- addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s2)
- addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"")
-}
-
-func addStructFormatterTests() {
- // Struct with primitives.
- type s1 struct {
- a int8
- b uint8
- }
- v := s1{127, 255}
- nv := (*s1)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "spew_test.s1"
- vt2 := "int8"
- vt3 := "uint8"
- vs := "{127 255}"
- vs2 := "{a:127 b:255}"
- vs3 := "{a:(" + vt2 + ")127 b:(" + vt3 + ")255}"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs2)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs2)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs2)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs3)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs3)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs3)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs3)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs3)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs3)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Struct that contains another struct.
- type s2 struct {
- s1 s1
- b bool
- }
- v2 := s2{s1{127, 255}, true}
- nv2 := (*s2)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "spew_test.s2"
- v2t2 := "spew_test.s1"
- v2t3 := "int8"
- v2t4 := "uint8"
- v2t5 := "bool"
- v2s := "{{127 255} true}"
- v2s2 := "{s1:{a:127 b:255} b:true}"
- v2s3 := "{s1:(" + v2t2 + "){a:(" + v2t3 + ")127 b:(" + v2t4 + ")255} b:(" +
- v2t5 + ")true}"
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%+v", v2, v2s2)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s2)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s2)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s3)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s3)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s3)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s3)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s3)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s3)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"")
-
- // Struct that contains custom type with Stringer pointer interface via both
- // exported and unexported fields.
- type s3 struct {
- s pstringer
- S pstringer
- }
- v3 := s3{"test", "test2"}
- nv3 := (*s3)(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "spew_test.s3"
- v3t2 := "spew_test.pstringer"
- v3s := "{stringer test stringer test2}"
- v3sp := v3s
- v3s2 := "{s:stringer test S:stringer test2}"
- v3s2p := v3s2
- v3s3 := "{s:(" + v3t2 + ")stringer test S:(" + v3t2 + ")stringer test2}"
- v3s3p := v3s3
- if spew.UnsafeDisabled {
- v3s = "{test test2}"
- v3sp = "{test stringer test2}"
- v3s2 = "{s:test S:test2}"
- v3s2p = "{s:test S:stringer test2}"
- v3s3 = "{s:(" + v3t2 + ")test S:(" + v3t2 + ")test2}"
- v3s3p = "{s:(" + v3t2 + ")test S:(" + v3t2 + ")stringer test2}"
- }
- addFormatterTest("%v", v3, v3s)
- addFormatterTest("%v", pv3, "<*>"+v3sp)
- addFormatterTest("%v", &pv3, "<**>"+v3sp)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%+v", v3, v3s2)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s2p)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s2p)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s3)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s3p)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s3p)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s3)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s3p)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s3p)
- addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"")
-
- // Struct that contains embedded struct and field to same struct.
- e := embed{"embedstr"}
- v4 := embedwrap{embed: &e, e: &e}
- nv4 := (*embedwrap)(nil)
- pv4 := &v4
- eAddr := fmt.Sprintf("%p", &e)
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "spew_test.embedwrap"
- v4t2 := "spew_test.embed"
- v4t3 := "string"
- v4s := "{<*>{embedstr} <*>{embedstr}}"
- v4s2 := "{embed:<*>(" + eAddr + "){a:embedstr} e:<*>(" + eAddr +
- "){a:embedstr}}"
- v4s3 := "{embed:(*" + v4t2 + "){a:(" + v4t3 + ")embedstr} e:(*" + v4t2 +
- "){a:(" + v4t3 + ")embedstr}}"
- v4s4 := "{embed:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 +
- ")embedstr} e:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + ")embedstr}}"
- addFormatterTest("%v", v4, v4s)
- addFormatterTest("%v", pv4, "<*>"+v4s)
- addFormatterTest("%v", &pv4, "<**>"+v4s)
- addFormatterTest("%+v", nv4, "")
- addFormatterTest("%+v", v4, v4s2)
- addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s2)
- addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s2)
- addFormatterTest("%+v", nv4, "")
- addFormatterTest("%#v", v4, "("+v4t+")"+v4s3)
- addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s3)
- addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s3)
- addFormatterTest("%#v", nv4, "(*"+v4t+")"+"")
- addFormatterTest("%#+v", v4, "("+v4t+")"+v4s4)
- addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s4)
- addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s4)
- addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"")
-}
-
-func addUintptrFormatterTests() {
- // Null pointer.
- v := uintptr(0)
- nv := (*uintptr)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "uintptr"
- vs := ""
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Address of real variable.
- i := 1
- v2 := uintptr(unsafe.Pointer(&i))
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "uintptr"
- v2s := fmt.Sprintf("%p", &i)
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
-}
-
-func addUnsafePointerFormatterTests() {
- // Null pointer.
- v := unsafe.Pointer(uintptr(0))
- nv := (*unsafe.Pointer)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "unsafe.Pointer"
- vs := ""
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Address of real variable.
- i := 1
- v2 := unsafe.Pointer(&i)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "unsafe.Pointer"
- v2s := fmt.Sprintf("%p", &i)
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
-}
-
-func addChanFormatterTests() {
- // Nil channel.
- var v chan int
- pv := &v
- nv := (*chan int)(nil)
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "chan int"
- vs := ""
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Real channel.
- v2 := make(chan int)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "chan int"
- v2s := fmt.Sprintf("%p", v2)
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
-}
-
-func addFuncFormatterTests() {
- // Function with no params and no returns.
- v := addIntFormatterTests
- nv := (*func())(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "func()"
- vs := fmt.Sprintf("%p", v)
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "