kubernetes Documentation

Production-Grade Container Scheduling and Management

0 stars Go Go 249 files · ~127,781 tokens
RAW Doc

Technical Documentation: dunglas/kubernetes

ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference

Overview (`README.md`)

Kubernetes


Kubernetes is an open source system for managing containerized applications
across multiple hosts, providing basic mechanisms for deployment, maintenance,
and scaling of applications.

Kubernetes builds upon a decade and a half of experience at Google running
production workloads at scale using a system called Borg,
combined with best-of-breed ideas and practices from the community.

Kubernetes is hosted by the Cloud Native Computing Foundation (CNCF).
If you are a company that wants to help shape the evolution of
technologies that are container-packaged, dynamically-scheduled
and microservices-oriented, consider joining the CNCF.
For details about who's involved and how Kubernetes plays a role,
read the CNCF announcement.


To start using Kubernetes

See our documentation on kubernetes.io.

Try our interactive tutorial.

Take a free course on Scalable Microservices with Kubernetes.

To start developing Kubernetes

The community repository hosts all information about
building Kubernetes from source, how to contribute code
and documentation, who to contact about what, etc.

If you want to build Kubernetes right away there are two options:

You have a working [Go environment].

text
$ go get -d k8s.io/kubernetes
$ cd $GOPATH/src/k8s.io/kubernetes
$ make

You have a working [Docker environment].

text
$ git clone https://github.com/kubernetes/kubernetes
$ cd kubernetes
$ make quick-release

For the full story, head over to the developer's documentation.

Support

If you need support, start with the troubleshooting guide
and work your way through the process that we've outlined.

That said, if you have questions, reach out to us
one way or another.


Overview (`build/README.md`)

Building Kubernetes

Building Kubernetes is easy if you take advantage of the containerized build environment. This document will help guide you through understanding this build process.

Requirements

  1. Docker, using one of the following configurations:
  • Mac OS X You can either use Docker for Mac or docker-machine. See installation instructions here.
    Note: You will want to set the Docker VM to have at least 3GB of initial memory or building will likely fail. (See: #11852)).
  • Linux with local Docker Install Docker according to the instructions for your OS.
  • Remote Docker engine Use a big machine in the cloud to build faster. This is a little trickier so look at the section later on.
  1. Optional Google Cloud SDK

You must install and configure Google Cloud SDK if you want to upload your release to Google Cloud Storage and may safely omit this otherwise.

Overview

While it is possible to build Kubernetes using a local golang installation, we have a build process that runs in a Docker container. This simplifies initial set up and provides for a very consistent build and test environment.

Key scripts

The following scripts are found in the build/ directory. Note that all scripts must be run from the Kubernetes root directory.

  • build/run.sh: Run a command in a build docker container. Common invocations:
    • build/run.sh make: Build just linux binaries in the container. Pass options and packages as necessary.
    • build/run.sh make cross: Build all binaries for all platforms
    • build/run.sh make test: Run all unit tests
    • build/run.sh make test-integration: Run integration test
    • build/run.sh make test-cmd: Run CLI tests
  • build/copy-output.sh: This will copy the contents of _output/dockerized/bin from the Docker container to the local _output/dockerized/bin. It will also copy out specific file patterns that are generated as part of the build process. This is run automatically as part of build/run.sh.
  • build/make-clean.sh: Clean out the contents of _output, remove any locally built container images and remove the data container.
  • /build/shell.sh: Drop into a bash shell in a build container with a snapshot of the current repo code.

Basic Flow

The scripts directly under build/ are used to build and test. They will ensure that the kube-build Docker image is built (based on build/build-image/Dockerfile) and then execute the appropriate command in that container. These scripts will both ensure that the right data is cached from run to run for incremental builds and will copy the results back out of the container.

The kube-build container image is built by first creating a "context" directory in _output/images/build-image. It is done there instead of at the root of the Kubernetes repo to minimize the amount of data we need to package up when building the image.

There are 3 different containers instances that are run from this image. The first is a "data" container to store all data that needs to persist across to support incremental builds. Next there is an "rsync" container that is used to transfer data in and out to the data container. Lastly there is a "build" container that is used for actually doing build actions. The data container persists across runs while the rsync and build containers are deleted after each use.

rsync is used transparently behind the scenes to efficiently move data in and out of the container. This will use an ephemeral port picked by Docker. You can modify this by setting the KUBE_RSYNC_PORT env variable.

All Docker names are suffixed with a hash derived from the file path (to allow concurrent usage on things like CI machines) and a version number. When the version number changes all state is cleared and clean build is started. This allows the build infrastructure to be changed and signal to CI systems that old artifacts need to be deleted.

Proxy Settings

If you are behind a proxy and you are letting these scripts use docker-machine to set up your local VM for you on macOS, you need to export proxy settings for Kubernetes build, the following environment variables should be defined.

text
export KUBERNETES_HTTP_PROXY=http://username:password@proxyaddr:proxyport
export KUBERNETES_HTTPS_PROXY=https://username:password@proxyaddr:proxyport

Optionally, you can specify addresses of no proxy for Kubernetes build, for example

text
export KUBERNETES_NO_PROXY=127.0.0.1

If you are using sudo to make Kubernetes build for example make quick-release, you need run sudo -E make quick-release to pass the environment variables.

Really Remote Docker Engine

It is possible to use a Docker Engine that is running remotely (under your desk or in the cloud). Docker must be configured to connect to that machine and the local rsync port must be forwarded (via SSH or nc) from localhost to the remote machine.

To do this easily with GCE and docker-machine, do something like this:

text
# Create the remote docker machine on GCE.  This is a pretty beefy machine with SSD disk.
KUBE_BUILD_VM=k8s-build
KUBE_BUILD_GCE_PROJECT=<project>
docker-machine create \
  --driver=google \
  --google-project=${KUBE_BUILD_GCE_PROJECT} \
  --google-zone=us-west1-a \
  --google-machine-type=n1-standard-8 \
  --google-disk-size=50 \
  --google-disk-type=pd-ssd \
  ${KUBE_BUILD_VM}

# Set up local docker to talk to that machine
eval $(docker-machine env ${KUBE_BUILD_VM})

# Pin down the port that rsync will be exposed on on the remote machine
export KUBE_RSYNC_PORT=8730

# forward local 8730 to that machine so that rsync works
docker-machine ssh ${KUBE_BUILD_VM} -L ${KUBE_RSYNC_PORT}:localhost:${KUBE_RSYNC_PORT} -N &

Look at docker-machine stop, docker-machine start and docker-machine rm to manage this VM.

Releasing

The build/release.sh script will build a release. It will build binaries, run tests, (optionally) build runtime Docker images.

The main output is a tar file: kubernetes.tar.gz. This includes:

  • Cross compiled client utilities.
  • Script (kubectl) for picking and running the right client binary based on platform.
  • Examples
  • Cluster deployment scripts for various clouds
  • Tar file containing all server binaries
  • Tar file containing salt deployment tree shared across multiple cloud deployments.

In addition, there are some other tar files that are created:

  • kubernetes-client-*.tar.gz Client binaries for a specific platform.
  • kubernetes-server-*.tar.gz Server binaries for a specific platform.
  • kubernetes-salt.tar.gz The salt script/tree shared across multiple deployment scripts.

When building final release tars, they are first staged into _output/release-stage before being tar'd up and put into _output/release-tars.


Overview (`cluster/README.md`)

Cluster Configuration

Deprecation Notice: This directory has entered maintenance mode and will not be accepting new providers. Please submit new automation deployments to [kube-deploy](https://github.com/kubernetes/kube-deploy). Deployments in this directory will continue to be maintained and supported at their current level of support.

The scripts and data in this directory automate creation and configuration of a Kubernetes cluster, including networking, DNS, nodes, and master components.

See the getting-started guides for examples of how to use the scripts.

cloudprovider/config-default.sh contains a set of tweakable definitions/parameters for the cluster.

The heavy lifting of configuring the VMs is done by SaltStack.


Overview (`examples/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/README.md


Overview (`staging/README.md`)

External Repository Staging Area

This directory is the staging area for packages that have been split to their
own repository. The content here will be periodically published to respective
top-level k8s.io repositories.

Repositories currently staged here:

The code in the staging/ directory is authoritative, i.e. the only copy of the
code. You can directly modify such code.

Using staged repositories from Kubernetes code

Kubernetes code uses the repositories in this directory via symlinks in the
vendor/k8s.io directory into this staging area. For example, when
Kubernetes code imports a package from the k8s.io/client-go repository, that
import is resolved to staging/src/k8s.io/client-go relative to the project
root:

go
// pkg/example/some_code.go
package example

import (
  "k8s.io/client-go/dynamic" // resolves to staging/src/k8s.io/client-go/dynamic
)

Once the change-over to external repositories is complete, these repositories
will actually be vendored from k8s.io/.


Overview (`translations/README.md`)

Translations README

This is a basic sketch of the workflow needed to add translations:

Adding/Updating Translations

New languages

Create translations/kubectl/<language>/LC_MESSAGES/k8s.po. There's
no need to update translations/test/... which is only used for unit tests.

There is an example PR here which adds support for French.

Once you've added a new language, you'll need to register it in
pkg/util/i18n/i18n.go by adding it to the knownTranslations map.

Wrapping strings

There is a simple script in translations/extract.py that performs
simple regular expression based wrapping of strings. It can always
use improvements to understand additional strings.

Extracting strings

Once the strings are wrapped, you can extract strings from go files using
the go-xgettext command which can be installed with:

console
go get github.com/gosexy/gettext/go-xgettext

Once that's installed you can run ./hack/update-translations.sh, which
will extract and sort any new strings.

Adding new translations

Edit the appropriate k8s.po file, poedit is a popular open source tool
for translations. You can load the translations/kubectl/template.pot file
to find messages that might be missing.

Once you are done with your k8s.po file, generate the corresponding k8s.mo
file. poedit does this automatically on save, but you can also run
./hack/update-translations.sh to perform the po to mo translation.

We use the English translation as the msgid.

Regenerating the bindata file

Run ./hack/generate-bindata.sh, this will turn the translation files
into generated code which will in turn be packaged into the Kubernetes
binaries.

Extracting strings

There is a script in translations/extract.py that knows how to do some
simple extraction. It needs a lot of work.

Using translations

To use translations, you simply need to add:

go
import pkg/i18n
...
// Get a translated string
translated := i18n.T("Your message in english here")

// Get a translated plural string
translated := i18n.T("You had % items", items)

// Translated error
return i18n.Error("Something bad happened")

// Translated plural error
return i18n.Error("%d bad things happened")


Overview (`api/openapi-spec/README.md`)

Kubernetes's OpenAPI Specification

This folder contains an [OpenAPI specification][openapi] for Kubernetes API.

Vendor Extensions

Kubernetes extends OpenAPI using these extensions. Note the version that
extensions has been added.

`x-kubernetes-group-version-kind`

Operations and Definitions may have x-kubernetes-group-version-kind if they
are associated with a kubernetes resource.

For example:

json
"paths": {
    ...
    "/api/v1/namespaces/{namespace}/pods/{name}": {
        ...
        "get": {
        ...
            "x-kubernetes-group-version-kind": {
            "group": "",
            "version": "v1",
            "kind": "Pod"
            }
        }
    }
}

`x-kubernetes-action`

Operations and Definitions may have x-kubernetes-action if they
are associated with a kubernetes resource.
Action can be one of get, list, put, patch, post, delete, deletecollection, watch, watchlist, proxy, or connect.

For example:

json
"paths": {
    ...
    "/api/v1/namespaces/{namespace}/pods/{name}": {
        ...
        "get": {
        ...
            "x-kubernetes-action": "list"
        }
    }
}

`x-kubernetes-patch-strategy` and `x-kubernetes-patch-merge-key`

Some of the definitions may have these extensions. For more information about PatchStrategy and PatchMergeKey see
[strategic-merge-patch] (https://github.com/kubernetes/community/blob/master/contributors/devel/strategic-merge-patch.md).


Overview (`build/debian-base/README.md`)

Kubernetes Debian Base

The Kubernetes debian-base image provides a common base for Kubernetes system images that require
external dependencies (such as iptables, sh, or anything that is more than a static go-binary).

This image differs from the standard debian image by removing a lot of packages and files that are
generally not necessary in containers. The end result is an image that is just over 40 MB, down from
123 MB.

The image also provides a convenience script /usr/local/bin/clean-install that encapsulates the
process of updating apt repositories, installing the packages, and then cleaning up unnecessary
caches & logs.


Overview (`build/debian-hyperkube-base/README.md`)

debian-hyperkube-base

Serves as the base image for gcr.io/google-containers/hyperkube-${ARCH}
images.

This image is compiled for multiple architectures.

How to release

If you're editing the Dockerfile or some other thing, please bump the TAG in the Makefile.

console
# Build for linux/amd64 (default)
$ make push ARCH=amd64
# ---> gcr.io/google-containers/debian-hyperkube-base-amd64:TAG

$ make push ARCH=arm
# ---> gcr.io/google-containers/debian-hyperkube-base-arm:TAG

$ make push ARCH=arm64
# ---> gcr.io/google-containers/debian-hyperkube-base-arm64:TAG

$ make push ARCH=ppc64le
# ---> gcr.io/google-containers/debian-hyperkube-base-ppc64le:TAG

$ make push ARCH=s390x
# ---> gcr.io/google-containers/debian-hyperkube-base-s390x:TAG

If you don't want to push the images, run make build instead


Overview (`build/debian-iptables/README.md`)

debian-iptables

Serves as the base image for gcr.io/google_containers/kube-proxy-${ARCH} and multiarch (not amd64) gcr.io/google_containers/flannel-${ARCH} images.

This image is compiled for multiple architectures.

How to release

If you're editing the Dockerfile or some other thing, please bump the TAG in the Makefile.

console
# Build for linux/amd64 (default)
$ make push ARCH=amd64
# ---> gcr.io/google_containers/debian-iptables-amd64:TAG

$ make push ARCH=arm
# ---> gcr.io/google_containers/debian-iptables-arm:TAG

$ make push ARCH=arm64
# ---> gcr.io/google_containers/debian-iptables-arm64:TAG

$ make push ARCH=ppc64le
# ---> gcr.io/google_containers/debian-iptables-ppc64le:TAG

$ make push ARCH=s390x
# ---> gcr.io/google_containers/debian-iptables-s390x:TAG

If you don't want to push the images, run make or make build instead


Overview (`build/visible_to/README.md`)

Package Groups Used in Kubernetes Visibility Rules

Background

BUILD rules define dependencies, answering the question:
on what packages does foo depend?

The BUILD file in this package allows one to define
allowed reverse dependencies, answering the question:
given a package foo, what other specific packages are
allowed to depend on it?

This is done via visibility rules.

Visibility rules discourage unintended, spurious
dependencies that blur code boundaries, slow CICD queues and
generally inhibit progress.

Facts

  • A package is any directory that contains a BUILD file.

  • A package_group is a BUILD file rule that defines a named
    set of packages for use in other rules, e.g., given

    text
    package_group(
      name = "database_CONSUMERS",
      packages = [
          "//foo/dbinitializer",
          "//foo/backend/...",  # `backend` and everything below it
      ],
    )

    one can specify the following visibility rule in any BUILD rule:

    text
    visibility = [ "//build/visible_to:database_CONSUMERS" ],
  • A visibility rule takes a list of package groups as its
    argument - or one of the pre-defined groups
    //visibility:private or //visibility:public.

  • If no visibility is explicitly defined, a package is
    private by default.

  • Violations in visibility cause make bazel-build to fail,
    which in turn causes the submit queue to fail - that's the
    enforcement.

Why define all package groups meant for visibility here (in one file)?

  • Ease discovery of appropriate groups for use in a rule.
  • Ease reuse (inclusions) of commonly used groups.
  • Consistent style:
    • easy to read //build/visible_to:math_library_CONSUMERS rules,
    • call out bad dependencies for eventual removal.
  • Make it more obvious in code reviews when visibility is being
    modified.
  • One set of OWNERS to manage visibility.

The alternative is to use special package literals directly
in visibility rules, e.g.

text
visibility = [
        "//foo/dbinitializer:__pkg__",
        "//foo/backend:__subpackages__",
  ],

The difference in style is similar to the difference between
using a named static constant like MAX_NODES rather than a
literal like 12. Names are preferable to literals for intent
documentation, search, changing one place rather than n,
associating usage in distant code blocks, etc.

Rule Examples

Nobody outside this package can depend on me.

text
visibility = ["//visibility:private"],

Since this is the default, there's no reason to use this
rule except as a means to override, for some specific
target, some broader, whole-package visibility rule.

Anyone can depend on me (eschew this).

text
visibility = ["//visibility:public"],

Only some servers can depend on me.

Appropriate for, say, backend storage utilities.

text
visibility = ["//visible_to:server_foo","//visible_to:server_bar"].

Both some client and some server can see me.

Appropriate for shared API definition files and generated code:

text
visibility = ["//visible_to:client_foo,//visible_to:server_foo"],

Handy commands

Quickly check for visibility violations

text
bazel build --check_visibility --nobuild \
    //cmd/... //pkg/... //plugin/... \
    //third_party/... //examples/... //test/... //vendor/k8s.io/...

Who depends on target _q_?

To create a seed set for a visibility group, one can ask what
packages currently depend on (must currently be able to see) a
given Go library target? It's a time consuming query.

text
q=//pkg/kubectl/cmd:go_default_library
bazel query "rdeps(...,${q})" | \
    grep go_default_library | \
    sed 's/\(.*\):go_default_library/ "\1",/'

What targets below _p_ are visible to anyone?

A means to look for things one missed when locking down p.

text
p=//pkg/kubectl/cmd
bazel query "visible(...,${p}/...)"

What packages below _p_ may target _q_ depend on without violating visibility rules?

A means to pinpoint unexpected visibility.

text
p=//pkg/kubectl
q=//cmd/kubelet:kubelet
bazel query "visible(${q},${p}/...)" | more

What packages does target _q_ need?

text
q=//cmd/kubectl:kubectl
bazel query "buildfiles(deps($q))" | \
    grep -v @bazel_tools | \
    grep -v @io_bazel_rules | \
    grep -v @io_kubernetes_build | \
    grep -v @local_config | \
    grep -v @local_jdk | \
    grep -v //visible_to: | \
    sed 's/:BUILD//' | \
    sort | uniq > ~/KUBECTL_BUILD.txt

or try

text
bazel query --nohost_deps --noimplicit_deps \
    "kind('source file', deps($q))" | wc -

How does kubectl depend on pkg/util/parsers?

text
bazel query "somepath(cmd/kubectl:kubectl, pkg/util/parsers:go_default_library)"

Overview (`cluster/addons/README.md`)

Legacy Cluster add-ons

For more information on add-ons see the documentation.

Overview

Cluster add-ons are resources like Services and Deployments (with pods) that are
shipped with the Kubernetes binaries and are considered an inherent part of the
Kubernetes clusters.

There are currently two classes of add-ons:

  • Add-ons that will be reconciled.
  • Add-ons that will be created if they don't exist.

More details could be found in addon-manager/README.md.

Cooperating Horizontal / Vertical Auto-Scaling with "reconcile class addons"

"Reconcile" class addons will be periodically reconciled to the original state given
by the initial config. In order to make Horizontal / Vertical Auto-scaling functional,
the related fields in config should be left unset. More specifically, leave replicas
in ReplicationController / Deployment / ReplicaSet unset for Horizontal Scaling,
leave resources for container unset for Vertical Scaling. The periodic reconcile
won't clobbered these fields, hence they could be managed by Horizontal / Vertical
Auto-scaler.

Add-on naming

The suggested naming for most of the resources is `` (with no version number).
Though resources like Pod, ReplicationController and DaemonSet are exceptional.
It would be hard to update Pod because many fields in Pod are immutable. For
ReplicationController and DaemonSet, in-place update may not trigger the underlying
pods to be re-created. You probably need to change their names during update to trigger
a complete deletion and creation.


Overview (`cluster/libvirt-coreos/README.md`)

Kubernetes CoreOS cluster

With this tutorial one creates a Kubernetes CoreOS cluster containing of one
master and three nodes (workers) running on 192.168.10.1-192.168.10.4.

For working correctly you need to create the directory addressed as POOL_PATH in
util.sh:

text
$ sudo mkdir /var/lib/libvirt/images/kubernetes
$ sudo chown -R $USER:$USER /var/lib/libvirt/images/kubernetes/

Then we follow the instructions in the main kubernetes directory.

For debugging set export UTIL_SH_DEBUG=1.

text
$ export KUBERNETES_PROVIDER=libvirt-coreos
$ make release-skip-tests
$ ./cluster/kube-up.sh

To bring the cluster down again, execute:

text
$ ./cluster/kube-down.sh

Have fun!


Overview (`cluster/saltbase/README.md`)

SaltStack configuration

This is the root of the SaltStack configuration for Kubernetes. A high
level overview for the Kubernetes SaltStack configuration can be found in the docs tree.

This SaltStack configuration currently applies to default
configurations for Debian-on-GCE, Fedora-on-Vagrant, Ubuntu-on-AWS and
Ubuntu-on-Azure. (That doesn't mean it can't be made to apply to an
arbitrary configuration, but those are only the in-tree OS/IaaS
combinations supported today.) As you peruse the configuration, these
are shorthanded as gce, vagrant, aws, azure-legacy in grains.cloud;
the documentation in this tree uses this same shorthand for convenience.

See more:


Overview (`cluster/vsphere/README.md`)

Please use Kubernetes-anywhere to get started on vSphere.


Overview (`examples/cluster-dns/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/cluster-dns/README.md


Overview (`examples/cockroachdb/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/cockroachdb/README.md


Overview (`examples/cpu-manager/README.md`)

CPU Manager Example

This example flow uses a pre-built docker image based on
cpuset-visualizer.
Each container run here hosts an endpoint serving an up-to-the-second
system representation generated by
lstopo.

Setup

  1. Start a local cluster with the static CPU manager policy enabled :

    text
    sudo PATH=$PATH \
      KUBELET_FLAGS="\
      --feature-gates=CPUManager=true \
      --cpu-manager-policy=static \
      --cpu-manager-reconcile-period=5s \
      --kube-reserved=cpu=500m" \
      ./hack/local-up-cluster.sh

Run pods

The example pods are in the /examples/cpu-manager directory of the
Kubernetes source tree. Your ability to run all of the example pods
simultaneously depends on how many CPUs are available on the test system.

The required CPUs for each example pod are listed below:

text
POD              | CPUs
------------------|---------
 be.yaml          | >= 1 CPU
 shared.yaml      | >= 1 CPU
 exclusive-1.yaml | >= 2 CPU
 exclusive-2.yaml | >= 3 CPU
 exclusive-3.yaml | >= 4 CPU
 exclusive-4.yaml | >= 5 CPU

Example

Run a pod with a single container in the shared pool, and another pod
with a single container in an exclusive cpuset with one CPU.

text
$ kubectl create -f examples/cpu-manager/shared.yaml
$ kubectl create -f examples/cpu-manager/exclusive-1.yaml

To list IP addresses of the pods running in the local cluster, do:

text
$ watch ./examples/cpu-manager/pod-ips
exclusive-1 http://172.17.0.4
shared http://172.17.0.3

Sample cpuset-visualizer output


Overview (`examples/elasticsearch/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/elasticsearch/README.md


Overview (`examples/explorer/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/explorer/README.md


Overview (`examples/guestbook-go/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/guestbook-go/README.md


Overview (`examples/guestbook/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/guestbook/README.md


Overview (`examples/https-nginx/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/https-nginx/README.md


Overview (`examples/javaee/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/javaee/README.md


Overview (`examples/javaweb-tomcat-sidecar/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/javaweb-tomcat-sidecar/README.md


Overview (`examples/kubectl-container/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/kubectl-container/README.md


Overview (`examples/meteor/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/meteor/README.md


Overview (`examples/mysql-cinder-pd/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/mysql-cinder-pd/README.md


Overview (`examples/mysql-wordpress-pd/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/mysql-wordpress-pd/README.md


Overview (`examples/newrelic-infrastructure/README.md`)

New Relic Infrastructure Server Monitoring Agent Example

This example shows how to run a New Relic Infrastructure server monitoring agent as a pod in a DaemonSet on an existing Kubernetes cluster.

This example will create a DaemonSet which places the New Relic Infrastructure monitoring agent on every node in the cluster. It's also fairly trivial to exclude specific Kubernetes nodes from the DaemonSet to just monitor specific servers. (The prior nrsysmond has been deprecated.)

Step 0: Prerequisites

This process will create privileged containers which have full access to the host system for logging. Beware of the security implications of this.

DaemonSets must be enabled on your cluster. Instructions for enabling DaemonSet can be found here.

Step 1: Configure New Relic Infrastructure Agent

The New Relic Infrastructure agent is configured via environment variables. We will configure these environment variables in a sourced bash script, encode the environment file data, and store it in a secret which will be loaded at container runtime. (Reread this sentence a few times, it's HOW the entire container works.)

The New Relic Linux Infrastructure Server configuration page lists all the other settings for the Infrastructure process.

To create an environment variable for a setting, prepend NRIA_ to its name and capitalize all of the env variable. For example,

console
log_file=/var/log/nr-infra.log

translates to

console
NRIA_LOG_FILE=/var/log/nr-infra.log

Edit examples/newrelic-infrastructure/nrconfig.env and configure relevant environment variables for your NewRelic Infrastructure agent. There are a few defauts defined, but the only required variable is the New Relic license key.

Now, let's vendor the config into a secret.

console
$ cd examples/newrelic-infrastructure/
$ ./config-to-secret.sh
yaml
apiVersion: v1
kind: Secret
metadata:
  name: newrelic-config
type: Opaque
data:
  config: {{config_data}}

Download example

The script will encode the config file and write it to newrelic-config.yaml.

Finally, submit the config to the cluster:

console
$ kubectl create -f examples/newrelic-infrastructure/newrelic-config.yaml

Step 2: Create the DaemonSet definition.

The DaemonSet definition instructs Kubernetes to place a newrelic Infrastructure agent on each Kubernetes node.

yaml
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: newrelic-infra-agent
  labels:
    tier: monitoring
    app: newrelic-infra-agent
    version: v1
spec:
  template:
    metadata:
      labels:
        name: newrelic
    spec:
      # Filter to specific nodes:
      # nodeSelector:
      #  app: newrelic
      hostPID: true
      hostIPC: true
      hostNetwork: true
      containers:
        - resources:
            requests:
              cpu: 0.15
          securityContext:
            privileged: true
          image: newrelic/infrastructure
          name: newrelic
          command: [ "bash", "-c", "source /etc/kube-nr-infra/config && /usr/bin/newrelic-infra" ]
          volumeMounts:
            - name: newrelic-config
              mountPath: /etc/kube-nr-infra
              readOnly: true
            - name: dev
              mountPath: /dev
            - name: run
              mountPath: /var/run/docker.sock
            - name: log
              mountPath: /var/log
            - name: host-root
              mountPath: /host
              readOnly: true
      volumes:
        - name: newrelic-config
          secret:
            secretName: newrelic-config
        - name: dev
          hostPath:
              path: /dev
        - name: run
          hostPath:
              path: /var/run/docker.sock
        - name: log
          hostPath:
              path: /var/log
        - name: host-root
          hostPath:
              path: /

Download example

The daemonset instructs Kubernetes to spawn pods on each node, mapping /dev/, /run/, and /var/log to the container. It also maps the entire kube node / to /host/ in the container with a read-only mount. It also maps the secrets we set up earlier to /etc/kube-newrelic/config, and sources them in the startup script, configuring the agent properly.

DaemonSet customization

Known issues

It's a bit cludgy to define the environment variables like we do here in these config files. There is another issue to discuss adding mapping secrets to environment variables in Kubernetes. (Personally I don't like that method and prefer to use the config secrets.)


Overview (`examples/newrelic/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/newrelic/README.md


Overview (`examples/nodesjs-mongodb/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/nodesjs-mongodb/README.md


Overview (`examples/oms/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/oms/README.md


Overview (`examples/openshift-origin/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/openshift-origin/README.md


Overview (`examples/persistent-volume-provisioning/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/persistent-volume-provisioning/README.md


Overview (`examples/phabricator/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/phabricator/README.md


Overview (`examples/runtime-constraints/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/runtime-constraints/README.md


Overview (`examples/selenium/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/selenium/README.md


Overview (`examples/sharing-clusters/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/sharing-clusters/README.md


Overview (`examples/spark/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/spark/README.md


Overview (`examples/storm/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/storm/README.md


Overview (`examples/sysdig-cloud/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/sysdig-cloud/README.md


Overview (`hack/gen-swagger-doc/README.md`)

This folder contains the sources needed to build the gen-swagger-doc container.

To build the container image,

text
$ sudo docker build -t gcr.io/google_containers/gen-swagger-docs:v1 .

To generate the html docs,

text
$ ./gen-swagger-docs.sh <API version> <absolute output path, default to PWD>

The generated definitions.html and operations.html will be stored in output paths.


Overview (`hack/jenkins/README.md`)

Jenkins

Jenkins is a pluggable continuous
integration system. The Google team is running two Jenkins servers in GCE for
the Kubernetes project. The post-commit instance runs continuous builds, unit
tests, integration tests, code verification tests, and end-to-end tests on
multiple providers using the latest commits to the Kubernetes repo from the
master and release branches. The PR Jenkins instance runs these tests on each
PR by a trusted contributor, it but only runs a subset of the end-to-end tests
and only on GCE.

General flow

The flow of the post-commit Jenkins instance:

  • Under the kubernetes-build job: Every 2 minutes, Jenkins polls for a batch
    of new commits, after which it runs the build.sh script (in this directory)
    on the latest tip. This results in build assets getting pushed to GCS and the
    latest.txt file in the ci bucket being updated.
  • On trigger, and every half hour (which effectively means all the time, unless
    we're failing cluster creation), e2e variants run, on the latest build assets
    in GCS:
    • kubernetes-e2e-gce: Standard GCE e2e.
    • kubernetes-e2e-gke: GKE provider e2e, with head k8s client and GKE
      creating clusters at its default version.
    • kubernetes-e2e-aws: AWS provider e2e. This only runs once a day.
  • Each job will not run concurrently with itself, so, for instance,
    Jenkins executor will only ever run one kubernetes-build
    job. However, it may run the jobs in parallel,
    i.e. kubernetes-build may be run at the same time as
    kubernetes-e2e-gce. For this reason, you may see your changes
    pushed to our GCS bucket rapidly, but they may take some time to
    fully work through Jenkins. Or you may get lucky and catch the
    train in 5 minutes.
  • There are many jobs not listed here, including upgrade tests, soak tests, and
    tests for previous releases.

Scripts

The scripts in this directory are directly used by Jenkins, either by
curl from githubusercontent (if we don't have a git checkout handy) or
by executing it from the git checkout. Since Jenkins is an entity
outside this repository, it's tricky to keep documentation for it up
to date quickly. However, the scripts themselves attempt to provide
color for the configuration(s) that each script runs in.

GCS Log Format

Our upload-to-gcs.sh script runs at the start and end of every job. Logs on
post-commit Jenkins go under gs://kubernetes-jenkins/logs/. Logs on PR
Jenkins go under gs://kubernetes-jenkins-pull/pr-logs/pull/PULL_NUMBER/.
Individual run logs go into the JOB_NAME/BUILD_NUMBER folder.

At the start of the job, it uploads started.json containing the version of
Kubernetes under test and the timestamp.

At the end, it uploads finished.json containing the result and timestamp, as
well as the build log into build-log.txt. Under artifacts/ we put our
test results in junit_XY.xml, along with gcp resource lists and cluster logs.

It also updates latest-build.txt at the end to point to this build number.
In the end, the directory structure looks like this:

text
gs://kubernetes-jenkins/logs/kubernetes-e2e-gce/
  latest-build.txt
  12345/
    build-log.txt
    started.json
    finished.json
    artifacts/
      gcp-resources-{before, after}.txt
      junit_{00, 01, ...}.xml
      jenkins-e2e-master/{kube-apiserver.log, ...}
      jenkins-e2e-node-abcd/{kubelet.log, ...}
  12344/
    ...

The munger uses latest-build.txt and the JUnit reports to figure out whether
or not the job is healthy.

Job Builder

New jobs should be specified as YAML files to be processed by Jenkins Job
Builder
. The YAML files
live in jenkins/job-configs and its subfolders in the
kubernetes/test-infra repository
.
Jenkins runs Jenkins Job Builder in a Docker container defined in
job-builder-image, and triggers it using update-jobs.sh. Jenkins Job Builder
uses a config file called
jenkins_jobs.ini
which contains the location and credentials of the Jenkins server.

E2E Job definitions are templated to avoid code duplication. To add a new job,
add a new entry to the appropriate project.
This
is an example of a commit which does this. If necessary, create a new project, as in
this
commit.


Overview (`pkg/cloudprovider/README.md`)

Deprecation Notice: This directory has entered maintenance mode and will not be accepting new providers. Cloud Providers in this directory will continue to be actively developed or maintained and supported at their current level of support as a longer-term solution evolves.

Overview:

The mechanism for supporting cloud providers is currently in transition: the original method of implementing cloud provider-specific functionality within the main kubernetes tree (here) is no longer advised; however, the proposed solution is still in development.

Guidance for potential cloud providers:

  • Support for cloud providers is currently in a state of flux. Background information on motivation and the proposal for improving is in the github proposal.
  • In support of this plan, a new cloud-controller-manager binary was added in 1.6. This was the first of several steps (see the proposal for more information).
  • Attempts to contribute new cloud providers or (to a lesser extent) persistent volumes to the core repo will likely meet with some pushback from reviewers/approvers.
  • It is understood that this is an unfortunate situation in which 'the old way is no longer supported but the new way is not ready yet', but the initial path is unsustainable, and contributors are encouraged to participate in the implementation of the proposed long-term solution, as there is risk that PRs for new cloud providers here will not be approved.
  • Though the fully productized support envisioned in the proposal is still 2 - 3 releases out, the foundational work is underway, and a motivated cloud provider could accomplish the work in a forward-looking way. Contributors are encouraged to assist with the implementation of the design outlined in the proposal.

Some additional context on status / direction:

  • 1.6 added a new cloud-controller-manager binary that may be used for testing the new out-of-core cloudprovider flow.
  • Setting cloud-provider=external allows for creation of a separate controller-manager binary
  • 1.7 adds extensible admission control, further enabling topology customization.

Overview (`test/conformance/README.md`)

This directory contains the regression test for controlling the list of all
conformance tests.

If you add or remove a conformance test, this test will fail and you will need
to update the golden list of tests stored in testdata/. Changes to that file
require review by sig-architecture.

To update the list, run

console
$ bazel build //test/conformance:list_conformance_tests
$ cp bazel-genfiles/test/conformance/conformance.txt test/conformance/testdata

Add the changed file to your PR, then send for review.


Overview (`test/e2e/README.md`)

See e2e-tests


Overview (`test/e2e_node/README.md`)

See e2e-node-tests


Overview (`third_party/intemp/README.md`)

intemp

A bash script to execute a command within a temporary work directory.

Dependencies

Requires: mktemp

Install

text
git clone https://github.com/karlkfi/intemp
cd intemp
make install

or

text
curl -o- https://raw.githubusercontent.com/karlkfi/intemp/master/install.sh | bash

Usage

text
intemp.sh [-t prefix] "<command>"

Example (install intemp using intemp):

text
intemp.sh -t intemp "git clone https://github.com/karlkfi/intemp . && make install"

License

Copyright 2015 Karl Isenberg

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

text
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.


Overview (`third_party/swagger-ui/README.md`)

Readme

URL: https://github.com/swagger-api/swagger-ui/tree/master/dist
License: Apache License, Version 2.0
License File: LICENSE

Description

Files from dist folder of https://github.com/swagger-api/swagger-ui.
These are dependency-free collection of HTML, Javascript, and CSS assets that
dynamically generate beautiful documentation and sandbox from a
Swagger-compliant API.
Instructions on how to use these:
https://github.com/swagger-api/swagger-ui#how-to-use-it

Local Modifications

LICENSE file has been created for compliance purposes.
Not included in original distribution.


Overview (`cluster/addons/addon-manager/README.md`)

Addon-manager

addon-manager manages two classes of addons with given template files in
$ADDON_PATH (default /etc/kubernetes/addons/).

  • Addons with label addonmanager.kubernetes.io/mode=Reconcile will be periodically
    reconciled. Direct manipulation to these addons through apiserver is discouraged because
    addon-manager will bring them back to the original state. In particular:
    • Addon will be re-created if it is deleted.
    • Addon will be reconfigured to the state given by the supplied fields in the template
      file periodically.
    • Addon will be deleted when its manifest file is deleted from the $ADDON_PATH.
  • Addons with label addonmanager.kubernetes.io/mode=EnsureExists will be checked for
    existence only. Users can edit these addons as they want. In particular:
    • Addon will only be created/re-created with the given template file when there is no
      instance of the resource with that name.
    • Addon will not be deleted when the manifest file is deleted from the $ADDON_PATH.

Notes:

  • Label kubernetes.io/cluster-service=true is deprecated (only for Addon Manager).
    In future release (after one year), Addon Manager may not respect it anymore. Addons
    have this label but without addonmanager.kubernetes.io/mode=EnsureExists will be
    treated as "reconcile class addons" for now.
  • Resources under $ADDON_PATH need to have either one of these two labels.
    Meanwhile namespaced resources need to be in kube-system namespace.
    Otherwise it will be omitted.
  • The above label and namespace rule does not stand for /opt/namespace.yaml and
    resources under /etc/kubernetes/admission-controls/. addon-manager will attempt to
    create them regardless during startup.

How to release

The addon-manager is built for multiple architectures.

  1. Change something in the source
  2. Bump VERSION in the Makefile
  3. Bump KUBECTL_VERSION in the Makefile if required
  4. Build the amd64 image and test it on a cluster
  5. Push all images
console
# Build for linux/amd64 (default)
$ make push ARCH=amd64
# ---> gcr.io/google-containers/kube-addon-manager-amd64:VERSION
# ---> gcr.io/google-containers/kube-addon-manager:VERSION (image with backwards-compatible naming)

$ make push ARCH=arm
# ---> gcr.io/google-containers/kube-addon-manager-arm:VERSION

$ make push ARCH=arm64
# ---> gcr.io/google-containers/kube-addon-manager-arm64:VERSION

$ make push ARCH=ppc64le
# ---> gcr.io/google-containers/kube-addon-manager-ppc64le:VERSION

$ make push ARCH=s390x
# ---> gcr.io/google-containers/kube-addon-manager-s390x:VERSION

If you don't want to push the images, run make or make build instead


Overview (`cluster/addons/calico-policy-controller/README.md`)

Calico Policy Controller

==============

Calico is an implementation of the Kubernetes network policy API. The provided manifests install:

  • A DaemonSet which runs Calico on each node in the cluster.
  • A Deployment which installs the Calico Typha agent.
  • A Service for the Calico Typha agent.

Learn More

Learn more about Calico at https://docs.projectcalico.org


Overview (`cluster/addons/cluster-monitoring/README.md`)

Kubernetes Monitoring

Heapster enables monitoring and performance analysis in Kubernetes Clusters.
Heapster collects signals from kubelets and the api server, processes them, and exports them via REST APIs or to a configurable timeseries storage backend.

More details can be found in Monitoring user guide.


Overview (`cluster/addons/dashboard/README.md`)

Kubernetes Dashboard

Kubernetes Dashboard is a general purpose, web-based UI for Kubernetes clusters.
It allows users to manage applications running in the cluster, troubleshoot them,
as well as manage the cluster itself.

Learn more at: https://github.com/kubernetes/dashboard


Overview (`cluster/addons/dns-horizontal-autoscaler/README.md`)

DNS Horizontal Autoscaler

DNS Horizontal Autoscaler enables horizontal autoscaling feature for DNS service
in Kubernetes clusters. This autoscaler runs as a Deployment. It collects cluster
status from the APIServer, horizontally scales the number of DNS backends based
on demand. Autoscaling parameters could be tuned by modifying the kube-dns-autoscaler
ConfigMap in kube-system namespace.

Learn more about:


Overview (`cluster/addons/dns/README.md`)

kube-dns

kube-dns schedules DNS Pods and Service on the cluster, other pods in cluster
can use the DNS Service’s IP to resolve DNS names.

Manually scale kube-dns Deployment

kube-dns creates only one DNS Pod by default. If
dns-horizontal-autoscaler
is not enabled, you may need to manually scale kube-dns Deployment.

Please use below kubectl scale command to scale:

text
kubectl --namespace=kube-system scale deployment kube-dns --replicas=<NUM_YOU_WANT>

Do not use kubectl edit to modify kube-dns Deployment object if it is
controlled by Addon Manager. Otherwise the modifications
will be clobbered, in addition the replicas count for kube-dns Deployment will
be reset to 1. See Cluster add-ons README and
#36411 for reference.

kube-dns addon templates

This directory contains the base UNDERSCORE templates that can be used to
generate the kube-dns.yaml.in needed in Salt format.

Due to a varied preference in templating language choices, the transform
Makefile in this directory should be enhanced to generate all required formats
from the base underscore templates.

N.B.: When you add a parameter you should also update the various scripts
that supply values for your new parameter. Here is one way you might find those
scripts:

text
cd kubernetes && git grep 'kube-dns.yaml'

Base Template files

These are the authoritative base templates.
Run 'make' to generate the Salt and Sed yaml templates from these.

text
kube-dns.yaml.base

Generated Salt files

text
kube-dns.yaml.in

Generated Sed files

text
kube-dns.yaml.sed


Overview (`cluster/addons/fluentd-elasticsearch/README.md`)

Elasticsearch Add-On

This add-on consists of a combination of Elasticsearch,
Fluentd and Kibana. Elasticsearch is a search engine
that is responsible for storing our logs and allowing for them to be queried.
Fluentd sends log messages from Kubernetes to Elasticsearch, whereas Kibana
is a graphical interface for viewing and querying the logs stored in
Elasticsearch.

Note: this addon should not be used as-is in production. This is
an example and you should treat it as such. Please see at least the
Security and the Storage sections for more
information.

Elasticsearch

Elasticsearch is deployed as a StatefulSet, which is like
a Deployment, but allows for maintaining state on storage volumes.

Security

Elasticsearch has capabilities to enable authorization using the
X-Pack plugin. See configuration parameter xpack.security.enabled
in Elasticsearch and Kibana configurations. It can also be set via the
XPACK_SECURITY_ENABLED env variable. After enabling the feature,
follow official documentation to set up credentials in
Elasticsearch and Kibana. Don't forget to propagate those credentials also to
Fluentd in its configuration, using for example
environment variables. You can utilize ConfigMaps
and Secrets to store credentials in the Kubernetes apiserver.

Initialization

The Elasticsearch StatefulSet manifest specifies that there shall be an
init container executing before Elasticsearch containers
themselves, in order to ensure that the kernel state variable
vm.max_map_count is at least 262144, since this is a requirement of
Elasticsearch. You may remove the init container if you know that your host
OS meets this requirement.

Storage

The Elasticsearch StatefulSet will use the EmptyDir volume to
store data. EmptyDir is erased when the pod terminates, here it is used only
for testing purposes. Important: please change the storage to persistent
volume claim before actually using this StatefulSet in your setup!

Fluentd

Fluentd is deployed as a DaemonSet which spawns a pod on each
node that reads logs, generated by kubelet, container runtime and containers
and sends them to Elasticsearch.

Note: in order for Fluentd to work, every Kubernetes node must be labeled
with beta.kubernetes.io/fluentd-ds-ready=true, as otherwise the Fluentd
DaemonSet will ignore them.

Learn more in the official Kubernetes documentation.

Known problems

Since Fluentd talks to the Elasticsearch service inside the cluster, instances
on masters won't work, because masters have no kube-proxy. Don't mark masters
with the label mentioned in the previous paragraph or add a taint on them to
avoid Fluentd pods scheduling there.


Overview (`cluster/addons/fluentd-gcp/README.md`)

Stackdriver Logging Agent

==============

Stackdriver Logging Agent is a DaemonSet which spawns a pod on each node
that reads logs, generated by kubelet, container runtime and containers
and sends them to the Stackdriver. When logs are exported to the Stackdriver,
they can be searched, viewed, and analyzed.

Learn more at: https://kubernetes.io/docs/tasks/debug-application-cluster/logging-stackdriver


Overview (`cluster/addons/metadata-agent/README.md`)

Kubernetes Metadata Agent

Metadata Agent is a source of metadata required by logging and monitoring agents
running on a cluster.


Overview (`cluster/addons/metadata-proxy/README.md`)

Metadata proxy

==============

This metadata proxy returns a 403 for kubelet's kube-env data, but otherwise allows
pods access to the metadata server.


Overview (`cluster/addons/node-problem-detector/README.md`)

Node Problem Detector

==============

Node Problem Detector is a DaemonSet running on each node, detecting node
problems.

Learn more at: https://github.com/kubernetes/node-problem-detector


Overview (`cluster/addons/python-image/README.md`)

Python image

The python image here is used by OS distros that don't have python installed to
run python scripts to parse the yaml files in the addon updater script.


Overview (`cluster/addons/registry/README.md`)

Private Docker Registry in Kubernetes

Kubernetes offers an optional private Docker registry addon, which you can turn
on when you bring up a cluster or install later. This gives you a place to
store truly private Docker images for your cluster.

How it works

The private registry runs as a Pod in your cluster. It does not currently
support SSL or authentication, which triggers Docker's "insecure registry"
logic. To work around this, we run a proxy on each node in the cluster,
exposing a port onto the node (via a hostPort), which Docker accepts as
"secure", since it is accessed by localhost.

Turning it on

Some cluster installs (e.g. GCE) support this as a cluster-birth flag. The
ENABLE_CLUSTER_REGISTRY variable in cluster/gce/config-default.sh governs
whether the registry is run or not. To set this flag, you can specify
KUBE_ENABLE_CLUSTER_REGISTRY=true when running kube-up.sh. If your cluster
does not include this flag, the following steps should work. Note that some of
this is cloud-provider specific, so you may have to customize it a bit.

Make some storage

The primary job of the registry is to store data. To do that we have to decide
where to store it. For cloud environments that have networked storage, we can
use Kubernetes's PersistentVolume abstraction. The following template is
expanded by salt in the GCE cluster turnup, but can easily be adapted to
other situations:

yaml
kind: PersistentVolume
apiVersion: v1
metadata:
  name: kube-system-kube-registry-pv
  labels:
    kubernetes.io/cluster-service: "true"
spec:
{% if pillar.get('cluster_registry_disk_type', '') == 'gce' %}
  capacity:
    storage: {{ pillar['cluster_registry_disk_size'] }}
  accessModes:
    - ReadWriteOnce
  gcePersistentDisk:
    pdName: "{{ pillar['cluster_registry_disk_name'] }}"
    fsType: "ext4"
{% endif %}

If, for example, you wanted to use NFS you would just need to change the
gcePersistentDisk block to nfs. See
here for more details on volumes.

Note that in any case, the storage (in the case the GCE PersistentDisk) must be
created independently - this is not something Kubernetes manages for you (yet).

I don't want or don't have persistent storage

If you are running in a place that doesn't have networked storage, or if you
just want to kick the tires on this without committing to it, you can easily
adapt the ReplicationController specification below to use a simple
emptyDir volume instead of a persistentVolumeClaim.

Claim the storage

Now that the Kubernetes cluster knows that some storage exists, you can put a
claim on that storage. As with the PersistentVolume above, you can start
with the salt template:

yaml
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: kube-registry-pvc
  namespace: kube-system
  labels:
    kubernetes.io/cluster-service: "true"
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: {{ pillar['cluster_registry_disk_size'] }}

This tells Kubernetes that you want to use storage, and the PersistentVolume
you created before will be bound to this claim (unless you have other
PersistentVolumes in which case those might get bound instead). This claim
gives you the right to use this storage until you release the claim.

Run the registry

Now we can run a Docker registry:

yaml
apiVersion: v1
kind: ReplicationController
metadata:
  name: kube-registry-v0
  namespace: kube-system
  labels:
    k8s-app: kube-registry-upstream
    version: v0
    kubernetes.io/cluster-service: "true"
spec:
  replicas: 1
  selector:
    k8s-app: kube-registry-upstream
    version: v0
  template:
    metadata:
      labels:
        k8s-app: kube-registry-upstream
        version: v0
        kubernetes.io/cluster-service: "true"
    spec:
      containers:
      - name: registry
        image: registry:2
        resources:
          limits:
            cpu: 100m
            memory: 100Mi
        env:
        - name: REGISTRY_HTTP_ADDR
          value: :5000
        - name: REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY
          value: /var/lib/registry
        volumeMounts:
        - name: image-store
          mountPath: /var/lib/registry
        ports:
        - containerPort: 5000
          name: registry
          protocol: TCP
      volumes:
      - name: image-store
        persistentVolumeClaim:
          claimName: kube-registry-pvc

Expose the registry in the cluster

Now that we have a registry Pod running, we can expose it as a Service:

yaml
apiVersion: v1
kind: Service
metadata:
  name: kube-registry
  namespace: kube-system
  labels:
    k8s-app: kube-registry-upstream
    kubernetes.io/cluster-service: "true"
    kubernetes.io/name: "KubeRegistry"
spec:
  selector:
    k8s-app: kube-registry-upstream
  ports:
  - name: registry
    port: 5000
    protocol: TCP

Expose the registry on each node

Now that we have a running Service, we need to expose it onto each Kubernetes
Node so that Docker will see it as localhost. We can load a Pod on every
node by creating following daemonset.

yaml
apiVersion: extensions/v1beta1
kind: DaemonSet
metadata:
  name: kube-registry-proxy
  namespace: kube-system
  labels:
    k8s-app: kube-registry-proxy
    kubernetes.io/cluster-service: "true"
    version: v0.4
spec:
  template:
    metadata:
      labels:
        k8s-app: kube-registry-proxy
        kubernetes.io/name: "kube-registry-proxy"
        kubernetes.io/cluster-service: "true"
        version: v0.4
    spec:
      containers:
      - name: kube-registry-proxy
        image: gcr.io/google_containers/kube-registry-proxy:0.4
        resources:
          limits:
            cpu: 100m
            memory: 50Mi
        env:
        - name: REGISTRY_HOST
          value: kube-registry.kube-system.svc.cluster.local
        - name: REGISTRY_PORT
          value: "5000"
        ports:
        - name: registry
          containerPort: 80
          hostPort: 5000

When modifying replication-controller, service and daemon-set defintions, take
care to ensure unique identifiers for the rc-svc couple and the daemon-set.
Failing to do so will have register the localhost proxy daemon-sets to the
upstream service. As a result they will then try to proxy themselves, which
will, for obvious reasons, not work.

This ensures that port 5000 on each node is directed to the registry Service.
You should be able to verify that it is running by hitting port 5000 with a web
browser and getting a 404 error:

console
$ curl localhost:5000
404 page not found

Using the registry

To use an image hosted by this registry, simply say this in your Pod's
spec.containers[].image field:

yaml
image: localhost:5000/user/container

Before you can use the registry, you have to be able to get images into it,
though. If you are building an image on your Kubernetes Node, you can spell
out localhost:5000 when you build and push. More likely, though, you are
building locally and want to push to your cluster.

You can use kubectl to set up a port-forward from your local node to a
running Pod:

console
$ POD=$(kubectl get pods --namespace kube-system -l k8s-app=kube-registry-upstream \
            -o template --template '{{range .items}}{{.metadata.name}} {{.status.phase}}{{"\n"}}{{end}}' \
            | grep Running | head -1 | cut -f1 -d' ')

$ kubectl port-forward --namespace kube-system $POD 5000:5000 &

Now you can build and push images on your local computer as
localhost:5000/yourname/container and those images will be available inside
your kubernetes cluster with the same name.

More Extensions

Future improvements

  • Allow port-forwarding to a Service rather than a pod (#15180)


Overview (`cluster/gce/addons/README.md`)

GCE Cluster addons

These cluster add-ons are specific to GCE and GKE clusters. The GCE-specific addon directory is
merged with the general cluster addon directory at release, so addon paths (relative to the addon
directory) must be unique across the 2 directory structures.

More details on addons in general can be found here.


Overview (`cluster/gce/container-linux/README.md`)

Container Linux image

The Container Linux Operating System is a Linux distribution optimized for running containers securely at scale.
CoreOS provides a Container Linux image for Google Cloud Platform (GCP).

This folder contains configuration and tooling to allow kube-up to create a Kubernetes cluster on Google Cloud Platform running on the official Container Linux image.


Overview (`cluster/gce/gci/README.md`)

Container-VM Image

Container-VM Image
is a container-optimized OS image for the Google Cloud Platform (GCP). It is
primarily for running Google services on GCP. Unlike the open preview version
of container-vm, the new Container-VM Image is based on the open source
ChromiumOS project, allowing us greater control over the build management,
security compliance, and customizations for GCP.


Overview (`cluster/images/etcd-version-monitor/README.md`)

etcd-version-monitor

This is a tool for exporting etcd metrics and supplementing them with etcd
server binary version and cluster version. These metrics are in
prometheus format and can be scraped by a prometheus server.
The metrics are exposed at the http://localhost:9101/metrics endpoint.

For etcd 3.1+, the
go-grpc-prometheus
metrics format, which backward incompatibly replaces the 3.0 legacy grpc metric
format, is exposed in both the 3.1 format and in the 3.0. This preserves
backward compatiblity.

For etcd 3.1+, the --metrics=extensive must be set on etcd for grpc request
latency metrics (etcd_grpc_unary_requests_duration_seconds) to be exposed.

RUNNING THE TOOL

To run this tool as a docker container:

  • make build
  • docker run --net=host -i -t gcr.io/google_containers/etcd-version-monitor:test /etcd-version-monitor --logtostderr

To run this as a pod on the kubernetes cluster:

  • Place the 'etcd-version-monitor.yaml' in the manifests directory of
    kubelet on the master machine.

Note: This tool has to run on the same machine as etcd, as communication
with etcd is over localhost.

VERIFYING THE TOOL


Overview (`cluster/images/etcd/README.md`)

etcd

This is a small etcd image used in Kubernetes setups where etcd is deployed as a docker image.

For amd64, official etcd and etcdctl binaries are downloaded from Github to maintain official support.
For other architectures, etcd is cross-compiled from source. Arch-specific busybox images serve as base images.

How to release

console
# Build for linux/amd64 (default)
$ make push ARCH=amd64
# ---> gcr.io/google_containers/etcd-amd64:TAG
# ---> gcr.io/google_containers/etcd:TAG

$ make push ARCH=arm
# ---> gcr.io/google_containers/etcd-arm:TAG

$ make push ARCH=arm64
# ---> gcr.io/google_containers/etcd-arm64:TAG

$ make push ARCH=ppc64le
# ---> gcr.io/google_containers/etcd-ppc64le:TAG

$ make push ARCH=s390x
# ---> gcr.io/google_containers/etcd-s390x:TAG

If you don't want to push the images, run make or make build instead


Overview (`cluster/images/hyperkube/README.md`)

hyperkube

hyperkube is an all-in-one binary for the Kubernetes server components
hyperkube is built for multiple architectures and the image is pushed automatically on every release.

How to release by hand

console
# First, build the binaries
$ build/run.sh make cross

# Build for linux/amd64 (default)
# export REGISTRY=$HOST/$ORG to switch from gcr.io/google_containers

$ make push VERSION={target_version} ARCH=amd64
# ---> gcr.io/google_containers/hyperkube-amd64:VERSION
# ---> gcr.io/google_containers/hyperkube:VERSION (image with backwards-compatible naming)

$ make push VERSION={target_version} ARCH=arm
# ---> gcr.io/google_containers/hyperkube-arm:VERSION

$ make push VERSION={target_version} ARCH=arm64
# ---> gcr.io/google_containers/hyperkube-arm64:VERSION

$ make push VERSION={target_version} ARCH=ppc64le
# ---> gcr.io/google_containers/hyperkube-ppc64le:VERSION

$ make push VERSION={target_version} ARCH=s390x
# ---> gcr.io/google_containers/hyperkube-s390x:VERSION

If you don't want to push the images, run make or make build instead


Overview (`cluster/juju/bundles/README.md`)

kubernetes-bundle

The kubernetes-bundle allows you to deploy the many services of
Kubernetes to a cloud environment and get started using the Kubernetes
technology quickly.

Kubernetes

Kubernetes is an open source system for managing containerized
applications. Kubernetes uses Docker to run
containerized applications.

Juju TL;DR

The Juju system provides provisioning and
orchestration across a variety of clouds and bare metal. A juju bundle
describes collection of services and how they interrelate. juju quickstart allows you to bootstrap a deployment environment and
deploy a bundle.

Dive in!

Install Juju Quickstart

You will need to
install the Juju client and
juju-quickstart as prerequisites. To deploy the bundle use
juju-quickstart which runs on Mac OS (brew install juju-quickstart) or Ubuntu (apt-get install juju-quickstart).

Deploy a Kubernetes Bundle

Use the 'juju quickstart' command to deploy a Kubernetes cluster to any cloud
supported by Juju.

The charm store version of the Kubernetes bundle can be deployed as follows:

text
juju quickstart u/kubernetes/kubernetes-cluster

Note: The charm store bundle may be locked to a specific Kubernetes release.

Alternately you could deploy a Kubernetes bundle straight from github or a file:

text
juju quickstart -i https://raw.githubusercontent.com/whitmo/bundle-kubernetes/master/bundles.yaml

The command above does few things for you:

  • Starts a curses based gui for managing your cloud or MAAS credentials
  • Looks for a bootstrapped deployment environment, and bootstraps if
    required. This will launch a bootstrap node in your chosen
    deployment environment (machine 0).
  • Deploys the Juju GUI to your environment onto the bootstrap node.
  • Provisions 4 machines, and deploys the Kubernetes services on top of
    them (Kubernetes-master, two Kubernetes nodes using flannel, and etcd).
  • Orchestrates the relations among the services, and exits.

Now you should have a running Kubernetes. Run juju status --format=oneline to see the address of your kubernetes-master unit.

For further reading on Juju Quickstart

Go to the Getting started with Juju guide
for more information about deploying a development Kubernetes cluster.

Using the Kubernetes Client

You'll need the Kubernetes command line client,
kubectl
to interact with the created cluster. The kubectl command is
installed on the kubernetes-master charm. If you want to work with
the cluster from your computer you will need to install the binary
locally.

You can access kubectl by a number ways using juju.

via juju run:

text
juju run --service kubernetes-master/0 "sudo kubectl get nodes"

via juju ssh:

text
juju ssh kubernetes-master/0 -t "sudo kubectl get nodes"

You may also SSH to the kubernetes-master unit (juju ssh kubernetes-master/0)
and call kubectl from the command prompt.

See the
kubectl documentation
for more details of what can be done with the command line tool.

Scaling up the cluster

You can add capacity by adding more Docker units:

text
juju add-unit docker

Known Limitations

Kubernetes currently has several platform specific functionality. For
example load balancers and persistence volumes only work with the
Google Compute provider at this time.

The Juju integration uses the Kubernetes null provider. This means
external load balancers and storage can't be directly driven through
Kubernetes config files at this time. We look forward to adding these
capabilities to the charms.

More about the components the bundle deploys

Kubernetes master

The master controls the Kubernetes cluster. It manages for the worker
nodes and provides the primary interface for control by the user.

Kubernetes node

The nodes are the servers that perform the work. Nodes must
communicate with the master and run the workloads that are assigned to
them.

Flannel-docker

Flannel provides individual subnets for each machine in the cluster by
creating a
software defined networking.

Docker

An open platform for distributed applications for developers and sysadmins.

Etcd

Etcd persists state for Flannel and Kubernetes. It is a distributed
key-value store with an http interface.

For further information on getting started with Juju

Juju has complete documentation with regard to setup, and cloud
configuration on it's own
documentation site.

Installing the kubectl outside of kubernetes-master unit

Download the Kubernetes release from:
https://github.com/kubernetes/kubernetes/releases and extract
the release, you can then just directly use the cli binary at
./kubernetes/platforms/linux/amd64/kubectl

You'll need the address of the kubernetes-master as environment variable :

text
juju status kubernetes-master/0

Grab the public-address there and export it as KUBERNETES_MASTER
environment variable :

text
export KUBERNETES_MASTER=$(juju status --format=oneline kubernetes-master | grep kubernetes-master | cut -d' ' -f3):8080

And now you can run kubectl on the command line :

text
kubectl get no

See the
kubectl documentation
for more details of what can be done with the command line tool.

Hacking on the kubernetes-bundle and associated charms

The kubernetes-bundle is open source and available on github.com. If
you want to get started developing on the bundle you can clone it from
github.

text
git clone https://github.com/kubernetes/kubernetes.git

Go to the Getting started with Juju guide
for more information about the bundle or charms.

How to contribute

Send us pull requests! We'll send you a cookie if they include tests and docs.

Current and Most Complete Information

The charms and bundles are in the kubernetes
repository in github.

More information about the
Kubernetes project
or check out the
Kubernetes Documentation
for more details about the Kubernetes concepts and terminology.

Having a problem? Check the Kubernetes issues database
for related issues.


Overview (`cluster/saltbase/pillar/README.md`)

The
SaltStack pillar
data is partially statically derived from the contents of this
directory. The bulk of the pillars are hard to perceive from browsing
this directory, though, because they are written into
cluster-params.sls at cluster inception.

  • cluster-params.sls is generated entirely at cluster inception. See e.g. configure-vm.sh
  • docker-images.sls stores the Docker tags of the current Docker-wrapped server binaries, twiddling by the Salt install script
  • logging.sls defines the cluster log level
  • mine.sls: defines the variables shared across machines in the Salt
    mine. It is starting to be largely deprecated in use, and is totally
    unavailable on GCE, which runs standalone.
  • privilege.sls defines whether privileged containers are allowed.
  • top.sls defines which pillars are active across the cluster.

Future work

Document the current pillars across providers


Overview (`cluster/saltbase/reactor/README.md`)

SaltStack reactor files, largely defining reactions to new nodes.

Ignored for GCE, which runs standalone on each machine


Overview (`cluster/saltbase/salt/README.md`)

This directory forms the base of the main SaltStack configuration. The
place to start with any SaltStack configuration is
top.sls. However, unless you are particularly keen on
reading Jinja templates, the following tables break down what
configurations run on what providers. (NB: The _states
directory is a special directory included by Salt for ensure blocks,
and is only used for the docker config.)

Key: M = Config applies to master, n = config applies to nodes

Config GCE Vagrant AWS Azure
debian-auto-upgrades M n M n M n M n
docker M n M n M n M n
etcd M M M M
generate-cert M M M M
kube-addons M M M M
kube-apiserver M M M M
kube-controller-manager M M M M
kube-proxy n n n n
kube-scheduler M M M M
kubelet M n M n M n M n
logrotate M n n M n M n
supervisord M n M n M n M n
base M n M n M n M n
kube-client-tools M M M M


Overview (`examples/elasticsearch/production_cluster/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/elasticsearch/production_cluster/README.md


Overview (`examples/job/expansions/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/job/expansions/README.md


Overview (`examples/job/work-queue-1/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/job/work-queue-1/README.md


Overview (`examples/job/work-queue-2/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/job/work-queue-2/README.md


Overview (`examples/meteor/dockerbase/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/meteor/dockerbase/README.md


Overview (`examples/podsecuritypolicy/rbac/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/podsecuritypolicy/rbac/README.md


Overview (`examples/spark/spark-gluster/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/spark/spark-gluster/README.md


Overview (`examples/storage/cassandra/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/cassandra/README.md


Overview (`examples/storage/hazelcast/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/storage/hazelcast/README.md


Overview (`examples/storage/minio/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/storage/minio/README.md


Overview (`examples/storage/mysql-galera/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/storage/mysql-galera/README.md


Overview (`examples/storage/redis/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/storage/redis/README.md


Overview (`examples/storage/rethinkdb/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/storage/rethinkdb/README.md


Overview (`examples/storage/vitess/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/storage/vitess/README.md


Overview (`examples/volumes/aws_ebs/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/volumes/aws_ebs/README.md


Overview (`examples/volumes/azure_disk/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/volumes/azure_disk/README.md


Overview (`examples/volumes/azure_file/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/volumes/azure_file/README.md


Overview (`examples/volumes/cephfs/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/volumes/cephfs/README.md


Overview (`examples/volumes/cinder/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/volumes/cinder/README.md


Overview (`examples/volumes/fibre_channel/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/volumes/fibre_channel/README.md


Overview (`examples/volumes/flexvolume/README.md`)

This file has moved to https://github.com/kubernetes/community/blob/master/contributors/devel/flexvolume.md


Overview (`examples/volumes/flocker/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/volumes/flocker/README.md


Overview (`examples/volumes/glusterfs/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/volumes/glusterfs/README.md


Overview (`examples/volumes/iscsi/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/volumes/iscsi/README.md


Overview (`examples/volumes/nfs/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/volumes/nfs/README.md


Overview (`examples/volumes/portworx/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/volumes/portworx/README.md


Overview (`examples/volumes/quobyte/Readme.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/volumes/quobyte/Readme.md


Overview (`examples/volumes/rbd/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/volumes/rbd/README.md


Overview (`examples/volumes/scaleio/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/volumes/scaleio/README.md


Overview (`examples/volumes/storageos/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/volumes/storageos/README.md


Overview (`examples/volumes/vsphere/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/volumes/vsphere/README.md


Overview (`pkg/proxy/ipvs/README.md`)

How to use IPVS

This document shows how to use kube-proxy ipvs mode.

What is IPVS

IPVS (IP Virtual Server) implements transport-layer load balancing, usually called Layer 4 LAN switching, as part of
Linux kernel.

IPVS runs on a host and acts as a load balancer in front of a cluster of real servers. IPVS can direct requests for TCP
and UDP-based services to the real servers, and make services of real servers appear as virtual services on a single IP address.

Run kube-proxy in ipvs mode

Currently, local-up scripts and kubeadm support switching IPVS proxy mode via exporting environment variables or specifying flags.

Local UP Cluster

Kube-proxy will run in iptables mode by default in a local-up cluster.

Users should export the env KUBEPROXY_MODE=ipvs to specify the ipvs mode before deploying the cluster if want to run kube-proxy in ipvs mode.

Cluster Created by Kubeadm

Kube-proxy will run in iptables mode by default in a cluster deployed by kubeadm.

Since IPVS mode is still feature-gated, users should add the flag --feature-gates=SupportIPVSProxyMode=true in kubeadm init command

text
kubeadm init --feature-gates=SupportIPVSProxyMode=true

to specify the ipvs mode before deploying the cluster if want to run kube-proxy in ipvs mode.

If you are using kubeadm with a configuration file, you can specify the ipvs mode adding SupportIPVSProxyMode: true below the featureGates field.
Then the configuration file is similar to:

json
kind: MasterConfiguration
apiVersion: kubeadm.k8s.io/v1alpha1
...
featureGates:
  SupportIPVSProxyMode: true
mode: ipvs

Debug

Check IPVS proxy rules

People can use ipvsadm tool to check whether kube-proxy are maintaining IPVS rules correctly. For example, we may get IPVS proxy rules like:

shell
# ipvsadm -ln
IP Virtual Server version 1.2.1 (size=4096)
Prot LocalAddress:Port Scheduler Flags
  -> RemoteAddress:Port           Forward Weight ActiveConn InActConn
TCP  10.0.0.1:443 rr persistent 10800
  -> 10.229.43.2:6443             Masq    1      0          0         
TCP  10.0.0.10:53 rr      
UDP  10.0.0.10:53 rr

Why kube-proxy can't start IPVS mode

People can do the following check list step by step:

1. Enable IPVS feature gateway

Currently IPVS-based kube-proxy is still in alpha phase, people need to enable --feature-gates=SupportIPVSProxyMode=true explicitly.

2. Specify proxy-mode=ipvs

Tell kube-proxy that proxy-mode=ipvs, please.

3. Load ipvs required kernel modules

The following kernel modules are required by IPVS-based kube-proxy:

shell
ip_vs
ip_vs_rr
ip_vs_wrr
ip_vs_sh
nf_conntrack_ipv4

IPVS-based kube-proxy will load them automatically. If it fails to load them, please check whether they are compiled into your kernel.


Overview (`test/e2e_node/jenkins/README.md`)

Node e2e job migration notice:

Sig-testing is actively migrating node e2e jobs from Jenkins to Prow,
and we are moving *.property and image-config.yaml files to test-infra

If you want to update those files, please also update them in test-infra.

If you have any questions, please contact @krzyzacy or #sig-testing.

Here's where the existing node e2e job config live:

Image config files

Node test job args (.properties equivalent)


Overview (`test/images/cuda-vector-add/README.md`)

cuda_vector_add

This is a small CUDA application that performs a simple vector addition. Useful for testing CUDA support in Kubernetes.

How to release:

text
# Build
$ make

# Push
$ make push

Overview (`test/images/iperf/README.md`)

This is a dockerfile which we curate inside of kubernetes for running iperf as a service.

Eventually we would like to update it to iperf3.

Possibly we might even start using a pure go based iperf and maintain the same cmd line abstraction.


Overview (`test/images/logs-generator/README.md`)

Logs Generator

Overview

Logs generator is a tool to create predictable load on the logs delivery system.
Is generates random lines with predictable format and predictable average length.
Each line can be later uniquely identified to ensure logs delivery.

Usage

Tool is parametrized with the total number of number that should be generated and the duration of
the generation process. For example, if you want to create a throughput of 100 lines per second
for a minute, you set total number of lines to 6000 and duration to 1 minute.

Parameters are passed through environment variables. There are no defaults, you should always
set up container parameters. Total number of line is parametrized through env variable
LOGS_GENERATOR_LINES_TOTAL and duration in go format is parametrized through env variable
LOGS_GENERATOR_DURATION.

Inside the container all log lines are written to the stdout.

Each line is on average 100 bytes long and follows this pattern:

text
2000-12-31T12:59:59Z <id> <method> /api/v1/namespaces/<namespace>/endpoints/<random_string> <random_number>

Where `` refers to the number from 0 to total_lines - 1, which is unique for each
line in a given run of the container.

Image

Image is located in the public repository of Google Container Registry under the name

text
gcr.io/google_containers/logs-generator:v0.1.1

Examples

text
docker run -i \
  -e "LOGS_GENERATOR_LINES_TOTAL=10" \
  -e "LOGS_GENERATOR_DURATION=1s" \
  gcr.io/google_containers/logs-generator:v0.1.1
text
kubectl run logs-generator \
  --generator=run-pod/v1 \
  --image=gcr.io/google_containers/logs-generator:v0.1.1 \
  --restart=Never \
  --env "LOGS_GENERATOR_LINES_TOTAL=1000" \
  --env "LOGS_GENERATOR_DURATION=1m"


Overview (`test/images/net/README.md`)

Overview

The goal of this Go project is to consolidate all low-level
network testing "daemons" into one place. In network testing we
frequently have need of simple daemons (common/Runner) that perform
some "trivial" set of actions on a socket.

Usage

  • A package for each general area that is being tested, for example
    nat/ will contain Runners that test various NAT features.
  • Every runner should be registered via main.go:makeRunnerMap().
  • Runners receive a JSON options structure as to their configuration. Run()
    should return the disposition of the test.

Runners can be executed into two different ways, either through the
the command-line or via an HTTP request:

Command-line

text
$ ./net -runner <runner> -options <json>
./net \
  -runner nat-closewait-client \
  -options '{"RemoteAddr":"127.0.0.1:9999"}'

HTTP server

text
$ ./net --serve :8889
$ curl -v -X POST localhost:8889/run/nat-closewait-server \
  -d '{"LocalAddr":"127.0.0.1:9999"}'


Overview (`test/images/porter/README.md`)

This directory contains go source, Dockerfile and Makefile for making a test
container which serves requested data on ports specified in ENV variables.

The included localhost.crt is a PEM-encoded TLS cert with SAN IPs
"127.0.0.1" and "[::1]", expiring in January 2084, generated from
src/crypto/tls:
go run generate_cert.go --rsa-bits 2048 --host 127.0.0.1,::1,example.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h

To use a different cert/key, mount them into the pod and set the
CERT_FILE and KEY_FILE environment variables to the desired paths.


Overview (`test/images/resource-consumer/README.md`)

Resource Consumer

Overview

Resource Consumer is a tool which allows to generate cpu/memory utilization in a container.
The reason why it was created is testing kubernetes autoscaling.
Resource Consumer can help with autoscaling tests for:

  • cluster size autoscaling,
  • horizontal autoscaling of pod - changing the size of replication controller,
  • vertical autoscaling of pod - changing its resource limits.

Usage

Resource Consumer starts an HTTP server and handle sent requests.
It listens on port given as a flag (default 8080).
Action of consuming resources is send to the container by a POST http request.
Each http request creates new process.
Http request handler is in file resource_consumer_handler.go

The container consumes specified amount of resources:

  • CPU in millicores,
  • Memory in megabytes,
  • Fake custom metrics.

###Consume CPU http request

  • suffix "ConsumeCPU",
  • parameters "millicores" and "durationSec".

Consumes specified amount of millicores for durationSec seconds.
Consume CPU uses "./consume-cpu/consume-cpu" binary (file consume-cpu/consume_cpu.go).
When CPU consumption is too low this binary uses cpu by calculating math.sqrt(0) 10^7 times
and if consumption is too high binary sleeps for 10 millisecond.
One replica of Resource Consumer cannot consume more that 1 cpu.

###Consume Memory http request

  • suffix "ConsumeMem",
  • parameters "megabytes" and "durationSec".

Consumes specified amount of megabytes for durationSec seconds.
Consume Memory uses stress tool (stress -m 1 --vm-bytes megabytes --vm-hang 0 -t durationSec).
Request leading to consuming more memory then container limit will be ignored.

###Bump value of a fake custom metric

  • suffix "BumpMetric",
  • parameters "metric", "delta" and "durationSec".

Bumps metric with given name by delta for durationSec seconds.
Custom metrics in Prometheus format are exposed on "/metrics" endpoint.

###CURL example

console
$ kubectl run resource-consumer --image=gcr.io/google_containers/resource_consumer:beta --expose --service-overrides='{ "spec": { "type": "LoadBalancer" } }' --port 8080
$ kubectl get services resource-consumer

There are two IPs. The first one is internal, while the second one is the external load-balanced IP. Both serve port 8080. (Use second one)

console
$ curl --data "millicores=300&durationSec=600" http://<EXTERNAL-IP>:8080/ConsumeCPU

300 millicores will be consumed for 600 seconds.

Image

Docker image of Resource Consumer can be found in Google Container Registry as gcr.io/google_containers/resource_consumer:beta

Use cases

###Cluster size autoscaling

  1. Consume more resources on each node that is specified for autoscaler
  2. Observe that cluster size increased

###Horizontal autoscaling of pod

  1. Create consuming RC and start consuming appropriate amount of resources
  2. Observe that RC has been resized
  3. Observe that usage on each replica decreased

###Vertical autoscaling of pod

  1. Create consuming pod and start consuming appropriate amount of resources
  2. Observed that limits has been increased


Overview (`test/images/serve-hostname/README.md`)

serve_hostname

This is a small util app to serve your hostname on TCP and/or UDP. Useful for testing.

The serve_hostname Makefile supports multiple architectures, which means it may cross-compile and build an docker image easily.
Arch-specific busybox images serve as base images.

If you are releasing a new version, please bump the TAG value in the Makefile before building the images.

How to release:

text
# Build cross-platform binaries
$ make all-push

# Build for linux/amd64 (default)
$ make push ARCH=amd64
# ---> gcr.io/google_containers/serve_hostname-amd64:TAG

$ make push ARCH=arm
# ---> gcr.io/google_containers/serve_hostname-arm:TAG

$ make push ARCH=arm64
# ---> gcr.io/google_containers/serve_hostname-arm64:TAG

$ make push ARCH=ppc64le
# ---> gcr.io/google_containers/serve_hostname-ppc64le:TAG

$ make push ARCH=s390x
# ---> gcr.io/google_containers/serve_hostname-s390x:TAG

Of course, if you don't want to push the images, run make all-container or make container ARCH={target_arch} instead.


Overview (`test/images/webhook/README.md`)

Kubernetes External Admission Webhook Example

The example shows how to build and deploy an external webhook that only admits
pods creation and update if the container images have the "grc.io" prefix.

Prerequisites

Please use a Kubernetes release at least as new as v1.8.0 or v1.9.0-alpha.1,
because the generated server cert/key only works with Kubernetes release that
contains this change.
Please checkout the pre-v1.8 tag for an example that works with older
clusters.

Please enable the admission webhook feature
(doc).

Build the code

bash
make build

Deploy the code

bash
make deploy-only

The Makefile assumes your cluster is created by the
hack/local-up-cluster.sh.
Please modify the Makefile accordingly if your cluster is created differently.

Explanation on the CAs/Certs/Keys

The apiserver initiates a tls connection with the webhook, so the apiserver is
the tls client, and the webhook is the tls server.

The webhook proves its identity by the serverCert in the certs.go. The server
cert is signed by the CA in certs.go. To let the apiserver trust the caCert,
the webhook registers itself with the apiserver via the
admissionregistration/v1beta1/externalAdmissionHook API, with
clientConfig.caBundle=caCert.

For maximum protection, this example webhook requires and verifies the client
(i.e., the apiserver in this case) cert. The cert presented by the apiserver is
signed by a client CA, whose cert is stored in the configmap
extension-apiserver-authentication in the kube-system namespace. See the
getAPIServerCert function for more information. Usually you don't need to
worry about setting up this CA cert. It's taken care of when the cluster is
created. You can disable the client cert verification by setting the
tls.Config.ClientAuth to tls.NoClientCert in config.go.


Overview (`test/integration/scheduler_perf/README.md`)

Scheduler Performance Test

Motivation

We already have a performance testing system -- Kubemark. However, Kubemark requires setting up and bootstrapping a whole cluster, which takes a lot of time.

We want to have a standard way to reproduce scheduling latency metrics result and benchmark scheduler as simple and fast as possible. We have the following goals:

  • Save time on testing
    • The test and benchmark can be run in a single box.
      We only set up components necessary to scheduling without booting up a cluster.
  • Profiling runtime metrics to find out bottleneck
    • Write scheduler integration test but focus on performance measurement.
      Take advantage of go profiling tools and collect fine-grained metrics,
      like cpu-profiling, memory-profiling and block-profiling.
  • Reproduce test result easily
    • We want to have a known place to do the performance related test for scheduler.
      Developers should just run one script to collect all the information they need.

Currently the test suite has the following:

  • density test (by adding a new Go test)
    • schedule 30k pods on 1000 (fake) nodes and 3k pods on 100 (fake) nodes
    • print out scheduling rate every second
    • let you learn the rate changes vs number of scheduled pods
  • benchmark
    • make use of go test -bench and report nanosecond/op.
    • schedule b.N pods when the cluster has N nodes and P scheduled pods. Since it takes relatively long time to finish one round, b.N is small: 10 - 100.

How To Run

shell
# In Kubernetes root path
make generated_files

cd test/integration/scheduler_perf
./test-performance.sh


Overview (`test/kubemark/pre-existing/README.md`)

Kubemark Pre-existing Provider Guide

Kubemark Master

  • A set of Kubernetes control plane components running in a VM

Kubernetes Cluster

  • A real Kubernetes Cluster that has master and nodes. The hollow-node pods
    are run in this cluster, but appear as nodes to the Kubemark Master

Introduction

Every running Kubemark setup looks like the following:

  1. A running Kubernetes cluster pointed to by the local kubeconfig
  2. A separate VM where the kubemark master is running
  3. Some hollow-nodes that run on the Kubernetes Cluster from #1
  4. The hollow-nodes are configured to talk with the kubemark master at #2

When using the pre-existing provider, the developer is responsible for creating
#1 and #2. Therefore, the kubemark scripts will not create any infrastructure
or start a kubemark master like in other providers. Instead, the existing
resources provided by the VM at $MASTER_IP will serve as the kubemark master.

Use Case

The goal of the pre-existing provider is to use the kubemark tools with an
existing kubermark master. It's meant to provide the developer with
additional flexibility to customize the cluster infrastructure and still use
the kubemark setup tools. The pre-existing provider is an advanced use
case that requires the developer to have knowledge of setting up a kubemark
master.

Requirements

To use the pre-existing provider, the expectation is that there's a kubemark
master that is rechable at $MASTER_IP. The machine that the kubemark master is
on has to be ssh able from the host that's executing the kubemark scripts. And
the user on that machine has to be 'kubernetes'.

Requirement checklist:

  • Set MASTER_IP to ip address to the kubemark master
  • The host where you execute the kubemark scripts must be able to ssh to
    kubernetes@$MASTER_IP

Example Configuration

test/kubemark/cloud-provider-config.sh

text
CLOUD_PROVIDER="pre-existing"
KUBEMARK_IMAGE_MAKE_TARGET="push"
CONTAINER_REGISTRY=docker.io
PROJECT="rthallisey"
MASTER_IP="192.168.121.29:6443"

Overview (`test/soak/serve_hostnames/README.md`)

Soak Test serve_hostnames

This directory contains the source for a soak test serve_hostnames which performs the following actions when used with the GCE provider:

  • A connection is established to the master of the cluster identified from the current context set in $HOME/.kube/.kubeconfig.
  • The nodes available on the cluster are enumerated (say N nodes).
  • On each node, M pods are created (by default 1). The pod encapsulates the serve_hostnames image which simply returns the name of the pod in response to a GET request.
    The pods are created individually (i.e. not with a replication controller).
  • A service is created which maps to these pods.
  • The program makes I iterations (default 1) where it issues QxNxM queries (Q default is 10) via the service proxy interface at the master.
  • The program verifies that every pod (and thus every node) responded to at least one query (the average should be about Q).
  • The time taken to perform various operations is reported and some operations are re-tried if they failed.

Here is some representative output.

text
/* Detailed source-code truncated for AI context efficiency. */

The pods are named with -N-M suffixes which identify the number of the node N and the number of the pod M on that node.
Notice that in this run the pod (number 0) running on node 3 did not respond to any queries.

The number of iterations to perform for issuing queries can be changed from the default of 1 to some higher value e.g. --up_to=3 and the number of pods per node can also be changed e.g. --pods_per_node=2:

text
/* Detailed source-code truncated for AI context efficiency. */

Notice here that for the first two iterations neither of the pods on node 2 responded but by the third iteration responses
were received from all nodes.

For a soak test use --up_to=-1 which will loop indefinitely.

Note that this is not designed to be a performance test. The goal for this program is to provide an easy way to have a soak test
that can run indefinitely an exercise enough of Kubernetes' functionality to be confident that the cluster is still up and healthy.
The reported QPS mainly indicates latency to the master since the proxy requests are issued (deliberately) in a serial manner.

A more detailed report can be produced with --v=4 which measures the time taken to perform various operations
and it also reports the distribution of responses received from the pods. In the example below
we see that the pod on node 0 returned 18 responses, the pod on node 1 returned 10 responses and the
pod on node 3 returned 12 responses and the pod on node 2 did not respond at all.

text
/* Detailed source-code truncated for AI context efficiency. */


Overview (`third_party/forked/etcd221/README.md`)

Forked from etcd 2.2 release branch to support migration from 3.0 WAL to 2.2 WAL format


Overview (`third_party/forked/etcd237/README.md`)

Forked from etcd 2.3 release branch to support migration from 3.0 WAL to 2.3 WAL format


Overview (`vendor/google.golang.org/grpc/README.md`)

gRPC-Go

The Go implementation of gRPC: A high performance, open source, general RPC framework that puts mobile and HTTP/2 first. For more information see the gRPC Quick Start guide.

Installation

To install this package, you need to install Go and setup your Go workspace on your computer. The simplest way to install the library is to run:

text
$ go get google.golang.org/grpc

Prerequisites

This requires Go 1.6 or later.

Constraints

The grpc package should only depend on standard Go packages and a small number of exceptions. If your contribution introduces new dependencies which are NOT in the list, you need a discussion with gRPC-Go authors and consultants.

Documentation

See API documentation for package and API descriptions and find examples in the examples directory.

Status

GA

FAQ

Compiling error, undefined: grpc.SupportPackageIsVersion

Please update proto package, gRPC package and rebuild the proto files:

  • go get -u github.com/golang/protobuf/{proto,protoc-gen-go}
  • go get -u google.golang.org/grpc
  • protoc --go_out=plugins=grpc:. *.proto

Overview (`vendor/gopkg.in/yaml.v2/README.md`)

YAML support for the Go language

Introduction

The yaml package enables Go programs to comfortably encode and decode YAML
values. It was developed within Canonical as
part of the juju project, and is based on a
pure Go port of the well-known libyaml
C library to parse and generate YAML data quickly and reliably.

Compatibility

The yaml package supports most of YAML 1.1 and 1.2, including support for
anchors, tags, map merging, etc. Multi-document unmarshalling is not yet
implemented, and base-60 floats from YAML 1.1 are purposefully not
supported since they're a poor design and are gone in YAML 1.2.

Installation and usage

The import path for the package is gopkg.in/yaml.v2.

To install it, run:

text
go get gopkg.in/yaml.v2

API documentation

If opened in a browser, the import path itself leads to the API documentation:

API stability

The package API for yaml v2 will remain stable as described in gopkg.in.

License

The yaml package is licensed under the LGPL with an exception that allows it to be linked statically. Please see the LICENSE file for details.

Example

go
package main

import (
        "fmt"
        "log"

        "gopkg.in/yaml.v2"
)

var data = `
a: Easy!
b:
  c: 2
  d: [3, 4]
`

type T struct {
        A string
        B struct {
                RenamedC int   `yaml:"c"`
                D        []int `yaml:",flow"`
        }
}

func main() {
        t := T{}
    
        err := yaml.Unmarshal([]byte(data), &t)
        if err != nil {
                log.Fatalf("error: %v", err)
        }
        fmt.Printf("--- t:\n%v\n\n", t)
    
        d, err := yaml.Marshal(&t)
        if err != nil {
                log.Fatalf("error: %v", err)
        }
        fmt.Printf("--- t dump:\n%s\n\n", string(d))
    
        m := make(map[interface{}]interface{})
    
        err = yaml.Unmarshal([]byte(data), &m)
        if err != nil {
                log.Fatalf("error: %v", err)
        }
        fmt.Printf("--- m:\n%v\n\n", m)
    
        d, err = yaml.Marshal(&m)
        if err != nil {
                log.Fatalf("error: %v", err)
        }
        fmt.Printf("--- m dump:\n%s\n\n", string(d))
}

This example will generate the following output:

text
--- t:
{Easy! {2 [3 4]}}

--- t dump:
a: Easy!
b:
  c: 2
  d: [3, 4]


--- m:
map[a:Easy! b:map[c:2 d:[3 4]]]

--- m dump:
a: Easy!
b:
  c: 2
  d:
  - 3
  - 4

Overview (`cluster/addons/cluster-loadbalancing/glbc/README.md`)

GCE Load-Balancer Controller (GLBC) Cluster Addon

This cluster addon is composed of:

It relies on the Ingress resource only available in Kubernetes version 1.1 and beyond.

Prerequisites

Before you can receive traffic through the GCE L7 Loadbalancer Controller you need:

  • A Working Kubernetes 1.1 cluster
  • At least 1 Kubernetes NodePort Service (this is the endpoint for your Ingress)
  • Firewall-rules that allow traffic to the NodePort service, as indicated by kubectl at Service creation time
  • Adequate quota, as mentioned in the next section
  • A single instance of the L7 Loadbalancer Controller pod (if you're using the default GCE setup, this should already be running in the kube-system namespace)

Quota

GLBC is not aware of your GCE quota. As of this writing users get 3 GCE Backend Services by default. If you plan on creating Ingresses for multiple Kubernetes Services, remember that each one requires a backend service, and request quota. Should you fail to do so the controller will poll periodically and grab the first free backend service slot it finds. You can view your quota:

console
$ gcloud compute project-info describe --project myproject

See GCE documentation for how to request more.

Latency

It takes ~1m to spin up a loadbalancer (this includes acquiring the public ip), and ~5-6m before the GCE api starts healthchecking backends. So as far as latency goes, here's what to expect:

Assume one creates the following simple Ingress:

yaml
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: test-ingress
spec:
  backend:
    # This will just loopback to the default backend of GLBC
    serviceName: default-http-backend
    servicePort: 80
  • time, t=0

    console
    $ kubectl get ing
    NAME           RULE      BACKEND                   ADDRESS
    test-ingress   -         default-http-backend:80
    $ kubectl describe ing
    No events.
  • time, t=1m

    console
    $ kubectl get ing
    NAME           RULE      BACKEND                   ADDRESS
    test-ingress   -         default-http-backend:80   130.211.5.27
    
    $ kubectl describe ing
    target-proxy:        k8s-tp-default-test-ingress
    url-map:            k8s-um-default-test-ingress
    backends:            {"k8s-be-32342":"UNKNOWN"}
    forwarding-rule:    k8s-fw-default-test-ingress
    Events:
      FirstSeen    LastSeen    Count    From                SubobjectPath    Reason    Message
      ─────────    ────────    ─────    ────                ─────────────    ──────    ───────
      46s        46s        1    {loadbalancer-controller }    Success    Created loadbalancer 130.211.5.27
  • time, t=5m

    console
    $ kubectl describe ing
    target-proxy:        k8s-tp-default-test-ingress
    url-map:            k8s-um-default-test-ingress
    backends:            {"k8s-be-32342":"HEALTHY"}
    forwarding-rule:    k8s-fw-default-test-ingress
    Events:
      FirstSeen    LastSeen    Count    From                SubobjectPath    Reason    Message
      ─────────    ────────    ─────    ────                ─────────────    ──────    ───────
      46s        46s        1    {loadbalancer-controller }    Success    Created loadbalancer 130.211.5.27

Disabling GLBC

Since GLBC runs as a cluster addon, you cannot simply delete the RC. The easiest way to disable it is to do as follows:

  • IFF you want to tear down existing L7 loadbalancers, hit the /delete-all-and-quit endpoint on the pod:

    console
    $ kubectl get pods --namespace=kube-system
    NAME                                               READY     STATUS    RESTARTS   AGE
    l7-lb-controller-7bb21                             1/1       Running   0          1h
    $ kubectl exec l7-lb-controller-7bb21 -c l7-lb-controller curl http://localhost:8081/delete-all-and-quit --namespace=kube-system
    $ kubectl logs l7-lb-controller-7b221 -c l7-lb-controller --follow
    ...
    I1007 00:30:00.322528       1 main.go:160] Handled quit, awaiting pod deletion.
  • Nullify the RC (but don't delete it or the addon controller will "fix" it for you)

    console
    $ kubectl scale rc l7-lb-controller --replicas=0 --namespace=kube-system

Limitations

  • This cluster addon is still in the Beta phase. It behooves you to read through the GLBC documentation mentioned above and make sure there are no surprises.
  • The recommended way to tear down a cluster with active Ingresses is to either delete each Ingress, or hit the /delete-all-and-quit endpoint on GLBC as described below, before invoking a cluster teardown script (eg: kube-down.sh). You will have to manually cleanup GCE resources through the cloud console or gcloud CLI if you simply tear down the cluster with active Ingresses.
  • All L7 Loadbalancers created by GLBC have a default backend. If you don't specify one in your Ingress, GLBC will assign the 404 default backend mentioned above.
  • All Kubernetes services must serve a 200 page on '/', or whatever custom value you've specified through GLBC's --health-check-path argument.
  • GLBC is not built for performance. Creating many Ingresses at a time can overwhelm it. It won't fall over, but will take its own time to churn through the Ingress queue. It doesn't understand concepts like fairness or backoff just yet.


Overview (`cluster/addons/fluentd-elasticsearch/fluentd-es-image/README.md`)

Collecting Docker Log Files with Fluentd and Elasticsearch

This directory contains the source files needed to make a Docker image
that collects Docker container log files using Fluentd
and sends them to an instance of Elasticsearch.
This image is designed to be used as part of the Kubernetes
cluster bring up process. The image resides at GCR under the name
gcr.io/google-containers/fluentd-elasticsearch.


Overview (`cluster/addons/fluentd-gcp/fluentd-gcp-image/README.md`)

Collecting Docker Log Files with Fluentd and sending to GCP.

The image was moved to the
new location.


Overview (`cluster/addons/registry/auth/README.md`)

Enable Authentication with Htpasswd for Kube-Registry

Docker registry support a few authentication providers. Full list of supported provider can be found here. This document describes how to enable authentication with htpasswd for kube-registry.

Prepare Htpasswd Secret

Please generate your own htpasswd file. Assuming the file you generated is htpasswd.
Creating secret to hold htpasswd...

console
$ kubectl --namespace=kube-system create secret generic registry-auth-secret --from-file=htpasswd=htpasswd

Run Registry

Please be noted that this sample rc is using emptyDir as storage backend for simplicity.

yaml
apiVersion: v1
kind: ReplicationController
metadata:
  name: kube-registry-v0
  namespace: kube-system
  labels:
    k8s-app: kube-registry
    version: v0
#    kubernetes.io/cluster-service: "true"
spec:
  replicas: 1
  selector:
    k8s-app: kube-registry
    version: v0
  template:
    metadata:
      labels:
        k8s-app: kube-registry
        version: v0
#        kubernetes.io/cluster-service: "true"
    spec:
      containers:
      - name: registry
        image: registry:2
        resources:
          # keep request = limit to keep this container in guaranteed class
          limits:
            cpu: 100m
            memory: 100Mi
          requests:
            cpu: 100m
            memory: 100Mi
        env:
        - name: REGISTRY_HTTP_ADDR
          value: :5000
        - name: REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY
          value: /var/lib/registry
        - name: REGISTRY_AUTH_HTPASSWD_REALM
          value: basic_realm
        - name: REGISTRY_AUTH_HTPASSWD_PATH
          value: /auth/htpasswd
        volumeMounts:
        - name: image-store
          mountPath: /var/lib/registry
        - name: auth-dir
          mountPath: /auth
        ports:
        - containerPort: 5000
          name: registry
          protocol: TCP
      volumes:
      - name: image-store
        emptyDir: {}
      - name: auth-dir
        secret:
          secretName: registry-auth-secret

No changes are needed for other components (kube-registry service and proxy).

To Verify

Setup proxy or port-forwarding to the kube-registry. Image push/pull should fail without authentication. Then use docker login to authenticate with kube-registry and see if it works.

Configure Nodes to Authenticate with Kube-Registry

By default, nodes assume no authentication is required by kube-registry. Without authentication, nodes cannot pull images from kube-registry. To solve this, more documentation can be found Here.


Overview (`cluster/addons/registry/gcs/README.md`)

Kube-Registry with GCS storage backend

Besides local file system, docker registry also supports a number of cloud storage backends. Full list of supported backend can be found here. This document describes how to enable GCS for kube-registry as storage backend.

A few preparation steps are needed.

  1. Create a bucket named kube-registry in GCS.
  2. Create a service account for GCS access and create key file in json format. Detail instruction can be found here.

Pack Keyfile into a Secret

Assuming you have downloaded the keyfile as keyfile.json. Create secret with the keyfile.json...

console
$ kubectl --namespace=kube-system create secret generic gcs-key-secret --from-file=keyfile=keyfile.json

Run Registry

yaml
apiVersion: v1
kind: ReplicationController
metadata:
  name: kube-registry-v0
  namespace: kube-system
  labels:
    k8s-app: kube-registry
    version: v0
#    kubernetes.io/cluster-service: "true"
spec:
  replicas: 1
  selector:
    k8s-app: kube-registry
    version: v0
  template:
    metadata:
      labels:
        k8s-app: kube-registry
        version: v0
#        kubernetes.io/cluster-service: "true"
    spec:
      containers:
      - name: registry
        image: registry:2
        resources:
          # keep request = limit to keep this container in guaranteed class
          limits:
            cpu: 100m
            memory: 100Mi
          requests:
            cpu: 100m
            memory: 100Mi
        env:
        - name: REGISTRY_HTTP_ADDR
          value: :5000
        - name: REGISTRY_STORAGE
          value: gcs
        - name: REGISTRY_STORAGE_GCS_BUCKET
          value: kube-registry
        - name: REGISTRY_STORAGE_GCS_KEYFILE
          value: /gcs/keyfile
        ports:
        - containerPort: 5000
          name: registry
          protocol: TCP
        volumeMounts:
        - name: gcs-key
          mountPath: /gcs
      volumes:
      - name: gcs-key
        secret:
          secretName: gcs-key-secret

No changes are needed for other components (kube-registry service and proxy).


Overview (`cluster/addons/registry/tls/README.md`)

Enable TLS for Kube-Registry

This document describes how to enable TLS for kube-registry. Before you start, please check if you have all the prerequisite:

  • A domain for kube-registry. Assuming it is myregistrydomain.com.
  • Domain certificate and key. Assuming they are domain.crt and domain.key

Pack domain.crt and domain.key into a Secret

console
$ kubectl --namespace=kube-system create secret generic registry-tls-secret --from-file=domain.crt=domain.crt --from-file=domain.key=domain.key

Run Registry

Please be noted that this sample rc is using emptyDir as storage backend for simplicity.

yaml
apiVersion: v1
kind: ReplicationController
metadata:
  name: kube-registry-v0
  namespace: kube-system
  labels:
    k8s-app: kube-registry
    version: v0
#    kubernetes.io/cluster-service: "true"
spec:
  replicas: 1
  selector:
    k8s-app: kube-registry
    version: v0
  template:
    metadata:
      labels:
        k8s-app: kube-registry
        version: v0
#        kubernetes.io/cluster-service: "true"
    spec:
      containers:
      - name: registry
        image: registry:2
        resources:
          # keep request = limit to keep this container in guaranteed class
          limits:
            cpu: 100m
            memory: 100Mi
          requests:
            cpu: 100m
            memory: 100Mi
        env:
        - name: REGISTRY_HTTP_ADDR
          value: :5000
        - name: REGISTRY_STORAGE_FILESYSTEM_ROOTDIRECTORY
          value: /var/lib/registry
        - name: REGISTRY_HTTP_TLS_CERTIFICATE
          value: /certs/domain.crt
        - name: REGISTRY_HTTP_TLS_KEY
          value: /certs/domain.key
        volumeMounts:
        - name: image-store
          mountPath: /var/lib/registry
        - name: cert-dir
          mountPath: /certs
        ports:
        - containerPort: 5000
          name: registry
          protocol: TCP
      volumes:
      - name: image-store
        emptyDir: {}
      - name: cert-dir
        secret:
          secretName: registry-tls-secret

Expose External IP for Kube-Registry

Modify the default kube-registry service to LoadBalancer type and point the DNS record of myregistrydomain.com to the service external ip.

yaml
apiVersion: v1
kind: Service
metadata:
  name: kube-registry
  namespace: kube-system
  labels:
    k8s-app: kube-registry
#    kubernetes.io/cluster-service: "true"
    kubernetes.io/name: "KubeRegistry"
spec:
  selector:
    k8s-app: kube-registry
  type: LoadBalancer
  ports:
  - name: registry
    port: 5000
    protocol: TCP

To Verify

Now you should be able to access your kube-registry from another docker host.

console
docker pull busybox
docker tag busybox myregistrydomain.com:5000/busybox
docker push myregistrydomain.com:5000/busybox
docker pull myregistrydomain.com:5000/busybox


Overview (`cluster/images/etcd/rollback/README.md`)

Rollback workflow

Build it in this directory.
Make sure you have etcd dependency ready. Last time we use etcd v3.0.7.

text
$ go build .

Run it:

text
$ ./rollback2 --data-dir $ETCD_DATA_DIR --ttl 1h

This will rollback KV pairs from v3 into v2.
If a key was attached to a lease before, it will be created with given TTL (default to 1h).

On success, it will print at the end:

text
Finished successfully

Repeat this on all etcd members.

You can do simple check on keys (if any exists):

text
etcdctl ls /

Important Note

This tool isn't recommended to use if any problem comes up in etcd3 backend.
Please report bugs and we will fix it soon.

If it's still preferred to run this tool, please backup all your data beforehand.
This tool will also back up datadir to same path with ".rollback.backup" suffix.

Caveats:

  • The tool doesn't preserve versions of keys.
  • If any v2 data exists before rollback, they will be wiped out.
  • v3 data only exists in the backup after successful rollback.


Overview (`cluster/juju/layers/kubeapi-load-balancer/README.md`)

kubeapi-load-balancer

Simple NGINX reverse proxy to lend a hand in HA kubernetes-master deployments.


Overview (`cluster/juju/layers/kubernetes-e2e/README.md`)

Kubernetes end to end

End-to-end (e2e) tests for Kubernetes provide a mechanism to test end-to-end
behavior of the system, and is the last signal to ensure end user operations
match developer specifications. Although unit and integration tests provide a
good signal, in a distributed system like Kubernetes it is not uncommon that a
minor change may pass all unit and integration tests, but cause unforeseen
changes at the system level.

The primary objectives of the e2e tests are to ensure a consistent and reliable
behavior of the kubernetes code base, and to catch hard-to-test bugs before
users do, when unit and integration tests are insufficient.

Usage

To deploy the end-to-end test suite, it is best to deploy the
kubernetes-core bundle
and then relate the kubernetes-e2e charm.

shell
juju deploy kubernetes-core
juju deploy cs:~containers/kubernetes-e2e
juju add-relation kubernetes-e2e:kube-control kubernetes-master:kube-control
juju add-relation kubernetes-e2e:kubernetes-master kubernetes-master:kube-api-endpoint
juju add-relation kubernetes-e2e easyrsa

Once the relations have settled, and the kubernetes-e2e charm reports
Ready to test. - you may kick off an end to end validation test.

Running the e2e test

The e2e test is encapsulated as an action to ensure consistent runs of the
end to end test. The defaults are sensible for most deployments.

shell
juju run-action kubernetes-e2e/0 test

Tuning the e2e test

The e2e test is configurable. By default it will focus on or skip the declared
conformance tests in a cloud agnostic way. Default behaviors are configurable.
This allows the operator to test only a subset of the conformance tests, or to
test more behaviors not enabled by default. You can see all tunable options on
the charm by inspecting the schema output of the actions:

shell
$ juju actions kubernetes-e2e --format=yaml --schema
test:
  description: Run end-to-end validation test suite
  properties:
    focus:
      default: \[Conformance\]
      description: Regex focus for executing the test
      type: string
    skip:
      default: \[Flaky\]
      description: Regex of tests to skip
      type: string
    timeout:
      default: 30000
      description: Timeout in nanoseconds
      type: integer
  title: test
  type: object

As an example, you can run a more limited set of tests for rapid validation of
a deployed cluster. The following example will skip the Flaky, Slow, and
Feature labeled tests:

shell
juju run-action kubernetes-e2e/0 test skip='\[(Flaky|Slow|Feature:.*)\]'

Note: the escaping of the regex due to how bash handles brackets.

To see the different types of tests the Kubernetes end-to-end charm has access
to, we encourage you to see the upstream documentation on the different types
of tests, and to strongly understand what subsets of the tests you are running.

Kinds of tests

More information on end-to-end testing

Along with the above descriptions, end-to-end testing is a much larger subject
than this readme can encapsulate. There is far more information in the
end-to-end testing guide.

Evaluating end-to-end results

It is not enough to just simply run the test. Result output is stored in two
places. The raw output of the e2e run is available in the juju show-action-output
command, as well as a flat file on disk on the kubernetes-e2e unit that
executed the test.

Note: The results will only be available once the action has
completed the test run. End-to-end testing can be quite time intensive. Often
times taking greater than 1 hour, depending on configuration.

Flat file

shell
$ juju run-action kubernetes-e2e/0 test
Action queued with id: 4ceed33a-d96d-465a-8f31-20d63442e51b

$ juju scp kubernetes-e2e/0:4ceed33a-d96d-465a-8f31-20d63442e51b.log .

Action result output

shell
$ juju run-action kubernetes-e2e/0 test
Action queued with id: 4ceed33a-d96d-465a-8f31-20d63442e51b

$ juju show-action-output 4ceed33a-d96d-465a-8f31-20d63442e51b

Known issues

The e2e test suite assumes egress network access. It will pull container
images from gcr.io. You will need to have this registry unblocked in your
firewall to successfully run e2e test results. Or you may use the exposed
proxy settings properly configured
on the kubernetes-worker units.

Help resources:


Overview (`cluster/juju/layers/kubernetes-master/README.md`)

Kubernetes-master

Kubernetes is an open source system for managing
application containers across a cluster of hosts. The Kubernetes project was
started by Google in 2014, combining the experience of running production
workloads combined with best practices from the community.

The Kubernetes project defines some new terms that may be unfamiliar to users
or operators. For more information please refer to the concept guide in the
getting started guide.

This charm is an encapsulation of the Kubernetes master processes and the
operations to run on any cloud for the entire lifecycle of the cluster.

This charm is built from other charm layers using the Juju reactive framework.
The other layers focus on specific subset of operations making this layer
specific to operations of Kubernetes master processes.

Deployment

This charm is not fully functional when deployed by itself. It requires other
charms to model a complete Kubernetes cluster. A Kubernetes cluster needs a
distributed key value store such as Etcd and the
kubernetes-worker charm which delivers the Kubernetes node services. A cluster
requires a Software Defined Network (SDN) and Transport Layer Security (TLS) so
the components in a cluster communicate securely.

Please take a look at the Canonical Distribution of Kubernetes
or the Kubernetes core bundles for
examples of complete models of Kubernetes clusters.

Resources

The kubernetes-master charm takes advantage of the Juju Resources
feature to deliver the Kubernetes software.

In deployments on public clouds the Charm Store provides the resource to the
charm automatically with no user intervention. Some environments with strict
firewall rules may not be able to contact the Charm Store. In these network
restricted environments the resource can be uploaded to the model by the Juju
operator.

Configuration

This charm supports some configuration options to set up a Kubernetes cluster
that works in your environment:

dns_domain

The domain name to use for the Kubernetes cluster for DNS.

enable-dashboard-addons

Enables the installation of Kubernetes dashboard, Heapster, Grafana, and
InfluxDB.

enable-rbac

Enable RBAC and Node authorisation.

DNS for the cluster

The DNS add-on allows the pods to have a DNS names in addition to IP addresses.
The Kubernetes cluster DNS server (based off the SkyDNS library) supports
forward lookups (A records), service lookups (SRV records) and reverse IP
address lookups (PTR records). More information about the DNS can be obtained
from the Kubernetes DNS admin guide.

Actions

The kubernetes-master charm models a few one time operations called
Juju actions that can be run by
Juju users.

create-rbd-pv

This action creates RADOS Block Device (RBD) in Ceph and defines a Persistent
Volume in Kubernetes so the containers can use durable storage. This action
requires a relation to the ceph-mon charm before it can create the volume.

restart

This action restarts the master processes kube-apiserver,
kube-controller-manager, and kube-scheduler when the user needs a restart.

More information

Contact

The kubernetes-master charm is free and open source operations created
by the containers team at Canonical.

Canonical also offers enterprise support and customization services. Please
refer to the Kubernetes product page
for more details.


Overview (`cluster/juju/layers/kubernetes-worker/README.md`)

Kubernetes Worker

Usage

This charm deploys a container runtime, and additionally stands up the Kubernetes
worker applications: kubelet, and kube-proxy.

In order for this charm to be useful, it should be deployed with its companion
charm kubernetes-master
and linked with an SDN-Plugin.

This charm has also been bundled up for your convenience so you can skip the
above steps, and deploy it with a single command:

shell
juju deploy canonical-kubernetes

For more information about Canonical Kubernetes
consult the bundle README.md file.

Scale out

To add additional compute capacity to your Kubernetes workers, you may
juju add-unit scale the cluster of applications. They will automatically
join any related kubernetes-master, and enlist themselves as ready once the
deployment is complete.

Operational actions

The kubernetes-worker charm supports the following Operational Actions:

Pause

Pausing the workload enables administrators to both drain and cordon
a unit for maintenance.

Resume

Resuming the workload will uncordon a paused unit. Workloads will automatically migrate unless otherwise directed via their application declaration.

Private registry

With the "registry" action that is part for the kubernetes-worker charm, you can very easily create a private docker registry, with authentication, and available over TLS. Please note that the registry deployed with the action is not HA, and uses storage tied to the kubernetes node where the pod is running. So if the registry pod changes is migrated from one node to another for whatever reason, you will need to re-publish the images.

Example usage

Create the relevant authentication files. Let's say you want user userA to authenticate with the password passwordA. Then you'll do :

text
echo -n "userA:passwordA" > htpasswd-plain
htpasswd -c -b -B htpasswd userA passwordA

(the htpasswd program comes with the apache2-utils package)

Supposing your registry will be reachable at myregistry.company.com, and that you already have your TLS key in the registry.key file, and your TLS certificate (with myregistry.company.com as Common Name) in the registry.crt file, you would then run :

text
juju run-action kubernetes-worker/0 registry domain=myregistry.company.com htpasswd="$(base64 -w0 htpasswd)" htpasswd-plain="$(base64 -w0 htpasswd-plain)" tlscert="$(base64 -w0 registry.crt)" tlskey="$(base64 -w0 registry.key)" ingress=true

If you then decide that you want do delete the registry, just run :

text
juju run-action kubernetes-worker/0 registry delete=true ingress=true

Known Limitations

Kubernetes workers currently only support 'phaux' HA scenarios. Even when configured with an HA cluster string, they will only ever contact the first unit in the cluster map. To enable a proper HA story, kubernetes-worker units are encouraged to proxy through a kubeapi-load-balancer
application. This enables a HA deployment without the need to
re-render configuration and disrupt the worker services.

External access to pods must be performed through a Kubernetes
Ingress Resource
.

When using NodePort type networking, there is no automation in exposing the
ports selected by kubernetes or chosen by the user. They will need to be
opened manually and can be performed across an entire worker pool.

If your NodePort service port selected is 30510 you can open this across all
members of a worker pool named kubernetes-worker like so:

text
juju run --application kubernetes-worker open-port 30510/tcp

Don't forget to expose the kubernetes-worker application if its not already
exposed, as this can cause confusion once the port has been opened and the
service is not reachable.

Note: When debugging connection issues with NodePort services, its important
to first check the kube-proxy service on the worker units. If kube-proxy is not
running, the associated port-mapping will not be configured in the iptables
rulechains.

If you need to close the NodePort once a workload has been terminated, you can
follow the same steps inversely.

text
juju run --application kubernetes-worker close-port 30510

Overview (`examples/storage/cassandra/java/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/storage/cassandra/java/README.md


Overview (`examples/volumes/nfs/nfs-data/README.md`)

This file has moved to https://github.com/kubernetes/examples/blob/master/staging/volumes/nfs/nfs-data/README.md


Overview (`staging/src/k8s.io/api/README.md`)

This repo is still in the experimental stage. Shortly it will contain the schema of the API that are served by the Kubernetes apiserver.


Overview (`staging/src/k8s.io/apiextensions-apiserver/README.md`)

apiextensions-apiserver

Implements: https://github.com/kubernetes/community/blob/master/contributors/design-proposals/api-machinery/thirdpartyresources.md

It provides an API for registering CustomResourceDefinitions.

Purpose

This API server provides the implementation for CustomResourceDefinitions which is included as
delegate server inside of kube-apiserver.

Compatibility

HEAD of this repo will match HEAD of k8s.io/apiserver, k8s.io/apimachinery, and k8s.io/client-go.

Where does it come from?

apiextensions-apiserver is synced from https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apiextensions-apiserver.
Code changes are made in that location, merged into k8s.io/kubernetes and later synced here.


Overview (`staging/src/k8s.io/apimachinery/README.md`)

apimachinery

Scheme, typing, encoding, decoding, and conversion packages for Kubernetes and Kubernetes-like API objects.

Purpose

This library is a shared dependency for servers and clients to work with Kubernetes API infrastructure without direct
type dependencies. Its first consumers are k8s.io/kubernetes, k8s.io/client-go, and k8s.io/apiserver.

Compatibility

There are NO compatibility guarantees for this repository. It is in direct support of Kubernetes, so branches
will track Kubernetes and be compatible with that repo. As we more cleanly separate the layers, we will review the
compatibility guarantee.

Where does it come from?

apimachinery is synced from https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery.
Code changes are made in that location, merged into k8s.io/kubernetes and later synced here.

Things you should *NOT* do

  1. Add API types to this repo. This is for the machinery, not for the types.
  2. Directly modify any files under pkg in this repo. Those are driven from k8s.io/kubernetes/staging/src/k8s.io/apimachinery.
  3. Expect compatibility. This repo is direct support of Kubernetes and the API isn't yet stable enough for API guarantees.

Overview (`staging/src/k8s.io/apiserver/README.md`)

apiserver

Generic library for building a Kubernetes aggregated API server.

Purpose

This library contains code to create Kubernetes aggregation server complete with delegated authentication and authorization,
kubectl compatible discovery information, optional admission chain, and versioned types. It's first consumers are
k8s.io/kubernetes, k8s.io/kube-aggregator, and github.com/kubernetes-incubator/service-catalog.

Compatibility

There are NO compatibility guarantees for this repository, yet. It is in direct support of Kubernetes, so branches
will track Kubernetes and be compatible with that repo. As we more cleanly separate the layers, we will review the
compatibility guarantee. We have a goal to make this easier to use in 2017.

Where does it come from?

apiserver is synced from https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apiserver.
Code changes are made in that location, merged into k8s.io/kubernetes and later synced here.

Things you should *NOT* do

  1. Directly modify any files under pkg in this repo. Those are driven from k8s.io/kuberenetes/staging/src/k8s.io/apiserver.
  2. Expect compatibility. This repo is changing quickly in direct support of
    Kubernetes and the API isn't yet stable enough for API guarantees.

Overview (`staging/src/k8s.io/code-generator/README.md`)

code-generator

Golang code-generators used to implement Kubernetes-style API types.

Purpose

These code-generators can be used

  • in the context of CustomResourceDefinition to build native, versioned clients,
    informers and other helpers
  • in the context of User-provider API Servers to build conversions between internal and versioned types, defaulters, protobuf codecs,
    internal and versioned clients and informers.

Resources

Compatibility

HEAD of this repo will match HEAD of k8s.io/apiserver, k8s.io/apimachinery, and k8s.io/client-go.

Where does it come from?

code-generator is synced from https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/code-generator.
Code changes are made in that location, merged into k8s.io/kubernetes and later synced here.


Overview (`staging/src/k8s.io/kube-aggregator/README.md`)

kube-aggregator

Coming Soon!

Implements https://github.com/kubernetes/community/blob/master/contributors/design-proposals/api-machinery/aggregated-api-servers.md.

It provides

  • Provide an API for registering API servers.
  • Summarize discovery information from all the servers.
  • Proxy client requests to individual servers.

Purpose

We want to divide the single monolithic API server into multiple aggregated
servers. Anyone should be able to write their own aggregated API server to expose APIs they want.
Cluster admins should be able to expose new APIs at runtime by bringing up new
aggregated servers.

Compatibility

HEAD of this repo will match HEAD of k8s.io/apiserver, k8s.io/apimachinery, and k8s.io/client-go.

Where does it come from?

kube-aggregator is synced from https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/kube-aggregator.
Code changes are made in that location, merged into k8s.io/kubernetes and later synced here.


Overview (`staging/src/k8s.io/metrics/README.md`)

metrics

Kubernetes metrics API type definitions and clients.

Purpose

This repository contains type definitions and client code for the metrics
APIs that Kubernetes makes use of. Depending on the API, the actual
implementations live elsewhere.

Consumers of the metrics APIs can make use of this repository to access
implementations of the APIs, while implementors should make use of this
library when implementing their API servers.

APIs

This repository contains types and clients for several APIs. For more
details on implemenations of these apis, see
IMPLEMENTATIONS.md.

Custom Metrics API

This API allows consumers to access arbitrary metrics which describe
Kubernetes resources.

The API is intended to be implemented by monitoring pipeline vendors, on
top of their metrics storage solutions.

If you want to implement this an API server for this API, please see the
kubernetes-incubator/custom-metrics-apiserver
library, which contains the basic infrastructure required to set up such
an API server.

Import Path: k8s.io/metrics/pkg/apis/custom_metrics.

Resource Metrics API

This API allows consumers to access resource metrics (CPU and memory) for
pods and nodes.

The API is implemented by Heapster
(https://github.com/kubernetes/heapster) and metrics-server
(https://github.com/kubernetes-incubator/metrics-server).

Import Path: k8s.io/metrics/pkg/apis/metrics.

Compatibility

The APIs in this repository follow the standard guarantees for Kubernetes
APIs, and will follow Kubernetes releases.

Community, discussion, contribution, and support

Learn how to engage with the Kubernetes community on the community
page
.

You can reach the maintainers of this repository at:

Code of Conduct

Participation in the Kubernetes community is governed by the Kubernetes
Code of Conduct
.

Contibution Guidelines

See CONTRIBUTING.md for more information.


Overview (`staging/src/k8s.io/sample-apiserver/README.md`)

sample-apiserver

Demonstration of how to use the k8s.io/apiserver library to build a functional API server.

Purpose

This is intended as an example of how to build a kube-like API server with a single type.

Compatibility

HEAD of this repo will match HEAD of k8s.io/apiserver, k8s.io/apimachinery, and k8s.io/client-go.

Where does it come from?

sample-apiserver is synced from https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/sample-apiserver.
Code changes are made in that location, merged into k8s.io/kubernetes and later synced here.


Overview (`staging/src/k8s.io/sample-controller/README.md`)

sample-controller

This repository implements a simple controller for watching Foo resources as
defined with a CustomResourceDefinition (CRD).

This particular example demonstrates how to perform basic operations such as:

  • How to register a new custom resource (custom resource type) of type Foo using a CustomResourceDefinition.
  • How to create/get/list instances of your new resource type Foo.
  • How to setup a controller on resource handling create/update/delete events.

It makes use of the generators in k8s.io/code-generator
to generate a typed client, informers, listers and deep-copy functions. You can
do this yourself using the ./hack/update-codegen.sh script.

The update-codegen script will automatically generate the following files &
directories:

  • pkg/apis/samplecontroller/v1alpha1/zz_generated.deepcopy.go
  • pkg/client/

Changes should not be made to these files manually, and when creating your own
controller based off of this implementation you should not copy these files and
instead run the update-codegen script to generate your own.

Purpose

This is an example of how to build a kube-like controller with a single type.

Running

sh
# assumes you have a working kubeconfig, not required if operating in-cluster
$ go run *.go -kubeconfig=$HOME/.kube/config

# create a CustomResourceDefinition
$ kubectl create -f artifacts/examples/crd.yaml

# create a custom resource of type Foo
$ kubectl create -f artifacts/examples/example-foo.yaml

# check deployments created through the custom resource
$ kubectl get deployments

Use Cases

CustomResourceDefinitions can be used to implement custom resource types for your Kubernetes cluster.
These act like most other Resources in Kubernetes, and may be kubectl apply'd, etc.

Some example use cases:

  • Provisioning/Management of external datastores/databases (eg. CloudSQL/RDS instances)
  • Higher level abstractions around Kubernetes primitives (eg. a single Resource to define an etcd cluster, backed by a Service and a ReplicationController)

Defining types

Each instance of your custom resource has an attached Spec, which should be defined via a struct{} to provide data format validation.
In practice, this Spec is arbitrary key-value data that specifies the configuration/behavior of your Resource.

For example, if you were implementing a custom resource for a Database, you might provide a DatabaseSpec like the following:

go
type DatabaseSpec struct {
	Databases []string `json:"databases"`
	Users     []User   `json:"users"`
	Version   string   `json:"version"`
}

type User struct {
	Name     string `json:"name"`
	Password string `json:"password"`
}

Cleanup

You can clean up the created CustomResourceDefinition with:

text
$ kubectl delete crd foos.samplecontroller.k8s.io

Compatibility

HEAD of this repository will match HEAD of k8s.io/apimachinery and
k8s.io/client-go.

Where does it come from?

sample-controller is synced from
https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/sample-controller.
Code changes are made in that location, merged into k8s.io/kubernetes and
later synced here.


Overview (`test/images/pets/peer-finder/README.md`)

Peer finder

This is a simple peer finder daemon that is useful with StatefulSet and related use cases.

All it does is watch DNS for changes in the set of endpoints that are part of the governing service
of the PetSet. It periodically looks up the SRV record of the DNS entry that corresponds to a Kubernetes
Service which enumerates the set of peers for this the specified service.

Be sure to use the service.alpha.kubernetes.io/tolerate-unready-endpoints on the governing service
of the StatefulSet so that all peers are listed in endpoints before any peers are started.

There are several ways to bundle it with your main application.

  1. In an init container,
    to help your pod determine its peers when it it first started (determine the desired set of
    peers from the governing service of the StatefulSet. For this use case, the --on-start option
    can be used, but the --on-change option should not be used since the init container will no
    longer be running after the pod is started. An example of an --on-start script would be to
    edit a configuration file for the main app to insert the list of peers. This file needs to be
    on a Volume shared between the init container and the main container.
  2. In a sidecar (e.g. a second container in the same pod as the main app), in which case the --on-change
    option can be used, but --on-start may not be useful without a way to guarantee the ordering
    of the sidecar relative to the main app container. An example of an on-change script would be to
    send an administrative command to the main container over the localhost network. (Note that signalling
    is not practical since pods currently do not share a PID namespace).
  3. As pid 1 of the main container, in which case both --on-change and --on-start may be used.
    In this mode, the ordering of the peer-finder relative to the main app is ensured by having the peer
    finder start the main app. An example script would be to modify a configuration file and send SIGHUP
    to the main process.
  4. Both 1 and 2.

Options 1 and 2 and 4 may be preferable since they do not require changes to the main container image.
Option 3 is useful is signalling is necessary.

The peer-finder tool is intended to help legacy applications run in containers on Kubernetes.
If possible, it may be preferable to modify an applications to poll DNS itself to determine its peer set.

Not all StatefulSets are able to be scaled. For unscalable StatefulSets, only the on-start message is needed, and
so option 1 is a good choice.


Overview (`test/images/pets/redis-installer/README.md`)

Redis statefulset e2e tester

The image in this directory is the init container for contrib/pets/redis but for one difference, it bakes a specific version of redis into the base image so we get deterministic test results without having to depend on a redis download server. Discussing the tradeoffs to either approach (download the version at runtime, or maintain an image per version) are outside the scope of this document.

You can execute the image locally via:

text
$ docker run -it gcr.io/google_containers/redis-install-3.2.0:e2e --cmd --install-into=/opt --work-dir=/work-dir

To share the installation with other containers mount the appropriate volumes as --install-into and --work-dir, where install-into is the directory to install redis into, and work-dir is the directory to install the user/admin supplied on-{start,change} hook scripts.


Overview (`test/images/pets/zookeeper-installer/README.md`)

Zookeeper statefulset e2e tester

The image in this directory is the init container for contrib/pets/zookeeper but for one difference, it bakes a specific version of zookeeper into the base image so we get deterministic test results without having to depend on a zookeeper download server. Discussing the tradeoffs to either approach (download the version at runtime, or maintain an image per version) are outside the scope of this document.

You can execute the image locally via:

text
$ docker run -it gcr.io/google_containers/zookeeper-install-3.5.0-alpha:e2e --cmd --install-into=/opt --work-dir=/work-dir

To share the installation with other containers mount the appropriate volumes as --install-into and --work-dir, where install-into is the directory to install zookeeper into, and work-dir is the directory to install the user/admin supplied on-{start,change} hook scripts.


Overview (`test/images/volumes-tester/ceph/README.md`)

Ceph server container for testing

This container exports ceph fs with an index.html inside.

Used by test/e2e/* to test CephFSVolumeSource. Not for production use!


Overview (`test/images/volumes-tester/gluster/README.md`)

Gluster server container for testing

This container exports test_vol volume with an index.html inside.

Used by test/e2e/* to test GlusterfsVolumeSource. Not for production use!


Overview (`test/images/volumes-tester/iscsi/README.md`)

iSCSI target container for testing.

Inspired by https://github.com/rvykydal/dockerfile-iscsid

  • The container needs /lib/modules from the host to insert appropriate
    kernel modules for iscsi. This assumes that these modules are installed
    on the host!

  • The container needs to run with docker --privileged

block.tar.gz is a small ext2 filesystem created by make block (run as root!)


Overview (`test/images/volumes-tester/nfs/README.md`)

NFS server container for testing

This container exports '/' directory with an index.html inside. NFSv4 only.

Accepts a -G option for specifying a group id to give exported directories.
Clients in the specified group will have full rwx permissions, others none.

Inspired by https://github.com/cpuguy83/docker-nfs-server.

Used by test/e2e/* to test NFSVolumeSource. Not for production use!


Overview (`third_party/forked/gonum/graph/README.md`)

Forked from gonum/graph@50b27dea7ebbfb052dfaf91681afc6fde28d8796 to support memory-use improvements to the simple graph


Overview (`vendor/bitbucket.org/bertimus9/systemstat/README.md`)

systemstat

Documentation online

systemstat is a package written in Go generated automatically by gobi.

systemstat allows you to add system statistics to your go program; it
currently polls the linux kernel for CPU usage, free/used memory and swap
sizes, and uptime for your go process, as well as the system you're running it
on, and the system load. It can be used to make a crippled version of top that
monitors the current go process and ignores other processes and the number of
users with ttys. See the examples directory for go-top.go, which is my attempt
at a top clone. Bear in mind that the intention of systemstat is to allow
your process to monitor itself and it's environment, not to replace top.

Install (with GOPATH set on your machine)


  • Step 1: Get the systemstat package
text
go get bitbucket.org/bertimus9/systemstat
  • Step 2 (Optional): Run tests
text
$ go test -v bitbucket.org/bertimus9/systemstat
  • Step 3 (Optional): Run example
bash
$ cd to the first directory in your $GOPATH
$ cd src/bitbucket.org/bertimus9/systemstat
$ go run examples/go-top.go

##Usage

text
package main

import (
	"bitbucket.org/bertimus9/systemstat"
	"fmt"
)

var sample systemstat.MemSample

// This example shows how easy it is to get memory information
func main() {
	sample = systemstat.GetMemSample()
	fmt.Println("Total available RAM in kb:", sample.MemTotal, "k total")
	fmt.Println("Used RAM in kb:", sample.MemUsed, "k used")
	fmt.Println("Free RAM in kb:", sample.MemFree, "k free")
	fmt.Printf("The output is similar to, but somewhat different than:\n\ttop -n1 | grep Mem:\n")
}

##License

Copyright (c) 2013 Phillip Bond

Licensed under the MIT License

see file LICENSE


Overview (`vendor/github.com/Azure/go-ansiterm/README.md`)

go-ansiterm

This is a cross platform Ansi Terminal Emulation library. It reads a stream of Ansi characters and produces the appropriate function calls. The results of the function calls are platform dependent.

For example the parser might receive "ESC, [, A" as a stream of three characters. This is the code for Cursor Up (http://www.vt100.net/docs/vt510-rm/CUU). The parser then calls the cursor up function (CUU()) on an event handler. The event handler determines what platform specific work must be done to cause the cursor to move up one position.

The parser (parser.go) is a partial implementation of this state machine (http://vt100.net/emu/vt500_parser.png). There are also two event handler implementations, one for tests (test_event_handler.go) to validate that the expected events are being produced and called, the other is a Windows implementation (winterm/win_event_handler.go).

See parser_test.go for examples exercising the state machine and generating appropriate function calls.


This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.


Overview (`vendor/github.com/MakeNowJust/heredoc/README.md`)

heredoc [](https://circleci.com/gh/MakeNowJust/heredoc) [](https://gowalker.org/github.com/MakeNowJust/heredoc)

About

Package heredoc provides the here-document with keeping indent.

Install

console
$ go get github.com/MakeNowJust/heredoc

Import

go
// usual
import "github.com/MakeNowJust/heredoc"
// shortcuts
import . "github.com/MakeNowJust/heredoc/dot"

Example

go
package main

import (
	"fmt"
	. "github.com/MakeNowJust/heredoc/dot"
)

func main() {
	fmt.Println(D(`
		Lorem ipsum dolor sit amet, consectetur adipisicing elit,
		sed do eiusmod tempor incididunt ut labore et dolore magna
		aliqua. Ut enim ad minim veniam, ...
	`))
	// Output:
	// Lorem ipsum dolor sit amet, consectetur adipisicing elit,
	// sed do eiusmod tempor incididunt ut labore et dolore magna
	// aliqua. Ut enim ad minim veniam, ...
	//
}

API Document

License

This software is released under the MIT License, see LICENSE.


Overview (`vendor/github.com/Microsoft/go-winio/README.md`)

go-winio

This repository contains utilities for efficiently performing Win32 IO operations in
Go. Currently, this is focused on accessing named pipes and other file handles, and
for using named pipes as a net transport.

This code relies on IO completion ports to avoid blocking IO on system threads, allowing Go
to reuse the thread to schedule another goroutine. This limits support to Windows Vista and
newer operating systems. This is similar to the implementation of network sockets in Go's net
package.

Please see the LICENSE file for licensing information.

This project has adopted the Microsoft Open Source Code of
Conduct
. For more information
see the Code of Conduct
FAQ
or contact
[email protected] with any additional
questions or comments.

Thanks to natefinch for the inspiration for this library. See https://github.com/natefinch/npipe
for another named pipe implementation.


Overview (`vendor/github.com/Microsoft/hcsshim/README.md`)

hcsshim

This package supports launching Windows Server containers from Go. It is
primarily used in the Docker Engine project,
but it can be freely used by other projects as well.

This project has adopted the Microsoft Open Source Code of
Conduct
. For more information
see the Code of Conduct
FAQ
or contact
[email protected] with any additional
questions or comments.


Overview (`vendor/github.com/NYTimes/gziphandler/README.md`)

Gzip Handler

This is a tiny Go package which wraps HTTP handlers to transparently gzip the
response body, for clients which support it. Although it's usually simpler to
leave that to a reverse proxy (like nginx or Varnish), this package is useful
when that's undesirable.

Usage

Call GzipHandler with any handler (an object which implements the
http.Handler interface), and it'll return a new handler which gzips the
response. For example:

go
package main

import (
	"io"
	"net/http"
	"github.com/NYTimes/gziphandler"
)

func main() {
	withoutGz := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain")
		io.WriteString(w, "Hello, World")
	})

	withGz := gziphandler.GzipHandler(withoutGz)

	http.Handle("/", withGz)
	http.ListenAndServe("0.0.0.0:8000", nil)
}

Documentation

The docs can be found at godoc.org, as usual.

License

Apache 2.0.


Overview (`vendor/github.com/PuerkitoBio/purell/README.md`)

Purell

Purell is a tiny Go library to normalize URLs. It returns a pure URL. Pure-ell. Sanitizer and all. Yeah, I know...

Based on the wikipedia paper and the RFC 3986 document.

Install

go get github.com/PuerkitoBio/purell

Changelog

  • 2016-07-27 (v1.0.0) : Normalize IDN to ASCII (thanks to @zenovich).
  • 2015-02-08 : Add fix for relative paths issue (PR #5) and add fix for unnecessary encoding of reserved characters (see issue #7).
  • v0.2.0 : Add benchmarks, Attempt IDN support.
  • v0.1.0 : Initial release.

Examples

From example_test.go (note that in your code, you would import "github.com/PuerkitoBio/purell", and would prefix references to its methods and constants with "purell."):

go
package purell

import (
  "fmt"
  "net/url"
)

func ExampleNormalizeURLString() {
  if normalized, err := NormalizeURLString("hTTp://someWEBsite.com:80/Amazing%3f/url/",
    FlagLowercaseScheme|FlagLowercaseHost|FlagUppercaseEscapes); err != nil {
    panic(err)
  } else {
    fmt.Print(normalized)
  }
  // Output: http://somewebsite.com:80/Amazing%3F/url/
}

func ExampleMustNormalizeURLString() {
  normalized := MustNormalizeURLString("hTTpS://someWEBsite.com:443/Amazing%fa/url/",
    FlagsUnsafeGreedy)
  fmt.Print(normalized)

  // Output: http://somewebsite.com/Amazing%FA/url
}

func ExampleNormalizeURL() {
  if u, err := url.Parse("Http://SomeUrl.com:8080/a/b/.././c///g?c=3&a=1&b=9&c=0#target"); err != nil {
    panic(err)
  } else {
    normalized := NormalizeURL(u, FlagsUsuallySafeGreedy|FlagRemoveDuplicateSlashes|FlagRemoveFragment)
    fmt.Print(normalized)
  }

  // Output: http://someurl.com:8080/a/c/g?c=3&a=1&b=9&c=0
}

API

As seen in the examples above, purell offers three methods, NormalizeURLString(string, NormalizationFlags) (string, error), MustNormalizeURLString(string, NormalizationFlags) (string) and NormalizeURL(*url.URL, NormalizationFlags) (string). They all normalize the provided URL based on the specified flags. Here are the available flags:

text
/* Detailed source-code truncated for AI context efficiency. */

For convenience, the set of flags FlagsSafe, FlagsUsuallySafe[Greedy|NonGreedy], FlagsUnsafe[Greedy|NonGreedy] and FlagsAll[Greedy|NonGreedy] are provided for the similarly grouped normalizations on wikipedia's URL normalization page. You can add (using the bitwise OR | operator) or remove (using the bitwise AND NOT &^ operator) individual flags from the sets if required, to build your own custom set.

The full godoc reference is available on gopkgdoc.

Some things to note:

  • FlagDecodeUnnecessaryEscapes, FlagEncodeNecessaryEscapes, FlagUppercaseEscapes and FlagRemoveEmptyQuerySeparator are always implicitly set, because internally, the URL string is parsed as an URL object, which automatically decodes unnecessary escapes, uppercases and encodes necessary ones, and removes empty query separators (an unnecessary ? at the end of the url). So this operation cannot not be done. For this reason, FlagRemoveEmptyQuerySeparator (as well as the other three) has been included in the FlagsSafe convenience set, instead of FlagsUnsafe, where Wikipedia puts it.

  • The FlagDecodeUnnecessaryEscapes decodes the following escapes (from -> to):

text
-    %24 -> $
-    %26 -> &
-    %2B-%3B -> +,-./0123456789:;
-    %3D -> =
-    %40-%5A -> @ABCDEFGHIJKLMNOPQRSTUVWXYZ
-    %5F -> _
-    %61-%7A -> abcdefghijklmnopqrstuvwxyz
-    %7E -> ~
  • When the NormalizeURL function is used (passing an URL object), this source URL object is modified (that is, after the call, the URL object will be modified to reflect the normalization).

  • The replace IP with domain name normalization (http://208.77.188.166/ → http://www.example.com/) is obviously not possible for a library without making some network requests. This is not implemented in purell.

  • The remove unused query string parameters and remove default query parameters are also not implemented, since this is a very case-specific normalization, and it is quite trivial to do with an URL object.

Safe vs Usually Safe vs Unsafe

Purell allows you to control the level of risk you take while normalizing an URL. You can aggressively normalize, play it totally safe, or anything in between.

Consider the following URL:

HTTPS://www.RooT.com/toto/t%45%1f///a/./b/../c/?z=3&w=2&a=4&w=1#invalid

Normalizing with the FlagsSafe gives:

https://www.root.com/toto/tE%1F///a/./b/../c/?z=3&w=2&a=4&w=1#invalid

With the FlagsUsuallySafeGreedy:

https://www.root.com/toto/tE%1F///a/c?z=3&w=2&a=4&w=1#invalid

And with FlagsUnsafeGreedy:

http://root.com/toto/tE%1F/a/c?a=4&w=1&w=2&z=3

TODOs

  • Add a class/default instance to allow specifying custom directory index names? At the moment, removing directory index removes (^|/)((?:default|index)\.\w{1,4})$.

Thanks / Contributions

@rogpeppe
@jehiah
@opennota
@pchristopher1275
@zenovich

License

The BSD 3-Clause license.


Overview (`vendor/github.com/PuerkitoBio/urlesc/README.md`)

urlesc [](https://travis-ci.org/PuerkitoBio/urlesc) [](http://godoc.org/github.com/PuerkitoBio/urlesc)

Package urlesc implements query escaping as per RFC 3986.

It contains some parts of the net/url package, modified so as to allow
some reserved characters incorrectly escaped by net/url (see issue 5684).

Install

text
go get github.com/PuerkitoBio/urlesc

License

Go license (BSD-3-Clause)


Overview (`vendor/github.com/abbot/go-http-auth/README.md`)

HTTP Authentication implementation in Go

This is an implementation of HTTP Basic and HTTP Digest authentication
in Go language. It is designed as a simple wrapper for
http.RequestHandler functions.

Features

  • Supports HTTP Basic and HTTP Digest authentication.
  • Supports htpasswd and htdigest formatted files.
  • Automatic reloading of password files.
  • Pluggable interface for user/password storage.
  • Supports MD5 and SHA1 for Basic authentication password storage.
  • Configurable Digest nonce cache size with expiration.
  • Wrapper for legacy http handlers (http.HandlerFunc interface)

Example usage

This is a complete working example for Basic auth:

text
package main

import (
        auth "github.com/abbot/go-http-auth"
        "fmt"
        "net/http"
)

func Secret(user, realm string) string {
        if user == "john" {
                // password is "hello"
                return "$1$dlPL2MqE$oQmn16q49SqdmhenQuNgs1"
        }
        return ""
}

func handle(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
        fmt.Fprintf(w, "<html><h1>Hello, %s!</h1></html>", r.Username)
}

func main() {
        authenticator := auth.NewBasicAuthenticator("example.com", Secret)
        http.HandleFunc("/", authenticator.Wrap(handle))
        http.ListenAndServe(":8080", nil)
}

See more examples in the "examples" directory.

This module is developed under Apache 2.0 license, and can be used for
open and proprietary projects.

Copyright 2012-2013 Lev Shamardin

Licensed under the Apache License, Version 2.0 (the "License"); you
may not use this file or any other part of this project 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.


Overview (`vendor/github.com/armon/circbuf/README.md`)

circbuf

This repository provides the circbuf package. This provides a Buffer object
which is a circular (or ring) buffer. It has a fixed size, but can be written
to infinitely. Only the last size bytes are ever retained. The buffer implements
the io.Writer interface.

Documentation

Full documentation can be found on Godoc

Usage

The circbuf package is very easy to use:

go
buf, _ := NewBuffer(6)
buf.Write([]byte("hello world"))

if string(buf.Bytes()) != " world" {
    panic("should only have last 6 bytes!")
}

Overview (`vendor/github.com/asaskevich/govalidator/README.md`)

govalidator


A package of validators and sanitizers for strings, structs and collections. Based on validator.js.

Installation

Make sure that Go is installed on your computer.
Type the following command in your terminal:

text
go get github.com/asaskevich/govalidator

or you can get specified release of the package with gopkg.in:

text
go get gopkg.in/asaskevich/govalidator.v4

After it the package is ready to use.

Import package in your project

Add following line in your *.go file:

go
import "github.com/asaskevich/govalidator"

If you are unhappy to use long govalidator, you can do something like this:

go
import (
  valid "github.com/asaskevich/govalidator"
)

Activate behavior to require all fields have a validation tag by default

SetFieldsRequiredByDefault causes validation to fail when struct fields do not include validations or are not explicitly marked as exempt (using valid:"-" or valid:"email,optional"). A good place to activate this is a package init function or the main() function.

go
import "github.com/asaskevich/govalidator"

func init() {
  govalidator.SetFieldsRequiredByDefault(true)
}

Here's some code to explain it:

go
// this struct definition will fail govalidator.ValidateStruct() (and the field values do not matter):
type exampleStruct struct {
  Name  string ``
  Email string `valid:"email"`
}

// this, however, will only fail when Email is empty or an invalid email address:
type exampleStruct2 struct {
  Name  string `valid:"-"`
  Email string `valid:"email"`
}

// lastly, this will only fail when Email is an invalid email address but not when it's empty:
type exampleStruct2 struct {
  Name  string `valid:"-"`
  Email string `valid:"email,optional"`
}

Recent breaking changes (see [#123](https://github.com/asaskevich/govalidator/pull/123))

Custom validator function signature

A context was added as the second parameter, for structs this is the object being validated – this makes dependent validation possible.

go
import "github.com/asaskevich/govalidator"

// old signature
func(i interface{}) bool

// new signature
func(i interface{}, o interface{}) bool

Adding a custom validator

This was changed to prevent data races when accessing custom validators.

go
import "github.com/asaskevich/govalidator"

// before
govalidator.CustomTypeTagMap["customByteArrayValidator"] = CustomTypeValidator(func(i interface{}, o interface{}) bool {
  // ...
})

// after
govalidator.CustomTypeTagMap.Set("customByteArrayValidator", CustomTypeValidator(func(i interface{}, o interface{}) bool {
  // ...
}))

List of functions:

text
/* Detailed source-code truncated for AI context efficiency. */

Examples

IsURL

go
println(govalidator.IsURL(`http://user@pass:domain.com/path/page`))

ToString

go
type User struct {
	FirstName string
	LastName string
}

str := govalidator.ToString(&User{"John", "Juan"})
println(str)

Each, Map, Filter, Count for slices

Each iterates over the slice/array and calls Iterator for every item

go
data := []interface{}{1, 2, 3, 4, 5}
var fn govalidator.Iterator = func(value interface{}, index int) {
	println(value.(int))
}
govalidator.Each(data, fn)
go
data := []interface{}{1, 2, 3, 4, 5}
var fn govalidator.ResultIterator = func(value interface{}, index int) interface{} {
	return value.(int) * 3
}
_ = govalidator.Map(data, fn) // result = []interface{}{1, 6, 9, 12, 15}
go
data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var fn govalidator.ConditionIterator = func(value interface{}, index int) bool {
	return value.(int)%2 == 0
}
_ = govalidator.Filter(data, fn) // result = []interface{}{2, 4, 6, 8, 10}
_ = govalidator.Count(data, fn) // result = 5

ValidateStruct [#2](https://github.com/asaskevich/govalidator/pull/2)

If you want to validate structs, you can use tag valid for any field in your structure. All validators used with this field in one tag are separated by comma. If you want to skip validation, place - in your tag. If you need a validator that is not on the list below, you can add it like this:

go
govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool {
	return str == "duck"
})

For completely custom validators (interface-based), see below.

Here is a list of available validators for struct fields (validator - used function):

go
"alpha":          IsAlpha,
"alphanum":       IsAlphanumeric,
"ascii":          IsASCII,
"base64":         IsBase64,
"creditcard":     IsCreditCard,
"datauri":        IsDataURI,
"dialstring":     IsDialString,
"dns":            IsDNSName,
"email":          IsEmail,
"float":          IsFloat,
"fullwidth":      IsFullWidth,
"halfwidth":      IsHalfWidth,
"hexadecimal":    IsHexadecimal,
"hexcolor":       IsHexcolor,
"host":           IsHost,
"int":            IsInt,
"ip":             IsIP,
"ipv4":           IsIPv4,
"ipv6":           IsIPv6,
"isbn10":         IsISBN10,
"isbn13":         IsISBN13,
"json":           IsJSON,
"latitude":       IsLatitude,
"longitude":      IsLongitude,
"lowercase":      IsLowerCase,
"mac":            IsMAC,
"multibyte":      IsMultibyte,
"null":           IsNull,
"numeric":        IsNumeric,
"port":           IsPort,
"printableascii": IsPrintableASCII,
"requri":         IsRequestURI,
"requrl":         IsRequestURL,
"rgbcolor":       IsRGBcolor,
"ssn":            IsSSN,
"semver":         IsSemver,
"uppercase":      IsUpperCase,
"url":            IsURL,
"utfdigit":       IsUTFDigit,
"utfletter":      IsUTFLetter,
"utfletternum":   IsUTFLetterNumeric,
"utfnumeric":     IsUTFNumeric,
"uuid":           IsUUID,
"uuidv3":         IsUUIDv3,
"uuidv4":         IsUUIDv4,
"uuidv5":         IsUUIDv5,
"variablewidth":  IsVariableWidth,

Validators with parameters

go
"length(min|max)": ByteLength,
"matches(pattern)": StringMatches,

And here is small example of usage:

go
type Post struct {
	Title    string `valid:"alphanum,required"`
	Message  string `valid:"duck,ascii"`
	AuthorIP string `valid:"ipv4"`
	Date     string `valid:"-"`
}
post := &Post{
	Title:   "My Example Post",
	Message: "duck",
	AuthorIP: "123.234.54.3",
}

// Add your own struct validation tags
govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool {
	return str == "duck"
})

result, err := govalidator.ValidateStruct(post)
if err != nil {
	println("error: " + err.Error())
}
println(result)

WhiteList

go
// Remove all characters from string ignoring characters between "a" and "z"
println(govalidator.WhiteList("a3a43a5a4a3a2a23a4a5a4a3a4", "a-z") == "aaaaaaaaaaaa")

Custom validation functions

Custom validation using your own domain specific validators is also available - here's an example of how to use it:

text
/* Detailed source-code truncated for AI context efficiency. */

Notes

Documentation is available here: godoc.org.
Full information about code coverage is also available here: govalidator on gocover.io.

Support

If you do have a contribution for the package feel free to put up a Pull Request or open Issue.

Special thanks to [contributors](https://github.com/asaskevich/govalidator/graphs/contributors)


Overview (`vendor/github.com/blang/semver/README.md`)

semver for golang [](https://drone.io/github.com/blang/semver/latest) [](https://godoc.org/github.com/blang/semver) [](https://coveralls.io/r/blang/semver?branch=master)

semver is a Semantic Versioning library written in golang. It fully covers spec version 2.0.0.

Usage

bash
$ go get github.com/blang/semver

Note: Always vendor your dependencies or fix on a specific version tag.

go
import github.com/blang/semver
v1, err := semver.Make("1.0.0-beta")
v2, err := semver.Make("2.0.0-beta")
v1.Compare(v2)

Also check the GoDocs.

Why should I use this lib?

  • Fully spec compatible
  • No reflection
  • No regex
  • Fully tested (Coverage >99%)
  • Readable parsing/validation errors
  • Fast (See Benchmarks)
  • Only Stdlib
  • Uses values instead of pointers
  • Many features, see below

Features

  • Parsing and validation at all levels
  • Comparator-like comparisons
  • Compare Helper Methods
  • InPlace manipulation
  • Ranges >=1.0.0 <2.0.0 || >=3.0.0 !3.0.1-beta.1
  • Sortable (implements sort.Interface)
  • database/sql compatible (sql.Scanner/Valuer)
  • encoding/json compatible (json.Marshaler/Unmarshaler)

Ranges

A Range is a set of conditions which specify which versions satisfy the range.

A condition is composed of an operator and a version. The supported operators are:

  • <1.0.0 Less than 1.0.0
  • <=1.0.0 Less than or equal to 1.0.0
  • >1.0.0 Greater than 1.0.0
  • >=1.0.0 Greater than or equal to 1.0.0
  • 1.0.0, =1.0.0, ==1.0.0 Equal to 1.0.0
  • !1.0.0, !=1.0.0 Not equal to 1.0.0. Excludes version 1.0.0.

A Range can link multiple Ranges separated by space:

Ranges can be linked by logical AND:

  • >1.0.0 <2.0.0 would match between both ranges, so 1.1.1 and 1.8.7 but not 1.0.0 or 2.0.0
  • >1.0.0 <3.0.0 !2.0.3-beta.2 would match every version between 1.0.0 and 3.0.0 except 2.0.3-beta.2

Ranges can also be linked by logical OR:

  • <2.0.0 || >=3.0.0 would match 1.x.x and 3.x.x but not 2.x.x

AND has a higher precedence than OR. It's not possible to use brackets.

Ranges can be combined by both AND and OR

  • >1.0.0 <2.0.0 || >3.0.0 !4.2.1 would match 1.2.3, 1.9.9, 3.1.1, but not 4.2.1, 2.1.1

Range usage:

text
v, err := semver.Parse("1.2.3")
range, err := semver.ParseRange(">1.0.0 <2.0.0 || >=3.0.0")
if range(v) {
    //valid
}

Example

Have a look at full examples in examples/main.go

go
import github.com/blang/semver

v, err := semver.Make("0.0.1-alpha.preview+123.github")
fmt.Printf("Major: %d\n", v.Major)
fmt.Printf("Minor: %d\n", v.Minor)
fmt.Printf("Patch: %d\n", v.Patch)
fmt.Printf("Pre: %s\n", v.Pre)
fmt.Printf("Build: %s\n", v.Build)

// Prerelease versions array
if len(v.Pre) > 0 {
    fmt.Println("Prerelease versions:")
    for i, pre := range v.Pre {
        fmt.Printf("%d: %q\n", i, pre)
    }
}

// Build meta data array
if len(v.Build) > 0 {
    fmt.Println("Build meta data:")
    for i, build := range v.Build {
        fmt.Printf("%d: %q\n", i, build)
    }
}

v001, err := semver.Make("0.0.1")
// Compare using helpers: v.GT(v2), v.LT, v.GTE, v.LTE
v001.GT(v) == true
v.LT(v001) == true
v.GTE(v) == true
v.LTE(v) == true

// Or use v.Compare(v2) for comparisons (-1, 0, 1):
v001.Compare(v) == 1
v.Compare(v001) == -1
v.Compare(v) == 0

// Manipulate Version in place:
v.Pre[0], err = semver.NewPRVersion("beta")
if err != nil {
    fmt.Printf("Error parsing pre release version: %q", err)
}

fmt.Println("\nValidate versions:")
v.Build[0] = "?"

err = v.Validate()
if err != nil {
    fmt.Printf("Validation failed: %s\n", err)
}

Benchmarks

text
BenchmarkParseSimple-4           5000000    390    ns/op    48 B/op   1 allocs/op
BenchmarkParseComplex-4          1000000   1813    ns/op   256 B/op   7 allocs/op
BenchmarkParseAverage-4          1000000   1171    ns/op   163 B/op   4 allocs/op
BenchmarkStringSimple-4         20000000    119    ns/op    16 B/op   1 allocs/op
BenchmarkStringLarger-4         10000000    206    ns/op    32 B/op   2 allocs/op
BenchmarkStringComplex-4         5000000    324    ns/op    80 B/op   3 allocs/op
BenchmarkStringAverage-4         5000000    273    ns/op    53 B/op   2 allocs/op
BenchmarkValidateSimple-4      200000000      9.33 ns/op     0 B/op   0 allocs/op
BenchmarkValidateComplex-4       3000000    469    ns/op     0 B/op   0 allocs/op
BenchmarkValidateAverage-4       5000000    256    ns/op     0 B/op   0 allocs/op
BenchmarkCompareSimple-4       100000000     11.8  ns/op     0 B/op   0 allocs/op
BenchmarkCompareComplex-4       50000000     30.8  ns/op     0 B/op   0 allocs/op
BenchmarkCompareAverage-4       30000000     41.5  ns/op     0 B/op   0 allocs/op
BenchmarkSort-4                  3000000    419    ns/op   256 B/op   2 allocs/op
BenchmarkRangeParseSimple-4      2000000    850    ns/op   192 B/op   5 allocs/op
BenchmarkRangeParseAverage-4     1000000   1677    ns/op   400 B/op  10 allocs/op
BenchmarkRangeParseComplex-4      300000   5214    ns/op  1440 B/op  30 allocs/op
BenchmarkRangeMatchSimple-4     50000000     25.6  ns/op     0 B/op   0 allocs/op
BenchmarkRangeMatchAverage-4    30000000     56.4  ns/op     0 B/op   0 allocs/op
BenchmarkRangeMatchComplex-4    10000000    153    ns/op     0 B/op   0 allocs/op

See benchmark cases at semver_test.go

Motivation

I simply couldn't find any lib supporting the full spec. Others were just wrong or used reflection and regex which i don't like.

Contribution

Feel free to make a pull request. For bigger changes create a issue first to discuss about it.

License

See LICENSE file.


Overview (`vendor/github.com/boltdb/bolt/README.md`)

Bolt [](https://coveralls.io/r/boltdb/bolt?branch=master) [](https://godoc.org/github.com/boltdb/bolt)

Bolt is a pure Go key/value store inspired by Howard Chu's
LMDB project. The goal of the project is to provide a simple,
fast, and reliable database for projects that don't require a full database
server such as Postgres or MySQL.

Since Bolt is meant to be used as such a low-level piece of functionality,
simplicity is key. The API will be small and only focus on getting values
and setting values. That's it.

Project Status

Bolt is stable and the API is fixed. Full unit test coverage and randomized
black box testing are used to ensure database consistency and thread safety.
Bolt is currently in high-load production environments serving databases as
large as 1TB. Many companies such as Shopify and Heroku use Bolt-backed
services every day.

Table of Contents

Getting Started

Installing

To start using Bolt, install Go and run go get:

sh
$ go get github.com/boltdb/bolt/...

This will retrieve the library and install the bolt command line utility into
your $GOBIN path.

Opening a database

The top-level object in Bolt is a DB. It is represented as a single file on
your disk and represents a consistent snapshot of your data.

To open your database, simply use the bolt.Open() function:

go
package main

import (
	"log"

	"github.com/boltdb/bolt"
)

func main() {
	// Open the my.db data file in your current directory.
	// It will be created if it doesn't exist.
	db, err := bolt.Open("my.db", 0600, nil)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	...
}

Please note that Bolt obtains a file lock on the data file so multiple processes
cannot open the same database at the same time. Opening an already open Bolt
database will cause it to hang until the other process closes it. To prevent
an indefinite wait you can pass a timeout option to the Open() function:

go
db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second})

Transactions

Bolt allows only one read-write transaction at a time but allows as many
read-only transactions as you want at a time. Each transaction has a consistent
view of the data as it existed when the transaction started.

Individual transactions and all objects created from them (e.g. buckets, keys)
are not thread safe. To work with data in multiple goroutines you must start
a transaction for each one or use locking to ensure only one goroutine accesses
a transaction at a time. Creating transaction from the DB is thread safe.

Read-only transactions and read-write transactions should not depend on one
another and generally shouldn't be opened simultaneously in the same goroutine.
This can cause a deadlock as the read-write transaction needs to periodically
re-map the data file but it cannot do so while a read-only transaction is open.

Read-write transactions

To start a read-write transaction, you can use the DB.Update() function:

go
err := db.Update(func(tx *bolt.Tx) error {
	...
	return nil
})

Inside the closure, you have a consistent view of the database. You commit the
transaction by returning nil at the end. You can also rollback the transaction
at any point by returning an error. All database operations are allowed inside
a read-write transaction.

Always check the return error as it will report any disk failures that can cause
your transaction to not complete. If you return an error within your closure
it will be passed through.

Read-only transactions

To start a read-only transaction, you can use the DB.View() function:

go
err := db.View(func(tx *bolt.Tx) error {
	...
	return nil
})

You also get a consistent view of the database within this closure, however,
no mutating operations are allowed within a read-only transaction. You can only
retrieve buckets, retrieve values, and copy the database within a read-only
transaction.

Batch read-write transactions

Each DB.Update() waits for disk to commit the writes. This overhead
can be minimized by combining multiple updates with the DB.Batch()
function:

go
err := db.Batch(func(tx *bolt.Tx) error {
	...
	return nil
})

Concurrent Batch calls are opportunistically combined into larger
transactions. Batch is only useful when there are multiple goroutines
calling it.

The trade-off is that Batch can call the given
function multiple times, if parts of the transaction fail. The
function must be idempotent and side effects must take effect only
after a successful return from DB.Batch().

For example: don't display messages from inside the function, instead
set variables in the enclosing scope:

go
var id uint64
err := db.Batch(func(tx *bolt.Tx) error {
	// Find last key in bucket, decode as bigendian uint64, increment
	// by one, encode back to []byte, and add new key.
	...
	id = newValue
	return nil
})
if err != nil {
	return ...
}
fmt.Println("Allocated ID %d", id)

Managing transactions manually

The DB.View() and DB.Update() functions are wrappers around the DB.Begin()
function. These helper functions will start the transaction, execute a function,
and then safely close your transaction if an error is returned. This is the
recommended way to use Bolt transactions.

However, sometimes you may want to manually start and end your transactions.
You can use the Tx.Begin() function directly but please be sure to close
the transaction.

go
// Start a writable transaction.
tx, err := db.Begin(true)
if err != nil {
    return err
}
defer tx.Rollback()

// Use the transaction...
_, err := tx.CreateBucket([]byte("MyBucket"))
if err != nil {
    return err
}

// Commit the transaction and check for error.
if err := tx.Commit(); err != nil {
    return err
}

The first argument to DB.Begin() is a boolean stating if the transaction
should be writable.

Using buckets

Buckets are collections of key/value pairs within the database. All keys in a
bucket must be unique. You can create a bucket using the DB.CreateBucket()
function:

go
db.Update(func(tx *bolt.Tx) error {
	b, err := tx.CreateBucket([]byte("MyBucket"))
	if err != nil {
		return fmt.Errorf("create bucket: %s", err)
	}
	return nil
})

You can also create a bucket only if it doesn't exist by using the
Tx.CreateBucketIfNotExists() function. It's a common pattern to call this
function for all your top-level buckets after you open your database so you can
guarantee that they exist for future transactions.

To delete a bucket, simply call the Tx.DeleteBucket() function.

Using key/value pairs

To save a key/value pair to a bucket, use the Bucket.Put() function:

go
db.Update(func(tx *bolt.Tx) error {
	b := tx.Bucket([]byte("MyBucket"))
	err := b.Put([]byte("answer"), []byte("42"))
	return err
})

This will set the value of the "answer" key to "42" in the MyBucket
bucket. To retrieve this value, we can use the Bucket.Get() function:

go
db.View(func(tx *bolt.Tx) error {
	b := tx.Bucket([]byte("MyBucket"))
	v := b.Get([]byte("answer"))
	fmt.Printf("The answer is: %s\n", v)
	return nil
})

The Get() function does not return an error because its operation is
guaranteed to work (unless there is some kind of system failure). If the key
exists then it will return its byte slice value. If it doesn't exist then it
will return nil. It's important to note that you can have a zero-length value
set to a key which is different than the key not existing.

Use the Bucket.Delete() function to delete a key from the bucket.

Please note that values returned from Get() are only valid while the
transaction is open. If you need to use a value outside of the transaction
then you must use copy() to copy it to another byte slice.

Autoincrementing integer for the bucket

By using the NextSequence() function, you can let Bolt determine a sequence
which can be used as the unique identifier for your key/value pairs. See the
example below.

go
// CreateUser saves u to the store. The new user ID is set on u once the data is persisted.
func (s *Store) CreateUser(u *User) error {
    return s.db.Update(func(tx *bolt.Tx) error {
        // Retrieve the users bucket.
        // This should be created when the DB is first opened.
        b := tx.Bucket([]byte("users"))

        // Generate ID for the user.
        // This returns an error only if the Tx is closed or not writeable.
        // That can't happen in an Update() call so I ignore the error check.
        id, _ := b.NextSequence()
        u.ID = int(id)

        // Marshal user data into bytes.
        buf, err := json.Marshal(u)
        if err != nil {
            return err
        }

        // Persist bytes to users bucket.
        return b.Put(itob(u.ID), buf)
    })
}

// itob returns an 8-byte big endian representation of v.
func itob(v int) []byte {
    b := make([]byte, 8)
    binary.BigEndian.PutUint64(b, uint64(v))
    return b
}

type User struct {
    ID int
    ...
}

Iterating over keys

Bolt stores its keys in byte-sorted order within a bucket. This makes sequential
iteration over these keys extremely fast. To iterate over keys we'll use a
Cursor:

go
db.View(func(tx *bolt.Tx) error {
	// Assume bucket exists and has keys
	b := tx.Bucket([]byte("MyBucket"))

	c := b.Cursor()

	for k, v := c.First(); k != nil; k, v = c.Next() {
		fmt.Printf("key=%s, value=%s\n", k, v)
	}

	return nil
})

The cursor allows you to move to a specific point in the list of keys and move
forward or backward through the keys one at a time.

The following functions are available on the cursor:

text
First()  Move to the first key.
Last()   Move to the last key.
Seek()   Move to a specific key.
Next()   Move to the next key.
Prev()   Move to the previous key.

Each of those functions has a return signature of (key []byte, value []byte).
When you have iterated to the end of the cursor then Next() will return a
nil key. You must seek to a position using First(), Last(), or Seek()
before calling Next() or Prev(). If you do not seek to a position then
these functions will return a nil key.

During iteration, if the key is non-nil but the value is nil, that means
the key refers to a bucket rather than a value. Use Bucket.Bucket() to
access the sub-bucket.

Prefix scans

To iterate over a key prefix, you can combine Seek() and bytes.HasPrefix():

go
db.View(func(tx *bolt.Tx) error {
	// Assume bucket exists and has keys
	c := tx.Bucket([]byte("MyBucket")).Cursor()

	prefix := []byte("1234")
	for k, v := c.Seek(prefix); bytes.HasPrefix(k, prefix); k, v = c.Next() {
		fmt.Printf("key=%s, value=%s\n", k, v)
	}

	return nil
})

Range scans

Another common use case is scanning over a range such as a time range. If you
use a sortable time encoding such as RFC3339 then you can query a specific
date range like this:

go
db.View(func(tx *bolt.Tx) error {
	// Assume our events bucket exists and has RFC3339 encoded time keys.
	c := tx.Bucket([]byte("Events")).Cursor()

	// Our time range spans the 90's decade.
	min := []byte("1990-01-01T00:00:00Z")
	max := []byte("2000-01-01T00:00:00Z")

	// Iterate over the 90's.
	for k, v := c.Seek(min); k != nil && bytes.Compare(k, max) <= 0; k, v = c.Next() {
		fmt.Printf("%s: %s\n", k, v)
	}

	return nil
})

Note that, while RFC3339 is sortable, the Golang implementation of RFC3339Nano does not use a fixed number of digits after the decimal point and is therefore not sortable.

ForEach()

You can also use the function ForEach() if you know you'll be iterating over
all the keys in a bucket:

go
db.View(func(tx *bolt.Tx) error {
	// Assume bucket exists and has keys
	b := tx.Bucket([]byte("MyBucket"))

	b.ForEach(func(k, v []byte) error {
		fmt.Printf("key=%s, value=%s\n", k, v)
		return nil
	})
	return nil
})

Nested buckets

You can also store a bucket in a key to create nested buckets. The API is the
same as the bucket management API on the DB object:

go
func (*Bucket) CreateBucket(key []byte) (*Bucket, error)
func (*Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error)
func (*Bucket) DeleteBucket(key []byte) error

Database backups

Bolt is a single file so it's easy to backup. You can use the Tx.WriteTo()
function to write a consistent view of the database to a writer. If you call
this from a read-only transaction, it will perform a hot backup and not block
your other database reads and writes.

By default, it will use a regular file handle which will utilize the operating
system's page cache. See the Tx
documentation for information about optimizing for larger-than-RAM datasets.

One common use case is to backup over HTTP so you can use tools like cURL to
do database backups:

go
func BackupHandleFunc(w http.ResponseWriter, req *http.Request) {
	err := db.View(func(tx *bolt.Tx) error {
		w.Header().Set("Content-Type", "application/octet-stream")
		w.Header().Set("Content-Disposition", `attachment; filename="my.db"`)
		w.Header().Set("Content-Length", strconv.Itoa(int(tx.Size())))
		_, err := tx.WriteTo(w)
		return err
	})
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

Then you can backup using this command:

sh
$ curl http://localhost/backup > my.db

Or you can open your browser to http://localhost/backup and it will download
automatically.

If you want to backup to another file you can use the Tx.CopyFile() helper
function.

Statistics

The database keeps a running count of many of the internal operations it
performs so you can better understand what's going on. By grabbing a snapshot
of these stats at two points in time we can see what operations were performed
in that time range.

For example, we could start a goroutine to log stats every 10 seconds:

go
go func() {
	// Grab the initial stats.
	prev := db.Stats()

	for {
		// Wait for 10s.
		time.Sleep(10 * time.Second)

		// Grab the current stats and diff them.
		stats := db.Stats()
		diff := stats.Sub(&prev)

		// Encode stats to JSON and print to STDERR.
		json.NewEncoder(os.Stderr).Encode(diff)

		// Save stats for the next loop.
		prev = stats
	}
}()

It's also useful to pipe these stats to a service such as statsd for monitoring
or to provide an HTTP endpoint that will perform a fixed-length sample.

Read-Only Mode

Sometimes it is useful to create a shared, read-only Bolt database. To this,
set the Options.ReadOnly flag when opening your database. Read-only mode
uses a shared lock to allow multiple processes to read from the database but
it will block any processes from opening the database in read-write mode.

go
db, err := bolt.Open("my.db", 0666, &bolt.Options{ReadOnly: true})
if err != nil {
	log.Fatal(err)
}

Mobile Use (iOS/Android)

Bolt is able to run on mobile devices by leveraging the binding feature of the
gomobile tool. Create a struct that will
contain your database logic and a reference to a *bolt.DB with a initializing
constructor that takes in a filepath where the database file will be stored.
Neither Android nor iOS require extra permissions or cleanup from using this method.

go
func NewBoltDB(filepath string) *BoltDB {
	db, err := bolt.Open(filepath+"/demo.db", 0600, nil)
	if err != nil {
		log.Fatal(err)
	}

	return &BoltDB{db}
}

type BoltDB struct {
	db *bolt.DB
	...
}

func (b *BoltDB) Path() string {
	return b.db.Path()
}

func (b *BoltDB) Close() {
	b.db.Close()
}

Database logic should be defined as methods on this wrapper struct.

To initialize this struct from the native language (both platforms now sync
their local storage to the cloud. These snippets disable that functionality for the
database file):

Android

java
String path;
if (android.os.Build.VERSION.SDK_INT >=android.os.Build.VERSION_CODES.LOLLIPOP){
    path = getNoBackupFilesDir().getAbsolutePath();
} else{
    path = getFilesDir().getAbsolutePath();
}
Boltmobiledemo.BoltDB boltDB = Boltmobiledemo.NewBoltDB(path)

iOS

objc
- (void)demo {
    NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
                                                          NSUserDomainMask,
                                                          YES) objectAtIndex:0];
	GoBoltmobiledemoBoltDB * demo = GoBoltmobiledemoNewBoltDB(path);
	[self addSkipBackupAttributeToItemAtPath:demo.path];
	//Some DB Logic would go here
	[demo close];
}

- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString
{
    NSURL* URL= [NSURL fileURLWithPath: filePathString];
    assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);

    NSError *error = nil;
    BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
                                  forKey: NSURLIsExcludedFromBackupKey error: &error];
    if(!success){
        NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
    }
    return success;
}

Resources

For more information on getting started with Bolt, check out the following articles:

Comparison with other databases

Postgres, MySQL, & other relational databases

Relational databases structure data into rows and are only accessible through
the use of SQL. This approach provides flexibility in how you store and query
your data but also incurs overhead in parsing and planning SQL statements. Bolt
accesses all data by a byte slice key. This makes Bolt fast to read and write
data by key but provides no built-in support for joining values together.

Most relational databases (with the exception of SQLite) are standalone servers
that run separately from your application. This gives your systems
flexibility to connect multiple application servers to a single database
server but also adds overhead in serializing and transporting data over the
network. Bolt runs as a library included in your application so all data access
has to go through your application's process. This brings data closer to your
application but limits multi-process access to the data.

LevelDB, RocksDB

LevelDB and its derivatives (RocksDB, HyperLevelDB) are similar to Bolt in that
they are libraries bundled into the application, however, their underlying
structure is a log-structured merge-tree (LSM tree). An LSM tree optimizes
random writes by using a write ahead log and multi-tiered, sorted files called
SSTables. Bolt uses a B+tree internally and only a single file. Both approaches
have trade-offs.

If you require a high random write throughput (>10,000 w/sec) or you need to use
spinning disks then LevelDB could be a good choice. If your application is
read-heavy or does a lot of range scans then Bolt could be a good choice.

One other important consideration is that LevelDB does not have transactions.
It supports batch writing of key/values pairs and it supports read snapshots
but it will not give you the ability to do a compare-and-swap operation safely.
Bolt supports fully serializable ACID transactions.

LMDB

Bolt was originally a port of LMDB so it is architecturally similar. Both use
a B+tree, have ACID semantics with fully serializable transactions, and support
lock-free MVCC using a single writer and multiple readers.

The two projects have somewhat diverged. LMDB heavily focuses on raw performance
while Bolt has focused on simplicity and ease of use. For example, LMDB allows
several unsafe actions such as direct writes for the sake of performance. Bolt
opts to disallow actions which can leave the database in a corrupted state. The
only exception to this in Bolt is DB.NoSync.

There are also a few differences in API. LMDB requires a maximum mmap size when
opening an mdb_env whereas Bolt will handle incremental mmap resizing
automatically. LMDB overloads the getter and setter functions with multiple
flags whereas Bolt splits these specialized cases into their own functions.

Caveats & Limitations

It's important to pick the right tool for the job and Bolt is no exception.
Here are a few things to note when evaluating and using Bolt:

  • Bolt is good for read intensive workloads. Sequential write performance is
    also fast but random writes can be slow. You can use DB.Batch() or add a
    write-ahead log to help mitigate this issue.

  • Bolt uses a B+tree internally so there can be a lot of random page access.
    SSDs provide a significant performance boost over spinning disks.

  • Try to avoid long running read transactions. Bolt uses copy-on-write so
    old pages cannot be reclaimed while an old transaction is using them.

  • Byte slices returned from Bolt are only valid during a transaction. Once the
    transaction has been committed or rolled back then the memory they point to
    can be reused by a new page or can be unmapped from virtual memory and you'll
    see an unexpected fault address panic when accessing it.

  • Be careful when using Bucket.FillPercent. Setting a high fill percent for
    buckets that have random inserts will cause your database to have very poor
    page utilization.

  • Use larger buckets in general. Smaller buckets causes poor page utilization
    once they become larger than the page size (typically 4KB).

  • Bulk loading a lot of random writes into a new bucket can be slow as the
    page will not split until the transaction is committed. Randomly inserting
    more than 100,000 key/value pairs into a single new bucket in a single
    transaction is not advised.

  • Bolt uses a memory-mapped file so the underlying operating system handles the
    caching of the data. Typically, the OS will cache as much of the file as it
    can in memory and will release memory as needed to other processes. This means
    that Bolt can show very high memory usage when working with large databases.
    However, this is expected and the OS will release memory as needed. Bolt can
    handle databases much larger than the available physical RAM, provided its
    memory-map fits in the process virtual address space. It may be problematic
    on 32-bits systems.

  • The data structures in the Bolt database are memory mapped so the data file
    will be endian specific. This means that you cannot copy a Bolt file from a
    little endian machine to a big endian machine and have it work. For most
    users this is not a concern since most modern CPUs are little endian.

  • Because of the way pages are laid out on disk, Bolt cannot truncate data files
    and return free pages back to the disk. Instead, Bolt maintains a free list
    of unused pages within its data file. These free pages can be reused by later
    transactions. This works well for many use cases as databases generally tend
    to grow. However, it's important to note that deleting large chunks of data
    will not allow you to reclaim that space on disk.

    For more information on page allocation, see this comment.

Reading the Source

Bolt is a relatively small code base (<3KLOC) for an embedded, serializable,
transactional key/value database so it can be a good starting point for people
interested in how databases work.

The best places to start are the main entry points into Bolt:

  • Open() - Initializes the reference to the database. It's responsible for
    creating the database if it doesn't exist, obtaining an exclusive lock on the
    file, reading the meta pages, & memory-mapping the file.

  • DB.Begin() - Starts a read-only or read-write transaction depending on the
    value of the writable argument. This requires briefly obtaining the "meta"
    lock to keep track of open transactions. Only one read-write transaction can
    exist at a time so the "rwlock" is acquired during the life of a read-write
    transaction.

  • Bucket.Put() - Writes a key/value pair into a bucket. After validating the
    arguments, a cursor is used to traverse the B+tree to the page and position
    where they key & value will be written. Once the position is found, the bucket
    materializes the underlying page and the page's parent pages into memory as
    "nodes". These nodes are where mutations occur during read-write transactions.
    These changes get flushed to disk during commit.

  • Bucket.Get() - Retrieves a key/value pair from a bucket. This uses a cursor
    to move to the page & position of a key/value pair. During a read-only
    transaction, the key and value data is returned as a direct reference to the
    underlying mmap file so there's no allocation overhead. For read-write
    transactions, this data may reference the mmap file or one of the in-memory
    node values.

  • Cursor - This object is simply for traversing the B+tree of on-disk pages
    or in-memory nodes. It can seek to a specific key, move to the first or last
    value, or it can move forward or backward. The cursor handles the movement up
    and down the B+tree transparently to the end user.

  • Tx.Commit() - Converts the in-memory dirty nodes and the list of free pages
    into pages to be written to disk. Writing to disk then occurs in two phases.
    First, the dirty pages are written to disk and an fsync() occurs. Second, a
    new meta page with an incremented transaction ID is written and another
    fsync() occurs. This two phase write ensures that partially written data
    pages are ignored in the event of a crash since the meta page pointing to them
    is never written. Partially written meta pages are invalidated because they
    are written with a checksum.

If you have additional notes that could be helpful for others, please submit
them via pull request.

Other Projects Using Bolt

Below is a list of public, open source projects that use Bolt:

  • BoltDbWeb - A web based GUI for BoltDB files.
  • Operation Go: A Routine Mission - An online programming game for Golang using Bolt for user accounts and a leaderboard.
  • Bazil - A file system that lets your data reside where it is most convenient for it to reside.
  • DVID - Added Bolt as optional storage engine and testing it against Basho-tuned leveldb.
  • Skybox Analytics - A standalone funnel analysis tool for web analytics.
  • Scuttlebutt - Uses Bolt to store and process all Twitter mentions of GitHub projects.
  • Wiki - A tiny wiki using Goji, BoltDB and Blackfriday.
  • ChainStore - Simple key-value interface to a variety of storage engines organized as a chain of operations.
  • MetricBase - Single-binary version of Graphite.
  • Gitchain - Decentralized, peer-to-peer Git repositories aka "Git meets Bitcoin".
  • event-shuttle - A Unix system service to collect and reliably deliver messages to Kafka.
  • ipxed - Web interface and api for ipxed.
  • BoltStore - Session store using Bolt.
  • photosite/session - Sessions for a photo viewing site.
  • LedisDB - A high performance NoSQL, using Bolt as optional storage.
  • ipLocator - A fast ip-geo-location-server using bolt with bloom filters.
  • cayley - Cayley is an open-source graph database using Bolt as optional backend.
  • bleve - A pure Go search engine similar to ElasticSearch that uses Bolt as the default storage backend.
  • tentacool - REST api server to manage system stuff (IP, DNS, Gateway...) on a linux server.
  • Seaweed File System - Highly scalable distributed key~file system with O(1) disk read.
  • InfluxDB - Scalable datastore for metrics, events, and real-time analytics.
  • Freehold - An open, secure, and lightweight platform for your files and data.
  • Prometheus Annotation Server - Annotation server for PromDash & Prometheus service monitoring system.
  • Consul - Consul is service discovery and configuration made easy. Distributed, highly available, and datacenter-aware.
  • Kala - Kala is a modern job scheduler optimized to run on a single node. It is persistent, JSON over HTTP API, ISO 8601 duration notation, and dependent jobs.
  • drive - drive is an unofficial Google Drive command line client for *NIX operating systems.
  • stow - a persistence manager for objects
    backed by boltdb.
  • buckets - a bolt wrapper streamlining
    simple tx and key scans.
  • mbuckets - A Bolt wrapper that allows easy operations on multi level (nested) buckets.
  • Request Baskets - A web service to collect arbitrary HTTP requests and inspect them via REST API or simple web UI, similar to RequestBin service
  • Go Report Card - Go code quality report cards as a (free and open source) service.
  • Boltdb Boilerplate - Boilerplate wrapper around bolt aiming to make simple calls one-liners.
  • lru - Easy to use Bolt-backed Least-Recently-Used (LRU) read-through cache with chainable remote stores.
  • Storm - Simple and powerful ORM for BoltDB.
  • GoWebApp - A basic MVC web application in Go using BoltDB.
  • SimpleBolt - A simple way to use BoltDB. Deals mainly with strings.
  • Algernon - A HTTP/2 web server with built-in support for Lua. Uses BoltDB as the default database backend.
  • MuLiFS - Music Library Filesystem creates a filesystem to organise your music files.
  • GoShort - GoShort is a URL shortener written in Golang and BoltDB for persistent key/value storage and for routing it's using high performent HTTPRouter.

If you are using Bolt in a project please send a pull request to add it to the list.


Overview (`vendor/github.com/clusterhq/flocker-go/README.md`)

flocker-go

flocker-go implements the package flocker that will let you easily interact
with a Flocker Control Service.

What can it do?

You can check the package documentation here: https://godoc.org/github.com/ClusterHQ/flocker-go

TODO

  • Define a proper interface flockerClientable with all the needed methods for
    wrapping the Flocker API.

Overview (`vendor/github.com/codedellemc/goscaleio/README.md`)

Goscaleio

The Goscaleio project represents API bindings that can be used to provide ScaleIO functionality into other Go applications.

Use Cases

Any application written in Go can take advantage of these bindings. Specifically, things that are involved in monitoring, management, and more specifically infrastructrue as code would find these bindings relevant.

Current State

Early build-out and pre-documentation stages. The basics around authentication and object models are there.

Usage

Logging in

text
client, err := goscaleio.NewClient()
if err != nil {
  log.Fatalf("err: %v", err)
}

_, err = client.Authenticate(&goscaleio.ConfigConnect{endpoint, username, password})
if err != nil {
  log.Fatalf("error authenticating: %v", err)
}

fmt.Println("Successfuly logged in to ScaleIO Gateway at", client.SIOEndpoint.String())

Reusing the authentication token

Once a client struct is created via the NewClient() function, you can replace the Token with the saved token.

text
client, err := goscaleio.NewClient()
if err != nil {
  log.Fatalf("error with NewClient: %s", err)
}

client.Token = oldToken

Get Systems

Retrieving systems is the first step after authentication which enables you to work with other necessary methods.

All Systems

text
systems, err := client.GetInstance()
if err != nil {
  log.Fatalf("err: problem getting instance %v", err)
}

Find a System

text
system, err := client.FindSystem(systemid,"","")
if err != nil {
  log.Fatalf("err: problem getting instance %v", err)
}

Get Protection Domains

Once you have a System struct you can then get other things like Protection Domains.

text
protectiondomains, err := system.GetProtectionDomain()
if err != nil {
  log.Fatalf("error getting protection domains: %v", err)
}

Licensing

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.

Support

Please file bugs and issues on the Github issues page for this project. This is to help keep track and document everything related to this repo. For general discussions and further support you can join the EMC {code} Community slack channel. Lastly, for questions asked on Stackoverflow.com please tag them with EMC. The code and documentation are released with no warranties or SLAs and are intended to be supported through a community driven process.


Overview (`vendor/github.com/codegangsta/negroni/README.md`)

Negroni [](http://godoc.org/github.com/codegangsta/negroni) [](https://app.wercker.com/project/bykey/13688a4a94b82d84a0b8d038c4965b61)

Negroni is an idiomatic approach to web middleware in Go. It is tiny, non-intrusive, and encourages use of net/http Handlers.

If you like the idea of Martini, but you think it contains too much magic, then Negroni is a great fit.

Language Translations:

Getting Started

After installing Go and setting up your GOPATH, create your first .go file. We'll call it server.go.

go
package main

import (
  "github.com/codegangsta/negroni"
  "net/http"
  "fmt"
)

func main() {
  mux := http.NewServeMux()
  mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
    fmt.Fprintf(w, "Welcome to the home page!")
  })

  n := negroni.Classic()
  n.UseHandler(mux)
  n.Run(":3000")
}

Then install the Negroni package (go 1.1 and greater is required):

text
go get github.com/codegangsta/negroni

Then run your server:

text
go run server.go

You will now have a Go net/http webserver running on localhost:3000.

Need Help?

If you have a question or feature request, go ask the mailing list. The GitHub issues for Negroni will be used exclusively for bug reports and pull requests.

Is Negroni a Framework?

Negroni is not a framework. It is a library that is designed to work directly with net/http.

Routing?

Negroni is BYOR (Bring your own Router). The Go community already has a number of great http routers available, Negroni tries to play well with all of them by fully supporting net/http. For instance, integrating with Gorilla Mux looks like so:

go
router := mux.NewRouter()
router.HandleFunc("/", HomeHandler)

n := negroni.New(Middleware1, Middleware2)
// Or use a middleware with the Use() function
n.Use(Middleware3)
// router goes last
n.UseHandler(router)

n.Run(":3000")

`negroni.Classic()`

negroni.Classic() provides some default middleware that is useful for most applications:

  • negroni.Recovery - Panic Recovery Middleware.
  • negroni.Logging - Request/Response Logging Middleware.
  • negroni.Static - Static File serving under the "public" directory.

This makes it really easy to get started with some useful features from Negroni.

Handlers

Negroni provides a bidirectional middleware flow. This is done through the negroni.Handler interface:

go
type Handler interface {
  ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)
}

If a middleware hasn't already written to the ResponseWriter, it should call the next http.HandlerFunc in the chain to yield to the next middleware handler. This can be used for great good:

go
func MyMiddleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
  // do some stuff before
  next(rw, r)
  // do some stuff after
}

And you can map it to the handler chain with the Use function:

go
n := negroni.New()
n.Use(negroni.HandlerFunc(MyMiddleware))

You can also map plain old http.Handlers:

go
n := negroni.New()

mux := http.NewServeMux()
// map your routes

n.UseHandler(mux)

n.Run(":3000")

`Run()`

Negroni has a convenience function called Run. Run takes an addr string identical to http.ListenAndServe.

go
n := negroni.Classic()
// ...
log.Fatal(http.ListenAndServe(":8080", n))

Route Specific Middleware

If you have a route group of routes that need specific middleware to be executed, you can simply create a new Negroni instance and use it as your route handler.

go
router := mux.NewRouter()
adminRoutes := mux.NewRouter()
// add admin routes here

// Create a new negroni for the admin middleware
router.Handle("/admin", negroni.New(
  Middleware1,
  Middleware2,
  negroni.Wrap(adminRoutes),
))

Third Party Middleware

Here is a current list of Negroni compatible middlware. Feel free to put up a PR linking your middleware if you have built one:

Middleware Author Description
RestGate Prasanga Siripala Secure authentication for REST API endpoints
Graceful Tyler Bunnell Graceful HTTP Shutdown
secure Cory Jacobsen Middleware that implements a few quick security wins
JWT Middleware Auth0 Middleware checks for a JWT on the Authorization header on incoming requests and decodes it
binding Matt Holt Data binding from HTTP requests into structs
logrus Dan Buch Logrus-based logger
render Cory Jacobsen Render JSON, XML and HTML templates
gorelic Jingwen Owen Ou New Relic agent for Go runtime
gzip phyber GZIP response compression
oauth2 David Bochenski oAuth2 middleware
sessions David Bochenski Session Management
permissions2 Alexander Rødseth Cookies, users and permissions
onthefly Alexander Rødseth Generate TinySVG, HTML and CSS on the fly
cors Olivier Poitrey Cross Origin Resource Sharing (CORS) support
xrequestid Andrea Franz Middleware that assigns a random X-Request-Id header to each request
VanGoH Taylor Wrobel Configurable AWS-Style HMAC authentication middleware
stats Florent Messa Store information about your web application (response time, etc.)

Examples

Alexander Rødseth created mooseware, a skeleton for writing a Negroni middleware handler.

Live code reload?

gin and fresh both live reload negroni apps.

Essential Reading for Beginners of Go & Negroni

About

Negroni is obsessively designed by none other than the Code Gangsta


Overview (`vendor/github.com/d2g/dhcp4/README.md`)

DHCP4 - A DHCP library written in Go.

Warning: This library is still being developed. Function calls will change.

I've removed Server Functionality, for me this project supports the underlying DHCP format not the implementation.


Overview (`vendor/github.com/d2g/dhcp4client/README.md`)

dhcp4client [](http://godoc.org/github.com/d2g/dhcp4client) [](https://coveralls.io/r/d2g/dhcp4client?branch=HEAD) [](https://codeship.com/projects/70187)

DHCP Client

Thanks to:

@eyakubovich For AF_PACKET support.


Overview (`vendor/github.com/daviddengcn/go-colortext/README.md`)

go-colortext package [](http://go-search.org/view?id=github.com%2Fdaviddengcn%2Fgo-colortext)

This is a package to change the color of the text and background in the console, working both under Windows and other systems.

Under Windows, the console APIs are used. Otherwise, ANSI texts are output.

Docs: http://godoc.org/github.com/daviddengcn/go-colortext (packages that import ct)

Usage:

go
ct.Foreground(Green, false)
fmt.Println("Green text starts here...")
ct.ChangeColor(Red, true, White, false)
fmt.Println(...)
ct.ResetColor()

LICENSE

BSD/MIT license


Overview (`vendor/github.com/dchest/safefile/README.md`)

safefile

Go package safefile implements safe "atomic" saving of files.

Instead of truncating and overwriting the destination file, it creates a
temporary file in the same directory, writes to it, and then renames the
temporary file to the original name when calling Commit.

Installation

text
$ go get github.com/dchest/safefile

Documentation

https://godoc.org/github.com/dchest/safefile

Example

go
f, err := safefile.Create("/home/ken/report.txt", 0644)
if err != nil {
	// ...
}
// Created temporary file /home/ken/sf-ppcyksu5hyw2mfec.tmp

defer f.Close()

_, err = io.WriteString(f, "Hello world")
if err != nil {
	// ...
}
// Wrote "Hello world" to /home/ken/sf-ppcyksu5hyw2mfec.tmp

err = f.Commit()
if err != nil {
    // ...
}
// Renamed /home/ken/sf-ppcyksu5hyw2mfec.tmp to /home/ken/report.txt

Overview (`vendor/github.com/dgrijalva/jwt-go/README.md`)

A go (or 'golang' for search engine friendliness) implementation of JSON Web Tokens

BREAKING CHANGES:* Version 3.0.0 is here. It includes a lot of changes including a few that break the API. We've tried to break as few things as possible, so there should just be a few type signature changes. A full list of breaking changes is available in VERSION_HISTORY.md. See MIGRATION_GUIDE.md for more information on updating your code.

NOTICE: A vulnerability in JWT was recently published. As this library doesn't force users to validate the alg is what they expected, it's possible your usage is effected. There will be an update soon to remedy this, and it will likey require backwards-incompatible changes to the API. In the short term, please make sure your implementation verifies the alg is what you expect.

What the heck is a JWT?

JWT.io has a great introduction to JSON Web Tokens.

In short, it's a signed JSON object that does something useful (for example, authentication). It's commonly used for Bearer tokens in Oauth 2. A token is made of three parts, separated by .'s. The first two parts are JSON objects, that have been base64url encoded. The last part is the signature, encoded the same way.

The first part is called the header. It contains the necessary information for verifying the last part, the signature. For example, which encryption method was used for signing and what key was used.

The part in the middle is the interesting bit. It's called the Claims and contains the actual stuff you care about. Refer to the RFC for information about reserved keys and the proper way to add your own.

What's in the box?

This library supports the parsing and verification as well as the generation and signing of JWTs. Current supported signing algorithms are HMAC SHA, RSA, RSA-PSS, and ECDSA, though hooks are present for adding your own.

Examples

See the project documentation for examples of usage:

Extensions

This library publishes all the necessary components for adding your own signing methods. Simply implement the SigningMethod interface and register a factory method using RegisterSigningMethod.

Here's an example of an extension that integrates with the Google App Engine signing tools: https://github.com/someone1/gcp-jwt-go

Compliance

This library was last reviewed to comply with RTF 7519 dated May 2015 with a few notable differences:

  • In order to protect against accidental use of Unsecured JWTs, tokens using alg=none will only be accepted if the constant jwt.UnsafeAllowNoneSignatureType is provided as the key.

Project Status & Versioning

This library is considered production ready. Feedback and feature requests are appreciated. The API should be considered stable. There should be very few backwards-incompatible changes outside of major version updates (and only with good reason).

This project uses Semantic Versioning 2.0.0. Accepted pull requests will land on master. Periodically, versions will be tagged from master. You can find all the releases on the project releases page.

While we try to make it obvious when we make breaking changes, there isn't a great mechanism for pushing announcements out to users. You may want to use this alternative package include: gopkg.in/dgrijalva/jwt-go.v2. It will do the right thing WRT semantic versioning.

Usage Tips

Signing vs Encryption

A token is simply a JSON object that is signed by its author. this tells you exactly two things about the data:

  • The author of the token was in the possession of the signing secret
  • The data has not been modified since it was signed

It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, JWE, that provides this functionality. JWE is currently outside the scope of this library.

Choosing a Signing Method

There are several signing methods available, and you should probably take the time to learn about the various options before choosing one. The principal design decision is most likely going to be symmetric vs asymmetric.

Symmetric signing methods, such as HSA, use only a single secret. This is probably the simplest signing method to use since any []byte can be used as a valid secret. They are also slightly computationally faster to use, though this rarely is enough to matter. Symmetric signing methods work the best when both producers and consumers of tokens are trusted, or even the same system. Since the same secret is used to both sign and validate tokens, you can't easily distribute the key for validation.

Asymmetric signing methods, such as RSA, use different keys for signing and verifying tokens. This makes it possible to produce tokens with a private key, and allow any consumer to access the public key for verification.

JWT and OAuth

It's worth mentioning that OAuth and JWT are not the same thing. A JWT token is simply a signed JSON object. It can be used anywhere such a thing is useful. There is some confusion, though, as JWT is the most common type of bearer token used in OAuth2 authentication.

Without going too far down the rabbit hole, here's a description of the interaction of these technologies:

  • OAuth is a protocol for allowing an identity provider to be separate from the service a user is logging in to. For example, whenever you use Facebook to log into a different service (Yelp, Spotify, etc), you are using OAuth.
  • OAuth defines several options for passing around authentication data. One popular method is called a "bearer token". A bearer token is simply a string that should only be held by an authenticated user. Thus, simply presenting this token proves your identity. You can probably derive from here why a JWT might make a good bearer token.
  • Because bearer tokens are used for authentication, it's important they're kept secret. This is why transactions that use bearer tokens typically happen over SSL.

More

Documentation can be found on godoc.org.

The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in to documentation.


Overview (`vendor/github.com/docker/go-units/README.md`)

Introduction

go-units is a library to transform human friendly measurements into machine friendly values.

Usage

See the docs in godoc for examples and documentation.

Copyright © 2015 Docker, Inc.

go-units is licensed under the Apache License, Version 2.0.
See LICENSE for the full text of the license.


Overview (`vendor/github.com/docker/libtrust/README.md`)

libtrust

Libtrust is library for managing authentication and authorization using public key cryptography.

Authentication is handled using the identity attached to the public key.
Libtrust provides multiple methods to prove possession of the private key associated with an identity.

  • TLS x509 certificates
  • Signature verification
  • Key Challenge

Authorization and access control is managed through a distributed trust graph.
Trust servers are used as the authorities of the trust graph and allow caching portions of the graph for faster access.

Code and documentation copyright 2014 Docker, inc. Code released under the Apache 2.0 license.
Docs released under Creative commons.


Overview (`vendor/github.com/docker/spdystream/README.md`)

SpdyStream

A multiplexed stream library using spdy

Usage

Client example (connecting to mirroring server without auth)

go
package main

import (
	"fmt"
	"github.com/docker/spdystream"
	"net"
	"net/http"
)

func main() {
	conn, err := net.Dial("tcp", "localhost:8080")
	if err != nil {
		panic(err)
	}
	spdyConn, err := spdystream.NewConnection(conn, false)
	if err != nil {
		panic(err)
	}
	go spdyConn.Serve(spdystream.NoOpStreamHandler)
	stream, err := spdyConn.CreateStream(http.Header{}, nil, false)
	if err != nil {
		panic(err)
	}

	stream.Wait()

	fmt.Fprint(stream, "Writing to stream")

	buf := make([]byte, 25)
	stream.Read(buf)
	fmt.Println(string(buf))

	stream.Close()
}

Server example (mirroring server without auth)

go
package main

import (
	"github.com/docker/spdystream"
	"net"
)

func main() {
	listener, err := net.Listen("tcp", "localhost:8080")
	if err != nil {
		panic(err)
	}
	for {
		conn, err := listener.Accept()
		if err != nil {
			panic(err)
		}
		spdyConn, err := spdystream.NewConnection(conn, true)
		if err != nil {
			panic(err)
		}
		go spdyConn.Serve(spdystream.MirrorStreamHandler)
	}
}

Copyright © 2014-2015 Docker, Inc. All rights reserved, except as follows. Code is released under the Apache 2.0 license. The README.md file, and files in the "docs" folder are licensed under the Creative Commons Attribution 4.0 International License under the terms and conditions set forth in the file "LICENSE.docs". You may obtain a duplicate copy of the same license, titled CC-BY-SA-4.0, at http://creativecommons.org/licenses/by/4.0/.


Overview (`vendor/github.com/elazarl/go-bindata-assetfs/README.md`)

go-bindata-assetfs

Serve embedded files from jteeuwen/go-bindata with net/http.

GoDoc

Installation

Install with

text
$ go get github.com/jteeuwen/go-bindata/...
$ go get github.com/elazarl/go-bindata-assetfs/...

Creating embedded data

Usage is identical to jteeuwen/go-bindata usage,
instead of running go-bindata run go-bindata-assetfs.

The tool will create a bindata_assetfs.go file, which contains the embedded data.

A typical use case is

text
$ go-bindata-assetfs data/...

Using assetFS in your code

The generated file provides an assetFS() function that returns a http.Filesystem
wrapping the embedded files. What you usually want to do is:

text
http.Handle("/", http.FileServer(assetFS()))

This would run an HTTP server serving the embedded files.

Without running binary tool

You can always just run the go-bindata tool, and then

use

text
import "github.com/elazarl/go-bindata-assetfs"
 ...
 http.Handle("/",
    http.FileServer(
    &assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "data"}))

to serve files embedded from the data directory.


Overview (`vendor/github.com/elazarl/goproxy/README.md`)

Introduction


Package goproxy provides a customizable HTTP proxy library for Go (golang),

It supports regular HTTP proxy, HTTPS through CONNECT, and "hijacking" HTTPS
connection using "Man in the Middle" style attack.

The intent of the proxy, is to be usable with reasonable amount of traffic
yet, customizable and programmable.

The proxy itself is simply a net/http handler.

In order to use goproxy, one should set their browser to use goproxy as an HTTP
proxy. Here is how you do that in Chrome
and in Firefox.

For example, the URL you should use as proxy when running ./bin/basic is
localhost:8080, as this is the default binding for the basic proxy.

Mailing List

New features would be discussed on the mailing list
before their development.

Latest Stable Release

Get the latest goproxy from gopkg.in/elazarl/goproxy.v1.

Why not Fiddler2?

Fiddler is an excellent software with similar intent. However, Fiddler is not
as customable as goproxy intend to be. The main difference is, Fiddler is not
intended to be used as a real proxy.

A possible use case that suits goproxy but
not Fiddler, is, gathering statistics on page load times for a certain website over a week.
With goproxy you could ask all your users to set their proxy to a dedicated machine running a
goproxy server. Fiddler is a GUI app not designed to be ran like a server for multiple users.

A taste of goproxy

To get a taste of goproxy, a basic HTTP/HTTPS transparent proxy

go
package main

import (
    "github.com/elazarl/goproxy"
    "log"
    "net/http"
)

func main() {
    proxy := goproxy.NewProxyHttpServer()
    proxy.Verbose = true
    log.Fatal(http.ListenAndServe(":8080", proxy))
}

This line will add X-GoProxy: yxorPoG-X header to all requests sent through the proxy

go
proxy.OnRequest().DoFunc(
    func(r *http.Request,ctx *goproxy.ProxyCtx)(*http.Request,*http.Response) {
        r.Header.Set("X-GoProxy","yxorPoG-X")
        return r,nil
    })

DoFunc will process all incoming requests to the proxy. It will add a header to the request
and return it. The proxy will send the modified request.

Note that we returned nil value as the response. Have we returned a response, goproxy would
have discarded the request and sent the new response to the client.

In order to refuse connections to reddit at work time

go
proxy.OnRequest(goproxy.DstHostIs("www.reddit.com")).DoFunc(
    func(r *http.Request,ctx *goproxy.ProxyCtx)(*http.Request,*http.Response) {
        if h,_,_ := time.Now().Clock(); h >= 8 && h <= 17 {
            return r,goproxy.NewResponse(r,
                    goproxy.ContentTypeText,http.StatusForbidden,
                    "Don't waste your time!")
        }
        return r,nil
})

DstHostIs returns a ReqCondition, that is a function receiving a Request and returning a boolean
we will only process requests that matches the condition. DstHostIs("www.reddit.com") will return
a ReqCondition accepting only requests directed to "www.reddit.com".

DoFunc will receive a function that will preprocess the request. We can change the request, or
return a response. If the time is between 8:00am and 17:00pm, we will neglect the request, and
return a precanned text response saying "do not waste your time".

See additional examples in the examples directory.

What's New

  1. Ability to Hijack CONNECT requests. See
    the eavesdropper example
  2. Transparent proxy support for http/https including MITM certificate generation for TLS. See the transparent example.

License

I put the software temporarily under the Go-compatible BSD license,
if this prevents someone from using the software, do let me know and I'll consider changing it.

At any rate, user feedback is very important for me, so I'll be delighted to know if you're using this package.

Beta Software

I've received a positive feedback from a few people who use goproxy in production settings.
I believe it is good enough for usage.

I'll try to keep reasonable backwards compatibility. In case of a major API change,
I'll change the import path.


Overview (`vendor/github.com/emicklei/go-restful-swagger12/README.md`)

go-restful-swagger12


How to use Swagger UI with go-restful

Get the Swagger UI sources (version 1.2 only)

text
git clone https://github.com/wordnik/swagger-ui.git

The project contains a "dist" folder.
Its contents has all the Swagger UI files you need.

The index.html has an url set to http://petstore.swagger.wordnik.com/api/api-docs.
You need to change that to match your WebService JSON endpoint e.g. http://localhost:8080/apidocs.json

Now, you can install the Swagger WebService for serving the Swagger specification in JSON.

text
config := swagger.Config{
	WebServices:    restful.RegisteredWebServices(),
	ApiPath:        "/apidocs.json",
	SwaggerPath:     "/apidocs/",
	SwaggerFilePath: "/Users/emicklei/Projects/swagger-ui/dist"}
swagger.InstallSwaggerService(config)

Documenting Structs

Currently there are 2 ways to document your structs in the go-restful Swagger.

By using struct tags

  • Use tag "description" to annotate a struct field with a description to show in the UI
  • Use tag "modelDescription" to annotate the struct itself with a description to show in the UI. The tag can be added in an field of the struct and in case that there are multiple definition, they will be appended with an empty line.

By using the SwaggerDoc method

Here is an example with an Address struct and the documentation for each of the fields. The "" is a special entry for documenting the struct itself.

text
type Address struct {
	Country  string `json:"country,omitempty"`
	PostCode int    `json:"postcode,omitempty"`
}

func (Address) SwaggerDoc() map[string]string {
	return map[string]string{
		"":         "Address doc",
		"country":  "Country doc",
		"postcode": "PostCode doc",
	}
}

This example will generate a JSON like this

text
{
	"Address": {
		"id": "Address",
		"description": "Address doc",
		"properties": {
			"country": {
			"type": "string",
			"description": "Country doc"
			},
			"postcode": {
			"type": "integer",
			"format": "int32",
			"description": "PostCode doc"
			}
		}
	}
}

Very Important Notes:

  • SwaggerDoc() is using a NON-Pointer receiver (e.g. func (Address) and not func (*Address))
  • The returned map should use as key the name of the field as defined in the JSON parameter (e.g. "postcode" and not "PostCode")

Notes

  • The Nickname of an Operation is automatically set by finding the name of the function. You can override it using RouteBuilder.Operation(..)
  • The WebServices field of swagger.Config can be used to control which service you want to expose and document ; you can have multiple configs and therefore multiple endpoints.

© 2017, ernestmicklei.com. MIT License. Contributions welcome.


Overview (`vendor/github.com/emicklei/go-restful/README.md`)

go-restful

package for building REST-style Web Services using Google Go



REST asks developers to use HTTP methods explicitly and in a way that's consistent with the protocol definition. This basic REST design principle establishes a one-to-one mapping between create, read, update, and delete (CRUD) operations and HTTP methods. According to this mapping:

  • GET = Retrieve a representation of a resource
  • POST = Create if you are sending content to the server to create a subordinate of the specified resource collection, using some server-side algorithm.
  • PUT = Create if you are sending the full content of the specified resource (URI).
  • PUT = Update if you are updating the full content of the specified resource.
  • DELETE = Delete if you are requesting the server to delete the resource
  • PATCH = Update partial content of a resource
  • OPTIONS = Get information about the communication options for the request URI

Example

go
ws := new(restful.WebService)
ws.
	Path("/users").
	Consumes(restful.MIME_XML, restful.MIME_JSON).
	Produces(restful.MIME_JSON, restful.MIME_XML)

ws.Route(ws.GET("/{user-id}").To(u.findUser).
	Doc("get a user").
	Param(ws.PathParameter("user-id", "identifier of the user").DataType("string")).
	Writes(User{}))		
...
	
func (u UserResource) findUser(request *restful.Request, response *restful.Response) {
	id := request.PathParameter("user-id")
	...
}

Full API of a UserResource

Features

  • Routes for request → function mapping with path parameter (e.g. {id}) support
  • Configurable router:
    • (default) Fast routing algorithm that allows static elements, regular expressions and dynamic parameters in the URL path (e.g. /meetings/{id} or /static/{subpath:*}
    • Routing algorithm after JSR311 that is implemented using (but does not accept) regular expressions
  • Request API for reading structs from JSON/XML and accesing parameters (path,query,header)
  • Response API for writing structs to JSON/XML and setting headers
  • Customizable encoding using EntityReaderWriter registration
  • Filters for intercepting the request → response flow on Service or Route level
  • Request-scoped variables using attributes
  • Containers for WebServices on different HTTP endpoints
  • Content encoding (gzip,deflate) of request and response payloads
  • Automatic responses on OPTIONS (using a filter)
  • Automatic CORS request handling (using a filter)
  • API declaration for Swagger UI (see go-restful-swagger12,go-restful-openapi)
  • Panic recovery to produce HTTP 500, customizable using RecoverHandler(...)
  • Route errors produce HTTP 404/405/406/415 errors, customizable using ServiceErrorHandler(...)
  • Configurable (trace) logging
  • Customizable gzip/deflate readers and writers using CompressorProvider registration

Resources

Type git shortlog -s for a full list of contributors.

© 2012 - 2017, http://ernestmicklei.com. MIT License. Contributions are welcome.


Overview (`vendor/github.com/evanphx/json-patch/README.md`)

JSON-Patch

Provides the ability to modify and test a JSON according to a
RFC6902 JSON patch and RFC7396 JSON Merge Patch.

Version: 1.0

API Usage

  • Given a []byte, obtain a Patch object

    obj, err := jsonpatch.DecodePatch(patch)

  • Apply the patch and get a new document back

    out, err := obj.Apply(doc)

  • Create a JSON Merge Patch document based on two json documents (a to b):

    mergeDoc, err := jsonpatch.CreateMergePatch(a, b)

  • Bonus API: compare documents for structural equality

    jsonpatch.Equal(doca, docb)


Overview (`vendor/github.com/exponent-io/jsonpath/README.md`)


jsonpath

This package extends the json.Decoder to support navigating a stream of JSON tokens. You should be able to use this extended Decoder places where a json.Decoder would have been used.

This Decoder has the following enhancements...

  • The Scan method supports scanning a JSON stream while extracting particular values along the way using PathActions.
  • The SeekTo method supports seeking forward in a JSON token stream to a particular path.
  • The Path method returns the path of the most recently parsed token.
  • The Token method has been modified to distinguish between strings that are object keys and strings that are values. Object key strings are returned as the KeyString type rather than a native string.

Installation

text
go get -u github.com/exponent-io/jsonpath

Example Usage

SeekTo

go
import "github.com/exponent-io/jsonpath"

var j = []byte(`[
  {"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}},
  {"Space": "RGB",   "Point": {"R": 98, "G": 218, "B": 255}}
]`)

w := json.NewDecoder(bytes.NewReader(j))
var v interface{}

w.SeekTo(1, "Point", "G")
w.Decode(&v) // v is 218

Scan with PathActions

go
var j = []byte(`{"colors":[
  {"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10, "A": 58}},
  {"Space": "RGB",   "Point": {"R": 98, "G": 218, "B": 255, "A": 231}}
]}`)

var actions PathActions

// Extract the value at Point.A
actions.Add(func(d *Decoder) error {
  var alpha int
  err := d.Decode(&alpha)
  fmt.Printf("Alpha: %v\n", alpha)
  return err
}, "Point", "A")

w := NewDecoder(bytes.NewReader(j))
w.SeekTo("colors", 0)

var ok = true
var err error
for ok {
  ok, err = w.Scan(&actions)
  if err != nil && err != io.EOF {
    panic(err)
  }
}

Overview (`vendor/github.com/fatih/camelcase/README.md`)

CamelCase [](http://godoc.org/github.com/fatih/camelcase) [](https://travis-ci.org/fatih/camelcase)

CamelCase is a Golang (Go) package to split the words of a camelcase type
string into a slice of words. It can be used to convert a camelcase word (lower
or upper case) into any type of word.

Splitting rules:

  1. If string is not valid UTF-8, return it without splitting as
    single item array.
  2. Assign all unicode characters into one of 4 sets: lower case
    letters, upper case letters, numbers, and all other characters.
  3. Iterate through characters of string, introducing splits
    between adjacent characters that belong to different sets.
  4. Iterate through array of split strings, and if a given string
    is upper case:
    • if subsequent string is lower case:
      • move last character of upper case string to beginning of
        lower case string

Install

bash
go get github.com/fatih/camelcase

Usage and examples

go
splitted := camelcase.Split("GolangPackage")

fmt.Println(splitted[0], splitted[1]) // prints: "Golang", "Package"

Both lower camel case and upper camel case are supported. For more info please
check: http://en.wikipedia.org/wiki/CamelCase

Below are some example cases:

text
"" =>                     []
"lowercase" =>            ["lowercase"]
"Class" =>                ["Class"]
"MyClass" =>              ["My", "Class"]
"MyC" =>                  ["My", "C"]
"HTML" =>                 ["HTML"]
"PDFLoader" =>            ["PDF", "Loader"]
"AString" =>              ["A", "String"]
"SimpleXMLParser" =>      ["Simple", "XML", "Parser"]
"vimRPCPlugin" =>         ["vim", "RPC", "Plugin"]
"GL11Version" =>          ["GL", "11", "Version"]
"99Bottles" =>            ["99", "Bottles"]
"May5" =>                 ["May", "5"]
"BFG9000" =>              ["BFG", "9000"]
"BöseÜberraschung" =>     ["Böse", "Überraschung"]
"Two  spaces" =>          ["Two", "  ", "spaces"]
"BadUTF8\xe2\xe2\xa1" =>  ["BadUTF8\xe2\xe2\xa1"]

Overview (`vendor/github.com/fsnotify/fsnotify/README.md`)

File system notifications for Go

fsnotify utilizes golang.org/x/sys rather than syscall from the standard library. Ensure you have the latest version installed by running:

console
go get -u golang.org/x/sys/...

Cross platform: Windows, Linux, BSD and OS X.

Adapter OS Status
inotify Linux 2.6.27 or later, Android* Supported
kqueue BSD, OS X, iOS* Supported
ReadDirectoryChangesW Windows Supported
FSEvents OS X Planned
FEN Solaris 11 In Progress
fanotify Linux 2.6.37+
USN Journals Windows Maybe
Polling All Maybe

* Android and iOS are untested.

Please see the documentation for usage. Consult the Wiki for the FAQ and further information.

API stability

fsnotify is a fork of howeyc/fsnotify with a new API as of v1.0. The API is based on this design document.

All releases are tagged based on Semantic Versioning. Further API changes are planned, and will be tagged with a new major revision number.

Go 1.6 supports dependencies located in the vendor/ folder. Unless you are creating a library, it is recommended that you copy fsnotify into vendor/github.com/fsnotify/fsnotify within your project, and likewise for golang.org/x/sys.

Contributing

Please refer to CONTRIBUTING before opening an issue or pull request.

Example

See example_test.go.


Overview (`vendor/github.com/ghodss/yaml/README.md`)

YAML marshaling and unmarshaling support for Go

Introduction

A wrapper around go-yaml designed to enable a better way of handling YAML when marshaling to and from structs.

In short, this library first converts YAML to JSON using go-yaml and then uses json.Marshal and json.Unmarshal to convert to or from the struct. This means that it effectively reuses the JSON struct tags as well as the custom JSON methods MarshalJSON and UnmarshalJSON unlike go-yaml. For a detailed overview of the rationale behind this method, see this blog post.

Compatibility

This package uses go-yaml v2 and therefore supports everything go-yaml supports.

Caveats

Caveat #1: When using yaml.Marshal and yaml.Unmarshal, binary data should NOT be preceded with the !!binary YAML tag. If you do, go-yaml will convert the binary data from base64 to native binary data, which is not compatible with JSON. You can still use binary in your YAML files though - just store them without the !!binary tag and decode the base64 in your code (e.g. in the custom JSON methods MarshalJSON and UnmarshalJSON). This also has the benefit that your YAML and your JSON binary data will be decoded exactly the same way. As an example:

text
BAD:
	exampleKey: !!binary gIGC

GOOD:
	exampleKey: gIGC
... and decode the base64 data in your code.

Caveat #2: When using YAMLToJSON directly, maps with keys that are maps will result in an error since this is not supported by JSON. This error will occur in Unmarshal as well since you can't unmarshal map keys anyways since struct fields can't be keys.

Installation and usage

To install, run:

text
$ go get github.com/ghodss/yaml

And import using:

text
import "github.com/ghodss/yaml"

Usage is very similar to the JSON library:

go
import (
	"fmt"

	"github.com/ghodss/yaml"
)

type Person struct {
	Name string `json:"name"`  // Affects YAML field names too.
	Age int `json:"name"`
}

func main() {
	// Marshal a Person struct to YAML.
	p := Person{"John", 30}
	y, err := yaml.Marshal(p)
	if err != nil {
		fmt.Printf("err: %v\n", err)
		return
	}
	fmt.Println(string(y))
	/* Output:
	name: John
	age: 30
	*/

	// Unmarshal the YAML back into a Person struct.
	var p2 Person
	err := yaml.Unmarshal(y, &p2)
	if err != nil {
		fmt.Printf("err: %v\n", err)
		return
	}
	fmt.Println(p2)
	/* Output:
	{John 30}
	*/
}

yaml.YAMLToJSON and yaml.JSONToYAML methods are also available:

go
import (
	"fmt"

	"github.com/ghodss/yaml"
)
func main() {
	j := []byte(`{"name": "John", "age": 30}`)
	y, err := yaml.JSONToYAML(j)
	if err != nil {
		fmt.Printf("err: %v\n", err)
		return
	}
	fmt.Println(string(y))
	/* Output:
	name: John
	age: 30
	*/
	j2, err := yaml.YAMLToJSON(y)
	if err != nil {
		fmt.Printf("err: %v\n", err)
		return
	}
	fmt.Println(string(j2))
	/* Output:
	{"age":30,"name":"John"}
	*/
}

Overview (`vendor/github.com/go-ini/ini/README.md`)

INI [](https://travis-ci.org/go-ini/ini) [](https://sourcegraph.com/github.com/go-ini/ini?badge)

Package ini provides INI file read and write functionality in Go.

简体中文

Feature

  • Load multiple data sources([]byte, file and io.ReadCloser) with overwrites.
  • Read with recursion values.
  • Read with parent-child sections.
  • Read with auto-increment key names.
  • Read with multiple-line values.
  • Read with tons of helper methods.
  • Read and convert values to Go types.
  • Read and WRITE comments of sections and keys.
  • Manipulate sections, keys and comments with ease.
  • Keep sections and keys in order as you parse and save.

Installation

To use a tagged revision:

text
go get gopkg.in/ini.v1

To use with latest changes:

text
go get github.com/go-ini/ini

Please add -u flag to update in the future.

Testing

If you want to test on your machine, please apply -t flag:

text
go get -t gopkg.in/ini.v1

Please add -u flag to update in the future.

Getting Started

Loading from data sources

A Data Source is either raw data in type []byte, a file name with type string or io.ReadCloser. You can load as many data sources as you want. Passing other types will simply return an error.

go
cfg, err := ini.Load([]byte("raw data"), "filename", ioutil.NopCloser(bytes.NewReader([]byte("some other data"))))

Or start with an empty object:

go
cfg := ini.Empty()

When you cannot decide how many data sources to load at the beginning, you will still be able to Append() them later.

go
err := cfg.Append("other file", []byte("other raw data"))

If you have a list of files with possibilities that some of them may not available at the time, and you don't know exactly which ones, you can use LooseLoad to ignore nonexistent files without returning error.

go
cfg, err := ini.LooseLoad("filename", "filename_404")

The cool thing is, whenever the file is available to load while you're calling Reload method, it will be counted as usual.

Ignore cases of key name

When you do not care about cases of section and key names, you can use InsensitiveLoad to force all names to be lowercased while parsing.

go
cfg, err := ini.InsensitiveLoad("filename")
//...

// sec1 and sec2 are the exactly same section object
sec1, err := cfg.GetSection("Section")
sec2, err := cfg.GetSection("SecTIOn")

// key1 and key2 are the exactly same key object
key1, err := cfg.GetKey("Key")
key2, err := cfg.GetKey("KeY")

MySQL-like boolean key

MySQL's configuration allows a key without value as follows:

ini
[mysqld]
...
skip-host-cache
skip-name-resolve

By default, this is considered as missing value. But if you know you're going to deal with those cases, you can assign advanced load options:

go
cfg, err := LoadSources(LoadOptions{AllowBooleanKeys: true}, "my.cnf"))

The value of those keys are always true, and when you save to a file, it will keep in the same foramt as you read.

To generate such keys in your program, you could use NewBooleanKey:

go
key, err := sec.NewBooleanKey("skip-host-cache")

Comment

Take care that following format will be treated as comment:

  1. Line begins with # or ;
  2. Words after # or ;
  3. Words after section name (i.e words after [some section name])

If you want to save a value with # or ;, please quote them with ` or """.

Working with sections

To get a section, you would need to:

go
section, err := cfg.GetSection("section name")

For a shortcut for default section, just give an empty string as name:

go
section, err := cfg.GetSection("")

When you're pretty sure the section exists, following code could make your life easier:

go
section := cfg.Section("section name")

What happens when the section somehow does not exist? Don't panic, it automatically creates and returns a new section to you.

To create a new section:

go
err := cfg.NewSection("new section")

To get a list of sections or section names:

go
sections := cfg.Sections()
names := cfg.SectionStrings()

Working with keys

To get a key under a section:

go
key, err := cfg.Section("").GetKey("key name")

Same rule applies to key operations:

go
key := cfg.Section("").Key("key name")

To check if a key exists:

go
yes := cfg.Section("").HasKey("key name")

To create a new key:

go
err := cfg.Section("").NewKey("name", "value")

To get a list of keys or key names:

go
keys := cfg.Section("").Keys()
names := cfg.Section("").KeyStrings()

To get a clone hash of keys and corresponding values:

go
hash := cfg.Section("").KeysHash()

Working with values

To get a string value:

go
val := cfg.Section("").Key("key name").String()

To validate key value on the fly:

go
val := cfg.Section("").Key("key name").Validate(func(in string) string {
	if len(in) == 0 {
		return "default"
	}
	return in
})

If you do not want any auto-transformation (such as recursive read) for the values, you can get raw value directly (this way you get much better performance):

go
val := cfg.Section("").Key("key name").Value()

To check if raw value exists:

go
yes := cfg.Section("").HasValue("test value")

To get value with types:

text
/* Detailed source-code truncated for AI context efficiency. */

What if my value is three-line long?

ini
[advance]
ADDRESS = """404 road,
NotFound, State, 5000
Earth"""

Not a problem!

go
cfg.Section("advance").Key("ADDRESS").String()

/* --- start ---
404 road,
NotFound, State, 5000
Earth
------  end  --- */

That's cool, how about continuation lines?

ini
[advance]
two_lines = how about \
	continuation lines?
lots_of_lines = 1 \
	2 \
	3 \
	4

Piece of cake!

go
cfg.Section("advance").Key("two_lines").String() // how about continuation lines?
cfg.Section("advance").Key("lots_of_lines").String() // 1 2 3 4

Well, I hate continuation lines, how do I disable that?

go
cfg, err := ini.LoadSources(ini.LoadOptions{
	IgnoreContinuation: true,
}, "filename")

Holy crap!

Note that single quotes around values will be stripped:

ini
foo = "some value" // foo: some value
bar = 'some value' // bar: some value

That's all? Hmm, no.

Helper methods of working with values

To get value with given candidates:

go
v = cfg.Section("").Key("STRING").In("default", []string{"str", "arr", "types"})
v = cfg.Section("").Key("FLOAT64").InFloat64(1.1, []float64{1.25, 2.5, 3.75})
v = cfg.Section("").Key("INT").InInt(5, []int{10, 20, 30})
v = cfg.Section("").Key("INT64").InInt64(10, []int64{10, 20, 30})
v = cfg.Section("").Key("UINT").InUint(4, []int{3, 6, 9})
v = cfg.Section("").Key("UINT64").InUint64(8, []int64{3, 6, 9})
v = cfg.Section("").Key("TIME").InTimeFormat(time.RFC3339, time.Now(), []time.Time{time1, time2, time3})
v = cfg.Section("").Key("TIME").InTime(time.Now(), []time.Time{time1, time2, time3}) // RFC3339

Default value will be presented if value of key is not in candidates you given, and default value does not need be one of candidates.

To validate value in a given range:

go
vals = cfg.Section("").Key("FLOAT64").RangeFloat64(0.0, 1.1, 2.2)
vals = cfg.Section("").Key("INT").RangeInt(0, 10, 20)
vals = cfg.Section("").Key("INT64").RangeInt64(0, 10, 20)
vals = cfg.Section("").Key("UINT").RangeUint(0, 3, 9)
vals = cfg.Section("").Key("UINT64").RangeUint64(0, 3, 9)
vals = cfg.Section("").Key("TIME").RangeTimeFormat(time.RFC3339, time.Now(), minTime, maxTime)
vals = cfg.Section("").Key("TIME").RangeTime(time.Now(), minTime, maxTime) // RFC3339

Auto-split values into a slice

To use zero value of type for invalid inputs:

go
// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4]
// Input: how, 2.2, are, you -> [0.0 2.2 0.0 0.0]
vals = cfg.Section("").Key("STRINGS").Strings(",")
vals = cfg.Section("").Key("FLOAT64S").Float64s(",")
vals = cfg.Section("").Key("INTS").Ints(",")
vals = cfg.Section("").Key("INT64S").Int64s(",")
vals = cfg.Section("").Key("UINTS").Uints(",")
vals = cfg.Section("").Key("UINT64S").Uint64s(",")
vals = cfg.Section("").Key("TIMES").Times(",")

To exclude invalid values out of result slice:

go
// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4]
// Input: how, 2.2, are, you -> [2.2]
vals = cfg.Section("").Key("FLOAT64S").ValidFloat64s(",")
vals = cfg.Section("").Key("INTS").ValidInts(",")
vals = cfg.Section("").Key("INT64S").ValidInt64s(",")
vals = cfg.Section("").Key("UINTS").ValidUints(",")
vals = cfg.Section("").Key("UINT64S").ValidUint64s(",")
vals = cfg.Section("").Key("TIMES").ValidTimes(",")

Or to return nothing but error when have invalid inputs:

go
// Input: 1.1, 2.2, 3.3, 4.4 -> [1.1 2.2 3.3 4.4]
// Input: how, 2.2, are, you -> error
vals = cfg.Section("").Key("FLOAT64S").StrictFloat64s(",")
vals = cfg.Section("").Key("INTS").StrictInts(",")
vals = cfg.Section("").Key("INT64S").StrictInt64s(",")
vals = cfg.Section("").Key("UINTS").StrictUints(",")
vals = cfg.Section("").Key("UINT64S").StrictUint64s(",")
vals = cfg.Section("").Key("TIMES").StrictTimes(",")

Save your configuration

Finally, it's time to save your configuration to somewhere.

A typical way to save configuration is writing it to a file:

go
// ...
err = cfg.SaveTo("my.ini")
err = cfg.SaveToIndent("my.ini", "\t")

Another way to save is writing to a io.Writer interface:

go
// ...
cfg.WriteTo(writer)
cfg.WriteToIndent(writer, "\t")

By default, spaces are used to align "=" sign between key and values, to disable that:

go
ini.PrettyFormat = false

Advanced Usage

Recursive Values

For all value of keys, there is a special syntax %(<name>)s, where <name> is the key name in same section or default section, and %(<name>)s will be replaced by corresponding value(empty string if key not found). You can use this syntax at most 99 level of recursions.

ini
NAME = ini

[author]
NAME = Unknwon
GITHUB = https://github.com/%(NAME)s

[package]
FULL_NAME = github.com/go-ini/%(NAME)s
go
cfg.Section("author").Key("GITHUB").String()		// https://github.com/Unknwon
cfg.Section("package").Key("FULL_NAME").String()	// github.com/go-ini/ini

Parent-child Sections

You can use . in section name to indicate parent-child relationship between two or more sections. If the key not found in the child section, library will try again on its parent section until there is no parent section.

ini
NAME = ini
VERSION = v1
IMPORT_PATH = gopkg.in/%(NAME)s.%(VERSION)s

[package]
CLONE_URL = https://%(IMPORT_PATH)s

[package.sub]
go
cfg.Section("package.sub").Key("CLONE_URL").String()	// https://gopkg.in/ini.v1

Retrieve parent keys available to a child section

go
cfg.Section("package.sub").ParentKeys() // ["CLONE_URL"]

Unparseable Sections

Sometimes, you have sections that do not contain key-value pairs but raw content, to handle such case, you can use LoadOptions.UnparsableSections:

go
cfg, err := LoadSources(LoadOptions{UnparseableSections: []string{"COMMENTS"}}, `[COMMENTS]
<1><L.Slide#2> This slide has the fuel listed in the wrong units <e.1>`))

body := cfg.Section("COMMENTS").Body()

/* --- start ---
<1><L.Slide#2> This slide has the fuel listed in the wrong units <e.1>
------  end  --- */

Auto-increment Key Names

If key name is - in data source, then it would be seen as special syntax for auto-increment key name start from 1, and every section is independent on counter.

ini
[features]
-: Support read/write comments of keys and sections
-: Support auto-increment of key names
-: Support load multiple files to overwrite key values
go
cfg.Section("features").KeyStrings()	// []{"#1", "#2", "#3"}

Map To Struct

Want more objective way to play with INI? Cool.

ini
Name = Unknwon
age = 21
Male = true
Born = 1993-01-01T20:17:05Z

[Note]
Content = Hi is a good man!
Cities = HangZhou, Boston
go
type Note struct {
	Content string
	Cities  []string
}

type Person struct {
	Name string
	Age  int `ini:"age"`
	Male bool
	Born time.Time
	Note
	Created time.Time `ini:"-"`
}

func main() {
	cfg, err := ini.Load("path/to/ini")
	// ...
	p := new(Person)
	err = cfg.MapTo(p)
	// ...

	// Things can be simpler.
	err = ini.MapTo(p, "path/to/ini")
	// ...

	// Just map a section? Fine.
	n := new(Note)
	err = cfg.Section("Note").MapTo(n)
	// ...
}

Can I have default value for field? Absolutely.

Assign it before you map to struct. It will keep the value as it is if the key is not presented or got wrong type.

go
// ...
p := &Person{
	Name: "Joe",
}
// ...

It's really cool, but what's the point if you can't give me my file back from struct?

Reflect From Struct

Why not?

go
type Embeded struct {
	Dates  []time.Time `delim:"|"`
	Places []string    `ini:"places,omitempty"`
	None   []int       `ini:",omitempty"`
}

type Author struct {
	Name      string `ini:"NAME"`
	Male      bool
	Age       int
	GPA       float64
	NeverMind string `ini:"-"`
	*Embeded
}

func main() {
	a := &Author{"Unknwon", true, 21, 2.8, "",
		&Embeded{
			[]time.Time{time.Now(), time.Now()},
			[]string{"HangZhou", "Boston"},
			[]int{},
		}}
	cfg := ini.Empty()
	err = ini.ReflectFrom(cfg, a)
	// ...
}

So, what do I get?

ini
NAME = Unknwon
Male = true
Age = 21
GPA = 2.8

[Embeded]
Dates = 2015-08-07T22:14:22+08:00|2015-08-07T22:14:22+08:00
places = HangZhou,Boston

Name Mapper

To save your time and make your code cleaner, this library supports NameMapper between struct field and actual section and key name.

There are 2 built-in name mappers:

  • AllCapsUnderscore: it converts to format ALL_CAPS_UNDERSCORE then match section or key.
  • TitleUnderscore: it converts to format title_underscore then match section or key.

To use them:

go
type Info struct {
	PackageName string
}

func main() {
	err = ini.MapToWithMapper(&Info{}, ini.TitleUnderscore, []byte("package_name=ini"))
	// ...

	cfg, err := ini.Load([]byte("PACKAGE_NAME=ini"))
	// ...
	info := new(Info)
	cfg.NameMapper = ini.AllCapsUnderscore
	err = cfg.MapTo(info)
	// ...
}

Same rules of name mapper apply to ini.ReflectFromWithMapper function.

Value Mapper

To expand values (e.g. from environment variables), you can use the ValueMapper to transform values:

go
type Env struct {
	Foo string `ini:"foo"`
}

func main() {
	cfg, err := ini.Load([]byte("[env]\nfoo = ${MY_VAR}\n")
	cfg.ValueMapper = os.ExpandEnv
	// ...
	env := &Env{}
	err = cfg.Section("env").MapTo(env)
}

This would set the value of env.Foo to the value of the environment variable MY_VAR.

Other Notes On Map/Reflect

Any embedded struct is treated as a section by default, and there is no automatic parent-child relations in map/reflect feature:

go
type Child struct {
	Age string
}

type Parent struct {
	Name string
	Child
}

type Config struct {
	City string
	Parent
}

Example configuration:

ini
City = Boston

[Parent]
Name = Unknwon

[Child]
Age = 21

What if, yes, I'm paranoid, I want embedded struct to be in the same section. Well, all roads lead to Rome.

go
type Child struct {
	Age string
}

type Parent struct {
	Name string
	Child `ini:"Parent"`
}

type Config struct {
	City string
	Parent
}

Example configuration:

ini
City = Boston

[Parent]
Name = Unknwon
Age = 21

Getting Help

FAQs

What does `BlockMode` field do?

By default, library lets you read and write values so we need a locker to make sure your data is safe. But in cases that you are very sure about only reading data through the library, you can set cfg.BlockMode = false to speed up read operations about 50-70% faster.

Why another INI library?

Many people are using my another INI library goconfig, so the reason for this one is I would like to make more Go style code. Also when you set cfg.BlockMode = false, this one is about 10-30% faster.

To make those changes I have to confirm API broken, so it's safer to keep it in another place and start using gopkg.in to version my package at this time.(PS: shorter import path)

License

This project is under Apache v2 License. See the LICENSE file for the full license text.


Overview (`vendor/github.com/go-openapi/analysis/README.md`)

OpenAPI initiative analysis [](https://ci.vmware.run/go-openapi/analysis) [](https://coverage.vmware.run/go-openapi/analysis) [](https://slackin.goswagger.io)

A foundational library to analyze an OAI specification document for easier reasoning about the content.


Overview (`vendor/github.com/go-openapi/errors/README.md`)

OpenAPI errors [](https://ci.vmware.run/go-openapi/errors) [](https://coverage.vmware.run/go-openapi/errors) [](https://slackin.goswagger.io)

Shared errors used throughout the various libraries for the go-openapi toolkit


Overview (`vendor/github.com/go-openapi/jsonpointer/README.md`)

gojsonpointer [](https://ci.vmware.run/go-openapi/jsonpointer) [](https://coverage.vmware.run/go-openapi/jsonpointer) [](https://slackin.goswagger.io)


An implementation of JSON Pointer - Go language

Status

Completed YES

Tested YES

References

http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07

Note

The 4.Evaluation part of the previous reference, starting with 'If the currently referenced value is a JSON array, the reference token MUST contain either...' is not implemented.


Overview (`vendor/github.com/go-openapi/jsonreference/README.md`)

gojsonreference [](https://ci.vmware.run/go-openapi/jsonreference) [](https://coverage.vmware.run/go-openapi/jsonreference) [](https://slackin.goswagger.io)


An implementation of JSON Reference - Go language

Status

Work in progress ( 90% done )

Dependencies

https://github.com/xeipuuv/gojsonpointer

References

http://tools.ietf.org/html/draft-ietf-appsawg-json-pointer-07

http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03


Overview (`vendor/github.com/go-openapi/loads/README.md`)

Loads OAI specs [](https://travis-ci.org/go-openapi/loads) [](https://codecov.io/gh/go-openapi/loads) [](https://slackin.goswagger.io)

Loading of OAI specification documents from local or remote locations.


Overview (`vendor/github.com/go-openapi/runtime/README.md`)

runtime [](https://ci.vmware.run/go-openapi/runtime) [](https://coverage.vmware.run/go-openapi/runtime) [](https://slackin.goswagger.io)

The runtime component for use in codegeneration or as untyped usage.


Overview (`vendor/github.com/go-openapi/spec/README.md`)

OAI object model [](https://travis-ci.org/go-openapi/spec) [](https://codecov.io/gh/go-openapi/spec) [](https://slackin.goswagger.io)

The object model for OpenAPI specification documents


Overview (`vendor/github.com/go-openapi/strfmt/README.md`)

Strfmt [](https://ci.vmware.run/go-openapi/strfmt) [](https://coverage.vmware.run/go-openapi/strfmt) [](https://slackin.goswagger.io)

strfmt represents a well known string format such as credit card or email. The go toolkit for open api specifications knows how to deal with those.


Overview (`vendor/github.com/go-openapi/swag/README.md`)

Swag [](https://travis-ci.org/go-openapi/swag) [](https://codecov.io/gh/go-openapi/swag) [](https://slackin.goswagger.io)

Contains a bunch of helper functions:

  • convert between value and pointers for builtins
  • convert from string to builtin
  • fast json concatenation
  • search in path
  • load from file or http
  • name manglin

Overview (`vendor/github.com/go-openapi/validate/README.md`)

Validation helpers [](https://ci.vmware.run/go-openapi/validate) [](https://coverage.vmware.run/go-openapi/validate) [](https://slackin.goswagger.io)


Overview (`vendor/github.com/google/btree/README.md`)

BTree implementation for Go

This package provides an in-memory B-Tree implementation for Go, useful as
an ordered, mutable data structure.

The API is based off of the wonderful
http://godoc.org/github.com/petar/GoLLRB/llrb, and is meant to allow btree to
act as a drop-in replacement for gollrb trees.

See http://godoc.org/github.com/google/btree for documentation.


Overview (`vendor/github.com/google/gofuzz/README.md`)

gofuzz

gofuzz is a library for populating go objects with random values.


This is useful for testing:

  • Do your project's objects really serialize/unserialize correctly in all cases?
  • Is there an incorrectly formatted object that will cause your project to panic?

Import with import "github.com/google/gofuzz"

You can use it on single variables:

go
f := fuzz.New()
var myInt int
f.Fuzz(&myInt) // myInt gets a random value.

You can use it on maps:

go
f := fuzz.New().NilChance(0).NumElements(1, 1)
var myMap map[ComplexKeyType]string
f.Fuzz(&myMap) // myMap will have exactly one element.

Customize the chance of getting a nil pointer:

go
f := fuzz.New().NilChance(.5)
var fancyStruct struct {
  A, B, C, D *string
}
f.Fuzz(&fancyStruct) // About half the pointers should be set.

You can even customize the randomization completely if needed:

go
type MyEnum string
const (
        A MyEnum = "A"
        B MyEnum = "B"
)
type MyInfo struct {
        Type MyEnum
        AInfo *string
        BInfo *string
}

f := fuzz.New().NilChance(0).Funcs(
        func(e *MyInfo, c fuzz.Continue) {
                switch c.Intn(2) {
                case 0:
                        e.Type = A
                        c.Fuzz(&e.AInfo)
                case 1:
                        e.Type = B
                        c.Fuzz(&e.BInfo)
                }
        },
)

var myObject MyInfo
f.Fuzz(&myObject) // Type will correspond to whether A or B info is set.

See more examples in example_test.go.

Happy testing!


Overview (`vendor/github.com/gophercloud/gophercloud/README.md`)

Gophercloud: an OpenStack SDK for Go


Gophercloud is an OpenStack Go SDK.

How to install

Before installing, you need to ensure that your GOPATH environment variable
is pointing to an appropriate directory where you want to install Gophercloud:

bash
mkdir $HOME/go
export GOPATH=$HOME/go

To protect yourself against changes in your dependencies, we highly recommend choosing a
dependency management solution for
your projects, such as godep. Once this is set up, you can install
Gophercloud as a dependency like so:

bash
go get github.com/gophercloud/gophercloud

# Edit your code to import relevant packages from "github.com/gophercloud/gophercloud"

godep save ./...

This will install all the source files you need into a Godeps/_workspace directory, which is
referenceable from your own source files when you use the godep go command.

Getting started

Credentials

Because you'll be hitting an API, you will need to retrieve your OpenStack
credentials and either store them as environment variables or in your local Go
files. The first method is recommended because it decouples credential
information from source code, allowing you to push the latter to your version
control system without any security risk.

You will need to retrieve the following:

  • username
  • password
  • a valid Keystone identity URL

For users that have the OpenStack dashboard installed, there's a shortcut. If
you visit the project/access_and_security path in Horizon and click on the
"Download OpenStack RC File" button at the top right hand corner, you will
download a bash file that exports all of your access details to environment
variables. To execute the file, run source admin-openrc.sh and you will be
prompted for your password.

Authentication

Once you have access to your credentials, you can begin plugging them into
Gophercloud. The next step is authentication, and this is handled by a base
"Provider" struct. To get one, you can either pass in your credentials
explicitly, or tell Gophercloud to use environment variables:

go
import (
  "github.com/gophercloud/gophercloud"
  "github.com/gophercloud/gophercloud/openstack"
  "github.com/gophercloud/gophercloud/openstack/utils"
)

// Option 1: Pass in the values yourself
opts := gophercloud.AuthOptions{
  IdentityEndpoint: "https://openstack.example.com:5000/v2.0",
  Username: "{username}",
  Password: "{password}",
}

// Option 2: Use a utility function to retrieve all your environment variables
opts, err := openstack.AuthOptionsFromEnv()

Once you have the opts variable, you can pass it in and get back a
ProviderClient struct:

go
provider, err := openstack.AuthenticatedClient(opts)

The ProviderClient is the top-level client that all of your OpenStack services
derive from. The provider contains all of the authentication details that allow
your Go code to access the API - such as the base URL and token ID.

Provision a server

Once we have a base Provider, we inject it as a dependency into each OpenStack
service. In order to work with the Compute API, we need a Compute service
client; which can be created like so:

go
client, err := openstack.NewComputeV2(provider, gophercloud.EndpointOpts{
  Region: os.Getenv("OS_REGION_NAME"),
})

We then use this client for any Compute API operation we want. In our case,
we want to provision a new server - so we invoke the Create method and pass
in the flavor ID (hardware specification) and image ID (operating system) we're
interested in:

go
import "github.com/gophercloud/gophercloud/openstack/compute/v2/servers"

server, err := servers.Create(client, servers.CreateOpts{
  Name:      "My new server!",
  FlavorRef: "flavor_id",
  ImageRef:  "image_id",
}).Extract()

The above code sample creates a new server with the parameters, and embodies the
new resource in the server variable (a
servers.Server struct).

Advanced Usage

Have a look at the FAQ for some tips on customizing the way Gophercloud works.

Backwards-Compatibility Guarantees

None. Vendor it and write tests covering the parts you use.

Contributing

See the contributing guide.

Help and feedback

If you're struggling with something or have spotted a potential bug, feel free
to submit an issue to our bug tracker.

Thank You

We'd like to extend special thanks and appreciation to the following:

OpenLab

OpenLab is providing a full CI environment to test each PR and merge for a variety of OpenStack releases.

VEXXHOST

VEXXHOST is providing their services to assist with the development and testing of Gophercloud.


Overview (`vendor/github.com/gorilla/context/README.md`)

context

gorilla/context is a general purpose registry for global request variables.

Read the full documentation here: http://www.gorillatoolkit.org/pkg/context


Overview (`vendor/github.com/gorilla/mux/README.md`)

mux

gorilla/mux is a powerful URL router and dispatcher.

Read the full documentation here: http://www.gorillatoolkit.org/pkg/mux


Overview (`vendor/github.com/gorilla/websocket/README.md`)

Gorilla WebSocket

Gorilla WebSocket is a Go implementation of the
WebSocket protocol.

Documentation

Status

The Gorilla WebSocket package provides a complete and tested implementation of
the WebSocket protocol. The
package API is stable.

Installation

text
go get github.com/gorilla/websocket

Protocol Compliance

The Gorilla WebSocket package passes the server tests in the Autobahn Test
Suite
using the application in the examples/autobahn
subdirectory
.

Gorilla WebSocket compared with other packages

github.com/gorilla golang.org/x/net
RFC 6455 Features
Passes Autobahn Test Suite Yes No
Receive fragmented messageYes No, see note 1
Send close message Yes No
Send pings and receive pongs Yes No
Get the type of a received data message Yes Yes, see note 2
Limit size of received message Yes No
Read message using io.Reader Yes No, see note 3
Write message using io.WriteCloser Yes No, see note 3

Notes:

  1. Large messages are fragmented in Chrome's new WebSocket implementation.
  2. The application can get the type of a received data message by implementing
    a Codec marshal
    function.
  3. The go.net io.Reader and io.Writer operate across WebSocket frame boundaries.
    Read returns when the input buffer is full or a frame boundary is
    encountered. Each call to Write sends a single frame message. The Gorilla
    io.Reader and io.WriteCloser operate on a single WebSocket message.

Overview (`vendor/github.com/gregjones/httpcache/README.md`)

httpcache

Package httpcache provides a http.RoundTripper implementation that works as a mostly RFC-compliant cache for http responses.

It is only suitable for use as a 'private' cache (i.e. for a web-browser or an API-client and not for a shared proxy).

Cache Backends

License


Overview (`vendor/github.com/grpc-ecosystem/go-grpc-prometheus/README.md`)

Go gRPC Interceptors for Prometheus monitoring






Prometheus monitoring for your gRPC Go servers and clients.

A sister implementation for gRPC Java (same metrics, same semantics) is in grpc-ecosystem/java-grpc-prometheus.

Interceptors

gRPC Go recently acquired support for Interceptors, i.e. middleware that is executed
by a gRPC Server before the request is passed onto the user's application logic. It is a perfect way to implement
common patterns: auth, logging and... monitoring.

To use Interceptors in chains, please see go-grpc-middleware.

Usage

There are two types of interceptors: client-side and server-side. This package provides monitoring Interceptors for both.

Server-side

go
import "github.com/grpc-ecosystem/go-grpc-prometheus"
...
    // Initialize your gRPC server's interceptor.
    myServer := grpc.NewServer(
        grpc.StreamInterceptor(grpc_prometheus.StreamServerInterceptor),
        grpc.UnaryInterceptor(grpc_prometheus.UnaryServerInterceptor),
    )
    // Register your gRPC service implementations.
    myservice.RegisterMyServiceServer(s.server, &myServiceImpl{})
    // After all your registrations, make sure all of the Prometheus metrics are initialized.
    grpc_prometheus.Register(myServer)
    // Register Prometheus metrics handler.    
    http.Handle("/metrics", prometheus.Handler())
...

Client-side

go
import "github.com/grpc-ecosystem/go-grpc-prometheus"
...
   clientConn, err = grpc.Dial(
       address,
		   grpc.WithUnaryInterceptor(UnaryClientInterceptor),
		   grpc.WithStreamInterceptor(StreamClientInterceptor)
   )
   client = pb_testproto.NewTestServiceClient(clientConn)
   resp, err := client.PingEmpty(s.ctx, &myservice.Request{Msg: "hello"})
...

Metrics

Labels

All server-side metrics start with grpc_server as Prometheus subsystem name. All client-side metrics start with grpc_client. Both of them have mirror-concepts. Similarly all methods
contain the same rich labels:

  • grpc_service - the gRPC service name, which is the combination of protobuf package and
    the grpc_service section name. E.g. for package = mwitkow.testproto and
    service TestService the label will be grpc_service="mwitkow.testproto.TestService"

  • grpc_method - the name of the method called on the gRPC service. E.g.
    grpc_method="Ping"

  • grpc_type - the gRPC type of request.
    Differentiating between the two is important especially for latency measurements.

    • unary is single request, single response RPC
    • client_stream is a multi-request, single response RPC
    • server_stream is a single request, multi-response RPC
    • bidi_stream is a multi-request, multi-response RPC

Additionally for completed RPCs, the following labels are used:

  • grpc_code - the human-readable gRPC status code.
    The list of all statuses is to long, but here are some common ones:

    • OK - means the RPC was successful
    • IllegalArgument - RPC contained bad values
    • Internal - server-side error not disclosed to the clients

Counters

The counters and their up to date documentation is in server_reporter.go and client_reporter.go
the respective Prometheus handler (usually /metrics).

For the purpose of this documentation we will only discuss grpc_server metrics. The grpc_client ones contain mirror concepts.

For simplicity, let's assume we're tracking a single server-side RPC call of mwitkow.testproto.TestService,
calling the method PingList. The call succeeds and returns 20 messages in the stream.

First, immediately after the server receives the call it will increment the
grpc_server_started_total and start the handling time clock (if histograms are enabled).

jsoniq
grpc_server_started_total{grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 1

Then the user logic gets invoked. It receives one message from the client containing the request
(it's a server_stream):

jsoniq
grpc_server_msg_received_total{grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 1

The user logic may return an error, or send multiple messages back to the client. In this case, on
each of the 20 messages sent back, a counter will be incremented:

jsoniq
grpc_server_msg_sent_total{grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 20

After the call completes, it's status (OK or other gRPC status code)
and the relevant call labels increment the grpc_server_handled_total counter.

jsoniq
grpc_server_handled_total{grpc_code="OK",grpc_method="PingList",grpc_service="mwitkow.testproto.TestService",grpc_type="server_stream"} 1

Histograms

Prometheus histograms are a great way
to measure latency distributions of your RPCs. However since it is bad practice to have metrics
of high cardinality)
the latency monitoring metrics are disabled by default. To enable them please call the following
in your server initialization code:

jsoniq
grpc_prometheus.EnableHandlingTimeHistogram()

After the call completes, it's handling time will be recorded in a Prometheus histogram
variable grpc_server_handling_seconds. It contains three sub-metrics:

  • grpc_server_handling_seconds_count - the count of all completed RPCs by status and method
  • grpc_server_handling_seconds_sum - cumulative time of RPCs by status and method, useful for
    calculating average handling times
  • grpc_server_handling_seconds_bucket - contains the counts of RPCs by status and method in respective
    handling-time buckets. These buckets can be used by Prometheus to estimate SLAs (see here)

The counter values will look as follows:

text
/* Detailed source-code truncated for AI context efficiency. */

Useful query examples

Prometheus philosophy is to provide the most detailed metrics possible to the monitoring system, and
let the aggregations be handled there. The verbosity of above metrics make it possible to have that
flexibility. Here's a couple of useful monitoring queries:

request inbound rate

jsoniq
sum(rate(grpc_server_started_total{job="foo"}[1m])) by (grpc_service)

For job="foo" (common label to differentiate between Prometheus monitoring targets), calculate the
rate of requests per second (1 minute window) for each gRPC grpc_service that the job has. Please note
how the grpc_method is being omitted here: all methods of a given gRPC service will be summed together.

unary request error rate

jsoniq
sum(rate(grpc_server_handled_total{job="foo",grpc_type="unary",grpc_code!="OK"}[1m])) by (grpc_service)

For job="foo", calculate the per-grpc_service rate of unary (1:1) RPCs that failed, i.e. the
ones that didn't finish with OK code.

unary request error percentage

jsoniq
sum(rate(grpc_server_handled_total{job="foo",grpc_type="unary",grpc_code!="OK"}[1m])) by (grpc_service)
 / 
sum(rate(grpc_server_started_total{job="foo",grpc_type="unary"}[1m])) by (grpc_service)
 * 100.0

For job="foo", calculate the percentage of failed requests by service. It's easy to notice that
this is a combination of the two above examples. This is an example of a query you would like to
alert on in your system for SLA violations, e.g.
"no more than 1% requests should fail".

average response stream size

jsoniq
sum(rate(grpc_server_msg_sent_total{job="foo",grpc_type="server_stream"}[10m])) by (grpc_service)
 /
sum(rate(grpc_server_started_total{job="foo",grpc_type="server_stream"}[10m])) by (grpc_service)

For job="foo" what is the grpc_service-wide 10m average of messages returned for all server_stream RPCs. This allows you to track the stream sizes returned by your system, e.g. allows
you to track when clients started to send "wide" queries that ret
Note the divisor is the number of started RPCs, in order to account for in-flight requests.

99%-tile latency of unary requests

jsoniq
histogram_quantile(0.99, 
  sum(rate(grpc_server_handling_seconds_bucket{job="foo",grpc_type="unary"}[5m])) by (grpc_service,le)
)

For job="foo", returns an 99%-tile quantile estimation
of the handling time of RPCs per service. Please note the 5m rate, this means that the quantile
estimation will take samples in a rolling 5m window. When combined with other quantiles
(e.g. 50%, 90%), this query gives you tremendous insight into the responsiveness of your system
(e.g. impact of caching).

percentage of slow unary queries (>250ms)

jsoniq
100.0 - (
sum(rate(grpc_server_handling_seconds_bucket{job="foo",grpc_type="unary",le="0.25"}[5m])) by (grpc_service)
 / 
sum(rate(grpc_server_handling_seconds_count{job="foo",grpc_type="unary"}[5m])) by (grpc_service)
) * 100.0

For job="foo" calculate the by-grpc_service fraction of slow requests that took longer than 0.25
seconds. This query is relatively complex, since the Prometheus aggregations use le (less or equal)
buckets, meaning that counting "fast" requests fractions is easier. However, simple maths helps.
This is an example of a query you would like to alert on in your system for SLA violations,
e.g. "less than 1% of requests are slower than 250ms".

Status

This code has been used since August 2015 as the basis for monitoring of production gRPC micro services at Improbable.

License

go-grpc-prometheus is released under the Apache 2.0 license. See the LICENSE file for details.


Overview (`vendor/github.com/hashicorp/golang-lru/README.md`)

golang-lru

This provides the lru package which implements a fixed-size
thread safe LRU cache. It is based on the cache in Groupcache.

Documentation

Full docs are available on Godoc

Example

Using the LRU is very simple:

go
l, _ := New(128)
for i := 0; i < 256; i++ {
    l.Add(i, nil)
}
if l.Len() != 128 {
    panic(fmt.Sprintf("bad len: %v", l.Len()))
}

Overview (`vendor/github.com/hashicorp/hcl/README.md`)

HCL

HCL (HashiCorp Configuration Language) is a configuration language built
by HashiCorp. The goal of HCL is to build a structured configuration language
that is both human and machine friendly for use with command-line tools, but
specifically targeted towards DevOps tools, servers, etc.

HCL is also fully JSON compatible. That is, JSON can be used as completely
valid input to a system expecting HCL. This helps makes systems
interoperable with other systems.

HCL is heavily inspired by
libucl,
nginx configuration, and others similar.

Why?

A common question when viewing HCL is to ask the question: why not
JSON, YAML, etc.?

Prior to HCL, the tools we built at HashiCorp
used a variety of configuration languages from full programming languages
such as Ruby to complete data structure languages such as JSON. What we
learned is that some people wanted human-friendly configuration languages
and some people wanted machine-friendly languages.

JSON fits a nice balance in this, but is fairly verbose and most
importantly doesn't support comments. With YAML, we found that beginners
had a really hard time determining what the actual structure was, and
ended up guessing more often than not whether to use a hyphen, colon, etc.
in order to represent some configuration key.

Full programming languages such as Ruby enable complex behavior
a configuration language shouldn't usually allow, and also forces
people to learn some set of Ruby.

Because of this, we decided to create our own configuration language
that is JSON-compatible. Our configuration language (HCL) is designed
to be written and modified by humans. The API for HCL allows JSON
as an input so that it is also machine-friendly (machines can generate
JSON instead of trying to generate HCL).

Our goal with HCL is not to alienate other configuration languages.
It is instead to provide HCL as a specialized language for our tools,
and JSON as the interoperability layer.

Syntax

For a complete grammar, please see the parser itself. A high-level overview
of the syntax and grammar is listed here.

  • Single line comments start with # or //

  • Multi-line comments are wrapped in /* and */. Nested block comments
    are not allowed. A multi-line comment (also known as a block comment)
    terminates at the first */ found.

  • Values are assigned with the syntax key = value (whitespace doesn't
    matter). The value can be any primitive: a string, number, boolean,
    object, or list.

  • Strings are double-quoted and can contain any UTF-8 characters.
    Example: "Hello, World"

  • Multi-line strings start with <<EOF at the end of a line, and end
    with EOF on its own line (here documents).
    Any text may be used in place of EOF. Example:

text
<<FOO
hello
world
FOO
  • Numbers are assumed to be base 10. If you prefix a number with 0x,
    it is treated as a hexadecimal. If it is prefixed with 0, it is
    treated as an octal. Numbers can be in scientific notation: "1e10".

  • Boolean values: true, false

  • Arrays can be made by wrapping it in []. Example:
    ["foo", "bar", 42]. Arrays can contain primitives,
    other arrays, and objects. As an alternative, lists
    of objects can be created with repeated blocks, using
    this structure:

    hcl
    service {
        key = "value"
    }
    
    service {
        key = "value"
    }

Objects and nested objects are created using the structure shown below:

text
variable "ami" {
    description = "the AMI to use"
}

Thanks

Thanks to:

  • @vstakhov - The original libucl parser
    and syntax that HCL was based off of.

  • @fatih - The rewritten HCL parser
    in pure Go (no goyacc) and support for a printer.


Overview (`vendor/github.com/howeyc/gopass/README.md`)

getpasswd in Go [](https://godoc.org/github.com/howeyc/gopass) [](http://travis-ci.org/howeyc/gopass)

Retrieve password from user terminal or piped input without echo.

Verified on BSD, Linux, and Windows.

Example:

go
package main

import "fmt"
import "github.com/howeyc/gopass"

func main() {
	fmt.Printf("Password: ")

	// Silent. For printing *'s use gopass.GetPasswdMasked()
	pass, err := gopass.GetPasswd()
	if err != nil {
		// Handle gopass.ErrInterrupted or getch() read error
	}

	// Do something with pass
}

Caution: Multi-byte characters not supported!


Overview (`vendor/github.com/imdario/mergo/README.md`)

Mergo

A helper to merge structs and maps in Golang. Useful for configuration default values, avoiding messy if-statements.

Also a lovely comune (municipality) in the Province of Ancona in the Italian region Marche.

Status

It is ready for production use. It works fine although it may use more of testing. Here some projects in the wild using Mergo:

Build Status

Installation

text
go get github.com/imdario/mergo

// use in your .go code
import (
    "github.com/imdario/mergo"
)

Usage

You can only merge same-type structs with exported fields initialized as zero value of their type and same-types maps. Mergo won't merge unexported (private) fields but will do recursively any exported one. Also maps will be merged recursively except for structs inside maps (because they are not addressable using Go reflection).

text
if err := mergo.Merge(&dst, src); err != nil {
    // ...
}

Additionally, you can map a map[string]interface{} to a struct (and otherwise, from struct to map), following the same restrictions as in Merge(). Keys are capitalized to find each corresponding exported field.

text
if err := mergo.Map(&dst, srcMap); err != nil {
    // ...
}

Warning: if you map a struct to map, it won't do it recursively. Don't expect Mergo to map struct members of your struct as map[string]interface{}. They will be just assigned as values.

More information and examples in godoc documentation.

Note: if test are failing due missing package, please execute:

text
go get gopkg.in/yaml.v1

Contact me

If I can help you, you have an idea or you are using Mergo in your projects, don't hesitate to drop me a line (or a pull request): @im_dario

About

Written by Dario Castañé.

License

BSD 3-Clause license, as Go language.


Overview (`vendor/github.com/inconshreveable/mousetrap/README.md`)

mousetrap

mousetrap is a tiny library that answers a single question.

On a Windows machine, was the process invoked by someone double clicking on
the executable file while browsing in explorer?

Motivation

Windows developers unfamiliar with command line tools will often "double-click"
the executable for a tool. Because most CLI tools print the help and then exit
when invoked without arguments, this is often very frustrating for those users.

mousetrap provides a way to detect these invocations so that you can provide
more helpful behavior and instructions on how to run the CLI tool. To see what
this looks like, both from an organizational and a technical perspective, see
https://inconshreveable.com/09-09-2014/sweat-the-small-stuff/

The interface

The library exposes a single interface:

text
func StartedByExplorer() (bool)

Overview (`vendor/github.com/jmespath/go-jmespath/README.md`)

go-jmespath - A JMESPath implementation in Go

See http://jmespath.org for more info.


Overview (`vendor/github.com/jonboulle/clockwork/README.md`)

clockwork

a simple fake clock for golang

Usage

Replace uses of the time package with the clockwork.Clock interface instead.

For example, instead of using time.Sleep directly:

text
func my_func() {
	time.Sleep(3 * time.Second)
	do_something()
}

inject a clock and use its Sleep method instead:

text
func my_func(clock clockwork.Clock) {
	clock.Sleep(3 * time.Second)
	do_something()
}

Now you can easily test my_func with a FakeClock:

text
func TestMyFunc(t *testing.T) {
	c := clockwork.NewFakeClock()

	// Start our sleepy function
	my_func(c)

	// Ensure we wait until my_func is sleeping
	c.BlockUntil(1)

	assert_state()

	// Advance the FakeClock forward in time
	c.Advance(3)

	assert_state()
}

and in production builds, simply inject the real clock instead:

text
my_func(clockwork.NewRealClock())

See example_test.go for a full example.

Credits

Inspired by @wickman's threaded fake clock, and the [Golang playground](http://blog.golang.org/playground#Faking time)


Overview (`vendor/github.com/json-iterator/go/README.md`)







A high-performance 100% compatible drop-in replacement of "encoding/json"

text
Go开发者们请加入我们,滴滴出行平台技术部 [email protected]

Benchmark

Source code: https://github.com/json-iterator/go-benchmark/blob/master/src/github.com/json-iterator/go-benchmark/benchmark_medium_payload_test.go

Raw Result (easyjson requires static code generation)

ns/op allocation bytes allocation times
std decode 35510 ns/op 1960 B/op 99 allocs/op
easyjson decode 8499 ns/op 160 B/op 4 allocs/op
jsoniter decode 5623 ns/op 160 B/op 3 allocs/op
std encode 2213 ns/op 712 B/op 5 allocs/op
easyjson encode 883 ns/op 576 B/op 3 allocs/op
jsoniter encode 837 ns/op 384 B/op 4 allocs/op

Usage

100% compatibility with standard lib

Replace

go
import "encoding/json"
json.Marshal(&data)

with

go
import "github.com/json-iterator/go"

var json = jsoniter.ConfigCompatibleWithStandardLibrary
json.Marshal(&data)

Replace

go
import "encoding/json"
json.Unmarshal(input, &data)

with

go
import "github.com/json-iterator/go"

var json = jsoniter.ConfigCompatibleWithStandardLibrary
json.Unmarshal(input, &data)

More documentation

How to get

text
go get github.com/json-iterator/go

Contribution Welcomed !

Contributors

Report issue or pull request, or email [email protected], or


Overview (`vendor/github.com/jteeuwen/go-bindata/README.md`)

bindata

This package converts any file into managable Go source code. Useful for
embedding binary data into a go program. The file data is optionally gzip
compressed before being converted to a raw byte slice.

It comes with a command line tool in the go-bindata sub directory.
This tool offers a set of command line options, used to customize the
output being generated.

Installation

To install the library and command line program, use the following:

text
go get -u github.com/jteeuwen/go-bindata/...

Usage

Conversion is done on one or more sets of files. They are all embedded in a new
Go source file, along with a table of contents and an Asset function,
which allows quick access to the asset, based on its name.

The simplest invocation generates a bindata.go file in the current
working directory. It includes all assets from the data directory.

text
$ go-bindata data/

To include all input sub-directories recursively, use the elipsis postfix
as defined for Go import paths. Otherwise it will only consider assets in the
input directory itself.

text
$ go-bindata data/...

To specify the name of the output file being generated, we use the following:

text
$ go-bindata -o myfile.go data/

Multiple input directories can be specified if necessary.

text
$ go-bindata dir1/... /path/to/dir2/... dir3

The following paragraphs detail some of the command line options which can be
supplied to go-bindata. Refer to the testdata/out directory for various
output examples from the assets in testdata/in. Each example uses different
command line options.

To ignore files, pass in regexes using -ignore, for example:

text
$ go-bindata -ignore=\\.gitignore data/...

Accessing an asset

To access asset data, we use the Asset(string) ([]byte, error) function which
is included in the generated output.

text
data, err := Asset("pub/style/foo.css")
if err != nil {
	// Asset was not found.
}

// use asset data

Debug vs Release builds

When invoking the program with the -debug flag, the generated code does
not actually include the asset data. Instead, it generates function stubs
which load the data from the original file on disk. The asset API remains
identical between debug and release builds, so your code will not have to
change.

This is useful during development when you expect the assets to change often.
The host application using these assets uses the same API in both cases and
will not have to care where the actual data comes from.

An example is a Go webserver with some embedded, static web content like
HTML, JS and CSS files. While developing it, you do not want to rebuild the
whole server and restart it every time you make a change to a bit of
javascript. You just want to build and launch the server once. Then just press
refresh in the browser to see those changes. Embedding the assets with the
debug flag allows you to do just that. When you are finished developing and
ready for deployment, just re-invoke go-bindata without the -debug flag.
It will now embed the latest version of the assets.

Lower memory footprint

Using the -nomemcopy flag, will alter the way the output file is generated.
It will employ a hack that allows us to read the file data directly from
the compiled program's .rodata section. This ensures that when we call
call our generated function, we omit unnecessary memcopies.

The downside of this, is that it requires dependencies on the reflect and
unsafe packages. These may be restricted on platforms like AppEngine and
thus prevent you from using this mode.

Another disadvantage is that the byte slice we create, is strictly read-only.
For most use-cases this is not a problem, but if you ever try to alter the
returned byte slice, a runtime panic is thrown. Use this mode only on target
platforms where memory constraints are an issue.

The default behaviour is to use the old code generation method. This
prevents the two previously mentioned issues, but will employ at least one
extra memcopy and thus increase memory requirements.

For instance, consider the following two examples:

This would be the default mode, using an extra memcopy but gives a safe
implementation without dependencies on reflect and unsafe:

go
func myfile() []byte {
    return []byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a}
}

Here is the same functionality, but uses the .rodata hack.
The byte slice returned from this example can not be written to without
generating a runtime error.

go
var _myfile = "\x89\x50\x4e\x47\x0d\x0a\x1a"

func myfile() []byte {
    var empty [0]byte
    sx := (*reflect.StringHeader)(unsafe.Pointer(&_myfile))
    b := empty[:]
    bx := (*reflect.SliceHeader)(unsafe.Pointer(&b))
    bx.Data = sx.Data
    bx.Len = len(_myfile)
    bx.Cap = bx.Len
    return b
}

Optional compression

When the -nocompress flag is given, the supplied resource is not GZIP
compressed before being turned into Go code. The data should still be accessed
through a function call, so nothing changes in the usage of the generated file.

This feature is useful if you do not care for compression, or the supplied
resource is already compressed. Doing it again would not add any value and may
even increase the size of the data.

The default behaviour of the program is to use compression.

Path prefix stripping

The keys used in the _bindata map, are the same as the input file name
passed to go-bindata. This includes the path. In most cases, this is not
desireable, as it puts potentially sensitive information in your code base.
For this purpose, the tool supplies another command line flag -prefix.
This accepts a portion of a path name, which should be stripped off from
the map keys and function names.

For example, running without the -prefix flag, we get:

text
$ go-bindata /path/to/templates/

_bindata["/path/to/templates/foo.html"] = path_to_templates_foo_html

Running with the -prefix flag, we get:

text
$ go-bindata -prefix "/path/to/" /path/to/templates/

_bindata["templates/foo.html"] = templates_foo_html

Build tags

With the optional -tags flag, you can specify any go build tags that
must be fulfilled for the output file to be included in a build. This
is useful when including binary data in multiple formats, where the desired
format is specified at build time with the appropriate tags.

The tags are appended to a // +build line in the beginning of the output file
and must follow the build tags syntax specified by the go tool.

go-bindata-assetfs -
implements http.FileSystem interface. Allows you to serve assets with net/http.


Overview (`vendor/github.com/juju/ratelimit/README.md`)

ratelimit

--
import "github.com/juju/ratelimit"

The ratelimit package provides an efficient token bucket implementation. See
http://en.wikipedia.org/wiki/Token_bucket.

Usage

func Reader

go
func Reader(r io.Reader, bucket *Bucket) io.Reader

Reader returns a reader that is rate limited by the given token bucket. Each
token in the bucket represents one byte.

func Writer

go
func Writer(w io.Writer, bucket *Bucket) io.Writer

Writer returns a writer that is rate limited by the given token bucket. Each
token in the bucket represents one byte.

type Bucket

go
type Bucket struct {
}

Bucket represents a token bucket that fills at a predetermined rate. Methods on
Bucket may be called concurrently.

func NewBucket

go
func NewBucket(fillInterval time.Duration, capacity int64) *Bucket

NewBucket returns a new token bucket that fills at the rate of one token every
fillInterval, up to the given maximum capacity. Both arguments must be positive.
The bucket is initially full.

func NewBucketWithQuantum

go
func NewBucketWithQuantum(fillInterval time.Duration, capacity, quantum int64) *Bucket

NewBucketWithQuantum is similar to NewBucket, but allows the specification of
the quantum size - quantum tokens are added every fillInterval.

func NewBucketWithRate

go
func NewBucketWithRate(rate float64, capacity int64) *Bucket

NewBucketWithRate returns a token bucket that fills the bucket at the rate of
rate tokens per second up to the given maximum capacity. Because of limited
clock resolution, at high rates, the actual rate may be up to 1% different from
the specified rate.

func (*Bucket) Rate

go
func (tb *Bucket) Rate() float64

Rate returns the fill rate of the bucket, in tokens per second.

func (*Bucket) Take

go
func (tb *Bucket) Take(count int64) time.Duration

Take takes count tokens from the bucket without blocking. It returns the time
that the caller should wait until the tokens are actually available.

Note that if the request is irrevocable - there is no way to return tokens to
the bucket once this method commits us to taking them.

func (*Bucket) TakeAvailable

go
func (tb *Bucket) TakeAvailable(count int64) int64

TakeAvailable takes up to count immediately available tokens from the bucket. It
returns the number of tokens removed, or zero if there are no available tokens.
It does not block.

func (*Bucket) TakeMaxDuration

go
func (tb *Bucket) TakeMaxDuration(count int64, maxWait time.Duration) (time.Duration, bool)

TakeMaxDuration is like Take, except that it will only take tokens from the
bucket if the wait time for the tokens is no greater than maxWait.

If it would take longer than maxWait for the tokens to become available, it does
nothing and reports false, otherwise it returns the time that the caller should
wait until the tokens are actually available, and reports true.

func (*Bucket) Wait

go
func (tb *Bucket) Wait(count int64)

Wait takes count tokens from the bucket, waiting until they are available.

func (*Bucket) WaitMaxDuration

go
func (tb *Bucket) WaitMaxDuration(count int64, maxWait time.Duration) bool

WaitMaxDuration is like Wait except that it will only take tokens from the
bucket if it needs to wait for no greater than maxWait. It reports whether any
tokens have been removed from the bucket If no tokens have been removed, it
returns immediately.


Overview (`vendor/github.com/kardianos/osext/README.md`)

Extensions to the "os" package.

Find the current Executable and ExecutableFolder.

There is sometimes utility in finding the current executable file
that is running. This can be used for upgrading the current executable
or finding resources located relative to the executable file.

Multi-platform and supports:

  • Linux
  • OS X
  • Windows
  • Plan 9
  • BSDs.

Overview (`vendor/github.com/karlseguin/ccache/readme.md`)

CCache

CCache is an LRU Cache, written in Go, focused on supporting high concurrency.

Lock contention on the list is reduced by:

  • Introducing a window which limits the frequency that an item can get promoted
  • Using a buffered channel to queue promotions for a single worker
  • Garbage collecting within the same thread as the worker

Setup

First, download the project:

text
go get github.com/karlseguin/ccache

Configuration

Next, import and create a Cache instance:

go
import (
  "github.com/karlseguin/ccache"
)

var cache = ccache.New(ccache.Configure())

Configure exposes a chainable API:

go
var cache = ccache.New(ccache.Configure().MaxSize(1000).ItemsToPrune(100))

The most likely configuration options to tweak are:

  • MaxSize(int) - the maximum number size to store in the cache (default: 5000)
  • GetsPerPromote(int) - the number of times an item is fetched before we promote it. For large caches with long TTLs, it normally isn't necessary to promote an item after every fetch (default: 3)
  • ItemsToPrune(int) - the number of items to prune when we hit MaxSize. Freeing up more than 1 slot at a time improved performance (default: 500)

Configurations that change the internals of the cache, which aren't as likely to need tweaking:

  • Buckets - ccache shards its internal map to provide a greater amount of concurrency. Must be a power of 2 (default: 16).
  • PromoteBuffer(int) - the size of the buffer to use to queue promotions (default: 1024)
  • DeleteBuffer(int) the size of the buffer to use to queue deletions (default: 1024)

Usage

Once the cache is setup, you can Get, Set and Delete items from it. A Get returns an *Item:

Get

go
item := cache.Get("user:4")
if item == nil {
  //handle
} else {
  user := item.Value().(*User)
}

The returned *Item exposes a number of methods:

  • Value() interface{} - the value cached
  • Expired() bool - whether the item is expired or not
  • TTL() time.Duration - the duration before the item expires (will be a negative value for expired items)
  • Expires() time.Time - the time the item will expire

By returning expired items, CCache lets you decide if you want to serve stale content or not. For example, you might decide to serve up slightly stale content (< 30 seconds old) while re-fetching newer data in the background. You might also decide to serve up infinitely stale content if you're unable to get new data from your source.

Set

Set expects the key, value and ttl:

go
cache.Set("user:4", user, time.Minute * 10)

Fetch

There's also a Fetch which mixes a Get and a Set:

go
item, err := cache.Fetch("user:4", time.Minute * 10, func() (interface{}, error) {
  //code to fetch the data incase of a miss
  //should return the data to cache and the error, if any
})

Delete

Delete expects the key to delete. It's ok to call Delete on a non-existant key:

go
cache.Delete("user:4")

Extend

The life of an item can be changed via the Extend method. This will change the expiry of the item by the specified duration relative to the current time.

Replace

The value of an item can be updated to a new value without renewing the item's TTL or it's position in the LRU:

go
cache.Replace("user:4", user)

Replace returns true if the item existed (and thus was replaced). In the case where the key was not in the cache, the value is not inserted and false is returned.

Stop

The cache's background worker can be stopped by calling Stop. Once Stop is called
the cache should not be used (calls are likely to panic). Stop must be called in order to allow the garbage collector to reap the cache.

Tracking

CCache supports a special tracking mode which is meant to be used in conjunction with other pieces of your code that maintains a long-lived reference to data.

When you configure your cache with Track():

go
cache = ccache.New(ccache.Configure().Track())

The items retrieved via TrackingGet will not be eligible for purge until Release is called on them:

go
item := cache.TrackingGet("user:4")
user := item.Value()   //will be nil if "user:4" didn't exist in the cache
item.Release()  //can be called even if item.Value() returned nil

In practive, Release wouldn't be called until later, at some other place in your code.

There's a couple reason to use the tracking mode if other parts of your code also hold references to objects. First, if you're already going to hold a reference to these objects, there's really no reason not to have them in the cache - the memory is used up anyways.

More important, it helps ensure that you're code returns consistent data. With tracking, "user:4" might be purged, and a subsequent Fetch would reload the data. This can result in different versions of "user:4" being returned by different parts of your system.

LayeredCache

CCache's LayeredCache stores and retrieves values by both a primary and secondary key. Deletion can happen against either the primary and secondary key, or the primary key only (removing all values that share the same primary key).

LayeredCache is useful for HTTP caching, when you want to purge all variations of a request.

LayeredCache takes the same configuration object as the main cache, exposes the same optional tracking capabilities, but exposes a slightly different API:

go
cache := ccache.Layered(ccache.Configure())

cache.Set("/users/goku", "type:json", "{value_to_cache}", time.Minute * 5)
cache.Set("/users/goku", "type:xml", "<value_to_cache>", time.Minute * 5)

json := cache.Get("/users/goku", "type:json")
xml := cache.Get("/users/goku", "type:xml")

cache.Delete("/users/goku", "type:json")
cache.Delete("/users/goku", "type:xml")
// OR
cache.DeleteAll("/users/goku")

SecondaryCache

In some cases, when using a LayeredCache, it may be desirable to always be acting on the secondary portion of the cache entry. This could be the case where the primary key is used as a key elsewhere in your code. The SecondaryCache is retrieved with:

go
cache := ccache.Layered(ccache.Configure())
sCache := cache.GetOrCreateSecondaryCache("/users/goku")
sCache.Set("type:json", "{value_to_cache}", time.Minute * 5)

The semantics for interacting with the SecondaryCache are exactly the same as for a regular Cache. However, one difference is that Get will not return nil, but will return an empty 'cache' for a non-existent primary key.

Size

By default, items added to a cache have a size of 1. This means that if you configure MaxSize(10000), you'll be able to store 10000 items in the cache.

However, if the values you set into the cache have a method Size() int64, this size will be used. Note that ccache has an overhead of ~350 bytes per entry, which isn't taken into account. In other words, given a filled up cache, with MaxSize(4096000) and items that return a Size() int64 of 2048, we can expect to find 2000 items (4096000/2048) taking a total space of 4796000 bytes.

Want Something Simpler?

For a simpler cache, checkout out rcache


Overview (`vendor/github.com/kr/pty/README.md`)

pty

Pty is a Go package for using unix pseudo-terminals.

Install

text
go get github.com/kr/pty

Example

go
package main

import (
	"github.com/kr/pty"
	"io"
	"os"
	"os/exec"
)

func main() {
	c := exec.Command("grep", "--color=auto", "bar")
	f, err := pty.Start(c)
	if err != nil {
		panic(err)
	}

	go func() {
		f.Write([]byte("foo\n"))
		f.Write([]byte("bar\n"))
		f.Write([]byte("baz\n"))
		f.Write([]byte{4}) // EOT
	}()
	io.Copy(os.Stdout, f)
}

Overview (`vendor/github.com/lpabon/godbc/README.md`)

godbc

Design by contract for Go

Installation

To install godbc, use go get:

text
go get github.com/lpabon/godbc

Import the godbc package into your code using this template:

text
import (
  "github.com/lpabon/godbc"
)

Documentation

Documentation is available at https://godoc.org/github.com/lpabon/godbc


Overview (`vendor/github.com/magiconair/properties/README.md`)

Overview [](https://travis-ci.org/magiconair/properties)

Current version: 1.7.0

properties is a Go library for reading and writing properties files.

It supports reading from multiple files or URLs and Spring style recursive
property expansion of expressions like ${key} to their corresponding value.
Value expressions can refer to other keys like in ${key} or to environment
variables like in ${USER}. Filenames can also contain environment variables
like in /home/${USER}/myapp.properties.

Properties can be decoded into structs, maps, arrays and values through
struct tags.

Comments and the order of keys are preserved. Comments can be modified
and can be written to the output.

The properties library supports both ISO-8859-1 and UTF-8 encoded data.

Starting from version 1.3.0 the behavior of the MustXXX() functions is
configurable by providing a custom ErrorHandler function. The default has
changed from panic to log.Fatal but this is configurable and custom
error handling functions can be provided. See the package documentation for
details.

Getting Started

go
import (
	"flag"
	"github.com/magiconair/properties"
)

func main() {
	p := properties.MustLoadFile("${HOME}/config.properties", properties.UTF8)

	// via getters
	host := p.MustGetString("host")
	port := p.GetInt("port", 8080)

	// or via decode
	type Config struct {
		Host    string        `properties:"host"`
		Port    int           `properties:"port,default=9000"`
		Accept  []string      `properties:"accept,default=image/png;image;gif"`
		Timeout time.Duration `properties:"timeout,default=5s"`
	}
	var cfg Config
	if err := p.Decode(&cfg); err != nil {
		log.Fatal(err)
	}

	// or via flags
	p.MustFlag(flag.CommandLine)

	// or via url
	p = properties.MustLoadURL("http://host/path")
}

Read the full documentation on GoDoc

Installation and Upgrade

text
$ go get -u github.com/magiconair/properties

License

2 clause BSD license. See LICENSE file for details.

ToDo

  • Dump contents with passwords and secrets obscured

Overview (`vendor/github.com/miekg/dns/README.md`)

Alternative (more granular) approach to a DNS library

Less is more.

Complete and usable DNS library. All widely used Resource Records are
supported, including the DNSSEC types. It follows a lean and mean philosophy.
If there is stuff you should know as a DNS programmer there isn't a convenience
function for it. Server side and client side programming is supported, i.e. you
can build servers and resolvers with it.

We try to keep the "master" branch as sane as possible and at the bleeding edge
of standards, avoiding breaking changes wherever reasonable. We support the last
two versions of Go, currently: 1.5 and 1.6.

Goals

  • KISS;
  • Fast;
  • Small API, if its easy to code in Go, don't make a function for it.

Users

A not-so-up-to-date-list-that-may-be-actually-current:

Send pull request if you want to be listed here.

Features

  • UDP/TCP queries, IPv4 and IPv6;
  • RFC 1035 zone file parsing ($INCLUDE, $ORIGIN, $TTL and $GENERATE (for all record types) are supported;
  • Fast:
    • Reply speed around ~ 80K qps (faster hardware results in more qps);
    • Parsing RRs ~ 100K RR/s, that's 5M records in about 50 seconds;
  • Server side programming (mimicking the net/http package);
  • Client side programming;
  • DNSSEC: signing, validating and key generation for DSA, RSA and ECDSA;
  • EDNS0, NSID, Cookies;
  • AXFR/IXFR;
  • TSIG, SIG(0);
  • DNS over TLS: optional encrypted connection between client and server;
  • DNS name compression;
  • Depends only on the standard library.

Have fun!

Miek Gieben - 2010-2012 - [email protected]

Building

Building is done with the go tool. If you have setup your GOPATH
correctly, the following should work:

text
go get github.com/miekg/dns
go build github.com/miekg/dns

Examples

A short "how to use the API" is at the beginning of doc.go (this also will show
when you call godoc github.com/miekg/dns).

Example programs can be found in the github.com/miekg/exdns repository.

Supported RFCs

all of them

  • 103{4,5} - DNS standard
  • 1348 - NSAP record (removed the record)
  • 1982 - Serial Arithmetic
  • 1876 - LOC record
  • 1995 - IXFR
  • 1996 - DNS notify
  • 2136 - DNS Update (dynamic updates)
  • 2181 - RRset definition - there is no RRset type though, just []RR
  • 2537 - RSAMD5 DNS keys
  • 2065 - DNSSEC (updated in later RFCs)
  • 2671 - EDNS record
  • 2782 - SRV record
  • 2845 - TSIG record
  • 2915 - NAPTR record
  • 2929 - DNS IANA Considerations
  • 3110 - RSASHA1 DNS keys
  • 3225 - DO bit (DNSSEC OK)
  • 340{1,2,3} - NAPTR record
  • 3445 - Limiting the scope of (DNS)KEY
  • 3597 - Unknown RRs
  • 403{3,4,5} - DNSSEC + validation functions
  • 4255 - SSHFP record
  • 4343 - Case insensitivity
  • 4408 - SPF record
  • 4509 - SHA256 Hash in DS
  • 4592 - Wildcards in the DNS
  • 4635 - HMAC SHA TSIG
  • 4701 - DHCID
  • 4892 - id.server
  • 5001 - NSID
  • 5155 - NSEC3 record
  • 5205 - HIP record
  • 5702 - SHA2 in the DNS
  • 5936 - AXFR
  • 5966 - TCP implementation recommendations
  • 6605 - ECDSA
  • 6725 - IANA Registry Update
  • 6742 - ILNP DNS
  • 6840 - Clarifications and Implementation Notes for DNS Security
  • 6844 - CAA record
  • 6891 - EDNS0 update
  • 6895 - DNS IANA considerations
  • 6975 - Algorithm Understanding in DNSSEC
  • 7043 - EUI48/EUI64 records
  • 7314 - DNS (EDNS) EXPIRE Option
  • 7553 - URI record
  • 7858 - DNS over TLS: Initiation and Performance Considerations (draft)
  • 7873 - Domain Name System (DNS) Cookies (draft-ietf-dnsop-cookies)
  • xxxx - EDNS0 DNS Update Lease (draft)

Loosely based upon

  • ldns
  • NSD
  • Net::DNS
  • GRONG

Overview (`vendor/github.com/mindprince/gonvml/README.md`)

Go Bindings for NVML

NVML or NVIDIA Management
Library
is a
C-based API that can be used for monitoring NVIDIA GPU devices. It's closed
source but can be downloaded as part of the GPU Deployment
Kit
.

The NVML API
Reference

describe various methods that are available as part of NVML.

The nvml.h file is included in this repository so that we don't depend on
the presence of NVML in the build environment.

The bindings.go file is the cgo bridge which calls the NVML functions. The
cgo preamble in bindings.go uses dlopen to dynamically load NVML and makes
its functions available.


Overview (`vendor/github.com/mistifyio/go-zfs/README.md`)

Go Wrapper for ZFS

Simple wrappers for ZFS command line tools.

Requirements

You need a working ZFS setup. To use on Ubuntu 14.04, setup ZFS:

text
sudo apt-get install python-software-properties
sudo apt-add-repository ppa:zfs-native/stable
sudo apt-get update
sudo apt-get install ubuntu-zfs libzfs-dev

Developed using Go 1.3, but currently there isn't anything 1.3 specific. Don't use Ubuntu packages for Go, use http://golang.org/doc/install

Generally you need root privileges to use anything zfs related.

Status

This has been only been tested on Ubuntu 14.04

In the future, we hope to work directly with libzfs.

Hacking

The tests have decent examples for most functions.

go
//assuming a zpool named test
//error handling ommitted


f, err := zfs.CreateFilesystem("test/snapshot-test", nil)
ok(t, err)

s, err := f.Snapshot("test", nil)
ok(t, err)

// snapshot is named "test/snapshot-test@test"

c, err := s.Clone("test/clone-test", nil)

err := c.Destroy()
err := s.Destroy()
err := f.Destroy()

Contributing

See the contributing guidelines


Overview (`vendor/github.com/mitchellh/go-wordwrap/README.md`)

go-wordwrap

go-wordwrap (Golang package: wordwrap) is a package for Go that
automatically wraps words into multiple lines. The primary use case for this
is in formatting CLI output, but of course word wrapping is a generally useful
thing to do.

Installation and Usage

Install using go get github.com/mitchellh/go-wordwrap.

Full documentation is available at
http://godoc.org/github.com/mitchellh/go-wordwrap

Below is an example of its usage ignoring errors:

go
wrapped := wordwrap.WrapString("foo bar baz", 3)
fmt.Println(wrapped)

Would output:

text
foo
bar
baz

Word Wrap Algorithm

This library doesn't use any clever algorithm for word wrapping. The wrapping
is actually very naive: whenever there is whitespace or an explicit linebreak.
The goal of this library is for word wrapping CLI output, so the input is
typically pretty well controlled human language. Because of this, the naive
approach typically works just fine.

In the future, we'd like to make the algorithm more advanced. We would do
so without breaking the API.


Overview (`vendor/github.com/mitchellh/mapstructure/README.md`)

mapstructure

mapstructure is a Go library for decoding generic map values to structures
and vice versa, while providing helpful error handling.

This library is most useful when decoding values from some data stream (JSON,
Gob, etc.) where you don't quite know the structure of the underlying data
until you read a part of it. You can therefore read a map[string]interface{}
and use this library to decode it into the proper underlying native Go
structure.

Installation

Standard go get:

text
$ go get github.com/mitchellh/mapstructure

Usage & Example

For usage and examples see the Godoc.

The Decode function has examples associated with it there.

But Why?!

Go offers fantastic standard libraries for decoding formats such as JSON.
The standard method is to have a struct pre-created, and populate that struct
from the bytes of the encoded format. This is great, but the problem is if
you have configuration or an encoding that changes slightly depending on
specific fields. For example, consider this JSON:

json
{
  "type": "person",
  "name": "Mitchell"
}

Perhaps we can't populate a specific structure without first reading
the "type" field from the JSON. We could always do two passes over the
decoding of the JSON (reading the "type" first, and the rest later).
However, it is much simpler to just decode this into a map[string]interface{}
structure, read the "type" key, then use something like this library
to decode it into the proper structure.


Overview (`vendor/github.com/mohae/deepcopy/README.md`)

deepCopy

DeepCopy makes deep copies of things: unexported field values are not copied.

Usage

text
cpy := deepcopy.Copy(orig)

Overview (`vendor/github.com/mreiferson/go-httpclient/README.md`)

go-httpclient

requires Go 1.1+ as of v0.4.0 the API has been completely re-written for Go 1.1 (for a Go
1.0.x compatible release see 1adef50)

BuildStatus

Provides an HTTP Transport that implements the RoundTripper interface and
can be used as a built in replacement for the standard library's, providing:

  • connection timeouts
  • request timeouts

This is a thin wrapper around http.Transport that sets dial timeouts and uses
Go's internal timer scheduler to call the Go 1.1+ CancelRequest() API.

Example

go
transport := &httpclient.Transport{
    ConnectTimeout:        1*time.Second,
    RequestTimeout:        10*time.Second,
    ResponseHeaderTimeout: 5*time.Second,
}
defer transport.Close()

client := &http.Client{Transport: transport}
req, _ := http.NewRequest("GET", "http://127.0.0.1/test", nil)
resp, err := client.Do(req)
if err != nil {
    return err
}
defer resp.Body.Close()

Note: you will want to re-use a single client object rather than creating one for each request, otherwise you will end up leaking connections.

Reference Docs

For API docs see godoc.


Overview (`vendor/github.com/mrunalp/fileutils/README.md`)

fileutils

Collection of utilities for file manipulation in golang

The library is based on docker pkg/archive pkg/idtools but does copies instead of handling archive formats.


Overview (`vendor/github.com/mvdan/xurls/README.md`)

xurls

Extract urls from text using regular expressions.

text
go get github.com/mvdan/xurls
go
import "github.com/mvdan/xurls"

func main() {
	xurls.Relaxed.FindString("Do gophers live in golang.org?")
	// "golang.org"
	xurls.Relaxed.FindAllString("foo.com is http://foo.com/.", -1)
	// []string{"foo.com", "http://foo.com/"}
	xurls.Strict.FindAllString("foo.com is http://foo.com/.", -1)
	// []string{"http://foo.com/"}
}

cmd/xurls

Reads text and prints one url per line.

text
go get github.com/mvdan/xurls/cmd/xurls
shell
$ echo "Do gophers live in http://golang.org?" | xurls
http://golang.org

Overview (`vendor/github.com/onsi/ginkgo/README.md`)

Jump to the docs to learn more. To start rolling your Ginkgo tests now keep reading!

To discuss Ginkgo and get updates, join the google group.

Feature List

  • Ginkgo uses Go's testing package and can live alongside your existing testing tests. It's easy to bootstrap and start writing your first tests

  • Structure your BDD-style tests expressively:

  • A comprehensive test runner that lets you:

    • Mark specs as pending
    • Focus individual specs, and groups of specs, either programmatically or on the command line
    • Run your tests in random order, and then reuse random seeds to replicate the same order.
    • Break up your test suite into parallel processes for straightforward test parallelization
  • ginkgo: a command line interface with plenty of handy command line arguments for running your tests and generating test files. Here are a few choice examples:

    • ginkgo -nodes=N runs your tests in N parallel processes and print out coherent output in realtime
    • ginkgo -cover runs your tests using Golang's code coverage tool
    • ginkgo convert converts an XUnit-style testing package to a Ginkgo-style package
    • ginkgo -focus="REGEXP" and ginkgo -skip="REGEXP" allow you to specify a subset of tests to run via regular expression
    • ginkgo -r runs all tests suites under the current directory
    • ginkgo -v prints out identifying information for each tests just before it runs

    And much more: run ginkgo help for details!

    The ginkgo CLI is convenient, but purely optional -- Ginkgo works just fine with go test

  • ginkgo watch watches packages and their dependencies for changes, then reruns tests. Run tests immediately as you develop!

  • Built-in support for testing asynchronicity

  • Built-in support for benchmarking your code. Control the number of benchmark samples as you gather runtimes and other, arbitrary, bits of numerical information about your code.

  • Completions for Sublime Text: just use Package Control to install Ginkgo Completions.

  • Straightforward support for third-party testing libraries such as Gomock and Testify. Check out the docs for details.

  • A modular architecture that lets you easily:

[Gomega](http://github.com/onsi/gomega): Ginkgo's Preferred Matcher Library

Ginkgo is best paired with Gomega. Learn more about Gomega here

[Agouti](http://github.com/sclevine/agouti): A Golang Acceptance Testing Framework

Agouti allows you run WebDriver integration tests. Learn more about Agouti here

Set Me Up!

You'll need Golang v1.3+ (Ubuntu users: you probably have Golang v1.0 -- you'll need to upgrade!)

bash
go get github.com/onsi/ginkgo/ginkgo  # installs the ginkgo CLI
go get github.com/onsi/gomega         # fetches the matcher library

cd path/to/package/you/want/to/test

ginkgo bootstrap # set up a new ginkgo suite
ginkgo generate  # will create a sample test file.  edit this file and add your tests then...

go test # to run your tests

ginkgo  # also runs your tests

I'm new to Go: What are my testing options?

Of course, I heartily recommend Ginkgo and Gomega. Both packages are seeing heavy, daily, production use on a number of projects and boast a mature and comprehensive feature-set.

With that said, it's great to know what your options are :)

What Golang gives you out of the box

Testing is a first class citizen in Golang, however Go's built-in testing primitives are somewhat limited: The testing package provides basic XUnit style tests and no assertion library.

Matcher libraries for Golang's XUnit style tests

A number of matcher libraries have been written to augment Go's built-in XUnit style tests. Here are two that have gained traction:

You can also use Ginkgo's matcher library Gomega in XUnit style tests

BDD style testing frameworks

There are a handful of BDD-style testing frameworks written for Golang. Here are a few:

Finally, @shageman has put together a comprehensive comparison of golang testing libraries.

Go explore!

License

Ginkgo is MIT-Licensed


Overview (`vendor/github.com/onsi/gomega/README.md`)

Jump straight to the docs to learn about Gomega, including a list of all available matchers.

To discuss Gomega and get updates, join the google group.

[Ginkgo](http://github.com/onsi/ginkgo): a BDD Testing Framework for Golang

Learn more about Ginkgo here

Community Matchers

A collection of community matchers is available on the wiki.

License

Gomega is MIT-Licensed

The ConsistOf matcher uses goraph which is embedded in the source to simplify distribution. goraph has an MIT license.


Overview (`vendor/github.com/opencontainers/go-digest/README.md`)

go-digest

Common digest package used across the container ecosystem.

Please see the godoc for more information.

What is a digest?

A digest is just a hash.

The most common use case for a digest is to create a content
identifier for use in Content Addressable Storage
systems:

go
id := digest.FromBytes([]byte("my content"))

In the example above, the id can be used to uniquely identify
the byte slice "my content". This allows two disparate applications
to agree on a verifiable identifier without having to trust one
another.

An identifying digest can be verified, as follows:

go
if id != digest.FromBytes([]byte("my content")) {
  return errors.New("the content has changed!")
}

A Verifier type can be used to handle cases where an io.Reader
makes more sense:

go
rd := getContent()
verifier := id.Verifier()
io.Copy(verifier, rd)

if !verifier.Verified() {
  return errors.New("the content has changed!")
}

Using Merkle DAGs, this
can power a rich, safe, content distribution system.

Usage

While the godoc is
considered the best resource, a few important items need to be called
out when using this package.

  1. Make sure to import the hash implementations into your application
    or the package will panic. You should have something like the
    following in the main (or other entrypoint) of your application:

    go
    import (
        _ "crypto/sha256"
           _ "crypto/sha512"
    )

    This may seem inconvenient but it allows you replace the hash
    implementations with others, such as https://github.com/stevvooe/resumable.

  2. Even though digest.Digest may be assemable as a string, always
    verify your input with digest.Parse or use Digest.Validate
    when accepting untrusted input. While there are measures to
    avoid common problems, this will ensure you have valid digests
    in the rest of your application.

Stability

The Go API, at this stage, is considered stable, unless otherwise noted.

As always, before using a package export, read the godoc.

Contributing

This package is considered fairly complete. It has been in production
in thousands (millions?) of deployments and is fairly battle-hardened.
New additions will be met with skepticism. If you think there is a
missing feature, please file a bug clearly describing the problem and
the alternatives you tried before submitting a PR.

Reporting security issues

The maintainers take security seriously. If you discover a security
issue, please bring it to their attention right away!

Please DO NOT file a public issue, instead send your report privately
to [email protected].

Security reports are greatly appreciated and we will publicly thank you
for it. We also like to send gifts—if you're into Docker schwag, make
sure to let us know. We currently do not offer a paid security bounty
program, but are not ruling it out in the future.

Copyright © 2016 Docker, Inc. All rights reserved, except as follows. Code is released under the Apache 2.0 license. This README.md file and the CONTRIBUTING.md file are licensed under the Creative Commons Attribution 4.0 International License under the terms and conditions set forth in the file LICENSE.docs. You may obtain a duplicate copy of the same license, titled CC BY-SA 4.0, at http://creativecommons.org/licenses/by-sa/4.0/.


Overview (`vendor/github.com/pelletier/go-buffruneio/README.md`)

buffruneio


Buffruneio is a wrapper around bufio to provide buffered runes access with
unlimited unreads.

go
import "github.com/pelletier/go-buffruneio"

Examples

go
import (
    "fmt"
    "github.com/pelletier/go-buffruneio"
    "strings"
)

reader := buffruneio.NewReader(strings.NewReader("abcd"))
fmt.Println(reader.ReadRune()) // 'a'
fmt.Println(reader.ReadRune()) // 'b'
fmt.Println(reader.ReadRune()) // 'c'
reader.UnreadRune()
reader.UnreadRune()
fmt.Println(reader.ReadRune()) // 'b'
fmt.Println(reader.ReadRune()) // 'c'

Documentation

The documentation and additional examples are available at
godoc.org.

Contribute

Feel free to report bugs and patches using GitHub's pull requests system on
pelletier/go-toml. Any feedback is
much appreciated!

LICENSE

Copyright (c) 2016 Thomas Pelletier

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.


Overview (`vendor/github.com/pelletier/go-toml/README.md`)

go-toml

Go library for the TOML format.

This library supports TOML version
v0.4.0



Features

Go-toml provides the following features for using data parsed from TOML documents:

  • Load TOML documents from files and string data
  • Easily navigate TOML structure using TomlTree
  • Line & column position data for all parsed elements
  • Query support similar to JSON-Path
  • Syntax errors contain line and column numbers

Go-toml is designed to help cover use-cases not covered by reflection-based TOML parsing:

  • Semantic evaluation of parsed TOML
  • Informing a user of mistakes in the source document, after it has been parsed
  • Programatic handling of default values on a case-by-case basis
  • Using a TOML document as a flexible data-store

Import

text
import "github.com/pelletier/go-toml"

Usage

Example

Say you have a TOML file that looks like this:

toml
[postgres]
user = "pelletier"
password = "mypassword"

Read the username and password like this:

go
import (
    "fmt"
    "github.com/pelletier/go-toml"
)

config, err := toml.LoadFile("config.toml")
if err != nil {
    fmt.Println("Error ", err.Error())
} else {
    // retrieve data directly
    user := config.Get("postgres.user").(string)
    password := config.Get("postgres.password").(string)

    // or using an intermediate object
    configTree := config.Get("postgres").(*toml.TomlTree)
    user = configTree.Get("user").(string)
    password = configTree.Get("password").(string)
    fmt.Println("User is ", user, ". Password is ", password)

    // show where elements are in the file
    fmt.Println("User position: %v", configTree.GetPosition("user"))
    fmt.Println("Password position: %v", configTree.GetPosition("password"))

    // use a query to gather elements without walking the tree
    results, _ := config.Query("$..[user,password]")
    for ii, item := range results.Values() {
      fmt.Println("Query result %d: %v", ii, item)
    }
}

Documentation

The documentation and additional examples are available at
godoc.org.

Tools

Go-toml provides two handy command line tools:

  • tomll: Reads TOML files and lint them.

    text
    go install github.com/pelletier/go-toml/cmd/tomll
    tomll --help
  • tomljson: Reads a TOML file and outputs its JSON representation.

    text
    go install github.com/pelletier/go-toml/cmd/tomjson
    tomljson --help

Contribute

Feel free to report bugs and patches using GitHub's pull requests system on
pelletier/go-toml. Any feedback would be
much appreciated!

Run tests

You have to make sure two kind of tests run:

  1. The Go unit tests
  2. The TOML examples base

You can run both of them using ./test.sh.

License

The MIT License (MIT). Read LICENSE.


Overview (`vendor/github.com/peterbourgon/diskv/README.md`)

What is diskv?

Diskv (disk-vee) is a simple, persistent key-value store written in the Go
language. It starts with an incredibly simple API for storing arbitrary data on
a filesystem by key, and builds several layers of performance-enhancing
abstraction on top. The end result is a conceptually simple, but highly
performant, disk-backed storage system.

Build Status

Installing

Install Go 1, either from source or with a prepackaged binary.
Then,

bash
$ go get github.com/peterbourgon/diskv

Usage

go
package main

import (
	"fmt"
	"github.com/peterbourgon/diskv"
)

func main() {
	// Simplest transform function: put all the data files into the base dir.
	flatTransform := func(s string) []string { return []string{} }

	// Initialize a new diskv store, rooted at "my-data-dir", with a 1MB cache.
	d := diskv.New(diskv.Options{
		BasePath:     "my-data-dir",
		Transform:    flatTransform,
		CacheSizeMax: 1024 * 1024,
	})

	// Write three bytes to the key "alpha".
	key := "alpha"
	d.Write(key, []byte{'1', '2', '3'})

	// Read the value back out of the store.
	value, _ := d.Read(key)
	fmt.Printf("%v\n", value)

	// Erase the key+value from the store (and the disk).
	d.Erase(key)
}

More complex examples can be found in the "examples" subdirectory.

Theory

Basic idea

At its core, diskv is a map of a key (string) to arbitrary data ([]byte).
The data is written to a single file on disk, with the same name as the key.
The key determines where that file will be stored, via a user-provided
TransformFunc, which takes a key and returns a slice ([]string)
corresponding to a path list where the key file will be stored. The simplest
TransformFunc,

go
func SimpleTransform (key string) []string {
    return []string{}
}

will place all keys in the same, base directory. The design is inspired by
Redis diskstore; a TransformFunc which emulates the default diskstore
behavior is available in the content-addressable-storage example.

Note that your TransformFunc should ensure that one valid key doesn't
transform to a subset of another valid key. That is, it shouldn't be possible
to construct valid keys that resolve to directory names. As a concrete example,
if your TransformFunc splits on every 3 characters, then

go
d.Write("abcabc", val) // OK: written to <base>/abc/abc/abcabc
d.Write("abc", val)    // Error: attempted write to <base>/abc/abc, but it's a directory

This will be addressed in an upcoming version of diskv.

Probably the most important design principle behind diskv is that your data is
always flatly available on the disk. diskv will never do anything that would
prevent you from accessing, copying, backing up, or otherwise interacting with
your data via common UNIX commandline tools.

Adding a cache

An in-memory caching layer is provided by combining the BasicStore
functionality with a simple map structure, and keeping it up-to-date as
appropriate. Since the map structure in Go is not threadsafe, it's combined
with a RWMutex to provide safe concurrent access.

Adding order

diskv is a key-value store and therefore inherently unordered. An ordering
system can be injected into the store by passing something which satisfies the
diskv.Index interface. (A default implementation, using Google's
btree package, is provided.) Basically, diskv keeps an ordered (by a
user-provided Less function) index of the keys, which can be queried.

Adding compression

Something which implements the diskv.Compression interface may be passed
during store creation, so that all Writes and Reads are filtered through
a compression/decompression pipeline. Several default implementations,
using stdlib compression algorithms, are provided. Note that data is cached
compressed; the cost of decompression is borne with each Read.

Streaming

diskv also now provides ReadStream and WriteStream methods, to allow very large
data to be handled efficiently.

Future plans

  • Needs plenty of robust testing: huge datasets, etc...
  • More thorough benchmarking
  • Your suggestions for use-cases I haven't thought of

Overview (`vendor/github.com/pkg/errors/README.md`)

errors [](https://travis-ci.org/pkg/errors) [](https://ci.appveyor.com/project/davecheney/errors/branch/master) [](http://godoc.org/github.com/pkg/errors) [](https://goreportcard.com/report/github.com/pkg/errors)

Package errors provides simple error handling primitives.

go get github.com/pkg/errors

The traditional error handling idiom in Go is roughly akin to

go
if err != nil {
        return err
}

which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error.

Adding context to an error

The errors.Wrap function returns a new error that adds context to the original error. For example

go
_, err := ioutil.ReadAll(r)
if err != nil {
        return errors.Wrap(err, "read failed")
}

Retrieving the cause of an error

Using errors.Wrap constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by errors.Cause.

go
type causer interface {
        Cause() error
}

errors.Cause will recursively retrieve the topmost error which does not implement causer, which is assumed to be the original cause. For example:

go
switch err := errors.Cause(err).(type) {
case *MyError:
        // handle specifically
default:
        // unknown error
}

Read the package documentation for more information.

Contributing

We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high.

Before proposing a change, please discuss your change by raising an issue.

Licence

BSD-2-Clause


Overview (`vendor/github.com/pkg/sftp/README.md`)

sftp

The sftp package provides support for file system operations on remote ssh servers using the SFTP subsystem.

usage and examples

See godoc.org/github.com/pkg/sftp for examples and usage.

The basic operation of the package mirrors the facilities of the os package.

The Walker interface for directory traversal is heavily inspired by Keith Rarick's fs package.

roadmap

  • There is way too much duplication in the Client methods. If there was an unmarshal(interface{}) method this would reduce a heap of the duplication.

contributing

We welcome pull requests, bug fixes and issue reports.

Before proposing a large change, first please discuss your change by raising an issue.


Overview (`vendor/github.com/prometheus/procfs/README.md`)

procfs

This procfs package provides functions to retrieve system, kernel and process
metrics from the pseudo-filesystem proc.

WARNING: This package is a work in progress. Its API may still break in
backwards-incompatible ways without warnings. Use it at your own risk.




Overview (`vendor/github.com/quobyte/api/README.md`)

Quobyte API Clients

Get the quoybte api client

bash
go get github.com/quobyte/api

Usage

go
package main

import (
  "log"
  quobyte_api "github.com/quobyte/api"
)

func main() {
    client := quobyte_api.NewQuobyteClient("http://apiserver:7860", "user", "password")
    req := &quobyte_api.CreateVolumeRequest{
        Name:              "MyVolume",
        RootUserID:        "root",
        RootGroupID:       "root",
        ConfigurationName: "BASE",
    }

    volumeUUID, err := client.CreateVolume(req)
    if err != nil {
        log.Fatalf("Error:", err)
    }

    log.Printf("%s", volumeUUID)
}

Overview (`vendor/github.com/renstrom/dedent/README.md`)

Dedent


Removes common leading whitespace from multiline strings. Inspired by textwrap.dedent in Python.

Usage / example

Imagine the following snippet that prints a multiline string. You want the indentation to both look nice in the code as well as in the actual output.

go
package main

import (
    "fmt"

    "github.com/renstrom/dedent"
)

func main() {
    s := `Lorem ipsum dolor sit amet,
        consectetur adipiscing elit.
        Curabitur justo tellus, facilisis nec efficitur dictum,
        fermentum vitae ligula. Sed eu convallis sapien.`
    fmt.Println(dedent.Dedent(s))
    fmt.Println("-------------")
    fmt.Println(s)
}

To illustrate the difference, here's the output:

bash
$ go run main.go
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Curabitur justo tellus, facilisis nec efficitur dictum,
fermentum vitae ligula. Sed eu convallis sapien.
-------------
Lorem ipsum dolor sit amet,
        consectetur adipiscing elit.
        Curabitur justo tellus, facilisis nec efficitur dictum,
        fermentum vitae ligula. Sed eu convallis sapien.

License

MIT


Overview (`vendor/github.com/robfig/cron/README.md`)



Overview (`vendor/github.com/russross/blackfriday/README.md`)

Blackfriday [](https://travis-ci.org/russross/blackfriday)

Blackfriday is a Markdown processor implemented in Go. It
is paranoid about its input (so you can safely feed it user-supplied
data), it is fast, it supports common extensions (tables, smart
punctuation substitutions, etc.), and it is safe for all utf-8
(unicode) input.

HTML output is currently supported, along with Smartypants
extensions. An experimental LaTeX output engine is also included.

It started as a translation from C of Sundown.

Installation

Blackfriday is compatible with Go 1. If you are using an older
release of Go, consider using v1.1 of blackfriday, which was based
on the last stable release of Go prior to Go 1. You can find it as a
tagged commit on github.

With Go 1 and git installed:

text
go get github.com/russross/blackfriday

will download, compile, and install the package into your $GOPATH
directory hierarchy. Alternatively, you can achieve the same if you
import it into a project:

text
import "github.com/russross/blackfriday"

and go get without parameters.

Usage

For basic usage, it is as simple as getting your input into a byte
slice and calling:

text
output := blackfriday.MarkdownBasic(input)

This renders it with no extensions enabled. To get a more useful
feature set, use this instead:

text
output := blackfriday.MarkdownCommon(input)

Sanitize untrusted content

Blackfriday itself does nothing to protect against malicious content. If you are
dealing with user-supplied markdown, we recommend running blackfriday's output
through HTML sanitizer such as
Bluemonday.

Here's an example of simple usage of blackfriday together with bluemonday:

go
import (
    "github.com/microcosm-cc/bluemonday"
    "github.com/russross/blackfriday"
)

// ...
unsafe := blackfriday.MarkdownCommon(input)
html := bluemonday.UGCPolicy().SanitizeBytes(unsafe)

Custom options

If you want to customize the set of options, first get a renderer
(currently either the HTML or LaTeX output engines), then use it to
call the more general Markdown function. For examples, see the
implementations of MarkdownBasic and MarkdownCommon in
markdown.go.

You can also check out blackfriday-tool for a more complete example
of how to use it. Download and install it using:

text
go get github.com/russross/blackfriday-tool

This is a simple command-line tool that allows you to process a
markdown file using a standalone program. You can also browse the
source directly on github if you are just looking for some example
code:

Note that if you have not already done so, installing
blackfriday-tool will be sufficient to download and install
blackfriday in addition to the tool itself. The tool binary will be
installed in $GOPATH/bin. This is a statically-linked binary that
can be copied to wherever you need it without worrying about
dependencies and library versions.

Features

All features of Sundown are supported, including:

  • Compatibility. The Markdown v1.0.3 test suite passes with
    the --tidy option. Without --tidy, the differences are
    mostly in whitespace and entity escaping, where blackfriday is
    more consistent and cleaner.

  • Common extensions, including table support, fenced code
    blocks, autolinks, strikethroughs, non-strict emphasis, etc.

  • Safety. Blackfriday is paranoid when parsing, making it safe
    to feed untrusted user input without fear of bad things
    happening. The test suite stress tests this and there are no
    known inputs that make it crash. If you find one, please let me
    know and send me the input that does it.

    NOTE: "safety" in this context means runtime safety only. In order to
    protect yourself agains JavaScript injection in untrusted content, see
    this example.

  • Fast processing. It is fast enough to render on-demand in
    most web applications without having to cache the output.

  • Thread safety. You can run multiple parsers in different
    goroutines without ill effect. There is no dependence on global
    shared state.

  • Minimal dependencies. Blackfriday only depends on standard
    library packages in Go. The source code is pretty
    self-contained, so it is easy to add to any project, including
    Google App Engine projects.

  • Standards compliant. Output successfully validates using the
    W3C validation tool for HTML 4.01 and XHTML 1.0 Transitional.

Extensions

In addition to the standard markdown syntax, this package
implements the following extensions:

  • Intra-word emphasis supression. The _ character is
    commonly used inside words when discussing code, so having
    markdown interpret it as an emphasis command is usually the
    wrong thing. Blackfriday lets you treat all emphasis markers as
    normal characters when they occur inside a word.

  • Tables. Tables can be created by drawing them in the input
    using a simple syntax:

    text
    Name    | Age
    --------|------
    Bob     | 27
    Alice   | 23
  • Fenced code blocks. In addition to the normal 4-space
    indentation to mark code blocks, you can explicitly mark them
    and supply a language (to make syntax highlighting simple). Just
    mark it like this:

    text
    ``` go
    func getTrue() bool {
        return true
    }
    ```

    You can use 3 or more backticks to mark the beginning of the
    block, and the same number to mark the end of the block.

  • Definition lists. A simple definition list is made of a single-line
    term followed by a colon and the definition for that term.

    text
    Cat
    : Fluffy animal everyone likes
    
    Internet
    : Vector of transmission for pictures of cats

    Terms must be separated from the previous definition by a blank line.

  • Footnotes. A marker in the text that will become a superscript number;
    a footnote definition that will be placed in a list of footnotes at the
    end of the document. A footnote looks like this:

    text
    This is a footnote.[^1]
    
    [^1]: the footnote text.
  • Autolinking. Blackfriday can find URLs that have not been
    explicitly marked as links and turn them into links.

  • Strikethrough. Use two tildes (~~) to mark text that
    should be crossed out.

  • Hard line breaks. With this extension enabled (it is off by
    default in the MarkdownBasic and MarkdownCommon convenience
    functions), newlines in the input translate into line breaks in
    the output.

  • Smart quotes. Smartypants-style punctuation substitution is
    supported, turning normal double- and single-quote marks into
    curly quotes, etc.

  • LaTeX-style dash parsing is an additional option, where --
    is translated into &ndash;, and --- is translated into
    &mdash;. This differs from most smartypants processors, which
    turn a single hyphen into an ndash and a double hyphen into an
    mdash.

  • Smart fractions, where anything that looks like a fraction
    is translated into suitable HTML (instead of just a few special
    cases like most smartypant processors). For example, 4/5
    becomes <sup>4</sup>&frasl;<sub>5</sub>, which renders as
    4⁄5.

Other renderers

Blackfriday is structured to allow alternative rendering engines. Here
are a few of note:

  • github_flavored_markdown:
    provides a GitHub Flavored Markdown renderer with fenced code block
    highlighting, clickable header anchor links.

    It's not customizable, and its goal is to produce HTML output
    equivalent to the GitHub Markdown API endpoint,
    except the rendering is performed locally.

  • markdownfmt: like gofmt,
    but for markdown.

  • LaTeX output: renders output as LaTeX. This is currently part of the
    main Blackfriday repository, but may be split into its own project
    in the future. If you are interested in owning and maintaining the
    LaTeX output component, please be in touch.

    It renders some basic documents, but is only experimental at this
    point. In particular, it does not do any inline escaping, so input
    that happens to look like LaTeX code will be passed through without
    modification.

  • Md2Vim: transforms markdown files into vimdoc format.

Todo

  • More unit testing
  • Improve unicode support. It does not understand all unicode
    rules (about what constitutes a letter, a punctuation symbol,
    etc.), so it may fail to detect word boundaries correctly in
    some instances. It is safe on all utf-8 input.

License

Blackfriday is distributed under the Simplified BSD License


Overview (`vendor/github.com/satori/uuid/README.md`)

UUID package for Go language



This package provides pure Go implementation of Universally Unique Identifier (UUID). Supported both creation and parsing of UUIDs.

With 100% test coverage and benchmarks out of box.

Supported versions:

  • Version 1, based on timestamp and MAC address (RFC 4122)
  • Version 2, based on timestamp, MAC address and POSIX UID/GID (DCE 1.1)
  • Version 3, based on MD5 hashing (RFC 4122)
  • Version 4, based on random numbers (RFC 4122)
  • Version 5, based on SHA-1 hashing (RFC 4122)

Installation

Use the go command:

text
$ go get github.com/satori/go.uuid

Requirements

UUID package requires Go >= 1.2.

Example

go
package main

import (
	"fmt"
	"github.com/satori/go.uuid"
)

func main() {
	// Creating UUID Version 4
	u1 := uuid.NewV4()
	fmt.Printf("UUIDv4: %s\n", u1)

	// Parsing UUID from string input
	u2, err := uuid.FromString("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
	if err != nil {
		fmt.Printf("Something gone wrong: %s", err)
	}
	fmt.Printf("Successfully parsed: %s", u2)
}

Documentation

Documentation is hosted at GoDoc project.

Copyright (C) 2013-2016 by Maxim Bublis .

UUID package released under MIT License.
See LICENSE for details.


Overview (`vendor/github.com/shurcooL/sanitized_anchor_name/README.md`)

sanitized_anchor_name [](https://travis-ci.org/shurcooL/sanitized_anchor_name) [](https://godoc.org/github.com/shurcooL/sanitized_anchor_name)

Package sanitized_anchor_name provides a func to create sanitized anchor names.

Its logic can be reused by multiple packages to create interoperable anchor names and links to those anchors.

At this time, it does not try to ensure that generated anchor names are unique, that responsibility falls on the caller.

Installation

bash
go get -u github.com/shurcooL/sanitized_anchor_name

Example

go
anchorName := sanitized_anchor_name.Create("This is a header")

fmt.Println(anchorName)

// Output:
// this-is-a-header

License


Overview (`vendor/github.com/sirupsen/logrus/README.md`)

Logrus  [](https://travis-ci.org/sirupsen/logrus) [](https://godoc.org/github.com/sirupsen/logrus)

Logrus is a structured logger for Go (golang), completely API compatible with
the standard library logger.

Seeing weird case-sensitive problems? It's in the past been possible to
import Logrus as both upper- and lower-case. Due to the Go package environment,
this caused issues in the community and we needed a standard. Some environments
experienced problems with the upper-case variant, so the lower-case was decided.
Everything using logrus will need to use the lower-case:
github.com/sirupsen/logrus. Any package that isn't, should be changed.

To fix Glide, see these
comments
.
For an in-depth explanation of the casing issue, see this
comment
.

Are you interested in assisting in maintaining Logrus? Currently I have a
lot of obligations, and I am unable to provide Logrus with the maintainership it
needs. If you'd like to help, please reach out to me at simon at author's username dot com.

Nicely color-coded in development (when a TTY is attached, otherwise just
plain text):

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 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

Case-sensitivity

The organization's name was changed to lower-case--and this will not be changed
back. If you are getting import conflicts due to case sensitivity, please use
the lower-case import: github.com/sirupsen/logrus.

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 (
  "os"
  "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 through 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. 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.

Hook Description
Airbrake "legacy" Send errors to an exception tracking service compatible with the Airbrake API V2. Uses airbrake-go behind the scenes.
Airbrake Send errors to the Airbrake API V3. Uses the official gobrake behind the scenes.
Amazon Kinesis Hook for logging to Amazon Kinesis
Amqp-Hook Hook for logging to Amqp broker (Like RabbitMQ)
AzureTableHook Hook for logging to Azure Table Storage
Bugsnag Send errors to the Bugsnag exception tracking service.
DeferPanic Hook for logging to DeferPanic
Discordrus Hook for logging to Discord
ElasticSearch Hook for logging to ElasticSearch
Firehose Hook for logging to Amazon Firehose
Fluentd Hook for logging to fluentd
Go-Slack Hook for logging to Slack
Graylog Hook for logging to Graylog
Hiprus Send errors to a channel in hipchat.
Honeybadger Hook for sending exceptions to Honeybadger
InfluxDB Hook for logging to influxdb
Influxus Hook for concurrently logging to InfluxDB
Journalhook Hook for logging to systemd-journald
KafkaLogrus Hook for logging to Kafka
LFShook Hook for logging to the local filesystem
Logentries Hook for logging to Logentries
Logentrus Hook for logging to Logentries
Logmatic.io Hook for logging to Logmatic.io
Logrusly Send logs to Loggly
Logstash Hook for logging to Logstash
Mail Hook for sending exceptions via mail
Mattermost Hook for logging to Mattermost
Mongodb Hook for logging to mongodb
NATS-Hook Hook for logging to NATS
Octokit Hook for logging to github via octokit
Papertrail Send errors to the Papertrail hosted logging service via UDP.
PostgreSQL Send logs to PostgreSQL
Pushover Send error via Pushover
Raygun Hook for logging to Raygun.io
Redis-Hook Hook for logging to a ELK stack (through Redis)
Rollrus Hook for sending errors to rollbar
Scribe Hook for logging to Scribe
Sentry Send errors to the Sentry error logging and aggregation service.
Slackrus Hook for Slack chat.
Stackdriver Hook for logging to Google Stackdriver
Sumorus Hook for logging to SumoLogic
Syslog Send errors to remote syslog server. Uses standard library log/syslog behind the scenes.
Syslog TLS Send errors to remote syslog server with TLS support.
Telegram Hook for logging errors to Telegram
TraceView Hook for logging to AppNeta TraceView
Typetalk Hook for logging to Typetalk
logz.io Hook for logging to logz.io, a Log as a Service using Logstash
SQS-Hook Hook for logging to Amazon Simple Queue Service (SQS)

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.
    • All options are listed in the generated docs.
  • logrus.JSONFormatter. Logs fields as JSON.

Third party logging formatters:

  • FluentdFormatter. Formats entries that can by parsed by Kubernetes and Google Container Engine.
  • logstash. Logs fields as Logstash Events.
  • prefixed. Displays log entry source along with alternative layout.
  • zalgo. 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 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 An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of Logrus Mate. sample

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
import(
  "github.com/sirupsen/logrus"
  "github.com/sirupsen/logrus/hooks/test"
  "github.com/stretchr/testify/assert"
  "testing"
)

func TestSomething(t*testing.T){
  logger, hook := test.NewNullLogger()
  logger.Error("Helloerror")

  assert.Equal(t, 1, len(hook.Entries))
  assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level)
  assert.Equal(t, "Helloerror", hook.LastEntry().Message)

  hook.Reset()
  assert.Nil(t, 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.

text
...
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/)


Overview (`vendor/github.com/spf13/afero/README.md`)

A FileSystem Abstraction System for Go

Overview

Afero is an filesystem framework providing a simple, uniform and universal API
interacting with any filesystem, as an abstraction layer providing interfaces,
types and methods. Afero has an exceptionally clean interface and simple design
without needless constructors or initialization methods.

Afero is also a library providing a base set of interoperable backend
filesystems that make it easy to work with afero while retaining all the power
and benefit of the os and ioutil packages.

Afero provides significant improvements over using the os package alone, most
notably the ability to create mock and testing filesystems without relying on the disk.

It is suitable for use in a any situation where you would consider using the OS
package as it provides an additional abstraction that makes it easy to use a
memory backed file system during testing. It also adds support for the http
filesystem for full interoperability.

Afero Features

  • A single consistent API for accessing a variety of filesystems
  • Interoperation between a variety of file system types
  • A set of interfaces to encourage and enforce interoperability between backends
  • An atomic cross platform memory backed file system
  • Support for compositional (union) file systems by combining multiple file systems acting as one
  • Specialized backends which modify existing filesystems (Read Only, Regexp filtered)
  • A set of utility functions ported from io, ioutil & hugo to be afero aware

Using Afero

Afero is easy to use and easier to adopt.

A few different ways you could use Afero:

  • Use the interfaces alone to define you own file system.
  • Wrap for the OS packages.
  • Define different filesystems for different parts of your application.
  • Use Afero for mock filesystems while testing

Step 1: Install Afero

First use go get to install the latest version of the library.

text
$ go get github.com/spf13/afero

Next include Afero in your application.

go
import "github.com/spf13/afero"

Step 2: Declare a backend

First define a package variable and set it to a pointer to a filesystem.

go
var AppFs afero.Fs = afero.NewMemMapFs()

or

var AppFs afero.Fs = afero.NewOsFs()

It is important to note that if you repeat the composite literal you
will be using a completely new and isolated filesystem. In the case of
OsFs it will still use the same underlying filesystem but will reduce
the ability to drop in other filesystems as desired.

Step 3: Use it like you would the OS package

Throughout your application use any function and method like you normally
would.

So if my application before had:

go
os.Open('/tmp/foo')

We would replace it with a call to AppFs.Open('/tmp/foo').

AppFs being the variable we defined above.

List of all available functions

File System Methods Available:

go
Chmod(name string, mode os.FileMode) : error
Chtimes(name string, atime time.Time, mtime time.Time) : error
Create(name string) : File, error
Mkdir(name string, perm os.FileMode) : error
MkdirAll(path string, perm os.FileMode) : error
Name() : string
Open(name string) : File, error
OpenFile(name string, flag int, perm os.FileMode) : File, error
Remove(name string) : error
RemoveAll(path string) : error
Rename(oldname, newname string) : error
Stat(name string) : os.FileInfo, error

File Interfaces and Methods Available:

go
io.Closer
io.Reader
io.ReaderAt
io.Seeker
io.Writer
io.WriterAt

Name() : string
Readdir(count int) : []os.FileInfo, error
Readdirnames(n int) : []string, error
Stat() : os.FileInfo, error
Sync() : error
Truncate(size int64) : error
WriteString(s string) : ret int, err error

In some applications it may make sense to define a new package that
simply exports the file system variable for easy access from anywhere.

Using Afero's utility functions

Afero provides a set of functions to make it easier to use the underlying file systems.
These functions have been primarily ported from io & ioutil with some developed for Hugo.

The afero utilities support all afero compatible backends.

The list of utilities includes:

go
DirExists(path string) (bool, error)
Exists(path string) (bool, error)
FileContainsBytes(filename string, subslice []byte) (bool, error)
GetTempDir(subPath string) string
IsDir(path string) (bool, error)
IsEmpty(path string) (bool, error)
ReadDir(dirname string) ([]os.FileInfo, error)
ReadFile(filename string) ([]byte, error)
SafeWriteReader(path string, r io.Reader) (err error)
TempDir(dir, prefix string) (name string, err error)
TempFile(dir, prefix string) (f File, err error)
Walk(root string, walkFn filepath.WalkFunc) error
WriteFile(filename string, data []byte, perm os.FileMode) error
WriteReader(path string, r io.Reader) (err error)

For a complete list see Afero's GoDoc

They are available under two different approaches to use. You can either call
them directly where the first parameter of each function will be the file
system, or you can declare a new Afero, a custom type used to bind these
functions as methods to a given filesystem.

Calling utilities directly

go
fs := new(afero.MemMapFs)
f, err := afero.TempFile(fs,"", "ioutil-test")

Calling via Afero

go
fs := afero.NewMemMapFs
afs := &Afero{Fs: fs}
f, err := afs.TempFile("", "ioutil-test")

Using Afero for Testing

There is a large benefit to using a mock filesystem for testing. It has a
completely blank state every time it is initialized and can be easily
reproducible regardless of OS. You could create files to your heart’s content
and the file access would be fast while also saving you from all the annoying
issues with deleting temporary files, Windows file locking, etc. The MemMapFs
backend is perfect for testing.

  • Much faster than performing I/O operations on disk
  • Avoid security issues and permissions
  • Far more control. 'rm -rf /' with confidence
  • Test setup is far more easier to do
  • No test cleanup needed

One way to accomplish this is to define a variable as mentioned above.
In your application this will be set to afero.NewOsFs() during testing you
can set it to afero.NewMemMapFs().

It wouldn't be uncommon to have each test initialize a blank slate memory
backend. To do this I would define my appFS = afero.NewOsFs() somewhere
appropriate in my application code. This approach ensures that Tests are order
independent, with no test relying on the state left by an earlier test.

Then in my tests I would initialize a new MemMapFs for each test:

go
func TestExist(t *testing.T) {
	appFS = afero.NewMemMapFs()
	// create test files and directories
	appFS.MkdirAll("src/a", 0755))
	afero.WriteFile(appFS, "src/a/b", []byte("file b"), 0644)
	afero.WriteFile(appFS, "src/c", []byte("file c"), 0644)
	_, err := appFS.Stat("src/c")
	if os.IsNotExist(err) {
        t.Errorf("file \"%s\" does not exist.\n", name)
	}
}

Available Backends

Operating System Native

OsFs

The first is simply a wrapper around the native OS calls. This makes it
very easy to use as all of the calls are the same as the existing OS
calls. It also makes it trivial to have your code use the OS during
operation and a mock filesystem during testing or as needed.

go
appfs := afero.NewOsFs()
appfs.MkdirAll("src/a", 0755))

Memory Backed Storage

MemMapFs

Afero also provides a fully atomic memory backed filesystem perfect for use in
mocking and to speed up unnecessary disk io when persistence isn’t
necessary. It is fully concurrent and will work within go routines
safely.

go
mm := afero.NewMemMapFs()
mm.MkdirAll("src/a", 0755))

InMemoryFile

As part of MemMapFs, Afero also provides an atomic, fully concurrent memory
backed file implementation. This can be used in other memory backed file
systems with ease. Plans are to add a radix tree memory stored file
system using InMemoryFile.

Network Interfaces

SftpFs

Afero has experimental support for secure file transfer protocol (sftp). Which can
be used to perform file operations over a encrypted channel.

Filtering Backends

BasePathFs

The BasePathFs restricts all operations to a given path within an Fs.
The given file name to the operations on this Fs will be prepended with
the base path before calling the source Fs.

go
bp := afero.NewBasePathFs(afero.NewOsFs(), "/base/path")

ReadOnlyFs

A thin wrapper around the source Fs providing a read only view.

go
fs := afero.NewReadOnlyFs(afero.NewOsFs())
_, err := fs.Create("/file.txt")
// err = syscall.EPERM

RegexpFs

A filtered view on file names, any file NOT matching
the passed regexp will be treated as non-existing.
Files not matching the regexp provided will not be created.
Directories are not filtered.

go
fs := afero.NewRegexpFs(afero.NewMemMapFs(), regexp.MustCompile(`\.txt$`))
_, err := fs.Create("/file.html")
// err = syscall.ENOENT

HttpFs

Afero provides an http compatible backend which can wrap any of the existing
backends.

The Http package requires a slightly specific version of Open which
returns an http.File type.

Afero provides an httpFs file system which satisfies this requirement.
Any Afero FileSystem can be used as an httpFs.

go
httpFs := afero.NewHttpFs(<ExistingFS>)
fileserver := http.FileServer(httpFs.Dir(<PATH>)))
http.Handle("/", fileserver)

Composite Backends

Afero provides the ability have two filesystems (or more) act as a single
file system.

CacheOnReadFs

The CacheOnReadFs will lazily make copies of any accessed files from the base
layer into the overlay. Subsequent reads will be pulled from the overlay
directly permitting the request is within the cache duration of when it was
created in the overlay.

If the base filesystem is writeable, any changes to files will be
done first to the base, then to the overlay layer. Write calls to open file
handles like Write() or Truncate() to the overlay first.

To writing files to the overlay only, you can use the overlay Fs directly (not
via the union Fs).

Cache files in the layer for the given time.Duration, a cache duration of 0
means "forever" meaning the file will not be re-requested from the base ever.

A read-only base will make the overlay also read-only but still copy files
from the base to the overlay when they're not present (or outdated) in the
caching layer.

go
base := afero.NewOsFs()
layer := afero.NewMemMapFs()
ufs := afero.NewCacheOnReadFs(base, layer, 100 * time.Second)

CopyOnWriteFs()

The CopyOnWriteFs is a read only base file system with a potentially
writeable layer on top.

Read operations will first look in the overlay and if not found there, will
serve the file from the base.

Changes to the file system will only be made in the overlay.

Any attempt to modify a file found only in the base will copy the file to the
overlay layer before modification (including opening a file with a writable
handle).

Removing and Renaming files present only in the base layer is not currently
permitted. If a file is present in the base layer and the overlay, only the
overlay will be removed/renamed.

go
base := afero.NewOsFs()
	roBase := afero.NewReadOnlyFs(base)
	ufs := afero.NewCopyOnWriteFs(roBase, afero.NewMemMapFs())

	fh, _ = ufs.Create("/home/test/file2.txt")
	fh.WriteString("This is a test")
	fh.Close()

In this example all write operations will only occur in memory (MemMapFs)
leaving the base filesystem (OsFs) untouched.

Desired/possible backends

The following is a short list of possible backends we hope someone will
implement:

  • SSH
  • ZIP
  • TAR
  • S3

About the project

What's in the name

Afero comes from the latin roots Ad-Facere.

"Ad" is a prefix meaning "to".

"Facere" is a form of the root "faciō" making "make or do".

The literal meaning of afero is "to make" or "to do" which seems very fitting
for a library that allows one to make files and directories and do things with them.

The English word that shares the same roots as Afero is "affair". Affair shares
the same concept but as a noun it means "something that is made or done" or "an
object of a particular type".

It's also nice that unlike some of my other libraries (hugo, cobra, viper) it
Googles very well.

Release Notes

  • 0.10.0 2015.12.10
    • Full compatibility with Windows
    • Introduction of afero utilities
    • Test suite rewritten to work cross platform
    • Normalize paths for MemMapFs
    • Adding Sync to the file interface
    • Breaking Change Walk and ReadDir have changed parameter order
    • Moving types used by MemMapFs to a subpackage
    • General bugfixes and improvements
  • 0.9.0 2015.11.05
    • New Walk function similar to filepath.Walk
    • MemMapFs.OpenFile handles O_CREATE, O_APPEND, O_TRUNC
    • MemMapFs.Remove now really deletes the file
    • InMemoryFile.Readdir and Readdirnames work correctly
    • InMemoryFile functions lock it for concurrent access
    • Test suite improvements
  • 0.8.0 2014.10.28
    • First public version
    • Interfaces feel ready for people to build using
    • Interfaces satisfy all known uses
    • MemMapFs passes the majority of the OS test suite
    • OsFs passes the majority of the OS test suite

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Contributors

Names in no particular order:

License

Afero is released under the Apache 2.0 license. See
LICENSE.txt


Overview (`vendor/github.com/spf13/cast/README.md`)

cast

Easy and safe casting from one type to another in Go

Don’t Panic! ... Cast

What is Cast?

Cast is a library to convert between different go types in a consistent and easy way.

Cast provides simple functions to easily convert a number to a string, an
interface into a bool, etc. Cast does this intelligently when an obvious
conversion is possible. It doesn’t make any attempts to guess what you meant,
for example you can only convert a string to an int when it is a string
representation of an int such as “8”. Cast was developed for use in
Hugo, a website engine which uses YAML, TOML or JSON
for meta data.

Why use Cast?

When working with dynamic data in Go you often need to cast or convert the data
from one type into another. Cast goes beyond just using type assertion (though
it uses that when possible) to provide a very straightforward and convenient
library.

If you are working with interfaces to handle things like dynamic content
you’ll need an easy way to convert an interface into a given type. This
is the library for you.

If you are taking in data from YAML, TOML or JSON or other formats which lack
full types, then Cast is the library for you.

Usage

Cast provides a handful of To_____ methods. These methods will always return
the desired type. If input is provided that will not convert to that type, the
0 or nil value for that type will be returned
.

Cast also provides identical methods To_____E. These return the same result as
the To_____ methods, plus an additional error which tells you if it successfully
converted. Using these methods you can tell the difference between when the
input matched the zero value or when the conversion failed and the zero value
was returned.

The following examples are merely a sample of what is available. Please review
the code for a complete set.

Example ‘ToString’:

text
cast.ToString("mayonegg")         // "mayonegg"
cast.ToString(8)                  // "8"
cast.ToString(8.31)               // "8.31"
cast.ToString([]byte("one time")) // "one time"
cast.ToString(nil)                // ""

var foo interface{} = "one more time"
cast.ToString(foo)                // "one more time"

Example ‘ToInt’:

text
cast.ToInt(8)                  // 8
cast.ToInt(8.31)               // 8
cast.ToInt("8")                // 8
cast.ToInt(true)               // 1
cast.ToInt(false)              // 0

var eight interface{} = 8
cast.ToInt(eight)              // 8
cast.ToInt(nil)                // 0

Overview (`vendor/github.com/spf13/cobra/README.md`)

Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files.

Many of the most widely used Go projects are built using Cobra including:



Overview

Cobra is a library providing a simple interface to create powerful modern CLI
interfaces similar to git & go tools.

Cobra is also an application that will generate your application scaffolding to rapidly
develop a Cobra-based application.

Cobra provides:

  • Easy subcommand-based CLIs: app server, app fetch, etc.
  • Fully POSIX-compliant flags (including short & long versions)
  • Nested subcommands
  • Global, local and cascading flags
  • Easy generation of applications & commands with cobra create appname & cobra add cmdname
  • Intelligent suggestions (app srver... did you mean app server?)
  • Automatic help generation for commands and flags
  • Automatic detailed help for app help [command]
  • Automatic help flag recognition of -h, --help, etc.
  • Automatically generated bash autocomplete for your application
  • Automatically generated man pages for your application
  • Command aliases so you can change things without breaking them
  • The flexibilty to define your own help, usage, etc.
  • Optional tight integration with viper for 12-factor apps

Cobra has an exceptionally clean interface and simple design without needless
constructors or initialization methods.

Applications built with Cobra commands are designed to be as user-friendly as
possible. Flags can be placed before or after the command (as long as a
confusing space isn’t provided). Both short and long flags can be used. A
command need not even be fully typed. Help is automatically generated and
available for the application or for a specific command using either the help
command or the --help flag.

Concepts

Cobra is built on a structure of commands, arguments & flags.

Commands represent actions, Args are things and Flags are modifiers for those actions.

The best applications will read like sentences when used. Users will know how
to use the application because they will natively understand how to use it.

The pattern to follow is
APPNAME VERB NOUN --ADJECTIVE.
or
APPNAME COMMAND ARG --FLAG

A few good real world examples may better illustrate this point.

In the following example, 'server' is a command, and 'port' is a flag:

text
> hugo server --port=1313

In this command we are telling Git to clone the url bare.

text
> git clone URL --bare

Commands

Command is the central point of the application. Each interaction that
the application supports will be contained in a Command. A command can
have children commands and optionally run an action.

In the example above, 'server' is the command.

A Command has the following structure:

go
type Command struct {
    Use string // The one-line usage message.
    Short string // The short description shown in the 'help' output.
    Long string // The long message shown in the 'help <this-command>' output.
    Run func(cmd *Command, args []string) // Run runs the command.
}

Flags

A Flag is a way to modify the behavior of a command. Cobra supports
fully POSIX-compliant flags as well as the Go flag package.
A Cobra command can define flags that persist through to children commands
and flags that are only available to that command.

In the example above, 'port' is the flag.

Flag functionality is provided by the pflag
library
, a fork of the flag standard library
which maintains the same interface while adding POSIX compliance.

Usage

Cobra works by creating a set of commands and then organizing them into a tree.
The tree defines the structure of the application.

Once each command is defined with its corresponding flags, then the
tree is assigned to the commander which is finally executed.

Installing

Using Cobra is easy. First, use go get to install the latest version
of the library. This command will install the cobra generator executible
along with the library:

text
> go get -v github.com/spf13/cobra/cobra

Next, include Cobra in your application:

go
import "github.com/spf13/cobra"

Getting Started

While you are welcome to provide your own organization, typically a Cobra based
application will follow the following organizational structure.

text
▾ appName/
    ▾ cmd/
        add.go
        your.go
        commands.go
        here.go
      main.go

In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.

go
package main

import "{pathToYourApp}/cmd"

func main() {
	if err := cmd.RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

Using the Cobra Generator

Cobra provides its own program that will create your application and add any
commands you want. It's the easiest way to incorporate Cobra into your application.

In order to use the cobra command, compile it using the following command:

text
> go install github.com/spf13/cobra/cobra

This will create the cobra executable under your go path bin directory!

cobra init

The cobra init [yourApp] command will create your initial application code
for you. It is a very powerful application that will populate your program with
the right structure so you can immediately enjoy all the benefits of Cobra. It
will also automatically apply the license you specify to your application.

Cobra init is pretty smart. You can provide it a full path, or simply a path
similar to what is expected in the import.

text
cobra init github.com/spf13/newAppName

cobra add

Once an application is initialized Cobra can create additional commands for you.
Let's say you created an app and you wanted the following commands for it:

  • app serve
  • app config
  • app config create

In your project directory (where your main.go file is) you would run the following:

text
cobra add serve
cobra add config
cobra add create -p 'configCmd'

Once you have run these three commands you would have an app structure that would look like:

text
▾ app/
    ▾ cmd/
        serve.go
        config.go
        create.go
      main.go

at this point you can run go run main.go and it would run your app. go run main.go serve, go run main.go config, go run main.go config create along
with go run main.go help serve, etc would all work.

Obviously you haven't added your own code to these yet, the commands are ready
for you to give them their tasks. Have fun.

Configuring the cobra generator

The cobra generator will be easier to use if you provide a simple configuration
file which will help you eliminate providing a bunch of repeated information in
flags over and over.

An example ~/.cobra.yaml file:

yaml
author: Steve Francia <[email protected]>
license: MIT

You can specify no license by setting license to none or you can specify
a custom license:

yaml
license:
  header: This file is part of {{ .appName }}.
  text: |
    {{ .copyright }}

    This is my license. There are many like it, but this one is mine.
    My license is my best friend. It is my life. I must master it as I must
    master my life.

Manually implementing Cobra

To manually implement cobra you need to create a bare main.go file and a RootCmd file.
You will optionally provide additional commands as you see fit.

Create the root command

The root command represents your binary itself.

Manually create rootCmd

Cobra doesn't require any special constructors. Simply create your commands.

Ideally you place this in app/cmd/root.go:

go
var RootCmd = &cobra.Command{
	Use:   "hugo",
	Short: "Hugo is a very fast static site generator",
	Long: `A Fast and Flexible Static Site Generator built with
                love by spf13 and friends in Go.
                Complete documentation is available at http://hugo.spf13.com`,
	Run: func(cmd *cobra.Command, args []string) {
		// Do Stuff Here
	},
}

You will additionally define flags and handle configuration in your init() function.

for example cmd/root.go:

go
func init() {
	cobra.OnInitialize(initConfig)
	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
	RootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory eg. github.com/spf13/")
	RootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution")
	RootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)")
	RootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration")
	viper.BindPFlag("author", RootCmd.PersistentFlags().Lookup("author"))
	viper.BindPFlag("projectbase", RootCmd.PersistentFlags().Lookup("projectbase"))
	viper.BindPFlag("useViper", RootCmd.PersistentFlags().Lookup("viper"))
	viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
	viper.SetDefault("license", "apache")
}

Create your main.go

With the root command you need to have your main function execute it.
Execute should be run on the root for clarity, though it can be called on any command.

In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.

go
package main

import "{pathToYourApp}/cmd"

func main() {
	if err := cmd.RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

Create additional commands

Additional commands can be defined and typically are each given their own file
inside of the cmd/ directory.

If you wanted to create a version command you would create cmd/version.go and
populate it with the following:

go
package cmd

import (
	"github.com/spf13/cobra"
)

func init() {
	RootCmd.AddCommand(versionCmd)
}

var versionCmd = &cobra.Command{
	Use:   "version",
	Short: "Print the version number of Hugo",
	Long:  `All software has versions. This is Hugo's`,
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
	},
}

Attach command to its parent

If you notice in the above example we attach the command to its parent. In
this case the parent is the rootCmd. In this example we are attaching it to the
root, but commands can be attached at any level.

go
RootCmd.AddCommand(versionCmd)

Remove a command from its parent

Removing a command is not a common action in simple programs, but it allows 3rd
parties to customize an existing command tree.

In this example, we remove the existing VersionCmd command of an existing
root command, and we replace it with our own version:

go
mainlib.RootCmd.RemoveCommand(mainlib.VersionCmd)
mainlib.RootCmd.AddCommand(versionCmd)

Working with Flags

Flags provide modifiers to control how the action command operates.

Assign flags to a command

Since the flags are defined and used in different locations, we need to
define a variable outside with the correct scope to assign the flag to
work with.

go
var Verbose bool
var Source string

There are two different approaches to assign a flag.

Persistent Flags

A flag can be 'persistent' meaning that this flag will be available to the
command it's assigned to as well as every command under that command. For
global flags, assign a flag as a persistent flag on the root.

go
RootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")

Local Flags

A flag can also be assigned locally which will only apply to that specific command.

go
RootCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")

Example

In the example below, we have defined three commands. Two are at the top level
and one (cmdTimes) is a child of one of the top commands. In this case the root
is not executable meaning that a subcommand is required. This is accomplished
by not providing a 'Run' for the 'rootCmd'.

We have only defined one flag for a single command.

More documentation about flags is available at https://github.com/spf13/pflag

go
package main

import (
	"fmt"
	"strings"

	"github.com/spf13/cobra"
)

func main() {

	var echoTimes int

	var cmdPrint = &cobra.Command{
		Use:   "print [string to print]",
		Short: "Print anything to the screen",
		Long: `print is for printing anything back to the screen.
            For many years people have printed back to the screen.
            `,
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Println("Print: " + strings.Join(args, " "))
		},
	}

	var cmdEcho = &cobra.Command{
		Use:   "echo [string to echo]",
		Short: "Echo anything to the screen",
		Long: `echo is for echoing anything back.
            Echo works a lot like print, except it has a child command.
            `,
		Run: func(cmd *cobra.Command, args []string) {
			fmt.Println("Print: " + strings.Join(args, " "))
		},
	}

	var cmdTimes = &cobra.Command{
		Use:   "times [# times] [string to echo]",
		Short: "Echo anything to the screen more times",
		Long: `echo things multiple times back to the user by providing
            a count and a string.`,
		Run: func(cmd *cobra.Command, args []string) {
			for i := 0; i < echoTimes; i++ {
				fmt.Println("Echo: " + strings.Join(args, " "))
			}
		},
	}

	cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")

	var rootCmd = &cobra.Command{Use: "app"}
	rootCmd.AddCommand(cmdPrint, cmdEcho)
	cmdEcho.AddCommand(cmdTimes)
	rootCmd.Execute()
}

For a more complete example of a larger application, please checkout Hugo.

The Help Command

Cobra automatically adds a help command to your application when you have subcommands.
This will be called when a user runs 'app help'. Additionally, help will also
support all other commands as input. Say, for instance, you have a command called
'create' without any additional configuration; Cobra will work when 'app help
create' is called. Every command will automatically have the '--help' flag added.

Example

The following output is automatically generated by Cobra. Nothing beyond the
command and flag definitions are needed.

text
> hugo help

hugo is the main command, used to build your Hugo site.

Hugo is a Fast and Flexible Static Site Generator
built with love by spf13 and friends in Go.

Complete documentation is available at http://gohugo.io/.

Usage:
  hugo [flags]
  hugo [command]

Available Commands:
  server          Hugo runs its own webserver to render the files
  version         Print the version number of Hugo
  config          Print the site configuration
  check           Check content in the source directory
  benchmark       Benchmark hugo by building a site a number of times.
  convert         Convert your content to different formats
  new             Create new content for your site
  list            Listing out various types of content
  undraft         Undraft changes the content's draft status from 'True' to 'False'
  genautocomplete Generate shell autocompletion script for Hugo
  gendoc          Generate Markdown documentation for the Hugo CLI.
  genman          Generate man page for Hugo
  import          Import your site from others.

Flags:
  -b, --baseURL="": hostname (and path) to the root, e.g. http://spf13.com/
  -D, --buildDrafts[=false]: include content marked as draft
  -F, --buildFuture[=false]: include content with publishdate in the future
      --cacheDir="": filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/
      --canonifyURLs[=false]: if true, all relative URLs will be canonicalized using baseURL
      --config="": config file (default is path/config.yaml|json|toml)
  -d, --destination="": filesystem path to write files to
      --disableRSS[=false]: Do not build RSS files
      --disableSitemap[=false]: Do not build Sitemap file
      --editor="": edit new content with this editor, if provided
      --ignoreCache[=false]: Ignores the cache directory for reading but still writes to it
      --log[=false]: Enable Logging
      --logFile="": Log File path (if set, logging enabled automatically)
      --noTimes[=false]: Don't sync modification time of files
      --pluralizeListTitles[=true]: Pluralize titles in lists using inflect
      --preserveTaxonomyNames[=false]: Preserve taxonomy names as written ("Gérard Depardieu" vs "gerard-depardieu")
  -s, --source="": filesystem path to read files relative from
      --stepAnalysis[=false]: display memory and timing of different steps of the program
  -t, --theme="": theme to use (located in /themes/THEMENAME/)
      --uglyURLs[=false]: if true, use /filename.html instead of /filename/
  -v, --verbose[=false]: verbose output
      --verboseLog[=false]: verbose logging
  -w, --watch[=false]: watch filesystem for changes and recreate as needed

Use "hugo [command] --help" for more information about a command.

Help is just a command like any other. There is no special logic or behavior
around it. In fact, you can provide your own if you want.

Defining your own help

You can provide your own Help command or your own template for the default command to use.

The default help command is

go
func (c *Command) initHelp() {
	if c.helpCommand == nil {
		c.helpCommand = &Command{
			Use:   "help [command]",
			Short: "Help about any command",
			Long: `Help provides help for any command in the application.
        Simply type ` + c.Name() + ` help [path to command] for full details.`,
			Run: c.HelpFunc(),
		}
	}
	c.AddCommand(c.helpCommand)
}

You can provide your own command, function or template through the following methods:

go
command.SetHelpCommand(cmd *Command)

command.SetHelpFunc(f func(*Command, []string))

command.SetHelpTemplate(s string)

The latter two will also apply to any children commands.

Usage

When the user provides an invalid flag or invalid command, Cobra responds by
showing the user the 'usage'.

Example

You may recognize this from the help above. That's because the default help
embeds the usage as part of its output.

text
Usage:
  hugo [flags]
  hugo [command]

Available Commands:
  server          Hugo runs its own webserver to render the files
  version         Print the version number of Hugo
  config          Print the site configuration
  check           Check content in the source directory
  benchmark       Benchmark hugo by building a site a number of times.
  convert         Convert your content to different formats
  new             Create new content for your site
  list            Listing out various types of content
  undraft         Undraft changes the content's draft status from 'True' to 'False'
  genautocomplete Generate shell autocompletion script for Hugo
  gendoc          Generate Markdown documentation for the Hugo CLI.
  genman          Generate man page for Hugo
  import          Import your site from others.

Flags:
  -b, --baseURL="": hostname (and path) to the root, e.g. http://spf13.com/
  -D, --buildDrafts[=false]: include content marked as draft
  -F, --buildFuture[=false]: include content with publishdate in the future
      --cacheDir="": filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/
      --canonifyURLs[=false]: if true, all relative URLs will be canonicalized using baseURL
      --config="": config file (default is path/config.yaml|json|toml)
  -d, --destination="": filesystem path to write files to
      --disableRSS[=false]: Do not build RSS files
      --disableSitemap[=false]: Do not build Sitemap file
      --editor="": edit new content with this editor, if provided
      --ignoreCache[=false]: Ignores the cache directory for reading but still writes to it
      --log[=false]: Enable Logging
      --logFile="": Log File path (if set, logging enabled automatically)
      --noTimes[=false]: Don't sync modification time of files
      --pluralizeListTitles[=true]: Pluralize titles in lists using inflect
      --preserveTaxonomyNames[=false]: Preserve taxonomy names as written ("Gérard Depardieu" vs "gerard-depardieu")
  -s, --source="": filesystem path to read files relative from
      --stepAnalysis[=false]: display memory and timing of different steps of the program
  -t, --theme="": theme to use (located in /themes/THEMENAME/)
      --uglyURLs[=false]: if true, use /filename.html instead of /filename/
  -v, --verbose[=false]: verbose output
      --verboseLog[=false]: verbose logging
  -w, --watch[=false]: watch filesystem for changes and recreate as needed

Defining your own usage

You can provide your own usage function or template for Cobra to use.

The default usage function is:

go
return func(c *Command) error {
	err := tmpl(c.Out(), c.UsageTemplate(), c)
	return err
}

Like help, the function and template are overridable through public methods:

go
command.SetUsageFunc(f func(*Command) error)

command.SetUsageTemplate(s string)

PreRun or PostRun Hooks

It is possible to run functions before or after the main Run function of your command. The PersistentPreRun and PreRun functions will be executed before Run. PersistentPostRun and PostRun will be executed after Run. The Persistent*Run functions will be inherrited by children if they do not declare their own. These function are run in the following order:

  • PersistentPreRun
  • PreRun
  • Run
  • PostRun
  • PersistentPostRun

An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's PersistentPreRun but not the root command's PersistentPostRun:

text
/* Detailed source-code truncated for AI context efficiency. */

Alternative Error Handling

Cobra also has functions where the return signature is an error. This allows for errors to bubble up to the top,
providing a way to handle the errors in one location. The current list of functions that return an error is:

  • PersistentPreRunE
  • PreRunE
  • RunE
  • PostRunE
  • PersistentPostRunE

If you would like to silence the default error and usage output in favor of your own, you can set SilenceUsage
and SilenceErrors to false on the command. A child command respects these flags if they are set on the parent
command.

Example Usage using RunE:

go
package main

import (
	"errors"
	"log"

	"github.com/spf13/cobra"
)

func main() {
	var rootCmd = &cobra.Command{
		Use:   "hugo",
		Short: "Hugo is a very fast static site generator",
		Long: `A Fast and Flexible Static Site Generator built with
                love by spf13 and friends in Go.
                Complete documentation is available at http://hugo.spf13.com`,
		RunE: func(cmd *cobra.Command, args []string) error {
			// Do Stuff Here
			return errors.New("some random error")
		},
	}

	if err := rootCmd.Execute(); err != nil {
		log.Fatal(err)
	}
}

Suggestions when "unknown command" happens

Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the git command when a typo happens. For example:

text
$ hugo srever
Error: unknown command "srever" for "hugo"

Did you mean this?
        server

Run 'hugo --help' for usage.

Suggestions are automatic based on every subcommand registered and use an implementation of Levenshtein distance. Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.

If you need to disable suggestions or tweak the string distance in your command, use:

go
command.DisableSuggestions = true

or

go
command.SuggestionsMinimumDistance = 1

You can also explicitly set names for which a given command will be suggested using the SuggestFor attribute. This allows suggestions for strings that are not close in terms of string distance, but makes sense in your set of commands and for some which you don't want aliases. Example:

text
$ kubectl remove
Error: unknown command "remove" for "kubectl"

Did you mean this?
        delete

Run 'kubectl help' for usage.

Generating Markdown-formatted documentation for your command

Cobra can generate a Markdown-formatted document based on the subcommands, flags, etc. A simple example of how to do this for your command can be found in Markdown Docs.

Generating man pages for your command

Cobra can generate a man page based on the subcommands, flags, etc. A simple example of how to do this for your command can be found in Man Docs.

Generating bash completions for your command

Cobra can generate a bash-completion file. If you add more information to your command, these completions can be amazingly powerful and flexible. Read more about it in Bash Completions.

Debugging

Cobra provides a ‘DebugFlags’ method on a command which, when called, will print
out everything Cobra knows about the flags for each command.

Example

go
command.DebugFlags()

Release Notes

  • 0.9.0 June 17, 2014
    • flags can appears anywhere in the args (provided they are unambiguous)
    • --help prints usage screen for app or command
    • Prefix matching for commands
    • Cleaner looking help and usage output
    • Extensive test suite
  • 0.8.0 Nov 5, 2013
    • Reworked interface to remove commander completely
    • Command now primary structure
    • No initialization needed
    • Usage & Help templates & functions definable at any level
    • Updated Readme
  • 0.7.0 Sept 24, 2013
    • Needs more eyes
    • Test suite
    • Support for automatic error messages
    • Support for help command
    • Support for printing to any io.Writer instead of os.Stderr
    • Support for persistent flags which cascade down tree
    • Ready for integration into Hugo
  • 0.1.0 Sept 3, 2013
    • Implement first draft

Extensions

Libraries for extending Cobra:

  • cmdns: Enables name spacing a command's immediate children. It provides an alternative way to structure subcommands, similar to heroku apps:create and ovrclk clusters:launch.

ToDo

  • Launch proper documentation site

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Contributors

Names in no particular order:

License

Cobra is released under the Apache 2.0 license. See LICENSE.txt


Overview (`vendor/github.com/spf13/jwalterweatherman/README.md`)

jWalterWeatherman

Seamless printing to the terminal (stdout) and logging to a io.Writer
(file) that’s as easy to use as fmt.Println.

Graphic by JonnyEtc

JWW is primarily a wrapper around the excellent standard log library. It
provides a few advantages over using the standard log library alone.

  1. Ready to go out of the box.
  2. One library for both printing to the terminal and logging (to files).
  3. Really easy to log to either a temp file or a file you specify.

I really wanted a very straightforward library that could seamlessly do
the following things.

  1. Replace all the println, printf, etc statements thought my code with
    something more useful
  2. Allow the user to easily control what levels are printed to stdout
  3. Allow the user to easily control what levels are logged
  4. Provide an easy mechanism (like fmt.Println) to print info to the user
    which can be easily logged as well
  5. Due to 2 & 3 provide easy verbose mode for output and logs
  6. Not have any unnecessary initialization cruft. Just use it.

Usage

Step 1. Use it

Put calls throughout your source based on type of feedback.
No initialization or setup needs to happen. Just start calling things.

Available Loggers are:

  • TRACE
  • DEBUG
  • INFO
  • WARN
  • ERROR
  • CRITICAL
  • FATAL

These each are loggers based on the log standard library and follow the
standard usage. Eg..

go
import (
        jww "github.com/spf13/jwalterweatherman"
    )

    ...

    if err != nil {

        // This is a pretty serious error and the user should know about
        // it. It will be printed to the terminal as well as logged under the
        // default thresholds.

        jww.ERROR.Println(err)
    }

    if err2 != nil {
        // This error isn’t going to materially change the behavior of the
        // application, but it’s something that may not be what the user
        // expects. Under the default thresholds, Warn will be logged, but
        // not printed to the terminal. 

        jww.WARN.Println(err2)
    }

    // Information that’s relevant to what’s happening, but not very
    // important for the user. Under the default thresholds this will be
    // discarded.

    jww.INFO.Printf("information %q", response)

Why 7 levels?

Maybe you think that 7 levels are too much for any application... and you
are probably correct. Just because there are seven levels doesn’t mean
that you should be using all 7 levels. Pick the right set for your needs.
Remember they only have to mean something to your project.

Step 2. Optionally configure JWW

Under the default thresholds :

  • Debug, Trace & Info goto /dev/null
  • Warn and above is logged (when a log file/io.Writer is provided)
  • Error and above is printed to the terminal (stdout)

Changing the thresholds

The threshold can be changed at any time, but will only affect calls that
execute after the change was made.

This is very useful if your application has a verbose mode. Of course you
can decide what verbose means to you or even have multiple levels of
verbosity.

go
import (
        jww "github.com/spf13/jwalterweatherman"
    )

    if Verbose {
        jww.SetLogThreshold(jww.LevelTrace)
        jww.SetStdoutThreshold(jww.LevelInfo)
    }

Note that JWW's own internal output uses log levels as well, so set the log
level before making any other calls if you want to see what it's up to.

Using a temp log file

JWW conveniently creates a temporary file and sets the log Handle to
a io.Writer created for it. You should call this early in your application
initialization routine as it will only log calls made after it is executed.
When this option is used, the library will fmt.Println where to find the
log file.

go
import (
        jww "github.com/spf13/jwalterweatherman"
    )

    jww.UseTempLogFile("YourAppName")

Setting a log file

JWW can log to any file you provide a path to (provided it’s writable).
Will only append to this file.

go
import (
        jww "github.com/spf13/jwalterweatherman"
    )

    jww.SetLogFile("/path/to/logfile")

More information

This is an early release. I’ve been using it for a while and this is the
third interface I’ve tried. I like this one pretty well, but no guarantees
that it won’t change a bit.

I wrote this for use in hugo. If you are looking
for a static website engine that’s super fast please checkout Hugo.


Overview (`vendor/github.com/spf13/pflag/README.md`)



Description

pflag is a drop-in replacement for Go's flag package, implementing
POSIX/GNU-style --flags.

pflag is compatible with the GNU extensions to the POSIX recommendations
for command-line options
. For a more precise description, see the
"Command-line flag syntax" section below.

pflag is available under the same style of BSD license as the Go language,
which can be found in the LICENSE file.

Installation

pflag is available using the standard go get command.

Install by running:

text
go get github.com/spf13/pflag

Run tests by running:

text
go test github.com/spf13/pflag

Usage

pflag is a drop-in replacement of Go's native flag package. If you import
pflag under the name "flag" then all code should continue to function
with no changes.

go
import flag "github.com/spf13/pflag"

There is one exception to this: if you directly instantiate the Flag struct
there is one more field "Shorthand" that you will need to set.
Most code never instantiates this struct directly, and instead uses
functions such as String(), BoolVar(), and Var(), and is therefore
unaffected.

Define flags using flag.String(), Bool(), Int(), etc.

This declares an integer flag, -flagname, stored in the pointer ip, with type *int.

go
var ip *int = flag.Int("flagname", 1234, "help message for flagname")

If you like, you can bind the flag to a variable using the Var() functions.

go
var flagvar int
func init() {
    flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
}

Or you can create custom flags that satisfy the Value interface (with
pointer receivers) and couple them to flag parsing by

go
flag.Var(&flagVal, "name", "help message for flagname")

For such flags, the default value is just the initial value of the variable.

After all flags are defined, call

go
flag.Parse()

to parse the command line into the defined flags.

Flags may then be used directly. If you're using the flags themselves,
they are all pointers; if you bind to variables, they're values.

go
fmt.Println("ip has value ", *ip)
fmt.Println("flagvar has value ", flagvar)

There are helpers function to get values later if you have the FlagSet but
it was difficult to keep up with all of the flag pointers in your code.
If you have a pflag.FlagSet with a flag called 'flagname' of type int you
can use GetInt() to get the int value. But notice that 'flagname' must exist
and it must be an int. GetString("flagname") will fail.

go
i, err := flagset.GetInt("flagname")

After parsing, the arguments after the flag are available as the
slice flag.Args() or individually as flag.Arg(i).
The arguments are indexed from 0 through flag.NArg()-1.

The pflag package also defines some new functions that are not in flag,
that give one-letter shorthands for flags. You can use these by appending
'P' to the name of any function that defines a flag.

go
var ip = flag.IntP("flagname", "f", 1234, "help message")
var flagvar bool
func init() {
	flag.BoolVarP(&flagvar, "boolname", "b", true, "help message")
}
flag.VarP(&flagVal, "varname", "v", "help message")

Shorthand letters can be used with single dashes on the command line.
Boolean shorthand flags can be combined with other shorthand flags.

The default set of command-line flags is controlled by
top-level functions. The FlagSet type allows one to define
independent sets of flags, such as to implement subcommands
in a command-line interface. The methods of FlagSet are
analogous to the top-level functions for the command-line
flag set.

Setting no option default values for flags

After you create a flag it is possible to set the pflag.NoOptDefVal for
the given flag. Doing this changes the meaning of the flag slightly. If
a flag has a NoOptDefVal and the flag is set on the command line without
an option the flag will be set to the NoOptDefVal. For example given:

go
var ip = flag.IntP("flagname", "f", 1234, "help message")
flag.Lookup("flagname").NoOptDefVal = "4321"

Would result in something like

Parsed Arguments Resulting Value
--flagname=1357 ip=1357
--flagname ip=4321
[nothing] ip=1234

Command line flag syntax

text
--flag    // boolean flags, or flags with no option default values
--flag x  // only on flags without a default value
--flag=x

Unlike the flag package, a single dash before an option means something
different than a double dash. Single dashes signify a series of shorthand
letters for flags. All but the last shorthand letter must be boolean flags
or a flag with a default value

text
// boolean or flags where the 'no option default value' is set
-f
-f=true
-abc
but
-b true is INVALID

// non-boolean and flags without a 'no option default value'
-n 1234
-n=1234
-n1234

// mixed
-abcs "hello"
-absd="hello"
-abcs1234

Flag parsing stops after the terminator "--". Unlike the flag package,
flags can be interspersed with arguments anywhere on the command line
before this terminator.

Integer flags accept 1234, 0664, 0x1234 and may be negative.
Boolean flags (in their long form) accept 1, 0, t, f, true, false,
TRUE, FALSE, True, False.
Duration flags accept any input valid for time.ParseDuration.

Mutating or "Normalizing" Flag names

It is possible to set a custom flag name 'normalization function.' It allows flag names to be mutated both when created in the code and when used on the command line to some 'normalized' form. The 'normalized' form is used for comparison. Two examples of using the custom normalization func follow.

Example #1: You want -, _, and . in flags to compare the same. aka --my-flag == --my_flag == --my.flag

go
func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
	from := []string{"-", "_"}
	to := "."
	for _, sep := range from {
		name = strings.Replace(name, sep, to, -1)
	}
	return pflag.NormalizedName(name)
}

myFlagSet.SetNormalizeFunc(wordSepNormalizeFunc)

Example #2: You want to alias two flags. aka --old-flag-name == --new-flag-name

go
func aliasNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
	switch name {
	case "old-flag-name":
		name = "new-flag-name"
		break
	}
	return pflag.NormalizedName(name)
}

myFlagSet.SetNormalizeFunc(aliasNormalizeFunc)

Deprecating a flag or its shorthand

It is possible to deprecate a flag, or just its shorthand. Deprecating a flag/shorthand hides it from help text and prints a usage message when the deprecated flag/shorthand is used.

Example #1: You want to deprecate a flag named "badflag" as well as inform the users what flag they should use instead.

go
// deprecate a flag by specifying its name and a usage message
flags.MarkDeprecated("badflag", "please use --good-flag instead")

This hides "badflag" from help text, and prints Flag --badflag has been deprecated, please use --good-flag instead when "badflag" is used.

Example #2: You want to keep a flag name "noshorthandflag" but deprecate its shortname "n".

go
// deprecate a flag shorthand by specifying its flag name and a usage message
flags.MarkShorthandDeprecated("noshorthandflag", "please use --noshorthandflag only")

This hides the shortname "n" from help text, and prints Flag shorthand -n has been deprecated, please use --noshorthandflag only when the shorthand "n" is used.

Note that usage message is essential here, and it should not be empty.

Hidden flags

It is possible to mark a flag as hidden, meaning it will still function as normal, however will not show up in usage/help text.

Example: You have a flag named "secretFlag" that you need for internal use only and don't want it showing up in help text, or for its usage text to be available.

go
// hide a flag by specifying its name
flags.MarkHidden("secretFlag")

Supporting Go flags when using pflag

In order to support flags defined using Go's flag package, they must be added to the pflag flagset. This is usually necessary
to support flags defined by third-party dependencies (e.g. golang/glog).

Example: You want to add the Go flags to the CommandLine flagset

go
import (
	goflag "flag"
	flag "github.com/spf13/pflag"
)

var ip *int = flag.Int("flagname", 1234, "help message for flagname")

func main() {
	flag.CommandLine.AddGoFlagSet(goflag.CommandLine)
	flag.Parse()
}

More info

You can see the full reference documentation of the pflag package
at godoc.org, or through go's standard documentation system by
running godoc -http=:6060 and browsing to
http://localhost:6060/pkg/github.com/ogier/pflag after
installation.


Overview (`vendor/github.com/spf13/viper/README.md`)

Go configuration with fangs!

Many Go projects are built using Viper including:

What is Viper?

Viper is a complete configuration solution for go applications including 12 factor apps. It is designed
to work within an application, and can handle all types of configuration needs
and formats. It supports:

  • setting defaults
  • reading from JSON, TOML, YAML, HCL, and Java properties config files
  • live watching and re-reading of config files (optional)
  • reading from environment variables
  • reading from remote config systems (etcd or Consul), and watching changes
  • reading from command line flags
  • reading from buffer
  • setting explicit values

Viper can be thought of as a registry for all of your applications
configuration needs.

Why Viper?

When building a modern application, you don’t want to worry about
configuration file formats; you want to focus on building awesome software.
Viper is here to help with that.

Viper does the following for you:

  1. Find, load, and unmarshal a configuration file in JSON, TOML, YAML, HCL, or Java properties formats.
  2. Provide a mechanism to set default values for your different
    configuration options.
  3. Provide a mechanism to set override values for options specified through
    command line flags.
  4. Provide an alias system to easily rename parameters without breaking existing
    code.
  5. Make it easy to tell the difference between when a user has provided a
    command line or config file which is the same as the default.

Viper uses the following precedence order. Each item takes precedence over the
item below it:

  • explicit call to Set
  • flag
  • env
  • config
  • key/value store
  • default

Viper configuration keys are case insensitive.

Putting Values into Viper

Establishing Defaults

A good configuration system will support default values. A default value is not
required for a key, but it's useful in the event that a key hasn’t been set via
config file, environment variable, remote configuration or flag.

Examples:

go
viper.SetDefault("ContentDir", "content")
viper.SetDefault("LayoutDir", "layouts")
viper.SetDefault("Taxonomies", map[string]string{"tag": "tags", "category": "categories"})

Reading Config Files

Viper requires minimal configuration so it knows where to look for config files.
Viper supports JSON, TOML, YAML, HCL, and Java Properties files. Viper can search multiple paths, but
currently a single Viper instance only supports a single configuration file.
Viper does not default to any configuration search paths leaving defaults decision
to an application.

Here is an example of how to use Viper to search for and read a configuration file.
None of the specific paths are required, but at least one path should be provided
where a configuration file is expected.

go
viper.SetConfigName("config") // name of config file (without extension)
viper.AddConfigPath("/etc/appname/")   // path to look for the config file in
viper.AddConfigPath("$HOME/.appname")  // call multiple times to add many search paths
viper.AddConfigPath(".")               // optionally look for config in the working directory
err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file
	panic(fmt.Errorf("Fatal error config file: %s \n", err))
}

Watching and re-reading config files

Viper supports the ability to have your application live read a config file while running.

Gone are the days of needing to restart a server to have a config take effect,
viper powered applications can read an update to a config file while running and
not miss a beat.

Simply tell the viper instance to watchConfig.
Optionally you can provide a function for Viper to run each time a change occurs.

Make sure you add all of the configPaths prior to calling WatchConfig()

go
viper.WatchConfig()
		viper.OnConfigChange(func(e fsnotify.Event) {
			fmt.Println("Config file changed:", e.Name)
		})

Reading Config from io.Reader

Viper predefines many configuration sources such as files, environment
variables, flags, and remote K/V store, but you are not bound to them. You can
also implement your own required configuration source and feed it to viper.

go
viper.SetConfigType("yaml") // or viper.SetConfigType("YAML")

// any approach to require this configuration into your program.
var yamlExample = []byte(`
Hacker: true
name: steve
hobbies:
- skateboarding
- snowboarding
- go
clothing:
  jacket: leather
  trousers: denim
age: 35
eyes : brown
beard: true
`)

viper.ReadConfig(bytes.NewBuffer(yamlExample))

viper.Get("name") // this would be "steve"

Setting Overrides

These could be from a command line flag, or from your own application logic.

go
viper.Set("Verbose", true)
viper.Set("LogFile", LogFile)

Registering and Using Aliases

Aliases permit a single value to be referenced by multiple keys

go
viper.RegisterAlias("loud", "Verbose")

viper.Set("verbose", true) // same result as next line
viper.Set("loud", true)   // same result as prior line

viper.GetBool("loud") // true
viper.GetBool("verbose") // true

Working with Environment Variables

Viper has full support for environment variables. This enables 12 factor
applications out of the box. There are four methods that exist to aid working
with ENV:

  • AutomaticEnv()
  • BindEnv(string...) : error
  • SetEnvPrefix(string)
  • SetEnvReplacer(string...) *strings.Replacer

When working with ENV variables, it’s important to recognize that Viper
treats ENV variables as case sensitive.

Viper provides a mechanism to try to ensure that ENV variables are unique. By
using SetEnvPrefix, you can tell Viper to use add a prefix while reading from
the environment variables. Both BindEnv and AutomaticEnv will use this
prefix.

BindEnv takes one or two parameters. The first parameter is the key name, the
second is the name of the environment variable. The name of the environment
variable is case sensitive. If the ENV variable name is not provided, then
Viper will automatically assume that the key name matches the ENV variable name,
but the ENV variable is IN ALL CAPS. When you explicitly provide the ENV
variable name, it does not automatically add the prefix.

One important thing to recognize when working with ENV variables is that the
value will be read each time it is accessed. Viper does not fix the value when
the BindEnv is called.

AutomaticEnv is a powerful helper especially when combined with
SetEnvPrefix. When called, Viper will check for an environment variable any
time a viper.Get request is made. It will apply the following rules. It will
check for a environment variable with a name matching the key uppercased and
prefixed with the EnvPrefix if set.

SetEnvReplacer allows you to use a strings.Replacer object to rewrite Env
keys to an