3 Commits

Author SHA1 Message Date
Andrew Suzuki b4cd68602c Print rancher error on ActionUpgrade fail
(cherry picked from commit 7e02dbece4)
2016-06-17 08:56:56 +02:00
Thomas Boerger 82ed2b7118 Switched to 0.5 build process 2016-06-15 13:29:04 +02:00
Thomas Boerger e4dc896623 Added vendoring for reproducable builds 2016-06-15 13:28:21 +02:00
289 changed files with 31819 additions and 16307 deletions
Executable → Regular
+19 -86
View File
@@ -1,93 +1,26 @@
workspace:
base: /go
path: src/github.com/josmo/drone-rancher
pipeline:
test:
image: golang:1.9
commands:
- go vet
- go test -cover -coverprofile=coverage.out
build_linux_amd64:
image: golang:1.9
group: build
image: golang:1.6
environment:
- GOOS=linux
- GOARCH=amd64
- CGO_ENABLED=0
- GOPATH=/drone
commands:
- go build -v -ldflags "-X main.build=${DRONE_BUILD_NUMBER}" -a -o release/linux/amd64/drone-rancher
build_linux_arm64:
image: golang:1.9
group: build
environment:
- GOOS=linux
- GOARCH=arm64
- CGO_ENABLED=0
commands:
- go build -v -ldflags "-X main.build=${DRONE_BUILD_NUMBER}" -a -o release/linux/arm64/drone-rancher
build_linux_arm:
image: golang:1.9
group: build
environment:
- GOOS=linux
- GOARCH=arm
- CGO_ENABLED=0
- GOARM=7
commands:
- go build -v -ldflags "-X main.build=${DRONE_BUILD_NUMBER}" -a -o release/linux/arm/drone-rancher
# build_windows_amd64:
# image: golang:1.9-nanoserver
# group: build
# environment:
# - GOOS=windows
# - GOARCH=amd64
# - CGO_ENABLED=0
# commands:
# - go build -v -ldflags "-X main.build=${DRONE_BUILD_NUMBER}" -a -o release/windows/amd64/drone-webhook
publish_linux_amd64:
image: plugins/docker
username: josmo
repo: peloton/drone-rancher
auto_tag: true
secrets: [ docker_password ]
dockerfile: Dockerfile
- make vet
- make build
- make test
docker:
storage_driver: overlay
repo: plugins/drone-rancher
tag: [ "latest" ]
when:
event: tag
branch: release/0.4
event: push
publish_linux_arm64:
image: plugins/docker
username: josmo
repo: peloton/drone-rancher
auto_tag: true
auto_tag_suffix: linux-arm64
secrets: [ docker_password ]
dockerfile: Dockerfile.arm64
when:
event: tag
publish_linux_arm:
image: plugins/docker
username: josmo
repo: peloton/drone-rancher
auto_tag: true
auto_tag_suffix: linux-arm
secrets: [ docker_password ]
dockerfile: Dockerfile.arm
when:
event: tag
# publish_windows_amd64:
# image: plugins/docker
# username: josmo
# repo: peloton/drone-rancher
# tags: [ windows-amd64 ]
# secrets: [ docker_password ]
# dockerfile: Dockerfile.windows
# when:
# branch: master
# event: push
plugin:
name: Rancher
desc: Deploy or update a project on Rancher
type: deploy
image: plugins/drone-rancher
labels:
- rancher
- docker
+1
View File
@@ -0,0 +1 @@
eyJhbGciOiJIUzI1NiJ9.cGlwZWxpbmU6CiAgdGVzdDoKICAgIGltYWdlOiBnb2xhbmc6MS42CiAgICBlbnZpcm9ubWVudDoKICAgICAgLSBDR09fRU5BQkxFRD0wCiAgICAgIC0gR09QQVRIPS9kcm9uZQogICAgY29tbWFuZHM6CiAgICAgIC0gbWFrZSB2ZXQKICAgICAgLSBtYWtlIGJ1aWxkCiAgICAgIC0gbWFrZSB0ZXN0CiAgZG9ja2VyOgogICAgc3RvcmFnZV9kcml2ZXI6IG92ZXJsYXkKICAgIHJlcG86IHBsdWdpbnMvZHJvbmUtcmFuY2hlcgogICAgdGFnOiBbICJsYXRlc3QiIF0KICAgIHdoZW46CiAgICAgIGJyYW5jaDogcmVsZWFzZS8wLjQKICAgICAgZXZlbnQ6IHB1c2gKCnBsdWdpbjoKICBuYW1lOiBSYW5jaGVyCiAgZGVzYzogRGVwbG95IG9yIHVwZGF0ZSBhIHByb2plY3Qgb24gUmFuY2hlcgogIHR5cGU6IGRlcGxveQogIGltYWdlOiBwbHVnaW5zL2Ryb25lLXJhbmNoZXIKICBsYWJlbHM6CiAgICAtIHJhbmNoZXIKICAgIC0gZG9ja2VyCg.Amvq0DkNvNUvgzDfSqI7H0xChF8iJu2IPKiheQfclhE
Executable → Regular
-2
View File
@@ -25,5 +25,3 @@ _testmain.go
coverage.out
drone-rancher
*.idea
Executable → Regular
+2 -8
View File
@@ -3,22 +3,19 @@ Use the rancher plugin to upgrade a service in [rancher](http://rancher.com).
The following parameters are used to configure this plugin:
- `url` - url to your rancher server, including protocol and port
- `rancher_access_key` - rancher api access key
- `rancher_secret_key` - rancher api secret key
- `access_key` - rancher api access key
- `secret_key` - rancher api secret key
- `service` - name of rancher service to act on
- `docker_image` - new image to assign to service, including tag (`drone/drone:latest`)
- `start_first` - start the new container before stopping the old one, defaults to `true`
- `confirm` - auto confirm the service upgrade if successful, defaults to `false`
- `timeout` - the maximum wait time in seconds for the service to upgrade, default to `30`
- `interval_millis` - the upgrade interval in milli seconds, defaults to `1000`
- `batch_size` - the upgrade batch size, defaults to `1`
The following is a sample Rancher configuration in your `.drone.yml` file:
```yaml
deploy:
rancher:
image: peloton/drone-rancher
url: https://example.rancher.com
access_key: 1234567abcdefg
secret_key: abcdefg1234567
@@ -26,7 +23,4 @@ deploy:
docker_image: drone/drone:latest
```
if you want to add secrets for the access_key and secret it's RANCHER_ACCESS_KEY and RANCHER_SECRET_KEY
Note that if your `service` is part of a stack, you should use the notation `stackname/servicename` as this will make sure that the found service is part of the correct stack. If no stack is specified, this plugin will update the first service with a matching name which may not be what you want.
Executable → Regular
+9 -14
View File
@@ -1,16 +1,11 @@
FROM alpine:3.6 as alpine
RUN apk add -U --no-cache ca-certificates
# Docker image for the Drone build runner
#
# CGO_ENABLED=0 go build -a -tags netgo
# docker build --rm=true -t plugins/drone-rancher .
FROM scratch
ENV GODEBUG=netdns=go
COPY --from=alpine /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
LABEL org.label-schema.version=latest
LABEL org.label-schema.vcs-url="https://github.com/josmo/drone-rancher.git"
LABEL org.label-schema.name="Drone Rancher"
LABEL org.label-schema.vendor="Josmo"
ADD release/linux/amd64/drone-rancher /bin/
FROM gliderlabs/alpine:3.2
RUN apk add --update \
ca-certificates
ADD drone-rancher /bin/
ENTRYPOINT ["/bin/drone-rancher"]
-17
View File
@@ -1,17 +0,0 @@
FROM alpine:3.6 as alpine
RUN apk add -U --no-cache ca-certificates
FROM scratch
ENV GODEBUG=netdns=go
COPY --from=alpine /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
LABEL org.label-schema.version=latest
LABEL org.label-schema.vcs-url="https://github.com/josmo/drone-rancher.git"
LABEL org.label-schema.name="Drone Rancher"
LABEL org.label-schema.vendor="Josmo"
LABEL org.label-schema.schema-version="1.0"
ADD release/linux/arm/drone-rancher /bin/
ENTRYPOINT ["/bin/drone-rancher"]
-17
View File
@@ -1,17 +0,0 @@
FROM alpine:3.6 as alpine
RUN apk add -U --no-cache ca-certificates
FROM scratch
ENV GODEBUG=netdns=go
COPY --from=alpine /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
LABEL org.label-schema.version=latest
LABEL org.label-schema.vcs-url="https://github.com/josmo/drone-rancher.git"
LABEL org.label-schema.name="Drone Rancher"
LABEL org.label-schema.vendor="Josmo"
LABEL org.label-schema.schema-version="1.0"
ADD release/linux/arm64/drone-rancher /bin/
ENTRYPOINT ["/bin/drone-rancher"]
-12
View File
@@ -1,12 +0,0 @@
FROM microsoft/nanoserver:latest
ENV GODEBUG=netdns=go
LABEL org.label-schema.version=latest
LABEL org.label-schema.vcs-url="https://github.com/josmo/drone-rancher.git"
LABEL org.label-schema.name="Drone Rancher"
LABEL org.label-schema.vendor="Josmo"
LABEL org.label-schema.schema-version="1.0"
ADD release/windows/amd64/drone-rancher /bin/
ENTRYPOINT [ "/bin/drone-rancher" ]
+46
View File
@@ -0,0 +1,46 @@
[people]
[people.bradrydzewski]
name = "Brad Rydzewski"
email = "brad@drone.io"
login = "bradrydzewski"
[people.Bugagazavr]
name = "Kirill"
email = ""
login = "Bugagazavr"
[people.donny-dont]
name = "Don Olmstead"
email = "donny-dont@gmail.com"
login = "donny-dont"
[people.jackspirou]
name = "Jack Spirou"
email = ""
login = "jackspirou"
[people.msteinert]
name = "Mike Steinert"
email = ""
login = "msteinert"
[people.nlf]
name = "Nathan LaFreniere"
email = ""
login = "nlf"
[people.tboerger]
name = "Thomas Boerger"
email = "thomas@webhippie.de"
login = "tboerger"
[people.athieriot]
name = "Aurélien Thieriot"
email = "a.thieriot@gmail.com"
login = "athieriot"
[org]
[org.core]
people = [
"bradrydzewski",
"Bugagazavr",
"donny-dont",
"jackspirou",
"msteinert",
"nlf",
"tboerger",
"athieriot"
]
+34
View File
@@ -0,0 +1,34 @@
.PHONY: all clean deps fmt vet test docker
EXECUTABLE ?= drone-rancher
IMAGE ?= plugins/$(EXECUTABLE)
COMMIT ?= $(shell git rev-parse --short HEAD)
LDFLAGS = -X "main.buildCommit=$(COMMIT)"
PACKAGES = $(shell go list ./... | grep -v /vendor/)
all: deps build test
clean:
go clean -i ./...
deps:
go get -t ./...
fmt:
go fmt $(PACKAGES)
vet:
go vet $(PACKAGES)
test:
@for PKG in $(PACKAGES); do go test -cover -coverprofile $$GOPATH/src/$$PKG/coverage.out $$PKG || exit 1; done;
docker:
GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -ldflags '-s -w $(LDFLAGS)'
docker build --rm -t $(IMAGE) .
$(EXECUTABLE): $(wildcard *.go)
go build -ldflags '-s -w $(LDFLAGS)'
build: $(EXECUTABLE)
Executable → Regular
+90 -18
View File
@@ -1,35 +1,107 @@
# drone-rancher
[![Build Status](https://drone.seattleslow.com/api/badges/josmo/drone-rancher/status.svg)](https://drone.seattleslow.com/josmo/drone-rancher)
[![Join the chat at https://gitter.im/drone/drone](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/drone/drone)
[![Go Doc](https://godoc.org/github.com/josmo/drone-rancher?status.svg)](http://godoc.org/github.com/josmo/drone-rancher)
[![Go Report](https://goreportcard.com/badge/github.com/josmo/drone-rancher)](https://goreportcard.com/report/github.com/josmo/drone-rancher)
[![](https://images.microbadger.com/badges/image/peloton/drone-rancher.svg)](https://microbadger.com/images/peloton/drone-rancher "Get your own image badge on microbadger.com")
[![Build Status](http://beta.drone.io/api/badges/drone-plugins/drone-rancher/status.svg)](http://beta.drone.io/drone-plugins/drone-rancher)
[![Coverage Status](https://aircover.co/badges/drone-plugins/drone-rancher/coverage.svg)](https://aircover.co/drone-plugins/drone-rancher)
[![](https://badge.imagelayers.io/plugins/drone-rancher:latest.svg)](https://imagelayers.io/?images=plugins/drone-rancher:latest 'Get your own badge on imagelayers.io')
Drone plugin to deploy or update a project on Rancher. For the usage information and a listing of the available options please take a look at [the docs](DOCS.md).
## Binary
Build the binary using `drone cli`:
Build the binary using `make`:
```
drone exec
make deps build
```
### Example
## Usage
```sh
./drone-rancher <<EOF
{
"repo": {
"clone_url": "git://github.com/drone/drone",
"owner": "drone",
"name": "drone",
"full_name": "drone/drone"
},
"system": {
"link_url": "https://beta.drone.io"
},
"build": {
"number": 22,
"status": "success",
"started_at": 1421029603,
"finished_at": 1421029813,
"message": "Update the Readme",
"author": "johnsmith",
"author_email": "john.smith@gmail.com"
"event": "push",
"branch": "master",
"commit": "436b7a6e2abaddfd35740527353e78a227ddcb2c",
"ref": "refs/heads/master"
},
"workspace": {
"root": "/drone/src",
"path": "/drone/src/github.com/drone/drone"
},
"vargs": {
"url": "https://example.rancher.com",
"access_key": "1234567abcdefg",
"secret_key": "abcdefg1234567",
"service": "drone/drone",
"docker_image": "drone/drone:latest"
}
}
EOF
```
Build and deploy from your current working directory:
## Docker
Build the container using `make`:
```
docker run --rm \
-e PLUGIN_URL=<source> \
-e PLUGIN_ACCESS_KEY=<key> \
-e PLUGIN_SECRET_KEY=<secret> \
-e PLUGIN_SERVICE=<service> \
-e PLUGIN_DOCKER_IMAGE=<image> \
-v $(pwd):$(pwd) \
-w $(pwd) \
peloton/drone-rancher
make deps docker
```
### Example
```sh
docker run -i plugins/drone-rancher <<EOF
{
"repo": {
"clone_url": "git://github.com/drone/drone",
"owner": "drone",
"name": "drone",
"full_name": "drone/drone"
},
"system": {
"link_url": "https://beta.drone.io"
},
"build": {
"number": 22,
"status": "success",
"started_at": 1421029603,
"finished_at": 1421029813,
"message": "Update the Readme",
"author": "johnsmith",
"author_email": "john.smith@gmail.com"
"event": "push",
"branch": "master",
"commit": "436b7a6e2abaddfd35740527353e78a227ddcb2c",
"ref": "refs/heads/master"
},
"workspace": {
"root": "/drone/src",
"path": "/drone/src/github.com/drone/drone"
},
"vargs": {
"url": "https://example.rancher.com",
"access_key": "1234567abcdefg",
"secret_key": "abcdefg1234567",
"service": "drone/drone",
"docker_image": "drone/drone:latest"
}
}
EOF
```
Executable → Regular
View File

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

Executable → Regular
+151 -90
View File
@@ -3,106 +3,167 @@ package main
import (
"fmt"
"os"
"strings"
"time"
log "github.com/Sirupsen/logrus"
"github.com/urfave/cli"
"github.com/drone/drone-go/plugin"
"github.com/rancher/go-rancher/client"
)
var build string // build number set at compile-time
type Rancher struct {
Url string `json:"url"`
AccessKey string `json:"access_key"`
SecretKey string `json:"secret_key"`
Service string `json:"service"`
Image string `json:"docker_image"`
StartFirst bool `json:"start_first"`
Confirm bool `json:"confirm"`
Timeout int `json:"timeout"`
}
var (
buildCommit string
)
func main() {
app := cli.NewApp()
app.Name = "rancher publish"
app.Usage = "rancher publish"
app.Action = run
app.Version = fmt.Sprintf("1.0.0+%s", build)
fmt.Printf("Drone Rancher Plugin built from %s\n", buildCommit)
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "url",
Usage: "url to the rancher api",
EnvVar: "PLUGIN_URL",
},
cli.StringFlag{
Name: "access-key",
Usage: "rancher access key",
EnvVar: "PLUGIN_ACCESS_KEY, RANCHER_ACCESS_KEY",
},
cli.StringFlag{
Name: "secret-key",
Usage: "rancher secret key",
EnvVar: "PLUGIN_SECRET_KEY, RANCHER_SECRET_KEY",
},
cli.StringFlag{
Name: "service",
Usage: "Service to act on",
EnvVar: "PLUGIN_SERVICE",
},
cli.StringSliceFlag{
Name: "sidekick",
Usage: "Service's sidekick name and image separated by the space, supports multiple flags",
EnvVar: "PLUGIN_SIDEKICK",
},
cli.StringFlag{
Name: "docker-image",
Usage: "image to use",
EnvVar: "PLUGIN_DOCKER_IMAGE",
},
cli.BoolTFlag{
Name: "start-first",
Usage: "Start new container before stoping old",
EnvVar: "PLUGIN_START_FIRST",
},
cli.BoolFlag{
Name: "confirm",
Usage: "auto confirm the service upgrade if successful",
EnvVar: "PLUGIN_CONFIRM",
},
cli.IntFlag{
Name: "timeout",
Usage: "the maximum wait time in seconds for the service to upgrade",
Value: 30,
EnvVar: "PLUGIN_TIMEOUT",
},
cli.Int64Flag{
Name: "interval-millis",
Usage: "The interval for batch size upgrade",
Value: 1000,
EnvVar: "PLUGIN_INTERVAL_MILLIS",
},
cli.Int64Flag{
Name: "batch-size",
Usage: "The upgrade batch size",
Value: 1,
EnvVar: "PLUGIN_BATCH_SIZE",
},
cli.BoolTFlag{
Name: "yaml-verified",
Usage: "Ensure the yaml was signed",
EnvVar: "DRONE_YAML_VERIFIED",
},
vargs := Rancher{
StartFirst: true,
Timeout: 30,
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
plugin.Param("vargs", &vargs)
err := plugin.Parse()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
if len(vargs.Url) == 0 || len(vargs.AccessKey) == 0 || len(vargs.SecretKey) == 0 || len(vargs.Service) == 0 {
return
}
if !strings.HasPrefix(vargs.Image, "docker:") {
vargs.Image = fmt.Sprintf("docker:%s", vargs.Image)
}
var wantedService, wantedStack string
if strings.Contains(vargs.Service, "/") {
parts := strings.SplitN(vargs.Service, "/", 2)
wantedStack = parts[0]
wantedService = parts[1]
} else {
wantedService = vargs.Service
}
rancher, err := client.NewRancherClient(&client.ClientOpts{
Url: vargs.Url,
AccessKey: vargs.AccessKey,
SecretKey: vargs.SecretKey,
})
if err != nil {
fmt.Printf("Failed to create rancher client: %s\n", err)
os.Exit(1)
}
var stackId string
if wantedStack != "" {
environments, err := rancher.Environment.List(&client.ListOpts{})
if err != nil {
fmt.Printf("Failed to list rancher environments: %s\n", err)
os.Exit(1)
}
for _, env := range environments.Data {
if env.Name == wantedStack {
stackId = env.Id
}
}
if stackId == "" {
fmt.Printf("Unable to find stack %s\n", wantedStack)
os.Exit(1)
}
}
services, err := rancher.Service.List(&client.ListOpts{})
if err != nil {
fmt.Printf("Failed to list rancher services: %s\n", err)
os.Exit(1)
}
found := false
var service client.Service
for _, svc := range services.Data {
if svc.Name == wantedService && ((wantedStack != "" && svc.EnvironmentId == stackId) || wantedStack == "") {
service = svc
found = true
}
}
if !found {
fmt.Printf("Unable to find service %s\n", vargs.Service)
os.Exit(1)
}
service.LaunchConfig.ImageUuid = vargs.Image
upgrade := &client.ServiceUpgrade{}
upgrade.InServiceStrategy = &client.InServiceUpgradeStrategy{
LaunchConfig: service.LaunchConfig,
SecondaryLaunchConfigs: service.SecondaryLaunchConfigs,
StartFirst: vargs.StartFirst,
}
upgrade.ToServiceStrategy = &client.ToServiceUpgradeStrategy{}
_, err = rancher.Service.ActionUpgrade(&service, upgrade)
if err != nil {
fmt.Printf("Unable to upgrade service %s: %s\n", vargs.Service, err)
os.Exit(1)
}
fmt.Printf("Upgraded %s to %s\n", vargs.Service, vargs.Image)
if vargs.Confirm {
srv, err := retry(func() (interface{}, error) {
s, e := rancher.Service.ById(service.Id)
if e != nil {
return nil, e
}
if s.State != "upgraded" {
return nil, fmt.Errorf("Service not upgraded: %s", s.State)
}
return s, nil
}, time.Duration(vargs.Timeout)*time.Second, 3*time.Second)
if err != nil {
fmt.Printf("Error waiting for service upgrade to complete: %s", err)
os.Exit(1)
}
_, err = rancher.Service.ActionFinishupgrade(srv.(*client.Service))
if err != nil {
fmt.Printf("Unable to finish upgrade %s: %s\n", vargs.Service, err)
os.Exit(1)
}
fmt.Printf("Finished upgrade %s\n", vargs.Service)
}
}
func run(c *cli.Context) error {
plugin := Plugin{
URL: c.String("url"),
Key: c.String("access-key"),
Secret: c.String("secret-key"),
Service: c.String("service"),
SidekickDockerImage: c.StringSlice("sidekick"),
DockerImage: c.String("docker-image"),
StartFirst: c.BoolT("start-first"),
Confirm: c.Bool("confirm"),
Timeout: c.Int("timeout"),
IntervalMillis: c.Int64("interval-millis"),
BatchSize: c.Int64("batch-size"),
YamlVerified: c.BoolT("yaml-verified"),
type retryFunc func() (interface{}, error)
func retry(f retryFunc, timeout time.Duration, interval time.Duration) (interface{}, error) {
finish := time.After(timeout)
for {
result, err := f()
if err == nil {
return result, nil
}
select {
case <-finish:
return nil, err
case <-time.After(interval):
}
}
return plugin.Exec()
}
-169
View File
@@ -1,169 +0,0 @@
package main
import (
"errors"
"fmt"
"strings"
"time"
log "github.com/Sirupsen/logrus"
client "github.com/rancher/go-rancher/v2"
)
type Plugin struct {
URL string
Key string
Secret string
Service string
SidekickDockerImage []string
DockerImage string
StartFirst bool
Confirm bool
Timeout int
IntervalMillis int64
BatchSize int64
YamlVerified bool
}
func (p *Plugin) Exec() error {
log.Info("Drone Rancher Plugin built")
if p.URL == "" || p.Key == "" || p.Secret == "" || p.Service == "" {
return errors.New("Eek: Must have url, key, secret, and service definied")
}
var wantedService, wantedStack string
if strings.Contains(p.Service, "/") {
parts := strings.SplitN(p.Service, "/", 2)
wantedStack = parts[0]
wantedService = parts[1]
} else {
wantedService = p.Service
}
rancher, err := client.NewRancherClient(&client.ClientOpts{
Url: p.URL,
AccessKey: p.Key,
SecretKey: p.Secret,
})
if err != nil {
return fmt.Errorf("Failed to create rancher client: %s", err)
}
// Prepare service filters for service listing
serviceFilters := map[string]interface{}{"name": wantedService}
// Query stacks with filter name=wantedStack
if wantedStack != "" {
stacks, err := rancher.Stack.List(&client.ListOpts{Filters: map[string]interface{}{"name": wantedStack}})
if err != nil {
return fmt.Errorf("Failed to list rancher environments: %s", err)
}
if len(stacks.Data) <= 0 {
return fmt.Errorf("Unable to find stack %s", wantedStack)
}
// If found add stackID to serviceFilters
serviceFilters["stackId"] = stacks.Data[0].Id
}
// Query services with prepared filters
services, err := rancher.Service.List(&client.ListOpts{Filters: serviceFilters})
if err != nil {
return fmt.Errorf("Failed to list rancher services: %s", err)
}
if len(services.Data) <= 0 {
return fmt.Errorf("Unable to find service %s", p.Service)
}
service := services.Data[0]
// Service is found, proceed with upgrade
// We want to exit if there is no docker image updates
if p.DockerImage == "" && len(p.SidekickDockerImage) <= 0 {
return fmt.Errorf("Nothing to upgrade")
}
// Only change value if it's not null.
if p.DockerImage != "" {
// Add prefix when missing to meet Rancher API requirement
service.LaunchConfig.ImageUuid = prepareDockerPrefix(p.DockerImage)
}
// Iterate over provided sidekick flags
for _, sidekick := range p.SidekickDockerImage {
// Split flag in two from "--sidekick nginx nginx:latest"
parts := strings.SplitN(sidekick, " ", 2)
wantedSidekick := parts[0]
wantedImage := parts[1]
for i, s := range service.SecondaryLaunchConfigs {
if wantedSidekick == s.Name {
service.SecondaryLaunchConfigs[i].ImageUuid = prepareDockerPrefix(wantedImage)
}
}
}
upgrade := &client.ServiceUpgrade{}
upgrade.InServiceStrategy = &client.InServiceUpgradeStrategy{
LaunchConfig: service.LaunchConfig,
SecondaryLaunchConfigs: service.SecondaryLaunchConfigs,
StartFirst: p.StartFirst,
IntervalMillis: p.IntervalMillis,
BatchSize: p.BatchSize,
}
upgrade.ToServiceStrategy = &client.ToServiceUpgradeStrategy{}
_, err = rancher.Service.ActionUpgrade(&service, upgrade)
if err != nil {
return fmt.Errorf("Unable to upgrade service %s: %s", p.Service, err)
}
if p.Confirm {
srv, err := retry(func() (interface{}, error) {
s, e := rancher.Service.ById(service.Id)
if e != nil {
return nil, e
}
if s.State != "upgraded" {
return nil, fmt.Errorf("Service not upgraded: %s", s.State)
}
return s, nil
}, time.Duration(p.Timeout)*time.Second, 3*time.Second)
if err != nil {
return fmt.Errorf("Error waiting for service upgrade to complete: %s", err)
}
_, err = rancher.Service.ActionFinishupgrade(srv.(*client.Service))
if err != nil {
return fmt.Errorf("Unable to finish upgrade %s: %s", p.Service, err)
}
log.Infof("Finished upgrade %s", p.Service)
}
log.Infof("Upgraded %s to %s", p.Service, p.DockerImage)
return nil
}
type retryFunc func() (interface{}, error)
func prepareDockerPrefix(image string) string {
if !strings.HasPrefix(image, "docker:") {
image = fmt.Sprintf("docker:%s", image)
}
return image
}
func retry(f retryFunc, timeout time.Duration, interval time.Duration) (interface{}, error) {
finish := time.After(timeout)
for {
result, err := f()
if err == nil {
return result, nil
}
select {
case <-finish:
return nil, err
case <-time.After(interval):
}
}
}
+7
View File
@@ -0,0 +1,7 @@
vendors:
- path: github.com/drone/drone-go
rev: eaa41f7836a191224ec5702d2458db07882ec269
- path: github.com/gorilla/websocket
rev: a68708917c6a4f06314ab4e52493cc61359c9d42
- path: github.com/rancher/go-rancher
rev: 6f68a5fa617dca7db1a509c2a789c1fffaca7b19
-66
View File
@@ -1,66 +0,0 @@
# 0.10.0
* feature: Add a test hook (#180)
* feature: `ParseLevel` is now case-insensitive (#326)
* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308)
* performance: avoid re-allocations on `WithFields` (#335)
# 0.9.0
* logrus/text_formatter: don't emit empty msg
* logrus/hooks/airbrake: move out of main repository
* logrus/hooks/sentry: move out of main repository
* logrus/hooks/papertrail: move out of main repository
* logrus/hooks/bugsnag: move out of main repository
* logrus/core: run tests with `-race`
* logrus/core: detect TTY based on `stderr`
* logrus/core: support `WithError` on logger
* logrus/core: Solaris support
# 0.8.7
* logrus/core: fix possible race (#216)
* logrus/doc: small typo fixes and doc improvements
# 0.8.6
* hooks/raven: allow passing an initialized client
# 0.8.5
* logrus/core: revert #208
# 0.8.4
* formatter/text: fix data race (#218)
# 0.8.3
* logrus/core: fix entry log level (#208)
* logrus/core: improve performance of text formatter by 40%
* logrus/core: expose `LevelHooks` type
* logrus/core: add support for DragonflyBSD and NetBSD
* formatter/text: print structs more verbosely
# 0.8.2
* logrus: fix more Fatal family functions
# 0.8.1
* logrus: fix not exiting on `Fatalf` and `Fatalln`
# 0.8.0
* logrus: defaults to stderr instead of stdout
* hooks/sentry: add special field for `*http.Request`
* formatter/text: ignore Windows for colors
# 0.7.3
* formatter/\*: allow configuration of timestamp layout
# 0.7.2
* formatter/text: Add configuration option for time format (#158)
-21
View File
@@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2014 Simon Eskildsen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-388
View File
@@ -1,388 +0,0 @@
# Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/>&nbsp;[![Build Status](https://travis-ci.org/Sirupsen/logrus.svg?branch=master)](https://travis-ci.org/Sirupsen/logrus)&nbsp;[![GoDoc](https://godoc.org/github.com/Sirupsen/logrus?status.svg)](https://godoc.org/github.com/Sirupsen/logrus)
Logrus is a structured logger for Go (golang), completely API compatible with
the standard library logger. [Godoc][godoc]. **Please note the Logrus API is not
yet stable (pre 1.0). Logrus itself is completely stable and has been used in
many large deployments. The core API is unlikely to change much but please
version control your Logrus to make sure you aren't fetching latest `master` on
every build.**
Nicely color-coded in development (when a TTY is attached, otherwise just
plain text):
![Colored](http://i.imgur.com/PY7qMwd.png)
With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash
or Splunk:
```json
{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the
ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"}
{"level":"warning","msg":"The group's number increased tremendously!",
"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"}
{"animal":"walrus","level":"info","msg":"A giant walrus appears!",
"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"}
{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.",
"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"}
{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,
"time":"2014-03-10 19:57:38.562543128 -0400 EDT"}
```
With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not
attached, the output is compatible with the
[logfmt](http://godoc.org/github.com/kr/logfmt) format:
```text
time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8
time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true
time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4
time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009
time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true
exit status 1
```
#### Example
The simplest way to use Logrus is simply the package-level exported logger:
```go
package main
import (
log "github.com/Sirupsen/logrus"
)
func main() {
log.WithFields(log.Fields{
"animal": "walrus",
}).Info("A walrus appears")
}
```
Note that it's completely api-compatible with the stdlib logger, so you can
replace your `log` imports everywhere with `log "github.com/Sirupsen/logrus"`
and you'll now have the flexibility of Logrus. You can customize it all you
want:
```go
package main
import (
"os"
log "github.com/Sirupsen/logrus"
)
func init() {
// Log as JSON instead of the default ASCII formatter.
log.SetFormatter(&log.JSONFormatter{})
// Output to stderr instead of stdout, could also be a file.
log.SetOutput(os.Stderr)
// Only log the warning severity or above.
log.SetLevel(log.WarnLevel)
}
func main() {
log.WithFields(log.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
log.WithFields(log.Fields{
"omg": true,
"number": 122,
}).Warn("The group's number increased tremendously!")
log.WithFields(log.Fields{
"omg": true,
"number": 100,
}).Fatal("The ice breaks!")
// A common pattern is to re-use fields between logging statements by re-using
// the logrus.Entry returned from WithFields()
contextLogger := log.WithFields(log.Fields{
"common": "this is a common field",
"other": "I also should be logged always",
})
contextLogger.Info("I'll be logged with common and other field")
contextLogger.Info("Me too")
}
```
For more advanced usage such as logging to multiple locations from the same
application, you can also create an instance of the `logrus` Logger:
```go
package main
import (
"github.com/Sirupsen/logrus"
)
// Create a new instance of the logger. You can have any number of instances.
var log = logrus.New()
func main() {
// The API for setting attributes is a little different than the package level
// exported logger. See Godoc.
log.Out = os.Stderr
log.WithFields(logrus.Fields{
"animal": "walrus",
"size": 10,
}).Info("A group of walrus emerges from the ocean")
}
```
#### Fields
Logrus encourages careful, structured logging though logging fields instead of
long, unparseable error messages. For example, instead of: `log.Fatalf("Failed
to send event %s to topic %s with key %d")`, you should log the much more
discoverable:
```go
log.WithFields(log.Fields{
"event": event,
"topic": topic,
"key": key,
}).Fatal("Failed to send event")
```
We've found this API forces you to think about logging in a way that produces
much more useful logging messages. We've been in countless situations where just
a single added field to a log statement that was already there would've saved us
hours. The `WithFields` call is optional.
In general, with Logrus using any of the `printf`-family functions should be
seen as a hint you should add a field, however, you can still use the
`printf`-family functions with Logrus.
#### Hooks
You can add hooks for logging levels. For example to send errors to an exception
tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to
multiple places simultaneously, e.g. syslog.
Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in
`init`:
```go
import (
log "github.com/Sirupsen/logrus"
"gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "aibrake"
logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog"
"log/syslog"
)
func init() {
// Use the Airbrake hook to report errors that have Error severity or above to
// an exception tracker. You can create custom hooks, see the Hooks section.
log.AddHook(airbrake.NewHook(123, "xyz", "production"))
hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
if err != nil {
log.Error("Unable to connect to local syslog daemon")
} else {
log.AddHook(hook)
}
}
```
Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md).
| Hook | Description |
| ----- | ----------- |
| [Airbrake](https://github.com/gemnasium/logrus-airbrake-hook) | Send errors to the Airbrake API V3. Uses the official [`gobrake`](https://github.com/airbrake/gobrake) behind the scenes. |
| [Airbrake "legacy"](https://github.com/gemnasium/logrus-airbrake-legacy-hook) | Send errors to an exception tracking service compatible with the Airbrake API V2. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. |
| [Papertrail](https://github.com/polds/logrus-papertrail-hook) | Send errors to the [Papertrail](https://papertrailapp.com) hosted logging service via UDP. |
| [Syslog](https://github.com/Sirupsen/logrus/blob/master/hooks/syslog/syslog.go) | Send errors to remote syslog server. Uses standard library `log/syslog` behind the scenes. |
| [Bugsnag](https://github.com/Shopify/logrus-bugsnag/blob/master/bugsnag.go) | Send errors to the Bugsnag exception tracking service. |
| [Sentry](https://github.com/evalphobia/logrus_sentry) | Send errors to the Sentry error logging and aggregation service. |
| [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. |
| [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) |
| [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. |
| [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` |
| [Graylog](https://github.com/gemnasium/logrus-graylog-hook) | Hook for logging to [Graylog](http://graylog2.org/) |
| [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) |
| [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem |
| [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger |
| [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail |
| [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar |
| [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd |
| [Mongodb](https://github.com/weekface/mgorus) | Hook for logging to mongodb |
| [InfluxDB](https://github.com/Abramovic/logrus_influxdb) | Hook for logging to influxdb |
| [Octokit](https://github.com/dorajistyle/logrus-octokit-hook) | Hook for logging to github via octokit |
| [DeferPanic](https://github.com/deferpanic/dp-logrus) | Hook for logging to DeferPanic |
| [Redis-Hook](https://github.com/rogierlommers/logrus-redis-hook) | Hook for logging to a ELK stack (through Redis) |
| [Amqp-Hook](https://github.com/vladoatanasov/logrus_amqp) | Hook for logging to Amqp broker (Like RabbitMQ) |
| [KafkaLogrus](https://github.com/goibibo/KafkaLogrus) | Hook for logging to kafka |
| [Typetalk](https://github.com/dragon3/logrus-typetalk-hook) | Hook for logging to [Typetalk](https://www.typetalk.in/) |
| [ElasticSearch](https://github.com/sohlich/elogrus) | Hook for logging to ElasticSearch|
#### Level logging
Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic.
```go
log.Debug("Useful debugging information.")
log.Info("Something noteworthy happened!")
log.Warn("You should probably take a look at this.")
log.Error("Something failed but I'm not quitting.")
// Calls os.Exit(1) after logging
log.Fatal("Bye.")
// Calls panic() after logging
log.Panic("I'm bailing.")
```
You can set the logging level on a `Logger`, then it will only log entries with
that severity or anything above it:
```go
// Will log anything that is info or above (warn, error, fatal, panic). Default.
log.SetLevel(log.InfoLevel)
```
It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose
environment if your application has that.
#### Entries
Besides the fields added with `WithField` or `WithFields` some fields are
automatically added to all logging events:
1. `time`. The timestamp when the entry was created.
2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after
the `AddFields` call. E.g. `Failed to send event.`
3. `level`. The logging level. E.g. `info`.
#### Environments
Logrus has no notion of environment.
If you wish for hooks and formatters to only be used in specific environments,
you should handle that yourself. For example, if your application has a global
variable `Environment`, which is a string representation of the environment you
could do:
```go
import (
log "github.com/Sirupsen/logrus"
)
init() {
// do something here to set environment depending on an environment variable
// or command-line flag
if Environment == "production" {
log.SetFormatter(&log.JSONFormatter{})
} else {
// The TextFormatter is default, you don't actually have to do this.
log.SetFormatter(&log.TextFormatter{})
}
}
```
This configuration is how `logrus` was intended to be used, but JSON in
production is mostly only useful if you do log aggregation with tools like
Splunk or Logstash.
#### Formatters
The built-in logging formatters are:
* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise
without colors.
* *Note:* to force colored output when there is no TTY, set the `ForceColors`
field to `true`. To force no colored output even if there is a TTY set the
`DisableColors` field to `true`
* `logrus.JSONFormatter`. Logs fields as JSON.
* `logrus/formatters/logstash.LogstashFormatter`. Logs fields as [Logstash](http://logstash.net) Events.
```go
logrus.SetFormatter(&logstash.LogstashFormatter{Type: "application_name"})
```
Third party logging formatters:
* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout.
* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦.
You can define your formatter by implementing the `Formatter` interface,
requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a
`Fields` type (`map[string]interface{}`) with all your fields as well as the
default ones (see Entries section above):
```go
type MyJSONFormatter struct {
}
log.SetFormatter(new(MyJSONFormatter))
func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
// Note this doesn't include Time, Level and Message which are available on
// the Entry. Consult `godoc` on information about those fields or read the
// source of the official loggers.
serialized, err := json.Marshal(entry.Data)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
return append(serialized, '\n'), nil
}
```
#### Logger as an `io.Writer`
Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it.
```go
w := logger.Writer()
defer w.Close()
srv := http.Server{
// create a stdlib log.Logger that writes to
// logrus.Logger.
ErrorLog: log.New(w, "", 0),
}
```
Each line written to that writer will be printed the usual way, using formatters
and hooks. The level for those entries is `info`.
#### Rotation
Log rotation is not provided with Logrus. Log rotation should be done by an
external program (like `logrotate(8)`) that can compress and delete old log
entries. It should not be a feature of the application-level logger.
#### Tools
| Tool | Description |
| ---- | ----------- |
|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.|
#### Testing
Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides:
* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook
* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any):
```go
logger, hook := NewNullLogger()
logger.Error("Hello error")
assert.Equal(1, len(hook.Entries))
assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
assert.Equal("Hello error", hook.LastEntry().Message)
hook.Reset()
assert.Nil(hook.LastEntry())
```
-26
View File
@@ -1,26 +0,0 @@
/*
Package logrus is a structured logger for Go, completely API compatible with the standard library logger.
The simplest way to use Logrus is simply the package-level exported logger:
package main
import (
log "github.com/Sirupsen/logrus"
)
func main() {
log.WithFields(log.Fields{
"animal": "walrus",
"number": 1,
"size": 10,
}).Info("A walrus appears")
}
Output:
time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10
For a full guide visit https://github.com/Sirupsen/logrus
*/
package logrus
-264
View File
@@ -1,264 +0,0 @@
package logrus
import (
"bytes"
"fmt"
"io"
"os"
"time"
)
// Defines the key when adding errors using WithError.
var ErrorKey = "error"
// An entry is the final or intermediate Logrus logging entry. It contains all
// the fields passed with WithField{,s}. It's finally logged when Debug, Info,
// Warn, Error, Fatal or Panic is called on it. These objects can be reused and
// passed around as much as you wish to avoid field duplication.
type Entry struct {
Logger *Logger
// Contains all the fields set by the user.
Data Fields
// Time at which the log entry was created
Time time.Time
// Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic
Level Level
// Message passed to Debug, Info, Warn, Error, Fatal or Panic
Message string
}
func NewEntry(logger *Logger) *Entry {
return &Entry{
Logger: logger,
// Default is three fields, give a little extra room
Data: make(Fields, 5),
}
}
// Returns a reader for the entry, which is a proxy to the formatter.
func (entry *Entry) Reader() (*bytes.Buffer, error) {
serialized, err := entry.Logger.Formatter.Format(entry)
return bytes.NewBuffer(serialized), err
}
// Returns the string representation from the reader and ultimately the
// formatter.
func (entry *Entry) String() (string, error) {
reader, err := entry.Reader()
if err != nil {
return "", err
}
return reader.String(), err
}
// Add an error as single field (using the key defined in ErrorKey) to the Entry.
func (entry *Entry) WithError(err error) *Entry {
return entry.WithField(ErrorKey, err)
}
// Add a single field to the Entry.
func (entry *Entry) WithField(key string, value interface{}) *Entry {
return entry.WithFields(Fields{key: value})
}
// Add a map of fields to the Entry.
func (entry *Entry) WithFields(fields Fields) *Entry {
data := make(Fields, len(entry.Data)+len(fields))
for k, v := range entry.Data {
data[k] = v
}
for k, v := range fields {
data[k] = v
}
return &Entry{Logger: entry.Logger, Data: data}
}
// This function is not declared with a pointer value because otherwise
// race conditions will occur when using multiple goroutines
func (entry Entry) log(level Level, msg string) {
entry.Time = time.Now()
entry.Level = level
entry.Message = msg
if err := entry.Logger.Hooks.Fire(level, &entry); err != nil {
entry.Logger.mu.Lock()
fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
entry.Logger.mu.Unlock()
}
reader, err := entry.Reader()
if err != nil {
entry.Logger.mu.Lock()
fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
entry.Logger.mu.Unlock()
}
entry.Logger.mu.Lock()
defer entry.Logger.mu.Unlock()
_, err = io.Copy(entry.Logger.Out, reader)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
}
// To avoid Entry#log() returning a value that only would make sense for
// panic() to use in Entry#Panic(), we avoid the allocation by checking
// directly here.
if level <= PanicLevel {
panic(&entry)
}
}
func (entry *Entry) Debug(args ...interface{}) {
if entry.Logger.Level >= DebugLevel {
entry.log(DebugLevel, fmt.Sprint(args...))
}
}
func (entry *Entry) Print(args ...interface{}) {
entry.Info(args...)
}
func (entry *Entry) Info(args ...interface{}) {
if entry.Logger.Level >= InfoLevel {
entry.log(InfoLevel, fmt.Sprint(args...))
}
}
func (entry *Entry) Warn(args ...interface{}) {
if entry.Logger.Level >= WarnLevel {
entry.log(WarnLevel, fmt.Sprint(args...))
}
}
func (entry *Entry) Warning(args ...interface{}) {
entry.Warn(args...)
}
func (entry *Entry) Error(args ...interface{}) {
if entry.Logger.Level >= ErrorLevel {
entry.log(ErrorLevel, fmt.Sprint(args...))
}
}
func (entry *Entry) Fatal(args ...interface{}) {
if entry.Logger.Level >= FatalLevel {
entry.log(FatalLevel, fmt.Sprint(args...))
}
os.Exit(1)
}
func (entry *Entry) Panic(args ...interface{}) {
if entry.Logger.Level >= PanicLevel {
entry.log(PanicLevel, fmt.Sprint(args...))
}
panic(fmt.Sprint(args...))
}
// Entry Printf family functions
func (entry *Entry) Debugf(format string, args ...interface{}) {
if entry.Logger.Level >= DebugLevel {
entry.Debug(fmt.Sprintf(format, args...))
}
}
func (entry *Entry) Infof(format string, args ...interface{}) {
if entry.Logger.Level >= InfoLevel {
entry.Info(fmt.Sprintf(format, args...))
}
}
func (entry *Entry) Printf(format string, args ...interface{}) {
entry.Infof(format, args...)
}
func (entry *Entry) Warnf(format string, args ...interface{}) {
if entry.Logger.Level >= WarnLevel {
entry.Warn(fmt.Sprintf(format, args...))
}
}
func (entry *Entry) Warningf(format string, args ...interface{}) {
entry.Warnf(format, args...)
}
func (entry *Entry) Errorf(format string, args ...interface{}) {
if entry.Logger.Level >= ErrorLevel {
entry.Error(fmt.Sprintf(format, args...))
}
}
func (entry *Entry) Fatalf(format string, args ...interface{}) {
if entry.Logger.Level >= FatalLevel {
entry.Fatal(fmt.Sprintf(format, args...))
}
os.Exit(1)
}
func (entry *Entry) Panicf(format string, args ...interface{}) {
if entry.Logger.Level >= PanicLevel {
entry.Panic(fmt.Sprintf(format, args...))
}
}
// Entry Println family functions
func (entry *Entry) Debugln(args ...interface{}) {
if entry.Logger.Level >= DebugLevel {
entry.Debug(entry.sprintlnn(args...))
}
}
func (entry *Entry) Infoln(args ...interface{}) {
if entry.Logger.Level >= InfoLevel {
entry.Info(entry.sprintlnn(args...))
}
}
func (entry *Entry) Println(args ...interface{}) {
entry.Infoln(args...)
}
func (entry *Entry) Warnln(args ...interface{}) {
if entry.Logger.Level >= WarnLevel {
entry.Warn(entry.sprintlnn(args...))
}
}
func (entry *Entry) Warningln(args ...interface{}) {
entry.Warnln(args...)
}
func (entry *Entry) Errorln(args ...interface{}) {
if entry.Logger.Level >= ErrorLevel {
entry.Error(entry.sprintlnn(args...))
}
}
func (entry *Entry) Fatalln(args ...interface{}) {
if entry.Logger.Level >= FatalLevel {
entry.Fatal(entry.sprintlnn(args...))
}
os.Exit(1)
}
func (entry *Entry) Panicln(args ...interface{}) {
if entry.Logger.Level >= PanicLevel {
entry.Panic(entry.sprintlnn(args...))
}
}
// Sprintlnn => Sprint no newline. This is to get the behavior of how
// fmt.Sprintln where spaces are always added between operands, regardless of
// their type. Instead of vendoring the Sprintln implementation to spare a
// string allocation, we do the simplest thing.
func (entry *Entry) sprintlnn(args ...interface{}) string {
msg := fmt.Sprintln(args...)
return msg[:len(msg)-1]
}
-193
View File
@@ -1,193 +0,0 @@
package logrus
import (
"io"
)
var (
// std is the name of the standard logger in stdlib `log`
std = New()
)
func StandardLogger() *Logger {
return std
}
// SetOutput sets the standard logger output.
func SetOutput(out io.Writer) {
std.mu.Lock()
defer std.mu.Unlock()
std.Out = out
}
// SetFormatter sets the standard logger formatter.
func SetFormatter(formatter Formatter) {
std.mu.Lock()
defer std.mu.Unlock()
std.Formatter = formatter
}
// SetLevel sets the standard logger level.
func SetLevel(level Level) {
std.mu.Lock()
defer std.mu.Unlock()
std.Level = level
}
// GetLevel returns the standard logger level.
func GetLevel() Level {
std.mu.Lock()
defer std.mu.Unlock()
return std.Level
}
// AddHook adds a hook to the standard logger hooks.
func AddHook(hook Hook) {
std.mu.Lock()
defer std.mu.Unlock()
std.Hooks.Add(hook)
}
// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.
func WithError(err error) *Entry {
return std.WithField(ErrorKey, err)
}
// WithField creates an entry from the standard logger and adds a field to
// it. If you want multiple fields, use `WithFields`.
//
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
// or Panic on the Entry it returns.
func WithField(key string, value interface{}) *Entry {
return std.WithField(key, value)
}
// WithFields creates an entry from the standard logger and adds multiple
// fields to it. This is simply a helper for `WithField`, invoking it
// once for each field.
//
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
// or Panic on the Entry it returns.
func WithFields(fields Fields) *Entry {
return std.WithFields(fields)
}
// Debug logs a message at level Debug on the standard logger.
func Debug(args ...interface{}) {
std.Debug(args...)
}
// Print logs a message at level Info on the standard logger.
func Print(args ...interface{}) {
std.Print(args...)
}
// Info logs a message at level Info on the standard logger.
func Info(args ...interface{}) {
std.Info(args...)
}
// Warn logs a message at level Warn on the standard logger.
func Warn(args ...interface{}) {
std.Warn(args...)
}
// Warning logs a message at level Warn on the standard logger.
func Warning(args ...interface{}) {
std.Warning(args...)
}
// Error logs a message at level Error on the standard logger.
func Error(args ...interface{}) {
std.Error(args...)
}
// Panic logs a message at level Panic on the standard logger.
func Panic(args ...interface{}) {
std.Panic(args...)
}
// Fatal logs a message at level Fatal on the standard logger.
func Fatal(args ...interface{}) {
std.Fatal(args...)
}
// Debugf logs a message at level Debug on the standard logger.
func Debugf(format string, args ...interface{}) {
std.Debugf(format, args...)
}
// Printf logs a message at level Info on the standard logger.
func Printf(format string, args ...interface{}) {
std.Printf(format, args...)
}
// Infof logs a message at level Info on the standard logger.
func Infof(format string, args ...interface{}) {
std.Infof(format, args...)
}
// Warnf logs a message at level Warn on the standard logger.
func Warnf(format string, args ...interface{}) {
std.Warnf(format, args...)
}
// Warningf logs a message at level Warn on the standard logger.
func Warningf(format string, args ...interface{}) {
std.Warningf(format, args...)
}
// Errorf logs a message at level Error on the standard logger.
func Errorf(format string, args ...interface{}) {
std.Errorf(format, args...)
}
// Panicf logs a message at level Panic on the standard logger.
func Panicf(format string, args ...interface{}) {
std.Panicf(format, args...)
}
// Fatalf logs a message at level Fatal on the standard logger.
func Fatalf(format string, args ...interface{}) {
std.Fatalf(format, args...)
}
// Debugln logs a message at level Debug on the standard logger.
func Debugln(args ...interface{}) {
std.Debugln(args...)
}
// Println logs a message at level Info on the standard logger.
func Println(args ...interface{}) {
std.Println(args...)
}
// Infoln logs a message at level Info on the standard logger.
func Infoln(args ...interface{}) {
std.Infoln(args...)
}
// Warnln logs a message at level Warn on the standard logger.
func Warnln(args ...interface{}) {
std.Warnln(args...)
}
// Warningln logs a message at level Warn on the standard logger.
func Warningln(args ...interface{}) {
std.Warningln(args...)
}
// Errorln logs a message at level Error on the standard logger.
func Errorln(args ...interface{}) {
std.Errorln(args...)
}
// Panicln logs a message at level Panic on the standard logger.
func Panicln(args ...interface{}) {
std.Panicln(args...)
}
// Fatalln logs a message at level Fatal on the standard logger.
func Fatalln(args ...interface{}) {
std.Fatalln(args...)
}
-48
View File
@@ -1,48 +0,0 @@
package logrus
import "time"
const DefaultTimestampFormat = time.RFC3339
// The Formatter interface is used to implement a custom Formatter. It takes an
// `Entry`. It exposes all the fields, including the default ones:
//
// * `entry.Data["msg"]`. The message passed from Info, Warn, Error ..
// * `entry.Data["time"]`. The timestamp.
// * `entry.Data["level"]. The level the entry was logged at.
//
// Any additional fields added with `WithField` or `WithFields` are also in
// `entry.Data`. Format is expected to return an array of bytes which are then
// logged to `logger.Out`.
type Formatter interface {
Format(*Entry) ([]byte, error)
}
// This is to not silently overwrite `time`, `msg` and `level` fields when
// dumping it. If this code wasn't there doing:
//
// logrus.WithField("level", 1).Info("hello")
//
// Would just silently drop the user provided level. Instead with this code
// it'll logged as:
//
// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."}
//
// It's not exported because it's still using Data in an opinionated way. It's to
// avoid code duplication between the two default formatters.
func prefixFieldClashes(data Fields) {
_, ok := data["time"]
if ok {
data["fields.time"] = data["time"]
}
_, ok = data["msg"]
if ok {
data["fields.msg"] = data["msg"]
}
_, ok = data["level"]
if ok {
data["fields.level"] = data["level"]
}
}
-34
View File
@@ -1,34 +0,0 @@
package logrus
// A hook to be fired when logging on the logging levels returned from
// `Levels()` on your implementation of the interface. Note that this is not
// fired in a goroutine or a channel with workers, you should handle such
// functionality yourself if your call is non-blocking and you don't wish for
// the logging calls for levels returned from `Levels()` to block.
type Hook interface {
Levels() []Level
Fire(*Entry) error
}
// Internal type for storing the hooks on a logger instance.
type LevelHooks map[Level][]Hook
// Add a hook to an instance of logger. This is called with
// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface.
func (hooks LevelHooks) Add(hook Hook) {
for _, level := range hook.Levels() {
hooks[level] = append(hooks[level], hook)
}
}
// Fire all the hooks for the passed level. Used by `entry.log` to fire
// appropriate hooks for a log entry.
func (hooks LevelHooks) Fire(level Level, entry *Entry) error {
for _, hook := range hooks[level] {
if err := hook.Fire(entry); err != nil {
return err
}
}
return nil
}
-41
View File
@@ -1,41 +0,0 @@
package logrus
import (
"encoding/json"
"fmt"
)
type JSONFormatter struct {
// TimestampFormat sets the format used for marshaling timestamps.
TimestampFormat string
}
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
data := make(Fields, len(entry.Data)+3)
for k, v := range entry.Data {
switch v := v.(type) {
case error:
// Otherwise errors are ignored by `encoding/json`
// https://github.com/Sirupsen/logrus/issues/137
data[k] = v.Error()
default:
data[k] = v
}
}
prefixFieldClashes(data)
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
timestampFormat = DefaultTimestampFormat
}
data["time"] = entry.Time.Format(timestampFormat)
data["msg"] = entry.Message
data["level"] = entry.Level.String()
serialized, err := json.Marshal(data)
if err != nil {
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
}
return append(serialized, '\n'), nil
}
-212
View File
@@ -1,212 +0,0 @@
package logrus
import (
"io"
"os"
"sync"
)
type Logger struct {
// The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
// file, or leave it default which is `os.Stderr`. You can also set this to
// something more adventorous, such as logging to Kafka.
Out io.Writer
// Hooks for the logger instance. These allow firing events based on logging
// levels and log entries. For example, to send errors to an error tracking
// service, log to StatsD or dump the core on fatal errors.
Hooks LevelHooks
// All log entries pass through the formatter before logged to Out. The
// included formatters are `TextFormatter` and `JSONFormatter` for which
// TextFormatter is the default. In development (when a TTY is attached) it
// logs with colors, but to a file it wouldn't. You can easily implement your
// own that implements the `Formatter` interface, see the `README` or included
// formatters for examples.
Formatter Formatter
// The logging level the logger should log at. This is typically (and defaults
// to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
// logged. `logrus.Debug` is useful in
Level Level
// Used to sync writing to the log.
mu sync.Mutex
}
// Creates a new logger. Configuration should be set by changing `Formatter`,
// `Out` and `Hooks` directly on the default logger instance. You can also just
// instantiate your own:
//
// var log = &Logger{
// Out: os.Stderr,
// Formatter: new(JSONFormatter),
// Hooks: make(LevelHooks),
// Level: logrus.DebugLevel,
// }
//
// It's recommended to make this a global instance called `log`.
func New() *Logger {
return &Logger{
Out: os.Stderr,
Formatter: new(TextFormatter),
Hooks: make(LevelHooks),
Level: InfoLevel,
}
}
// Adds a field to the log entry, note that you it doesn't log until you call
// Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry.
// If you want multiple fields, use `WithFields`.
func (logger *Logger) WithField(key string, value interface{}) *Entry {
return NewEntry(logger).WithField(key, value)
}
// Adds a struct of fields to the log entry. All it does is call `WithField` for
// each `Field`.
func (logger *Logger) WithFields(fields Fields) *Entry {
return NewEntry(logger).WithFields(fields)
}
// Add an error as single field to the log entry. All it does is call
// `WithError` for the given `error`.
func (logger *Logger) WithError(err error) *Entry {
return NewEntry(logger).WithError(err)
}
func (logger *Logger) Debugf(format string, args ...interface{}) {
if logger.Level >= DebugLevel {
NewEntry(logger).Debugf(format, args...)
}
}
func (logger *Logger) Infof(format string, args ...interface{}) {
if logger.Level >= InfoLevel {
NewEntry(logger).Infof(format, args...)
}
}
func (logger *Logger) Printf(format string, args ...interface{}) {
NewEntry(logger).Printf(format, args...)
}
func (logger *Logger) Warnf(format string, args ...interface{}) {
if logger.Level >= WarnLevel {
NewEntry(logger).Warnf(format, args...)
}
}
func (logger *Logger) Warningf(format string, args ...interface{}) {
if logger.Level >= WarnLevel {
NewEntry(logger).Warnf(format, args...)
}
}
func (logger *Logger) Errorf(format string, args ...interface{}) {
if logger.Level >= ErrorLevel {
NewEntry(logger).Errorf(format, args...)
}
}
func (logger *Logger) Fatalf(format string, args ...interface{}) {
if logger.Level >= FatalLevel {
NewEntry(logger).Fatalf(format, args...)
}
os.Exit(1)
}
func (logger *Logger) Panicf(format string, args ...interface{}) {
if logger.Level >= PanicLevel {
NewEntry(logger).Panicf(format, args...)
}
}
func (logger *Logger) Debug(args ...interface{}) {
if logger.Level >= DebugLevel {
NewEntry(logger).Debug(args...)
}
}
func (logger *Logger) Info(args ...interface{}) {
if logger.Level >= InfoLevel {
NewEntry(logger).Info(args...)
}
}
func (logger *Logger) Print(args ...interface{}) {
NewEntry(logger).Info(args...)
}
func (logger *Logger) Warn(args ...interface{}) {
if logger.Level >= WarnLevel {
NewEntry(logger).Warn(args...)
}
}
func (logger *Logger) Warning(args ...interface{}) {
if logger.Level >= WarnLevel {
NewEntry(logger).Warn(args...)
}
}
func (logger *Logger) Error(args ...interface{}) {
if logger.Level >= ErrorLevel {
NewEntry(logger).Error(args...)
}
}
func (logger *Logger) Fatal(args ...interface{}) {
if logger.Level >= FatalLevel {
NewEntry(logger).Fatal(args...)
}
os.Exit(1)
}
func (logger *Logger) Panic(args ...interface{}) {
if logger.Level >= PanicLevel {
NewEntry(logger).Panic(args...)
}
}
func (logger *Logger) Debugln(args ...interface{}) {
if logger.Level >= DebugLevel {
NewEntry(logger).Debugln(args...)
}
}
func (logger *Logger) Infoln(args ...interface{}) {
if logger.Level >= InfoLevel {
NewEntry(logger).Infoln(args...)
}
}
func (logger *Logger) Println(args ...interface{}) {
NewEntry(logger).Println(args...)
}
func (logger *Logger) Warnln(args ...interface{}) {
if logger.Level >= WarnLevel {
NewEntry(logger).Warnln(args...)
}
}
func (logger *Logger) Warningln(args ...interface{}) {
if logger.Level >= WarnLevel {
NewEntry(logger).Warnln(args...)
}
}
func (logger *Logger) Errorln(args ...interface{}) {
if logger.Level >= ErrorLevel {
NewEntry(logger).Errorln(args...)
}
}
func (logger *Logger) Fatalln(args ...interface{}) {
if logger.Level >= FatalLevel {
NewEntry(logger).Fatalln(args...)
}
os.Exit(1)
}
func (logger *Logger) Panicln(args ...interface{}) {
if logger.Level >= PanicLevel {
NewEntry(logger).Panicln(args...)
}
}
-143
View File
@@ -1,143 +0,0 @@
package logrus
import (
"fmt"
"log"
"strings"
)
// Fields type, used to pass to `WithFields`.
type Fields map[string]interface{}
// Level type
type Level uint8
// Convert the Level to a string. E.g. PanicLevel becomes "panic".
func (level Level) String() string {
switch level {
case DebugLevel:
return "debug"
case InfoLevel:
return "info"
case WarnLevel:
return "warning"
case ErrorLevel:
return "error"
case FatalLevel:
return "fatal"
case PanicLevel:
return "panic"
}
return "unknown"
}
// ParseLevel takes a string level and returns the Logrus log level constant.
func ParseLevel(lvl string) (Level, error) {
switch strings.ToLower(lvl) {
case "panic":
return PanicLevel, nil
case "fatal":
return FatalLevel, nil
case "error":
return ErrorLevel, nil
case "warn", "warning":
return WarnLevel, nil
case "info":
return InfoLevel, nil
case "debug":
return DebugLevel, nil
}
var l Level
return l, fmt.Errorf("not a valid logrus Level: %q", lvl)
}
// A constant exposing all logging levels
var AllLevels = []Level{
PanicLevel,
FatalLevel,
ErrorLevel,
WarnLevel,
InfoLevel,
DebugLevel,
}
// These are the different logging levels. You can set the logging level to log
// on your instance of logger, obtained with `logrus.New()`.
const (
// PanicLevel level, highest level of severity. Logs and then calls panic with the
// message passed to Debug, Info, ...
PanicLevel Level = iota
// FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the
// logging level is set to Panic.
FatalLevel
// ErrorLevel level. Logs. Used for errors that should definitely be noted.
// Commonly used for hooks to send errors to an error tracking service.
ErrorLevel
// WarnLevel level. Non-critical entries that deserve eyes.
WarnLevel
// InfoLevel level. General operational entries about what's going on inside the
// application.
InfoLevel
// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
DebugLevel
)
// Won't compile if StdLogger can't be realized by a log.Logger
var (
_ StdLogger = &log.Logger{}
_ StdLogger = &Entry{}
_ StdLogger = &Logger{}
)
// StdLogger is what your logrus-enabled library should take, that way
// it'll accept a stdlib logger and a logrus logger. There's no standard
// interface, this is the closest we get, unfortunately.
type StdLogger interface {
Print(...interface{})
Printf(string, ...interface{})
Println(...interface{})
Fatal(...interface{})
Fatalf(string, ...interface{})
Fatalln(...interface{})
Panic(...interface{})
Panicf(string, ...interface{})
Panicln(...interface{})
}
// The FieldLogger interface generalizes the Entry and Logger types
type FieldLogger interface {
WithField(key string, value interface{}) *Entry
WithFields(fields Fields) *Entry
WithError(err error) *Entry
Debugf(format string, args ...interface{})
Infof(format string, args ...interface{})
Printf(format string, args ...interface{})
Warnf(format string, args ...interface{})
Warningf(format string, args ...interface{})
Errorf(format string, args ...interface{})
Fatalf(format string, args ...interface{})
Panicf(format string, args ...interface{})
Debug(args ...interface{})
Info(args ...interface{})
Print(args ...interface{})
Warn(args ...interface{})
Warning(args ...interface{})
Error(args ...interface{})
Fatal(args ...interface{})
Panic(args ...interface{})
Debugln(args ...interface{})
Infoln(args ...interface{})
Println(args ...interface{})
Warnln(args ...interface{})
Warningln(args ...interface{})
Errorln(args ...interface{})
Fatalln(args ...interface{})
Panicln(args ...interface{})
}
-9
View File
@@ -1,9 +0,0 @@
// +build darwin freebsd openbsd netbsd dragonfly
package logrus
import "syscall"
const ioctlReadTermios = syscall.TIOCGETA
type Termios syscall.Termios
-12
View File
@@ -1,12 +0,0 @@
// Based on ssh/terminal:
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package logrus
import "syscall"
const ioctlReadTermios = syscall.TCGETS
type Termios syscall.Termios
-21
View File
@@ -1,21 +0,0 @@
// Based on ssh/terminal:
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build linux darwin freebsd openbsd netbsd dragonfly
package logrus
import (
"syscall"
"unsafe"
)
// IsTerminal returns true if stderr's file descriptor is a terminal.
func IsTerminal() bool {
fd := syscall.Stderr
var termios Termios
_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
return err == 0
}
-15
View File
@@ -1,15 +0,0 @@
// +build solaris
package logrus
import (
"os"
"golang.org/x/sys/unix"
)
// IsTerminal returns true if the given file descriptor is a terminal.
func IsTerminal() bool {
_, err := unix.IoctlGetTermios(int(os.Stdout.Fd()), unix.TCGETA)
return err == nil
}
-27
View File
@@ -1,27 +0,0 @@
// Based on ssh/terminal:
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build windows
package logrus
import (
"syscall"
"unsafe"
)
var kernel32 = syscall.NewLazyDLL("kernel32.dll")
var (
procGetConsoleMode = kernel32.NewProc("GetConsoleMode")
)
// IsTerminal returns true if stderr's file descriptor is a terminal.
func IsTerminal() bool {
fd := syscall.Stderr
var st uint32
r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0)
return r != 0 && e == 0
}
-161
View File
@@ -1,161 +0,0 @@
package logrus
import (
"bytes"
"fmt"
"runtime"
"sort"
"strings"
"time"
)
const (
nocolor = 0
red = 31
green = 32
yellow = 33
blue = 34
gray = 37
)
var (
baseTimestamp time.Time
isTerminal bool
)
func init() {
baseTimestamp = time.Now()
isTerminal = IsTerminal()
}
func miniTS() int {
return int(time.Since(baseTimestamp) / time.Second)
}
type TextFormatter struct {
// Set to true to bypass checking for a TTY before outputting colors.
ForceColors bool
// Force disabling colors.
DisableColors bool
// Disable timestamp logging. useful when output is redirected to logging
// system that already adds timestamps.
DisableTimestamp bool
// Enable logging the full timestamp when a TTY is attached instead of just
// the time passed since beginning of execution.
FullTimestamp bool
// TimestampFormat to use for display when a full timestamp is printed
TimestampFormat string
// The fields are sorted by default for a consistent output. For applications
// that log extremely frequently and don't use the JSON formatter this may not
// be desired.
DisableSorting bool
}
func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
var keys []string = make([]string, 0, len(entry.Data))
for k := range entry.Data {
keys = append(keys, k)
}
if !f.DisableSorting {
sort.Strings(keys)
}
b := &bytes.Buffer{}
prefixFieldClashes(entry.Data)
isColorTerminal := isTerminal && (runtime.GOOS != "windows")
isColored := (f.ForceColors || isColorTerminal) && !f.DisableColors
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
timestampFormat = DefaultTimestampFormat
}
if isColored {
f.printColored(b, entry, keys, timestampFormat)
} else {
if !f.DisableTimestamp {
f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat))
}
f.appendKeyValue(b, "level", entry.Level.String())
if entry.Message != "" {
f.appendKeyValue(b, "msg", entry.Message)
}
for _, key := range keys {
f.appendKeyValue(b, key, entry.Data[key])
}
}
b.WriteByte('\n')
return b.Bytes(), nil
}
func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) {
var levelColor int
switch entry.Level {
case DebugLevel:
levelColor = gray
case WarnLevel:
levelColor = yellow
case ErrorLevel, FatalLevel, PanicLevel:
levelColor = red
default:
levelColor = blue
}
levelText := strings.ToUpper(entry.Level.String())[0:4]
if !f.FullTimestamp {
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, miniTS(), entry.Message)
} else {
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message)
}
for _, k := range keys {
v := entry.Data[k]
fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=%+v", levelColor, k, v)
}
}
func needsQuoting(text string) bool {
for _, ch := range text {
if !((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') ||
ch == '-' || ch == '.') {
return false
}
}
return true
}
func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
b.WriteString(key)
b.WriteByte('=')
switch value := value.(type) {
case string:
if needsQuoting(value) {
b.WriteString(value)
} else {
fmt.Fprintf(b, "%q", value)
}
case error:
errmsg := value.Error()
if needsQuoting(errmsg) {
b.WriteString(errmsg)
} else {
fmt.Fprintf(b, "%q", value)
}
default:
fmt.Fprint(b, value)
}
b.WriteByte(' ')
}
-31
View File
@@ -1,31 +0,0 @@
package logrus
import (
"bufio"
"io"
"runtime"
)
func (logger *Logger) Writer() *io.PipeWriter {
reader, writer := io.Pipe()
go logger.writerScanner(reader)
runtime.SetFinalizer(writer, writerFinalizer)
return writer
}
func (logger *Logger) writerScanner(reader *io.PipeReader) {
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
logger.Print(scanner.Text())
}
if err := scanner.Err(); err != nil {
logger.Errorf("Error while reading from Writer: %s", err)
}
reader.Close()
}
func writerFinalizer(writer *io.PipeWriter) {
writer.Close()
}
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+50
View File
@@ -0,0 +1,50 @@
# drone-go
[![Build Status](http://beta.drone.io/api/badges/drone/drone-go/status.svg)](http://beta.drone.io/drone/drone-go)
drone-go is a Go client library for accessing the Drone [API](http://readme.drone.io/devs/api/builds/) and writing [plugins](http://readme.drone.io/plugins/).
Download the package using `go get`:
```Go
go get "github.com/drone/drone-go/drone"
go get "github.com/drone/drone-go/plugin"
```
Import the package:
```Go
import "github.com/drone/drone-go/drone"
```
Create the client:
```Go
const (
token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
host = "http://drone.company.com"
)
client := drone.NewClientToken(host, token)
```
Get the current user:
```Go
user, err := client.Self()
fmt.Println(user)
```
Get the repository list:
```Go
repos, err := client.RepoList()
fmt.Println(repos)
```
Get the named repository:
```Go
repo, err := client.Repo("drone", "drone-go")
fmt.Println(repo)
```
+134
View File
@@ -0,0 +1,134 @@
package plugin
import (
"bytes"
"encoding/json"
"fmt"
"io"
"os"
)
// Standard Input
var Stdin *ParamSet
func init() {
// defaults to stdin
Stdin = NewParamSet(os.Stdin)
// check for params after the double dash
// in the command string
for i, argv := range os.Args {
if argv == "--" {
arg := os.Args[i+1]
buf := bytes.NewBufferString(arg)
Stdin = NewParamSet(buf)
break
}
}
}
// this init function is deprecated, but I'm keeping it
// around just in case it proves useful in the future.
func deprecated_init() {
// if piping from stdin we can just exit
// and use the default Stdin value
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
return
}
// check for params after the double dash
// in the command string
for i, argv := range os.Args {
if argv == "--" {
arg := os.Args[i+1]
buf := bytes.NewBufferString(arg)
Stdin = NewParamSet(buf)
return
}
}
// else use the first variable in the list
if len(os.Args) > 1 {
buf := bytes.NewBufferString(os.Args[1])
Stdin = NewParamSet(buf)
}
}
// ParamSet describes a parameter set.
type ParamSet struct {
reader io.Reader
params map[string]interface{}
}
// NewParamSet takes a io.Reader and returns a ParamSet.
func NewParamSet(reader io.Reader) *ParamSet {
var p = new(ParamSet)
p.reader = reader
p.params = map[string]interface{}{}
return p
}
// Param defines a parameter with the specified name.
func (p ParamSet) Param(name string, value interface{}) {
p.params[name] = value
}
// Parse parses parameter definitions from the map.
func (p ParamSet) Parse() error {
raw := map[string]json.RawMessage{}
err := json.NewDecoder(p.reader).Decode(&raw)
if err != nil {
return err
}
for key, val := range p.params {
data, ok := raw[key]
if !ok {
continue
}
err := json.Unmarshal(data, val)
if err != nil {
return fmt.Errorf("Unable to unarmshal %s. %s", key, err)
}
}
return nil
}
// Unmarshal parses the JSON payload from the command
// arguments and unmarshal into a value pointed to by v.
func (p ParamSet) Unmarshal(v interface{}) error {
return json.NewDecoder(p.reader).Decode(v)
}
// Param defines a parameter with the specified name.
func Param(name string, value interface{}) {
Stdin.Param(name, value)
}
// Parse parses parameter definitions from the map.
func Parse() error {
return Stdin.Parse()
}
// Unmarshal parses the JSON payload from the command
// arguments and unmarshal into a value pointed to by v.
func Unmarshal(v interface{}) error {
return Stdin.Unmarshal(v)
}
// MustUnmarshal parses the JSON payload from the command
// arguments and unmarshal into a value pointed to by v.
func MustUnmarshal(v interface{}) error {
return Stdin.Unmarshal(v)
}
// MustParse parses parameter definitions from the map
// and panics if there is a parsing error.
func MustParse() {
err := Parse()
if err != nil {
panic(err)
}
}
+1 -4
View File
@@ -3,9 +3,6 @@
Gorilla WebSocket is a [Go](http://golang.org/) implementation of the
[WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol.
[![Build Status](https://travis-ci.org/gorilla/websocket.svg?branch=master)](https://travis-ci.org/gorilla/websocket)
[![GoDoc](https://godoc.org/github.com/gorilla/websocket?status.svg)](https://godoc.org/github.com/gorilla/websocket)
### Documentation
* [API Reference](http://godoc.org/github.com/gorilla/websocket)
@@ -46,7 +43,7 @@ subdirectory](https://github.com/gorilla/websocket/tree/master/examples/autobahn
<tr><td>Send <a href="https://tools.ietf.org/html/rfc6455#section-5.5.2">pings</a> and receive <a href="https://tools.ietf.org/html/rfc6455#section-5.5.3">pongs</a></td><td><a href="http://godoc.org/github.com/gorilla/websocket#hdr-Control_Messages">Yes</a></td><td>No</td></tr>
<tr><td>Get the <a href="https://tools.ietf.org/html/rfc6455#section-5.6">type</a> of a received data message</td><td>Yes</td><td>Yes, see note 2</td></tr>
<tr><td colspan="3">Other Features</tr></td>
<tr><td><a href="https://tools.ietf.org/html/rfc7692">Compression Extensions</a></td><td>Experimental</td><td>No</td></tr>
<tr><td>Limit size of received message</td><td><a href="http://godoc.org/github.com/gorilla/websocket#Conn.SetReadLimit">Yes</a></td><td><a href="https://code.google.com/p/go/issues/detail?id=5082">No</a></td></tr>
<tr><td>Read message using io.Reader</td><td><a href="http://godoc.org/github.com/gorilla/websocket#Conn.NextReader">Yes</a></td><td>No, see note 3</td></tr>
<tr><td>Write message using io.WriteCloser</td><td><a href="http://godoc.org/github.com/gorilla/websocket#Conn.NextWriter">Yes</a></td><td>No, see note 3</td></tr>
</table>
+32 -49
View File
@@ -23,8 +23,6 @@ import (
// invalid.
var ErrBadHandshake = errors.New("websocket: bad handshake")
var errInvalidCompression = errors.New("websocket: invalid compression negotiation")
// NewClient creates a new client connection using the given net connection.
// The URL u specifies the host and request URI. Use requestHeader to specify
// the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies
@@ -66,24 +64,12 @@ type Dialer struct {
// HandshakeTimeout specifies the duration for the handshake to complete.
HandshakeTimeout time.Duration
// ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer
// size is zero, then a useful default size is used. The I/O buffer sizes
// do not limit the size of the messages that can be sent or received.
// Input and output buffer sizes. If the buffer size is zero, then a
// default value of 4096 is used.
ReadBufferSize, WriteBufferSize int
// Subprotocols specifies the client's requested subprotocols.
Subprotocols []string
// EnableCompression specifies if the client should attempt to negotiate
// per message compression (RFC 7692). Setting this value to true does not
// guarantee that compression will be supported. Currently only "no context
// takeover" modes are supported.
EnableCompression bool
// Jar specifies the cookie jar.
// If Jar is nil, cookies are not sent in requests and ignored
// in responses.
Jar http.CookieJar
}
var errMalformedURL = errors.New("malformed ws or wss URL")
@@ -97,6 +83,7 @@ func parseURL(s string) (*url.URL, error) {
//
// ws-URI = "ws:" "//" host [ ":" port ] path [ "?" query ]
// wss-URI = "wss:" "//" host [ ":" port ] path [ "?" query ]
var u url.URL
switch {
case strings.HasPrefix(s, "ws://"):
@@ -206,13 +193,6 @@ func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Re
Host: u.Host,
}
// Set the cookies present in the cookie jar of the dialer
if d.Jar != nil {
for _, cookie := range d.Jar.Cookies(u) {
req.AddCookie(cookie)
}
}
// Set the request headers using the capitalization for names and values in
// RFC examples. Although the capitalization shouldn't matter, there are
// servers that depend on it. The Header.Set method is not used because the
@@ -234,7 +214,6 @@ func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Re
k == "Connection" ||
k == "Sec-Websocket-Key" ||
k == "Sec-Websocket-Version" ||
k == "Sec-Websocket-Extensions" ||
(k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0):
return nil, nil, errors.New("websocket: duplicate header not allowed: " + k)
default:
@@ -242,10 +221,6 @@ func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Re
}
}
if d.EnableCompression {
req.Header.Set("Sec-Websocket-Extensions", "permessage-deflate; server_no_context_takeover; client_no_context_takeover")
}
hostPort, hostNoPort := hostPortNoPort(u)
var proxyURL *url.URL
@@ -349,13 +324,6 @@ func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Re
if err != nil {
return nil, nil, err
}
if d.Jar != nil {
if rc := resp.Cookies(); len(rc) > 0 {
d.Jar.SetCookies(u, rc)
}
}
if resp.StatusCode != 101 ||
!strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
!strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
@@ -369,20 +337,6 @@ func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Re
return nil, resp, ErrBadHandshake
}
for _, ext := range parseExtensions(resp.Header) {
if ext[""] != "permessage-deflate" {
continue
}
_, snct := ext["server_no_context_takeover"]
_, cnct := ext["client_no_context_takeover"]
if !snct || !cnct {
return nil, resp, errInvalidCompression
}
conn.newCompressionWriter = compressNoContextTakeover
conn.newDecompressionReader = decompressNoContextTakeover
break
}
resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")
@@ -390,3 +344,32 @@ func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Re
netConn = nil // to avoid close in defer.
return conn, resp, nil
}
// cloneTLSConfig clones all public fields except the fields
// SessionTicketsDisabled and SessionTicketKey. This avoids copying the
// sync.Mutex in the sync.Once and makes it safe to call cloneTLSConfig on a
// config in active use.
func cloneTLSConfig(cfg *tls.Config) *tls.Config {
if cfg == nil {
return &tls.Config{}
}
return &tls.Config{
Rand: cfg.Rand,
Time: cfg.Time,
Certificates: cfg.Certificates,
NameToCertificate: cfg.NameToCertificate,
GetCertificate: cfg.GetCertificate,
RootCAs: cfg.RootCAs,
NextProtos: cfg.NextProtos,
ServerName: cfg.ServerName,
ClientAuth: cfg.ClientAuth,
ClientCAs: cfg.ClientCAs,
InsecureSkipVerify: cfg.InsecureSkipVerify,
CipherSuites: cfg.CipherSuites,
PreferServerCipherSuites: cfg.PreferServerCipherSuites,
ClientSessionCache: cfg.ClientSessionCache,
MinVersion: cfg.MinVersion,
MaxVersion: cfg.MaxVersion,
CurvePreferences: cfg.CurvePreferences,
}
}
-16
View File
@@ -1,16 +0,0 @@
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build go1.8
package websocket
import "crypto/tls"
func cloneTLSConfig(cfg *tls.Config) *tls.Config {
if cfg == nil {
return &tls.Config{}
}
return cfg.Clone()
}
-38
View File
@@ -1,38 +0,0 @@
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// +build !go1.8
package websocket
import "crypto/tls"
// cloneTLSConfig clones all public fields except the fields
// SessionTicketsDisabled and SessionTicketKey. This avoids copying the
// sync.Mutex in the sync.Once and makes it safe to call cloneTLSConfig on a
// config in active use.
func cloneTLSConfig(cfg *tls.Config) *tls.Config {
if cfg == nil {
return &tls.Config{}
}
return &tls.Config{
Rand: cfg.Rand,
Time: cfg.Time,
Certificates: cfg.Certificates,
NameToCertificate: cfg.NameToCertificate,
GetCertificate: cfg.GetCertificate,
RootCAs: cfg.RootCAs,
NextProtos: cfg.NextProtos,
ServerName: cfg.ServerName,
ClientAuth: cfg.ClientAuth,
ClientCAs: cfg.ClientCAs,
InsecureSkipVerify: cfg.InsecureSkipVerify,
CipherSuites: cfg.CipherSuites,
PreferServerCipherSuites: cfg.PreferServerCipherSuites,
ClientSessionCache: cfg.ClientSessionCache,
MinVersion: cfg.MinVersion,
MaxVersion: cfg.MaxVersion,
CurvePreferences: cfg.CurvePreferences,
}
}
-148
View File
@@ -1,148 +0,0 @@
// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package websocket
import (
"compress/flate"
"errors"
"io"
"strings"
"sync"
)
const (
minCompressionLevel = -2 // flate.HuffmanOnly not defined in Go < 1.6
maxCompressionLevel = flate.BestCompression
defaultCompressionLevel = 1
)
var (
flateWriterPools [maxCompressionLevel - minCompressionLevel + 1]sync.Pool
flateReaderPool = sync.Pool{New: func() interface{} {
return flate.NewReader(nil)
}}
)
func decompressNoContextTakeover(r io.Reader) io.ReadCloser {
const tail =
// Add four bytes as specified in RFC
"\x00\x00\xff\xff" +
// Add final block to squelch unexpected EOF error from flate reader.
"\x01\x00\x00\xff\xff"
fr, _ := flateReaderPool.Get().(io.ReadCloser)
fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil)
return &flateReadWrapper{fr}
}
func isValidCompressionLevel(level int) bool {
return minCompressionLevel <= level && level <= maxCompressionLevel
}
func compressNoContextTakeover(w io.WriteCloser, level int) io.WriteCloser {
p := &flateWriterPools[level-minCompressionLevel]
tw := &truncWriter{w: w}
fw, _ := p.Get().(*flate.Writer)
if fw == nil {
fw, _ = flate.NewWriter(tw, level)
} else {
fw.Reset(tw)
}
return &flateWriteWrapper{fw: fw, tw: tw, p: p}
}
// truncWriter is an io.Writer that writes all but the last four bytes of the
// stream to another io.Writer.
type truncWriter struct {
w io.WriteCloser
n int
p [4]byte
}
func (w *truncWriter) Write(p []byte) (int, error) {
n := 0
// fill buffer first for simplicity.
if w.n < len(w.p) {
n = copy(w.p[w.n:], p)
p = p[n:]
w.n += n
if len(p) == 0 {
return n, nil
}
}
m := len(p)
if m > len(w.p) {
m = len(w.p)
}
if nn, err := w.w.Write(w.p[:m]); err != nil {
return n + nn, err
}
copy(w.p[:], w.p[m:])
copy(w.p[len(w.p)-m:], p[len(p)-m:])
nn, err := w.w.Write(p[:len(p)-m])
return n + nn, err
}
type flateWriteWrapper struct {
fw *flate.Writer
tw *truncWriter
p *sync.Pool
}
func (w *flateWriteWrapper) Write(p []byte) (int, error) {
if w.fw == nil {
return 0, errWriteClosed
}
return w.fw.Write(p)
}
func (w *flateWriteWrapper) Close() error {
if w.fw == nil {
return errWriteClosed
}
err1 := w.fw.Flush()
w.p.Put(w.fw)
w.fw = nil
if w.tw.p != [4]byte{0, 0, 0xff, 0xff} {
return errors.New("websocket: internal error, unexpected bytes at end of flate stream")
}
err2 := w.tw.w.Close()
if err1 != nil {
return err1
}
return err2
}
type flateReadWrapper struct {
fr io.ReadCloser
}
func (r *flateReadWrapper) Read(p []byte) (int, error) {
if r.fr == nil {
return 0, io.ErrClosedPipe
}
n, err := r.fr.Read(p)
if err == io.EOF {
// Preemptively place the reader back in the pool. This helps with
// scenarios where the application does not call NextReader() soon after
// this final read.
r.Close()
}
return n, err
}
func (r *flateReadWrapper) Close() error {
if r.fr == nil {
return io.ErrClosedPipe
}
err := r.fr.Close()
flateReaderPool.Put(r.fr)
r.fr = nil
return err
}
+147 -345
View File
@@ -13,25 +13,16 @@ import (
"math/rand"
"net"
"strconv"
"sync"
"time"
"unicode/utf8"
)
const (
// Frame header byte 0 bits from Section 5.2 of RFC 6455
finalBit = 1 << 7
rsv1Bit = 1 << 6
rsv2Bit = 1 << 5
rsv3Bit = 1 << 4
// Frame header byte 1 bits from Section 5.2 of RFC 6455
maskBit = 1 << 7
maxFrameHeaderSize = 2 + 8 + 4 // Fixed header + length + mask
maxControlFramePayloadSize = 125
writeWait = time.Second
finalBit = 1 << 7
maskBit = 1 << 7
writeWait = time.Second
defaultReadBufferSize = 4096
defaultWriteBufferSize = 4096
@@ -181,11 +172,6 @@ var (
errInvalidControlFrame = errors.New("websocket: invalid control frame")
)
func newMaskKey() [4]byte {
n := rand.Uint32()
return [4]byte{byte(n), byte(n >> 8), byte(n >> 16), byte(n >> 24)}
}
func hideTempErr(err error) error {
if e, ok := err.(net.Error); ok && e.Temporary() {
err = &netError{msg: e.Error(), timeout: e.Timeout()}
@@ -224,28 +210,39 @@ func isValidReceivedCloseCode(code int) bool {
return validReceivedCloseCodes[code] || (code >= 3000 && code <= 4999)
}
// The Conn type represents a WebSocket connection.
func maskBytes(key [4]byte, pos int, b []byte) int {
for i := range b {
b[i] ^= key[pos&3]
pos++
}
return pos & 3
}
func newMaskKey() [4]byte {
n := rand.Uint32()
return [4]byte{byte(n), byte(n >> 8), byte(n >> 16), byte(n >> 24)}
}
// Conn represents a WebSocket connection.
type Conn struct {
conn net.Conn
isServer bool
subprotocol string
// Write fields
mu chan bool // used as mutex to protect write to conn
writeBuf []byte // frame is constructed in this buffer.
writeDeadline time.Time
writer io.WriteCloser // the current writer returned to the application
isWriting bool // for best-effort concurrent write detection
mu chan bool // used as mutex to protect write to conn and closeSent
closeSent bool // true if close message was sent
writeErrMu sync.Mutex
writeErr error
enableWriteCompression bool
compressionLevel int
newCompressionWriter func(io.WriteCloser, int) io.WriteCloser
// Message writer fields.
writeErr error
writeBuf []byte // frame is constructed in this buffer.
writePos int // end of data in writeBuf.
writeFrameType int // type of the current frame.
writeDeadline time.Time
isWriting bool // for best-effort concurrent write detection
messageWriter *messageWriter // the current writer
// Read fields
reader io.ReadCloser // the current reader returned to the application
readErr error
br *bufio.Reader
readRemaining int64 // bytes remaining in current frame.
@@ -256,83 +253,34 @@ type Conn struct {
readMaskKey [4]byte
handlePong func(string) error
handlePing func(string) error
handleClose func(int, string) error
readErrCount int
messageReader *messageReader // the current low-level reader
readDecompress bool // whether last read frame had RSV1 set
newDecompressionReader func(io.Reader) io.ReadCloser
messageReader *messageReader // the current reader
}
func newConn(conn net.Conn, isServer bool, readBufferSize, writeBufferSize int) *Conn {
return newConnBRW(conn, isServer, readBufferSize, writeBufferSize, nil)
}
type writeHook struct {
p []byte
}
func (wh *writeHook) Write(p []byte) (int, error) {
wh.p = p
return len(p), nil
}
func newConnBRW(conn net.Conn, isServer bool, readBufferSize, writeBufferSize int, brw *bufio.ReadWriter) *Conn {
mu := make(chan bool, 1)
mu <- true
var br *bufio.Reader
if readBufferSize == 0 && brw != nil && brw.Reader != nil {
// Reuse the supplied bufio.Reader if the buffer has a useful size.
// This code assumes that peek on a reader returns
// bufio.Reader.buf[:0].
brw.Reader.Reset(conn)
if p, err := brw.Reader.Peek(0); err == nil && cap(p) >= 256 {
br = brw.Reader
}
if readBufferSize == 0 {
readBufferSize = defaultReadBufferSize
}
if br == nil {
if readBufferSize == 0 {
readBufferSize = defaultReadBufferSize
}
if readBufferSize < maxControlFramePayloadSize {
readBufferSize = maxControlFramePayloadSize
}
br = bufio.NewReaderSize(conn, readBufferSize)
if readBufferSize < maxControlFramePayloadSize {
readBufferSize = maxControlFramePayloadSize
}
var writeBuf []byte
if writeBufferSize == 0 && brw != nil && brw.Writer != nil {
// Use the bufio.Writer's buffer if the buffer has a useful size. This
// code assumes that bufio.Writer.buf[:1] is passed to the
// bufio.Writer's underlying writer.
var wh writeHook
brw.Writer.Reset(&wh)
brw.Writer.WriteByte(0)
brw.Flush()
if cap(wh.p) >= maxFrameHeaderSize+256 {
writeBuf = wh.p[:cap(wh.p)]
}
}
if writeBuf == nil {
if writeBufferSize == 0 {
writeBufferSize = defaultWriteBufferSize
}
writeBuf = make([]byte, writeBufferSize+maxFrameHeaderSize)
if writeBufferSize == 0 {
writeBufferSize = defaultWriteBufferSize
}
c := &Conn{
isServer: isServer,
br: br,
conn: conn,
mu: mu,
readFinal: true,
writeBuf: writeBuf,
enableWriteCompression: true,
compressionLevel: defaultCompressionLevel,
isServer: isServer,
br: bufio.NewReaderSize(conn, readBufferSize),
conn: conn,
mu: mu,
readFinal: true,
writeBuf: make([]byte, writeBufferSize+maxFrameHeaderSize),
writeFrameType: noFrame,
writePos: maxFrameHeaderSize,
}
c.SetCloseHandler(nil)
c.SetPingHandler(nil)
c.SetPongHandler(nil)
return c
@@ -360,40 +308,29 @@ func (c *Conn) RemoteAddr() net.Addr {
// Write methods
func (c *Conn) writeFatal(err error) error {
err = hideTempErr(err)
c.writeErrMu.Lock()
if c.writeErr == nil {
c.writeErr = err
}
c.writeErrMu.Unlock()
return err
}
func (c *Conn) write(frameType int, deadline time.Time, bufs ...[]byte) error {
<-c.mu
defer func() { c.mu <- true }()
c.writeErrMu.Lock()
err := c.writeErr
c.writeErrMu.Unlock()
if err != nil {
return err
if c.closeSent {
return ErrCloseSent
} else if frameType == CloseMessage {
c.closeSent = true
}
c.conn.SetWriteDeadline(deadline)
for _, buf := range bufs {
if len(buf) > 0 {
_, err := c.conn.Write(buf)
n, err := c.conn.Write(buf)
if n != len(buf) {
// Close on partial write.
c.conn.Close()
}
if err != nil {
return c.writeFatal(err)
return err
}
}
}
if frameType == CloseMessage {
c.writeFatal(ErrCloseSent)
}
return nil
}
@@ -442,41 +379,18 @@ func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) er
}
defer func() { c.mu <- true }()
c.writeErrMu.Lock()
err := c.writeErr
c.writeErrMu.Unlock()
if err != nil {
return err
if c.closeSent {
return ErrCloseSent
} else if messageType == CloseMessage {
c.closeSent = true
}
c.conn.SetWriteDeadline(deadline)
_, err = c.conn.Write(buf)
if err != nil {
return c.writeFatal(err)
n, err := c.conn.Write(buf)
if n != 0 && n != len(buf) {
c.conn.Close()
}
if messageType == CloseMessage {
c.writeFatal(ErrCloseSent)
}
return err
}
func (c *Conn) prepWrite(messageType int) error {
// Close previous writer if not already closed by the application. It's
// probably better to return an error in this situation, but we cannot
// change this without breaking existing applications.
if c.writer != nil {
c.writer.Close()
c.writer = nil
}
if !isControl(messageType) && !isData(messageType) {
return errBadWriteOpCode
}
c.writeErrMu.Lock()
err := c.writeErr
c.writeErrMu.Unlock()
return err
return hideTempErr(err)
}
// NextWriter returns a writer for the next message to send. The writer's Close
@@ -485,61 +399,42 @@ func (c *Conn) prepWrite(messageType int) error {
// There can be at most one open writer on a connection. NextWriter closes the
// previous writer if the application has not already done so.
func (c *Conn) NextWriter(messageType int) (io.WriteCloser, error) {
if err := c.prepWrite(messageType); err != nil {
return nil, err
if c.writeErr != nil {
return nil, c.writeErr
}
mw := &messageWriter{
c: c,
frameType: messageType,
pos: maxFrameHeaderSize,
if c.writeFrameType != noFrame {
if err := c.flushFrame(true, nil); err != nil {
return nil, err
}
}
c.writer = mw
if c.newCompressionWriter != nil && c.enableWriteCompression && isData(messageType) {
w := c.newCompressionWriter(c.writer, c.compressionLevel)
mw.compress = true
c.writer = w
if !isControl(messageType) && !isData(messageType) {
return nil, errBadWriteOpCode
}
return c.writer, nil
c.writeFrameType = messageType
w := &messageWriter{c}
c.messageWriter = w
return w, nil
}
type messageWriter struct {
c *Conn
compress bool // whether next call to flushFrame should set RSV1
pos int // end of data in writeBuf.
frameType int // type of the current frame.
err error
}
func (w *messageWriter) fatal(err error) error {
if w.err != nil {
w.err = err
w.c.writer = nil
}
return err
}
// flushFrame writes buffered data and extra as a frame to the network. The
// final argument indicates that this is the last frame in the message.
func (w *messageWriter) flushFrame(final bool, extra []byte) error {
c := w.c
length := w.pos - maxFrameHeaderSize + len(extra)
func (c *Conn) flushFrame(final bool, extra []byte) error {
length := c.writePos - maxFrameHeaderSize + len(extra)
// Check for invalid control frames.
if isControl(w.frameType) &&
if isControl(c.writeFrameType) &&
(!final || length > maxControlFramePayloadSize) {
return w.fatal(errInvalidControlFrame)
c.messageWriter = nil
c.writeFrameType = noFrame
c.writePos = maxFrameHeaderSize
return errInvalidControlFrame
}
b0 := byte(w.frameType)
b0 := byte(c.writeFrameType)
if final {
b0 |= finalBit
}
if w.compress {
b0 |= rsv1Bit
}
w.compress = false
b1 := byte(0)
if !c.isServer {
b1 |= maskBit
@@ -571,9 +466,10 @@ func (w *messageWriter) flushFrame(final bool, extra []byte) error {
if !c.isServer {
key := newMaskKey()
copy(c.writeBuf[maxFrameHeaderSize-4:], key[:])
maskBytes(key, 0, c.writeBuf[maxFrameHeaderSize:w.pos])
maskBytes(key, 0, c.writeBuf[maxFrameHeaderSize:c.writePos])
if len(extra) > 0 {
return c.writeFatal(errors.New("websocket: internal error, extra used in client mode"))
c.writeErr = errors.New("websocket: internal error, extra used in client mode")
return c.writeErr
}
}
@@ -586,35 +482,43 @@ func (w *messageWriter) flushFrame(final bool, extra []byte) error {
}
c.isWriting = true
err := c.write(w.frameType, c.writeDeadline, c.writeBuf[framePos:w.pos], extra)
c.writeErr = c.write(c.writeFrameType, c.writeDeadline, c.writeBuf[framePos:c.writePos], extra)
if !c.isWriting {
panic("concurrent write to websocket connection")
}
c.isWriting = false
if err != nil {
return w.fatal(err)
}
if final {
c.writer = nil
return nil
}
// Setup for next frame.
w.pos = maxFrameHeaderSize
w.frameType = continuationFrame
c.writePos = maxFrameHeaderSize
c.writeFrameType = continuationFrame
if final {
c.messageWriter = nil
c.writeFrameType = noFrame
}
return c.writeErr
}
type messageWriter struct{ c *Conn }
func (w *messageWriter) err() error {
c := w.c
if c.messageWriter != w {
return errWriteClosed
}
if c.writeErr != nil {
return c.writeErr
}
return nil
}
func (w *messageWriter) ncopy(max int) (int, error) {
n := len(w.c.writeBuf) - w.pos
n := len(w.c.writeBuf) - w.c.writePos
if n <= 0 {
if err := w.flushFrame(false, nil); err != nil {
if err := w.c.flushFrame(false, nil); err != nil {
return 0, err
}
n = len(w.c.writeBuf) - w.pos
n = len(w.c.writeBuf) - w.c.writePos
}
if n > max {
n = max
@@ -622,14 +526,14 @@ func (w *messageWriter) ncopy(max int) (int, error) {
return n, nil
}
func (w *messageWriter) Write(p []byte) (int, error) {
if w.err != nil {
return 0, w.err
func (w *messageWriter) write(final bool, p []byte) (int, error) {
if err := w.err(); err != nil {
return 0, err
}
if len(p) > 2*len(w.c.writeBuf) && w.c.isServer {
// Don't buffer large messages.
err := w.flushFrame(false, p)
err := w.c.flushFrame(final, p)
if err != nil {
return 0, err
}
@@ -642,16 +546,20 @@ func (w *messageWriter) Write(p []byte) (int, error) {
if err != nil {
return 0, err
}
copy(w.c.writeBuf[w.pos:], p[:n])
w.pos += n
copy(w.c.writeBuf[w.c.writePos:], p[:n])
w.c.writePos += n
p = p[n:]
}
return nn, nil
}
func (w *messageWriter) Write(p []byte) (int, error) {
return w.write(false, p)
}
func (w *messageWriter) WriteString(p string) (int, error) {
if w.err != nil {
return 0, w.err
if err := w.err(); err != nil {
return 0, err
}
nn := len(p)
@@ -660,27 +568,27 @@ func (w *messageWriter) WriteString(p string) (int, error) {
if err != nil {
return 0, err
}
copy(w.c.writeBuf[w.pos:], p[:n])
w.pos += n
copy(w.c.writeBuf[w.c.writePos:], p[:n])
w.c.writePos += n
p = p[n:]
}
return nn, nil
}
func (w *messageWriter) ReadFrom(r io.Reader) (nn int64, err error) {
if w.err != nil {
return 0, w.err
if err := w.err(); err != nil {
return 0, err
}
for {
if w.pos == len(w.c.writeBuf) {
err = w.flushFrame(false, nil)
if w.c.writePos == len(w.c.writeBuf) {
err = w.c.flushFrame(false, nil)
if err != nil {
break
}
}
var n int
n, err = r.Read(w.c.writeBuf[w.pos:])
w.pos += n
n, err = r.Read(w.c.writeBuf[w.c.writePos:])
w.c.writePos += n
nn += int64(n)
if err != nil {
if err == io.EOF {
@@ -693,59 +601,27 @@ func (w *messageWriter) ReadFrom(r io.Reader) (nn int64, err error) {
}
func (w *messageWriter) Close() error {
if w.err != nil {
return w.err
}
if err := w.flushFrame(true, nil); err != nil {
if err := w.err(); err != nil {
return err
}
w.err = errWriteClosed
return nil
}
// WritePreparedMessage writes prepared message into connection.
func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error {
frameType, frameData, err := pm.frame(prepareKey{
isServer: c.isServer,
compress: c.newCompressionWriter != nil && c.enableWriteCompression && isData(pm.messageType),
compressionLevel: c.compressionLevel,
})
if err != nil {
return err
}
if c.isWriting {
panic("concurrent write to websocket connection")
}
c.isWriting = true
err = c.write(frameType, c.writeDeadline, frameData, nil)
if !c.isWriting {
panic("concurrent write to websocket connection")
}
c.isWriting = false
return err
return w.c.flushFrame(true, nil)
}
// WriteMessage is a helper method for getting a writer using NextWriter,
// writing the message and closing the writer.
func (c *Conn) WriteMessage(messageType int, data []byte) error {
if c.isServer && (c.newCompressionWriter == nil || !c.enableWriteCompression) {
// Fast path with no allocations and single frame.
if err := c.prepWrite(messageType); err != nil {
return err
}
mw := messageWriter{c: c, frameType: messageType, pos: maxFrameHeaderSize}
n := copy(c.writeBuf[mw.pos:], data)
mw.pos += n
data = data[n:]
return mw.flushFrame(true, data)
}
w, err := c.NextWriter(messageType)
if err != nil {
return err
}
if _, ok := w.(*messageWriter); ok && c.isServer {
// Optimize write as a single frame.
n := copy(c.writeBuf[c.writePos:], data)
c.writePos += n
data = data[n:]
err = c.flushFrame(true, data)
return err
}
if _, err = w.Write(data); err != nil {
return err
}
@@ -782,17 +658,12 @@ func (c *Conn) advanceFrame() (int, error) {
final := p[0]&finalBit != 0
frameType := int(p[0] & 0xf)
reserved := int((p[0] >> 4) & 0x7)
mask := p[1]&maskBit != 0
c.readRemaining = int64(p[1] & 0x7f)
c.readDecompress = false
if c.newDecompressionReader != nil && (p[0]&rsv1Bit) != 0 {
c.readDecompress = true
p[0] &^= rsv1Bit
}
if rsv := p[0] & (rsv1Bit | rsv2Bit | rsv3Bit); rsv != 0 {
return noFrame, c.handleProtocolError("unexpected reserved bits 0x" + strconv.FormatInt(int64(rsv), 16))
if reserved != 0 {
return noFrame, c.handleProtocolError("unexpected reserved bits " + strconv.Itoa(reserved))
}
switch frameType {
@@ -888,9 +759,11 @@ func (c *Conn) advanceFrame() (int, error) {
return noFrame, err
}
case CloseMessage:
echoMessage := []byte{}
closeCode := CloseNoStatusReceived
closeText := ""
if len(payload) >= 2 {
echoMessage = payload[:2]
closeCode = int(binary.BigEndian.Uint16(payload))
if !isValidReceivedCloseCode(closeCode) {
return noFrame, c.handleProtocolError("invalid close code")
@@ -900,9 +773,7 @@ func (c *Conn) advanceFrame() (int, error) {
return noFrame, c.handleProtocolError("invalid utf8 payload in close frame")
}
}
if err := c.handleClose(closeCode, closeText); err != nil {
return noFrame, err
}
c.WriteControl(CloseMessage, echoMessage, time.Now().Add(writeWait))
return noFrame, &CloseError{Code: closeCode, Text: closeText}
}
@@ -925,11 +796,6 @@ func (c *Conn) handleProtocolError(message string) error {
// permanent. Once this method returns a non-nil error, all subsequent calls to
// this method return the same error.
func (c *Conn) NextReader() (messageType int, r io.Reader, err error) {
// Close previous reader, only relevant for decompression.
if c.reader != nil {
c.reader.Close()
c.reader = nil
}
c.messageReader = nil
c.readLength = 0
@@ -941,12 +807,9 @@ func (c *Conn) NextReader() (messageType int, r io.Reader, err error) {
break
}
if frameType == TextMessage || frameType == BinaryMessage {
c.messageReader = &messageReader{c}
c.reader = c.messageReader
if c.readDecompress {
c.reader = c.newDecompressionReader(c.reader)
}
return frameType, c.reader, nil
r := &messageReader{c}
c.messageReader = r
return frameType, r, nil
}
}
@@ -1008,10 +871,6 @@ func (r *messageReader) Read(b []byte) (int, error) {
return 0, err
}
func (r *messageReader) Close() error {
return nil
}
// ReadMessage is a helper method for getting a reader using NextReader and
// reading from that reader to a buffer.
func (c *Conn) ReadMessage() (messageType int, p []byte, err error) {
@@ -1039,38 +898,6 @@ func (c *Conn) SetReadLimit(limit int64) {
c.readLimit = limit
}
// CloseHandler returns the current close handler
func (c *Conn) CloseHandler() func(code int, text string) error {
return c.handleClose
}
// SetCloseHandler sets the handler for close messages received from the peer.
// The code argument to h is the received close code or CloseNoStatusReceived
// if the close message is empty. The default close handler sends a close frame
// back to the peer.
//
// The application must read the connection to process close messages as
// described in the section on Control Frames above.
//
// The connection read methods return a CloseError when a close frame is
// received. Most applications should handle close messages as part of their
// normal error handling. Applications should only set a close handler when the
// application must perform some action before sending a close frame back to
// the peer.
func (c *Conn) SetCloseHandler(h func(code int, text string) error) {
if h == nil {
h = func(code int, text string) error {
message := []byte{}
if code != CloseNoStatusReceived {
message = FormatCloseMessage(code, "")
}
c.WriteControl(CloseMessage, message, time.Now().Add(writeWait))
return nil
}
}
c.handleClose = h
}
// PingHandler returns the current ping handler
func (c *Conn) PingHandler() func(appData string) error {
return c.handlePing
@@ -1079,9 +906,6 @@ func (c *Conn) PingHandler() func(appData string) error {
// SetPingHandler sets the handler for ping messages received from the peer.
// The appData argument to h is the PING frame application data. The default
// ping handler sends a pong to the peer.
//
// The application must read the connection to process ping messages as
// described in the section on Control Frames above.
func (c *Conn) SetPingHandler(h func(appData string) error) {
if h == nil {
h = func(message string) error {
@@ -1105,9 +929,6 @@ func (c *Conn) PongHandler() func(appData string) error {
// SetPongHandler sets the handler for pong messages received from the peer.
// The appData argument to h is the PONG frame application data. The default
// pong handler does nothing.
//
// The application must read the connection to process ping messages as
// described in the section on Control Frames above.
func (c *Conn) SetPongHandler(h func(appData string) error) {
if h == nil {
h = func(string) error { return nil }
@@ -1121,25 +942,6 @@ func (c *Conn) UnderlyingConn() net.Conn {
return c.conn
}
// EnableWriteCompression enables and disables write compression of
// subsequent text and binary messages. This function is a noop if
// compression was not negotiated with the peer.
func (c *Conn) EnableWriteCompression(enable bool) {
c.enableWriteCompression = enable
}
// SetCompressionLevel sets the flate compression level for subsequent text and
// binary messages. This function is a noop if compression was not negotiated
// with the peer. See the compress/flate package for a description of
// compression levels.
func (c *Conn) SetCompressionLevel(level int) error {
if !isValidCompressionLevel(level) {
return errors.New("websocket: invalid compression level")
}
c.compressionLevel = level
return nil
}
// FormatCloseMessage formats closeCode and text as a WebSocket close message.
func FormatCloseMessage(closeCode int, text string) []byte {
buf := make([]byte, 2+len(text))
+10 -37
View File
@@ -6,8 +6,9 @@
//
// Overview
//
// The Conn type represents a WebSocket connection. A server application calls
// the Upgrader.Upgrade method from an HTTP request handler to get a *Conn:
// The Conn type represents a WebSocket connection. A server application uses
// the Upgrade function from an Upgrader object with a HTTP request handler
// to get a pointer to a Conn:
//
// var upgrader = websocket.Upgrader{
// ReadBufferSize: 1024,
@@ -32,7 +33,7 @@
// if err != nil {
// return
// }
// if err := conn.WriteMessage(messageType, p); err != nil {
// if err = conn.WriteMessage(messageType, p); err != nil {
// return err
// }
// }
@@ -117,10 +118,9 @@
//
// Applications are responsible for ensuring that no more than one goroutine
// calls the write methods (NextWriter, SetWriteDeadline, WriteMessage,
// WriteJSON, EnableWriteCompression, SetCompressionLevel) concurrently and
// that no more than one goroutine calls the read methods (NextReader,
// SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPingHandler)
// concurrently.
// WriteJSON) concurrently and that no more than one goroutine calls the read
// methods (NextReader, SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler,
// SetPingHandler) concurrently.
//
// The Close and WriteControl methods can be called concurrently with all other
// methods.
@@ -146,34 +146,7 @@
// CheckOrigin: func(r *http.Request) bool { return true },
// }
//
// The deprecated package-level Upgrade function does not perform origin
// checking. The application is responsible for checking the Origin header
// before calling the Upgrade function.
//
// Compression EXPERIMENTAL
//
// Per message compression extensions (RFC 7692) are experimentally supported
// by this package in a limited capacity. Setting the EnableCompression option
// to true in Dialer or Upgrader will attempt to negotiate per message deflate
// support.
//
// var upgrader = websocket.Upgrader{
// EnableCompression: true,
// }
//
// If compression was successfully negotiated with the connection's peer, any
// message received in compressed form will be automatically decompressed.
// All Read methods will return uncompressed bytes.
//
// Per message compression of messages written to a connection can be enabled
// or disabled by calling the corresponding Conn method:
//
// conn.EnableWriteCompression(false)
//
// Currently this package does not support compression with "context takeover".
// This means that messages must be compressed and decompressed in isolation,
// without retaining sliding window or dictionary state across messages. For
// more details refer to RFC 7692.
//
// Use of compression is experimental and may result in decreased performance.
// The deprecated Upgrade function does not enforce an origin policy. It's the
// application's responsibility to check the Origin header before calling
// Upgrade.
package websocket
+3 -8
View File
@@ -9,14 +9,12 @@ import (
"io"
)
// WriteJSON writes the JSON encoding of v as a message.
//
// Deprecated: Use c.WriteJSON instead.
// WriteJSON is deprecated, use c.WriteJSON instead.
func WriteJSON(c *Conn, v interface{}) error {
return c.WriteJSON(v)
}
// WriteJSON writes the JSON encoding of v as a message.
// WriteJSON writes the JSON encoding of v to the connection.
//
// See the documentation for encoding/json Marshal for details about the
// conversion of Go values to JSON.
@@ -33,10 +31,7 @@ func (c *Conn) WriteJSON(v interface{}) error {
return err2
}
// ReadJSON reads the next JSON-encoded message from the connection and stores
// it in the value pointed to by v.
//
// Deprecated: Use c.ReadJSON instead.
// ReadJSON is deprecated, use c.ReadJSON instead.
func ReadJSON(c *Conn, v interface{}) error {
return c.ReadJSON(v)
}
-55
View File
@@ -1,55 +0,0 @@
// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in the
// LICENSE file.
// +build !appengine
package websocket
import "unsafe"
const wordSize = int(unsafe.Sizeof(uintptr(0)))
func maskBytes(key [4]byte, pos int, b []byte) int {
// Mask one byte at a time for small buffers.
if len(b) < 2*wordSize {
for i := range b {
b[i] ^= key[pos&3]
pos++
}
return pos & 3
}
// Mask one byte at a time to word boundary.
if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 {
n = wordSize - n
for i := range b[:n] {
b[i] ^= key[pos&3]
pos++
}
b = b[n:]
}
// Create aligned word size key.
var k [wordSize]byte
for i := range k {
k[i] = key[(pos+i)&3]
}
kw := *(*uintptr)(unsafe.Pointer(&k))
// Mask one word at a time.
n := (len(b) / wordSize) * wordSize
for i := 0; i < n; i += wordSize {
*(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(i))) ^= kw
}
// Mask one byte at a time for remaining bytes.
b = b[n:]
for i := range b {
b[i] ^= key[pos&3]
pos++
}
return pos & 3
}
-15
View File
@@ -1,15 +0,0 @@
// Copyright 2016 The Gorilla WebSocket Authors. All rights reserved. Use of
// this source code is governed by a BSD-style license that can be found in the
// LICENSE file.
// +build appengine
package websocket
func maskBytes(key [4]byte, pos int, b []byte) int {
for i := range b {
b[i] ^= key[pos&3]
pos++
}
return pos & 3
}
-103
View File
@@ -1,103 +0,0 @@
// Copyright 2017 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package websocket
import (
"bytes"
"net"
"sync"
"time"
)
// PreparedMessage caches on the wire representations of a message payload.
// Use PreparedMessage to efficiently send a message payload to multiple
// connections. PreparedMessage is especially useful when compression is used
// because the CPU and memory expensive compression operation can be executed
// once for a given set of compression options.
type PreparedMessage struct {
messageType int
data []byte
err error
mu sync.Mutex
frames map[prepareKey]*preparedFrame
}
// prepareKey defines a unique set of options to cache prepared frames in PreparedMessage.
type prepareKey struct {
isServer bool
compress bool
compressionLevel int
}
// preparedFrame contains data in wire representation.
type preparedFrame struct {
once sync.Once
data []byte
}
// NewPreparedMessage returns an initialized PreparedMessage. You can then send
// it to connection using WritePreparedMessage method. Valid wire
// representation will be calculated lazily only once for a set of current
// connection options.
func NewPreparedMessage(messageType int, data []byte) (*PreparedMessage, error) {
pm := &PreparedMessage{
messageType: messageType,
frames: make(map[prepareKey]*preparedFrame),
data: data,
}
// Prepare a plain server frame.
_, frameData, err := pm.frame(prepareKey{isServer: true, compress: false})
if err != nil {
return nil, err
}
// To protect against caller modifying the data argument, remember the data
// copied to the plain server frame.
pm.data = frameData[len(frameData)-len(data):]
return pm, nil
}
func (pm *PreparedMessage) frame(key prepareKey) (int, []byte, error) {
pm.mu.Lock()
frame, ok := pm.frames[key]
if !ok {
frame = &preparedFrame{}
pm.frames[key] = frame
}
pm.mu.Unlock()
var err error
frame.once.Do(func() {
// Prepare a frame using a 'fake' connection.
// TODO: Refactor code in conn.go to allow more direct construction of
// the frame.
mu := make(chan bool, 1)
mu <- true
var nc prepareConn
c := &Conn{
conn: &nc,
mu: mu,
isServer: key.isServer,
compressionLevel: key.compressionLevel,
enableWriteCompression: true,
writeBuf: make([]byte, defaultWriteBufferSize+maxFrameHeaderSize),
}
if key.compress {
c.newCompressionWriter = compressNoContextTakeover
}
err = c.WriteMessage(pm.messageType, pm.data)
frame.data = nc.buf.Bytes()
})
return pm.messageType, frame.data, err
}
type prepareConn struct {
buf bytes.Buffer
net.Conn
}
func (pc *prepareConn) Write(p []byte) (int, error) { return pc.buf.Write(p) }
func (pc *prepareConn) SetWriteDeadline(t time.Time) error { return nil }
+18 -50
View File
@@ -28,9 +28,8 @@ type Upgrader struct {
HandshakeTimeout time.Duration
// ReadBufferSize and WriteBufferSize specify I/O buffer sizes. If a buffer
// size is zero, then buffers allocated by the HTTP server are used. The
// I/O buffer sizes do not limit the size of the messages that can be sent
// or received.
// size is zero, then a default value of 4096 is used. The I/O buffer sizes
// do not limit the size of the messages that can be sent or received.
ReadBufferSize, WriteBufferSize int
// Subprotocols specifies the server's supported protocols in order of
@@ -47,12 +46,6 @@ type Upgrader struct {
// CheckOrigin is nil, the host in the Origin header must not be set or
// must match the host of the request.
CheckOrigin func(r *http.Request) bool
// EnableCompression specify if the server should attempt to negotiate per
// message compression (RFC 7692). Setting this value to true does not
// guarantee that compression will be supported. Currently only "no context
// takeover" modes are supported.
EnableCompression bool
}
func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) {
@@ -60,7 +53,6 @@ func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status in
if u.Error != nil {
u.Error(w, r, status, err)
} else {
w.Header().Set("Sec-Websocket-Version", "13")
http.Error(w, http.StatusText(status), status)
}
return nil, err
@@ -105,23 +97,18 @@ func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header
// response.
func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) {
if r.Method != "GET" {
return u.returnError(w, r, http.StatusMethodNotAllowed, "websocket: not a websocket handshake: request method is not GET")
return u.returnError(w, r, http.StatusMethodNotAllowed, "websocket: method not GET")
}
if _, ok := responseHeader["Sec-Websocket-Extensions"]; ok {
return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific 'Sec-Websocket-Extensions' headers are unsupported")
if values := r.Header["Sec-Websocket-Version"]; len(values) == 0 || values[0] != "13" {
return u.returnError(w, r, http.StatusBadRequest, "websocket: version != 13")
}
if !tokenListContainsValue(r.Header, "Connection", "upgrade") {
return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'upgrade' token not found in 'Connection' header")
return u.returnError(w, r, http.StatusBadRequest, "websocket: could not find connection header with token 'upgrade'")
}
if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: 'websocket' token not found in 'Upgrade' header")
}
if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") {
return u.returnError(w, r, http.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header")
return u.returnError(w, r, http.StatusBadRequest, "websocket: could not find upgrade header with token 'websocket'")
}
checkOrigin := u.CheckOrigin
@@ -129,30 +116,19 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade
checkOrigin = checkSameOrigin
}
if !checkOrigin(r) {
return u.returnError(w, r, http.StatusForbidden, "websocket: 'Origin' header value not allowed")
return u.returnError(w, r, http.StatusForbidden, "websocket: origin not allowed")
}
challengeKey := r.Header.Get("Sec-Websocket-Key")
if challengeKey == "" {
return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: `Sec-Websocket-Key' header is missing or blank")
return u.returnError(w, r, http.StatusBadRequest, "websocket: key missing or blank")
}
subprotocol := u.selectSubprotocol(r, responseHeader)
// Negotiate PMCE
var compress bool
if u.EnableCompression {
for _, ext := range parseExtensions(r.Header) {
if ext[""] != "permessage-deflate" {
continue
}
compress = true
break
}
}
var (
netConn net.Conn
br *bufio.Reader
err error
)
@@ -160,25 +136,21 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade
if !ok {
return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker")
}
var brw *bufio.ReadWriter
netConn, brw, err = h.Hijack()
var rw *bufio.ReadWriter
netConn, rw, err = h.Hijack()
if err != nil {
return u.returnError(w, r, http.StatusInternalServerError, err.Error())
}
br = rw.Reader
if brw.Reader.Buffered() > 0 {
if br.Buffered() > 0 {
netConn.Close()
return nil, errors.New("websocket: client sent data before handshake is complete")
}
c := newConnBRW(netConn, true, u.ReadBufferSize, u.WriteBufferSize, brw)
c := newConn(netConn, true, u.ReadBufferSize, u.WriteBufferSize)
c.subprotocol = subprotocol
if compress {
c.newCompressionWriter = compressNoContextTakeover
c.newDecompressionReader = decompressNoContextTakeover
}
p := c.writeBuf[:0]
p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...)
p = append(p, computeAcceptKey(challengeKey)...)
@@ -188,9 +160,6 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade
p = append(p, c.subprotocol...)
p = append(p, "\r\n"...)
}
if compress {
p = append(p, "Sec-Websocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n"...)
}
for k, vs := range responseHeader {
if k == "Sec-Websocket-Protocol" {
continue
@@ -230,11 +199,10 @@ func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeade
// Upgrade upgrades the HTTP server connection to the WebSocket protocol.
//
// Deprecated: Use websocket.Upgrader instead.
// This function is deprecated, use websocket.Upgrader instead.
//
// Upgrade does not perform origin checking. The application is responsible for
// checking the Origin header before calling Upgrade. An example implementation
// of the same origin policy check is:
// The application is responsible for checking the request origin before
// calling Upgrade. An example implementation of the same origin policy is:
//
// if req.Header.Get("Origin") != "http://"+req.Host {
// http.Error(w, "Origin not allowed", 403)
+2 -2
View File
@@ -111,14 +111,14 @@ func nextTokenOrQuoted(s string) (value string, rest string) {
case escape:
escape = false
p[j] = b
j++
j += 1
case b == '\\':
escape = true
case b == '"':
return string(p[:j]), s[i+1:]
default:
p[j] = b
j++
j += 1
}
}
return "", ""
-23
View File
@@ -1,23 +0,0 @@
Copyright (c) 2015, Dave Cheney <dave@cheney.net>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-52
View File
@@ -1,52 +0,0 @@
# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors)
Package errors provides simple error handling primitives.
`go get github.com/pkg/errors`
The traditional error handling idiom in Go is roughly akin to
```go
if err != nil {
return err
}
```
which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error.
## Adding context to an error
The errors.Wrap function returns a new error that adds context to the original error. For example
```go
_, err := ioutil.ReadAll(r)
if err != nil {
return errors.Wrap(err, "read failed")
}
```
## Retrieving the cause of an error
Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`.
```go
type causer interface {
Cause() error
}
```
`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example:
```go
switch err := errors.Cause(err).(type) {
case *MyError:
// handle specifically
default:
// unknown error
}
```
[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors).
## Contributing
We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high.
Before proposing a change, please discuss your change by raising an issue.
## Licence
BSD-2-Clause
-32
View File
@@ -1,32 +0,0 @@
version: build-{build}.{branch}
clone_folder: C:\gopath\src\github.com\pkg\errors
shallow_clone: true # for startup speed
environment:
GOPATH: C:\gopath
platform:
- x64
# http://www.appveyor.com/docs/installed-software
install:
# some helpful output for debugging builds
- go version
- go env
# pre-installed MinGW at C:\MinGW is 32bit only
# but MSYS2 at C:\msys64 has mingw64
- set PATH=C:\msys64\mingw64\bin;%PATH%
- gcc --version
- g++ --version
build_script:
- go install -v ./...
test_script:
- set PATH=C:\gopath\bin;%PATH%
- go test -v ./...
#artifacts:
# - path: '%GOPATH%\bin\*.exe'
deploy: off
-269
View File
@@ -1,269 +0,0 @@
// Package errors provides simple error handling primitives.
//
// The traditional error handling idiom in Go is roughly akin to
//
// 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 by recording a stack trace at the point Wrap is called,
// and the supplied message. For example
//
// _, err := ioutil.ReadAll(r)
// if err != nil {
// return errors.Wrap(err, "read failed")
// }
//
// If additional control is required the errors.WithStack and errors.WithMessage
// functions destructure errors.Wrap into its component operations of annotating
// an error with a stack trace and an a message, respectively.
//
// 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
//
// type causer interface {
// Cause() error
// }
//
// can be inspected by errors.Cause. errors.Cause will recursively retrieve
// the topmost error which does not implement causer, which is assumed to be
// the original cause. For example:
//
// switch err := errors.Cause(err).(type) {
// case *MyError:
// // handle specifically
// default:
// // unknown error
// }
//
// causer interface is not exported by this package, but is considered a part
// of stable public API.
//
// Formatted printing of errors
//
// All error values returned from this package implement fmt.Formatter and can
// be formatted by the fmt package. The following verbs are supported
//
// %s print the error. If the error has a Cause it will be
// printed recursively
// %v see %s
// %+v extended format. Each Frame of the error's StackTrace will
// be printed in detail.
//
// Retrieving the stack trace of an error or wrapper
//
// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are
// invoked. This information can be retrieved with the following interface.
//
// type stackTracer interface {
// StackTrace() errors.StackTrace
// }
//
// Where errors.StackTrace is defined as
//
// type StackTrace []Frame
//
// The Frame type represents a call site in the stack trace. Frame supports
// the fmt.Formatter interface that can be used for printing information about
// the stack trace of this error. For example:
//
// if err, ok := err.(stackTracer); ok {
// for _, f := range err.StackTrace() {
// fmt.Printf("%+s:%d", f)
// }
// }
//
// stackTracer interface is not exported by this package, but is considered a part
// of stable public API.
//
// See the documentation for Frame.Format for more details.
package errors
import (
"fmt"
"io"
)
// New returns an error with the supplied message.
// New also records the stack trace at the point it was called.
func New(message string) error {
return &fundamental{
msg: message,
stack: callers(),
}
}
// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
// Errorf also records the stack trace at the point it was called.
func Errorf(format string, args ...interface{}) error {
return &fundamental{
msg: fmt.Sprintf(format, args...),
stack: callers(),
}
}
// fundamental is an error that has a message and a stack, but no caller.
type fundamental struct {
msg string
*stack
}
func (f *fundamental) Error() string { return f.msg }
func (f *fundamental) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
io.WriteString(s, f.msg)
f.stack.Format(s, verb)
return
}
fallthrough
case 's':
io.WriteString(s, f.msg)
case 'q':
fmt.Fprintf(s, "%q", f.msg)
}
}
// WithStack annotates err with a stack trace at the point WithStack was called.
// If err is nil, WithStack returns nil.
func WithStack(err error) error {
if err == nil {
return nil
}
return &withStack{
err,
callers(),
}
}
type withStack struct {
error
*stack
}
func (w *withStack) Cause() error { return w.error }
func (w *withStack) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
fmt.Fprintf(s, "%+v", w.Cause())
w.stack.Format(s, verb)
return
}
fallthrough
case 's':
io.WriteString(s, w.Error())
case 'q':
fmt.Fprintf(s, "%q", w.Error())
}
}
// Wrap returns an error annotating err with a stack trace
// at the point Wrap is called, and the supplied message.
// If err is nil, Wrap returns nil.
func Wrap(err error, message string) error {
if err == nil {
return nil
}
err = &withMessage{
cause: err,
msg: message,
}
return &withStack{
err,
callers(),
}
}
// Wrapf returns an error annotating err with a stack trace
// at the point Wrapf is call, and the format specifier.
// If err is nil, Wrapf returns nil.
func Wrapf(err error, format string, args ...interface{}) error {
if err == nil {
return nil
}
err = &withMessage{
cause: err,
msg: fmt.Sprintf(format, args...),
}
return &withStack{
err,
callers(),
}
}
// WithMessage annotates err with a new message.
// If err is nil, WithMessage returns nil.
func WithMessage(err error, message string) error {
if err == nil {
return nil
}
return &withMessage{
cause: err,
msg: message,
}
}
type withMessage struct {
cause error
msg string
}
func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() }
func (w *withMessage) Cause() error { return w.cause }
func (w *withMessage) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
fmt.Fprintf(s, "%+v\n", w.Cause())
io.WriteString(s, w.msg)
return
}
fallthrough
case 's', 'q':
io.WriteString(s, w.Error())
}
}
// Cause returns the underlying cause of the error, if possible.
// An error value has a cause if it implements the following
// interface:
//
// type causer interface {
// Cause() error
// }
//
// If the error does not implement Cause, the original error will
// be returned. If the error is nil, nil will be returned without further
// investigation.
func Cause(err error) error {
type causer interface {
Cause() error
}
for err != nil {
cause, ok := err.(causer)
if !ok {
break
}
err = cause.Cause()
}
return err
}
-186
View File
@@ -1,186 +0,0 @@
package errors
import (
"fmt"
"io"
"path"
"runtime"
"strings"
)
// Frame represents a program counter inside a stack frame.
type Frame uintptr
// pc returns the program counter for this frame;
// multiple frames may have the same PC value.
func (f Frame) pc() uintptr { return uintptr(f) - 1 }
// file returns the full path to the file that contains the
// function for this Frame's pc.
func (f Frame) file() string {
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return "unknown"
}
file, _ := fn.FileLine(f.pc())
return file
}
// line returns the line number of source code of the
// function for this Frame's pc.
func (f Frame) line() int {
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return 0
}
_, line := fn.FileLine(f.pc())
return line
}
// Format formats the frame according to the fmt.Formatter interface.
//
// %s source file
// %d source line
// %n function name
// %v equivalent to %s:%d
//
// Format accepts flags that alter the printing of some verbs, as follows:
//
// %+s path of source file relative to the compile time GOPATH
// %+v equivalent to %+s:%d
func (f Frame) Format(s fmt.State, verb rune) {
switch verb {
case 's':
switch {
case s.Flag('+'):
pc := f.pc()
fn := runtime.FuncForPC(pc)
if fn == nil {
io.WriteString(s, "unknown")
} else {
file, _ := fn.FileLine(pc)
fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file)
}
default:
io.WriteString(s, path.Base(f.file()))
}
case 'd':
fmt.Fprintf(s, "%d", f.line())
case 'n':
name := runtime.FuncForPC(f.pc()).Name()
io.WriteString(s, funcname(name))
case 'v':
f.Format(s, 's')
io.WriteString(s, ":")
f.Format(s, 'd')
}
}
// StackTrace is stack of Frames from innermost (newest) to outermost (oldest).
type StackTrace []Frame
// Format formats the stack of Frames according to the fmt.Formatter interface.
//
// %s lists source files for each Frame in the stack
// %v lists the source file and line number for each Frame in the stack
//
// Format accepts flags that alter the printing of some verbs, as follows:
//
// %+v Prints filename, function, and line number for each Frame in the stack.
func (st StackTrace) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
switch {
case s.Flag('+'):
for _, f := range st {
fmt.Fprintf(s, "\n%+v", f)
}
case s.Flag('#'):
fmt.Fprintf(s, "%#v", []Frame(st))
default:
fmt.Fprintf(s, "%v", []Frame(st))
}
case 's':
fmt.Fprintf(s, "%s", []Frame(st))
}
}
// stack represents a stack of program counters.
type stack []uintptr
func (s *stack) Format(st fmt.State, verb rune) {
switch verb {
case 'v':
switch {
case st.Flag('+'):
for _, pc := range *s {
f := Frame(pc)
fmt.Fprintf(st, "\n%+v", f)
}
}
}
}
func (s *stack) StackTrace() StackTrace {
f := make([]Frame, len(*s))
for i := 0; i < len(f); i++ {
f[i] = Frame((*s)[i])
}
return f
}
func callers() *stack {
const depth = 32
var pcs [depth]uintptr
n := runtime.Callers(3, pcs[:])
var st stack = pcs[0:n]
return &st
}
// funcname removes the path prefix component of a function's name reported by func.Name().
func funcname(name string) string {
i := strings.LastIndex(name, "/")
name = name[i+1:]
i = strings.Index(name, ".")
return name[i+1:]
}
func trimGOPATH(name, file string) string {
// Here we want to get the source file path relative to the compile time
// GOPATH. As of Go 1.6.x there is no direct way to know the compiled
// GOPATH at runtime, but we can infer the number of path segments in the
// GOPATH. We note that fn.Name() returns the function name qualified by
// the import path, which does not include the GOPATH. Thus we can trim
// segments from the beginning of the file path until the number of path
// separators remaining is one more than the number of path separators in
// the function name. For example, given:
//
// GOPATH /home/user
// file /home/user/src/pkg/sub/file.go
// fn.Name() pkg/sub.Type.Method
//
// We want to produce:
//
// pkg/sub/file.go
//
// From this we can easily see that fn.Name() has one less path separator
// than our desired output. We count separators from the end of the file
// path until it finds two more than in the function name and then move
// one character forward to preserve the initial path segment without a
// leading separator.
const sep = "/"
goal := strings.Count(name, sep) + 2
i := len(file)
for n := 0; n < goal; n++ {
i = strings.LastIndex(file[:i], sep)
if i == -1 {
// not enough separators found, set i so that the slice expression
// below leaves file unmodified
i = -len(sep)
break
}
}
// get back to 0 or trim the leading separator
file = file[i+len(sep):]
return file
}
+4
View File
@@ -0,0 +1,4 @@
FROM rancher/dind:v0.3.0
COPY ./scripts/bootstrap /scripts/bootstrap
RUN /scripts/bootstrap
WORKDIR /source
+35
View File
@@ -0,0 +1,35 @@
# Go Bindings for Rancher API
# Building
```sh
godep go build ./client
```
# Tests
```sh
godep go test ./client
```
# Contact
For bugs, questions, comments, corrections, suggestions, etc., open an issue in
[rancher/rancher](//github.com/rancher/rancher/issues) with a title starting with `[go-rancher] `.
Or just [click here](//github.com/rancher/rancher/issues/new?title=%5Bgo-rancher%5D%20) to create a new issue.
# License
Copyright (c) 2014-2015 [Rancher Labs, Inc.](http://rancher.com)
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](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.
+7
View File
@@ -0,0 +1,7 @@
package client
type RancherBaseClient struct {
Opts *ClientOpts
Schemas *Schemas
Types map[string]Schema
}
@@ -2,8 +2,8 @@ package client
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
@@ -11,11 +11,10 @@ import (
"net/url"
"os"
"regexp"
"strings"
"time"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
)
const (
@@ -24,9 +23,8 @@ const (
)
var (
debug = false
dialer = &websocket.Dialer{}
privateFieldRegex = regexp.MustCompile("^[[:lower:]]")
debug = false
dialer = &websocket.Dialer{}
)
type ClientOpts struct {
@@ -118,41 +116,14 @@ func appendFilters(urlString string, filters map[string]interface{}) (string, er
q := u.Query()
for k, v := range filters {
if l, ok := v.([]string); ok {
for _, v := range l {
q.Add(k, v)
}
} else {
q.Add(k, fmt.Sprintf("%v", v))
}
q.Add(k, fmt.Sprintf("%v", v))
}
u.RawQuery = q.Encode()
return u.String(), nil
}
func NormalizeUrl(existingUrl string) (string, error) {
u, err := url.Parse(existingUrl)
if err != nil {
return "", err
}
if u.Path == "" || u.Path == "/" {
u.Path = "v2-beta"
} else if u.Path == "/v1" || strings.HasPrefix(u.Path, "/v1/") {
u.Path = strings.Replace(u.Path, "/v1", "/v2-beta", 1)
}
return u.String(), nil
}
func setupRancherBaseClient(rancherClient *RancherBaseClientImpl, opts *ClientOpts) error {
var err error
opts.Url, err = NormalizeUrl(opts.Url)
if err != nil {
return err
}
func setupRancherBaseClient(rancherClient *RancherBaseClient, opts *ClientOpts) error {
if opts.Timeout == 0 {
opts.Timeout = time.Second * 10
}
@@ -226,18 +197,18 @@ func NewListOpts() *ListOpts {
}
}
func (rancherClient *RancherBaseClientImpl) setupRequest(req *http.Request) {
func (rancherClient *RancherBaseClient) setupRequest(req *http.Request) {
req.SetBasicAuth(rancherClient.Opts.AccessKey, rancherClient.Opts.SecretKey)
}
func (rancherClient *RancherBaseClientImpl) newHttpClient() *http.Client {
func (rancherClient *RancherBaseClient) newHttpClient() *http.Client {
if rancherClient.Opts.Timeout == 0 {
rancherClient.Opts.Timeout = time.Second * 10
}
return &http.Client{Timeout: rancherClient.Opts.Timeout}
}
func (rancherClient *RancherBaseClientImpl) doDelete(url string) error {
func (rancherClient *RancherBaseClient) doDelete(url string) error {
client := rancherClient.newHttpClient()
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
@@ -261,21 +232,11 @@ func (rancherClient *RancherBaseClientImpl) doDelete(url string) error {
return nil
}
func (rancherClient *RancherBaseClientImpl) Websocket(url string, headers map[string][]string) (*websocket.Conn, *http.Response, error) {
httpHeaders := http.Header{}
for k, v := range httpHeaders {
httpHeaders[k] = v
}
if rancherClient.Opts != nil {
s := rancherClient.Opts.AccessKey + ":" + rancherClient.Opts.SecretKey
httpHeaders.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(s)))
}
return dialer.Dial(url, http.Header(httpHeaders))
func (rancherClient *RancherBaseClient) Websocket(url string, headers map[string][]string) (*websocket.Conn, *http.Response, error) {
return dialer.Dial(url, http.Header(headers))
}
func (rancherClient *RancherBaseClientImpl) doGet(url string, opts *ListOpts, respObject interface{}) error {
func (rancherClient *RancherBaseClient) doGet(url string, opts *ListOpts, respObject interface{}) error {
if opts == nil {
opts = NewListOpts()
}
@@ -316,18 +277,14 @@ func (rancherClient *RancherBaseClientImpl) doGet(url string, opts *ListOpts, re
fmt.Println("Response <= " + string(byteContent))
}
if err := json.Unmarshal(byteContent, respObject); err != nil {
return errors.Wrap(err, fmt.Sprintf("Failed to parse: %s", byteContent))
}
return nil
return json.Unmarshal(byteContent, respObject)
}
func (rancherClient *RancherBaseClientImpl) List(schemaType string, opts *ListOpts, respObject interface{}) error {
func (rancherClient *RancherBaseClient) List(schemaType string, opts *ListOpts, respObject interface{}) error {
return rancherClient.doList(schemaType, opts, respObject)
}
func (rancherClient *RancherBaseClientImpl) doList(schemaType string, opts *ListOpts, respObject interface{}) error {
func (rancherClient *RancherBaseClient) doList(schemaType string, opts *ListOpts, respObject interface{}) error {
schema, ok := rancherClient.Types[schemaType]
if !ok {
return errors.New("Unknown schema type [" + schemaType + "]")
@@ -345,15 +302,11 @@ func (rancherClient *RancherBaseClientImpl) doList(schemaType string, opts *List
return rancherClient.doGet(collectionUrl, opts, respObject)
}
func (rancherClient *RancherBaseClientImpl) doNext(nextUrl string, respObject interface{}) error {
return rancherClient.doGet(nextUrl, nil, respObject)
}
func (rancherClient *RancherBaseClientImpl) Post(url string, createObj interface{}, respObject interface{}) error {
func (rancherClient *RancherBaseClient) Post(url string, createObj interface{}, respObject interface{}) error {
return rancherClient.doModify("POST", url, createObj, respObject)
}
func (rancherClient *RancherBaseClientImpl) GetLink(resource Resource, link string, respObject interface{}) error {
func (rancherClient *RancherBaseClient) GetLink(resource Resource, link string, respObject interface{}) error {
url := resource.Links[link]
if url == "" {
return fmt.Errorf("Failed to find link: %s", link)
@@ -362,7 +315,7 @@ func (rancherClient *RancherBaseClientImpl) GetLink(resource Resource, link stri
return rancherClient.doGet(url, &ListOpts{}, respObject)
}
func (rancherClient *RancherBaseClientImpl) doModify(method string, url string, createObj interface{}, respObject interface{}) error {
func (rancherClient *RancherBaseClient) doModify(method string, url string, createObj interface{}, respObject interface{}) error {
bodyContent, err := json.Marshal(createObj)
if err != nil {
return err
@@ -381,6 +334,7 @@ func (rancherClient *RancherBaseClientImpl) doModify(method string, url string,
rancherClient.setupRequest(req)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Content-Length", string(len(bodyContent)))
resp, err := client.Do(req)
if err != nil {
@@ -408,11 +362,11 @@ func (rancherClient *RancherBaseClientImpl) doModify(method string, url string,
return nil
}
func (rancherClient *RancherBaseClientImpl) Create(schemaType string, createObj interface{}, respObject interface{}) error {
func (rancherClient *RancherBaseClient) Create(schemaType string, createObj interface{}, respObject interface{}) error {
return rancherClient.doCreate(schemaType, createObj, respObject)
}
func (rancherClient *RancherBaseClientImpl) doCreate(schemaType string, createObj interface{}, respObject interface{}) error {
func (rancherClient *RancherBaseClient) doCreate(schemaType string, createObj interface{}, respObject interface{}) error {
if createObj == nil {
createObj = map[string]string{}
}
@@ -440,11 +394,11 @@ func (rancherClient *RancherBaseClientImpl) doCreate(schemaType string, createOb
return rancherClient.doModify("POST", collectionUrl, createObj, respObject)
}
func (rancherClient *RancherBaseClientImpl) Update(schemaType string, existing *Resource, updates interface{}, respObject interface{}) error {
func (rancherClient *RancherBaseClient) Update(schemaType string, existing *Resource, updates interface{}, respObject interface{}) error {
return rancherClient.doUpdate(schemaType, existing, updates, respObject)
}
func (rancherClient *RancherBaseClientImpl) doUpdate(schemaType string, existing *Resource, updates interface{}, respObject interface{}) error {
func (rancherClient *RancherBaseClient) doUpdate(schemaType string, existing *Resource, updates interface{}, respObject interface{}) error {
if existing == nil {
return errors.New("Existing object is nil")
}
@@ -474,11 +428,11 @@ func (rancherClient *RancherBaseClientImpl) doUpdate(schemaType string, existing
return rancherClient.doModify("PUT", selfUrl, updates, respObject)
}
func (rancherClient *RancherBaseClientImpl) ById(schemaType string, id string, respObject interface{}) error {
func (rancherClient *RancherBaseClient) ById(schemaType string, id string, respObject interface{}) error {
return rancherClient.doById(schemaType, id, respObject)
}
func (rancherClient *RancherBaseClientImpl) doById(schemaType string, id string, respObject interface{}) error {
func (rancherClient *RancherBaseClient) doById(schemaType string, id string, respObject interface{}) error {
schema, ok := rancherClient.Types[schemaType]
if !ok {
return errors.New("Unknown schema type [" + schemaType + "]")
@@ -498,14 +452,14 @@ func (rancherClient *RancherBaseClientImpl) doById(schemaType string, id string,
return err
}
func (rancherClient *RancherBaseClientImpl) Delete(existing *Resource) error {
func (rancherClient *RancherBaseClient) Delete(existing *Resource) error {
if existing == nil {
return nil
}
return rancherClient.doResourceDelete(existing.Type, existing)
}
func (rancherClient *RancherBaseClientImpl) doResourceDelete(schemaType string, existing *Resource) error {
func (rancherClient *RancherBaseClient) doResourceDelete(schemaType string, existing *Resource) error {
schema, ok := rancherClient.Types[schemaType]
if !ok {
return errors.New("Unknown schema type [" + schemaType + "]")
@@ -523,7 +477,7 @@ func (rancherClient *RancherBaseClientImpl) doResourceDelete(schemaType string,
return rancherClient.doDelete(selfUrl)
}
func (rancherClient *RancherBaseClientImpl) Reload(existing *Resource, output interface{}) error {
func (rancherClient *RancherBaseClient) Reload(existing *Resource, output interface{}) error {
selfUrl, ok := existing.Links[SELF]
if !ok {
return errors.New(fmt.Sprintf("Failed to find self URL of [%v]", existing))
@@ -532,12 +486,7 @@ func (rancherClient *RancherBaseClientImpl) Reload(existing *Resource, output in
return rancherClient.doGet(selfUrl, NewListOpts(), output)
}
func (rancherClient *RancherBaseClientImpl) Action(schemaType string, action string,
existing *Resource, inputObject, respObject interface{}) error {
return rancherClient.doAction(schemaType, action, existing, inputObject, respObject)
}
func (rancherClient *RancherBaseClientImpl) doAction(schemaType string, action string,
func (rancherClient *RancherBaseClient) doAction(schemaType string, action string,
existing *Resource, inputObject, respObject interface{}) error {
if existing == nil {
@@ -600,18 +549,6 @@ func (rancherClient *RancherBaseClientImpl) doAction(schemaType string, action s
return json.Unmarshal(byteContent, respObject)
}
func (rancherClient *RancherBaseClientImpl) GetOpts() *ClientOpts {
return rancherClient.Opts
}
func (rancherClient *RancherBaseClientImpl) GetSchemas() *Schemas {
return rancherClient.Schemas
}
func (rancherClient *RancherBaseClientImpl) GetTypes() map[string]Schema {
return rancherClient.Types
}
func init() {
debug = os.Getenv("RANCHER_CLIENT_DEBUG") == "true"
if debug {
@@ -36,14 +36,11 @@ type Account struct {
TransitioningProgress int64 `json:"transitioningProgress,omitempty" yaml:"transitioning_progress,omitempty"`
Uuid string `json:"uuid,omitempty" yaml:"uuid,omitempty"`
Version string `json:"version,omitempty" yaml:"version,omitempty"`
}
type AccountCollection struct {
Collection
Data []Account `json:"data,omitempty"`
client *AccountClient
Data []Account `json:"data,omitempty"`
}
type AccountClient struct {
@@ -67,9 +64,9 @@ type AccountOperations interface {
ActionRemove(*Account) (*Account, error)
ActionUpdate(*Account) (*Account, error)
ActionRestore(*Account) (*Account, error)
ActionUpgrade(*Account) (*Account, error)
ActionUpdate(*Account) (*Account, error)
}
func newAccountClient(rancherClient *RancherClient) *AccountClient {
@@ -93,20 +90,9 @@ func (c *AccountClient) Update(existing *Account, updates interface{}) (*Account
func (c *AccountClient) List(opts *ListOpts) (*AccountCollection, error) {
resp := &AccountCollection{}
err := c.rancherClient.doList(ACCOUNT_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *AccountCollection) Next() (*AccountCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &AccountCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *AccountClient) ById(id string) (*Account, error) {
resp := &Account{}
err := c.rancherClient.doById(ACCOUNT_TYPE, id, resp)
@@ -167,6 +153,15 @@ func (c *AccountClient) ActionRemove(resource *Account) (*Account, error) {
return resp, err
}
func (c *AccountClient) ActionRestore(resource *Account) (*Account, error) {
resp := &Account{}
err := c.rancherClient.doAction(ACCOUNT_TYPE, "restore", &resource.Resource, nil, resp)
return resp, err
}
func (c *AccountClient) ActionUpdate(resource *Account) (*Account, error) {
resp := &Account{}
@@ -175,12 +170,3 @@ func (c *AccountClient) ActionUpdate(resource *Account) (*Account, error) {
return resp, err
}
func (c *AccountClient) ActionUpgrade(resource *Account) (*Account, error) {
resp := &Account{}
err := c.rancherClient.doAction(ACCOUNT_TYPE, "upgrade", &resource.Resource, nil, resp)
return resp, err
}
@@ -20,8 +20,7 @@ type ActiveSetting struct {
type ActiveSettingCollection struct {
Collection
Data []ActiveSetting `json:"data,omitempty"`
client *ActiveSettingClient
Data []ActiveSetting `json:"data,omitempty"`
}
type ActiveSettingClient struct {
@@ -57,20 +56,9 @@ func (c *ActiveSettingClient) Update(existing *ActiveSetting, updates interface{
func (c *ActiveSettingClient) List(opts *ListOpts) (*ActiveSettingCollection, error) {
resp := &ActiveSettingCollection{}
err := c.rancherClient.doList(ACTIVE_SETTING_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *ActiveSettingCollection) Next() (*ActiveSettingCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &ActiveSettingCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *ActiveSettingClient) ById(id string) (*ActiveSetting, error) {
resp := &ActiveSetting{}
err := c.rancherClient.doById(ACTIVE_SETTING_TYPE, id, resp)
@@ -0,0 +1,64 @@
package client
const (
ADD_LABEL_INPUT_TYPE = "addLabelInput"
)
type AddLabelInput struct {
Resource
Key string `json:"key,omitempty"`
Value string `json:"value,omitempty"`
}
type AddLabelInputCollection struct {
Collection
Data []AddLabelInput `json:"data,omitempty"`
}
type AddLabelInputClient struct {
rancherClient *RancherClient
}
type AddLabelInputOperations interface {
List(opts *ListOpts) (*AddLabelInputCollection, error)
Create(opts *AddLabelInput) (*AddLabelInput, error)
Update(existing *AddLabelInput, updates interface{}) (*AddLabelInput, error)
ById(id string) (*AddLabelInput, error)
Delete(container *AddLabelInput) error
}
func newAddLabelInputClient(rancherClient *RancherClient) *AddLabelInputClient {
return &AddLabelInputClient{
rancherClient: rancherClient,
}
}
func (c *AddLabelInputClient) Create(container *AddLabelInput) (*AddLabelInput, error) {
resp := &AddLabelInput{}
err := c.rancherClient.doCreate(ADD_LABEL_INPUT_TYPE, container, resp)
return resp, err
}
func (c *AddLabelInputClient) Update(existing *AddLabelInput, updates interface{}) (*AddLabelInput, error) {
resp := &AddLabelInput{}
err := c.rancherClient.doUpdate(ADD_LABEL_INPUT_TYPE, &existing.Resource, updates, resp)
return resp, err
}
func (c *AddLabelInputClient) List(opts *ListOpts) (*AddLabelInputCollection, error) {
resp := &AddLabelInputCollection{}
err := c.rancherClient.doList(ADD_LABEL_INPUT_TYPE, opts, resp)
return resp, err
}
func (c *AddLabelInputClient) ById(id string) (*AddLabelInput, error) {
resp := &AddLabelInput{}
err := c.rancherClient.doById(ADD_LABEL_INPUT_TYPE, id, resp)
return resp, err
}
func (c *AddLabelInputClient) Delete(container *AddLabelInput) error {
return c.rancherClient.doResourceDelete(ADD_LABEL_INPUT_TYPE, &container.Resource)
}
@@ -0,0 +1,69 @@
package client
const (
ADD_LOAD_BALANCER_INPUT_TYPE = "addLoadBalancerInput"
)
type AddLoadBalancerInput struct {
Resource
LoadBalancerId string `json:"loadBalancerId,omitempty" yaml:"load_balancer_id,omitempty"`
Weight int64 `json:"weight,omitempty" yaml:"weight,omitempty"`
}
type AddLoadBalancerInputCollection struct {
Collection
Data []AddLoadBalancerInput `json:"data,omitempty"`
}
type AddLoadBalancerInputClient struct {
rancherClient *RancherClient
}
type AddLoadBalancerInputOperations interface {
List(opts *ListOpts) (*AddLoadBalancerInputCollection, error)
Create(opts *AddLoadBalancerInput) (*AddLoadBalancerInput, error)
Update(existing *AddLoadBalancerInput, updates interface{}) (*AddLoadBalancerInput, error)
ById(id string) (*AddLoadBalancerInput, error)
Delete(container *AddLoadBalancerInput) error
}
func newAddLoadBalancerInputClient(rancherClient *RancherClient) *AddLoadBalancerInputClient {
return &AddLoadBalancerInputClient{
rancherClient: rancherClient,
}
}
func (c *AddLoadBalancerInputClient) Create(container *AddLoadBalancerInput) (*AddLoadBalancerInput, error) {
resp := &AddLoadBalancerInput{}
err := c.rancherClient.doCreate(ADD_LOAD_BALANCER_INPUT_TYPE, container, resp)
return resp, err
}
func (c *AddLoadBalancerInputClient) Update(existing *AddLoadBalancerInput, updates interface{}) (*AddLoadBalancerInput, error) {
resp := &AddLoadBalancerInput{}
err := c.rancherClient.doUpdate(ADD_LOAD_BALANCER_INPUT_TYPE, &existing.Resource, updates, resp)
return resp, err
}
func (c *AddLoadBalancerInputClient) List(opts *ListOpts) (*AddLoadBalancerInputCollection, error) {
resp := &AddLoadBalancerInputCollection{}
err := c.rancherClient.doList(ADD_LOAD_BALANCER_INPUT_TYPE, opts, resp)
return resp, err
}
func (c *AddLoadBalancerInputClient) ById(id string) (*AddLoadBalancerInput, error) {
resp := &AddLoadBalancerInput{}
err := c.rancherClient.doById(ADD_LOAD_BALANCER_INPUT_TYPE, id, resp)
if apiError, ok := err.(*ApiError); ok {
if apiError.StatusCode == 404 {
return nil, nil
}
}
return resp, err
}
func (c *AddLoadBalancerInputClient) Delete(container *AddLoadBalancerInput) error {
return c.rancherClient.doResourceDelete(ADD_LOAD_BALANCER_INPUT_TYPE, &container.Resource)
}
@@ -12,8 +12,7 @@ type AddOutputsInput struct {
type AddOutputsInputCollection struct {
Collection
Data []AddOutputsInput `json:"data,omitempty"`
client *AddOutputsInputClient
Data []AddOutputsInput `json:"data,omitempty"`
}
type AddOutputsInputClient struct {
@@ -49,20 +48,9 @@ func (c *AddOutputsInputClient) Update(existing *AddOutputsInput, updates interf
func (c *AddOutputsInputClient) List(opts *ListOpts) (*AddOutputsInputCollection, error) {
resp := &AddOutputsInputCollection{}
err := c.rancherClient.doList(ADD_OUTPUTS_INPUT_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *AddOutputsInputCollection) Next() (*AddOutputsInputCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &AddOutputsInputCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *AddOutputsInputClient) ById(id string) (*AddOutputsInput, error) {
resp := &AddOutputsInput{}
err := c.rancherClient.doById(ADD_OUTPUTS_INPUT_TYPE, id, resp)
@@ -0,0 +1,67 @@
package client
const (
ADD_REMOVE_CLUSTER_HOST_INPUT_TYPE = "addRemoveClusterHostInput"
)
type AddRemoveClusterHostInput struct {
Resource
HostId string `json:"hostId,omitempty" yaml:"host_id,omitempty"`
}
type AddRemoveClusterHostInputCollection struct {
Collection
Data []AddRemoveClusterHostInput `json:"data,omitempty"`
}
type AddRemoveClusterHostInputClient struct {
rancherClient *RancherClient
}
type AddRemoveClusterHostInputOperations interface {
List(opts *ListOpts) (*AddRemoveClusterHostInputCollection, error)
Create(opts *AddRemoveClusterHostInput) (*AddRemoveClusterHostInput, error)
Update(existing *AddRemoveClusterHostInput, updates interface{}) (*AddRemoveClusterHostInput, error)
ById(id string) (*AddRemoveClusterHostInput, error)
Delete(container *AddRemoveClusterHostInput) error
}
func newAddRemoveClusterHostInputClient(rancherClient *RancherClient) *AddRemoveClusterHostInputClient {
return &AddRemoveClusterHostInputClient{
rancherClient: rancherClient,
}
}
func (c *AddRemoveClusterHostInputClient) Create(container *AddRemoveClusterHostInput) (*AddRemoveClusterHostInput, error) {
resp := &AddRemoveClusterHostInput{}
err := c.rancherClient.doCreate(ADD_REMOVE_CLUSTER_HOST_INPUT_TYPE, container, resp)
return resp, err
}
func (c *AddRemoveClusterHostInputClient) Update(existing *AddRemoveClusterHostInput, updates interface{}) (*AddRemoveClusterHostInput, error) {
resp := &AddRemoveClusterHostInput{}
err := c.rancherClient.doUpdate(ADD_REMOVE_CLUSTER_HOST_INPUT_TYPE, &existing.Resource, updates, resp)
return resp, err
}
func (c *AddRemoveClusterHostInputClient) List(opts *ListOpts) (*AddRemoveClusterHostInputCollection, error) {
resp := &AddRemoveClusterHostInputCollection{}
err := c.rancherClient.doList(ADD_REMOVE_CLUSTER_HOST_INPUT_TYPE, opts, resp)
return resp, err
}
func (c *AddRemoveClusterHostInputClient) ById(id string) (*AddRemoveClusterHostInput, error) {
resp := &AddRemoveClusterHostInput{}
err := c.rancherClient.doById(ADD_REMOVE_CLUSTER_HOST_INPUT_TYPE, id, resp)
if apiError, ok := err.(*ApiError); ok {
if apiError.StatusCode == 404 {
return nil, nil
}
}
return resp, err
}
func (c *AddRemoveClusterHostInputClient) Delete(container *AddRemoveClusterHostInput) error {
return c.rancherClient.doResourceDelete(ADD_REMOVE_CLUSTER_HOST_INPUT_TYPE, &container.Resource)
}
@@ -0,0 +1,67 @@
package client
const (
ADD_REMOVE_LOAD_BALANCER_HOST_INPUT_TYPE = "addRemoveLoadBalancerHostInput"
)
type AddRemoveLoadBalancerHostInput struct {
Resource
HostId string `json:"hostId,omitempty" yaml:"host_id,omitempty"`
}
type AddRemoveLoadBalancerHostInputCollection struct {
Collection
Data []AddRemoveLoadBalancerHostInput `json:"data,omitempty"`
}
type AddRemoveLoadBalancerHostInputClient struct {
rancherClient *RancherClient
}
type AddRemoveLoadBalancerHostInputOperations interface {
List(opts *ListOpts) (*AddRemoveLoadBalancerHostInputCollection, error)
Create(opts *AddRemoveLoadBalancerHostInput) (*AddRemoveLoadBalancerHostInput, error)
Update(existing *AddRemoveLoadBalancerHostInput, updates interface{}) (*AddRemoveLoadBalancerHostInput, error)
ById(id string) (*AddRemoveLoadBalancerHostInput, error)
Delete(container *AddRemoveLoadBalancerHostInput) error
}
func newAddRemoveLoadBalancerHostInputClient(rancherClient *RancherClient) *AddRemoveLoadBalancerHostInputClient {
return &AddRemoveLoadBalancerHostInputClient{
rancherClient: rancherClient,
}
}
func (c *AddRemoveLoadBalancerHostInputClient) Create(container *AddRemoveLoadBalancerHostInput) (*AddRemoveLoadBalancerHostInput, error) {
resp := &AddRemoveLoadBalancerHostInput{}
err := c.rancherClient.doCreate(ADD_REMOVE_LOAD_BALANCER_HOST_INPUT_TYPE, container, resp)
return resp, err
}
func (c *AddRemoveLoadBalancerHostInputClient) Update(existing *AddRemoveLoadBalancerHostInput, updates interface{}) (*AddRemoveLoadBalancerHostInput, error) {
resp := &AddRemoveLoadBalancerHostInput{}
err := c.rancherClient.doUpdate(ADD_REMOVE_LOAD_BALANCER_HOST_INPUT_TYPE, &existing.Resource, updates, resp)
return resp, err
}
func (c *AddRemoveLoadBalancerHostInputClient) List(opts *ListOpts) (*AddRemoveLoadBalancerHostInputCollection, error) {
resp := &AddRemoveLoadBalancerHostInputCollection{}
err := c.rancherClient.doList(ADD_REMOVE_LOAD_BALANCER_HOST_INPUT_TYPE, opts, resp)
return resp, err
}
func (c *AddRemoveLoadBalancerHostInputClient) ById(id string) (*AddRemoveLoadBalancerHostInput, error) {
resp := &AddRemoveLoadBalancerHostInput{}
err := c.rancherClient.doById(ADD_REMOVE_LOAD_BALANCER_HOST_INPUT_TYPE, id, resp)
if apiError, ok := err.(*ApiError); ok {
if apiError.StatusCode == 404 {
return nil, nil
}
}
return resp, err
}
func (c *AddRemoveLoadBalancerHostInputClient) Delete(container *AddRemoveLoadBalancerHostInput) error {
return c.rancherClient.doResourceDelete(ADD_REMOVE_LOAD_BALANCER_HOST_INPUT_TYPE, &container.Resource)
}
@@ -0,0 +1,67 @@
package client
const (
ADD_REMOVE_LOAD_BALANCER_LISTENER_INPUT_TYPE = "addRemoveLoadBalancerListenerInput"
)
type AddRemoveLoadBalancerListenerInput struct {
Resource
LoadBalancerListenerId string `json:"loadBalancerListenerId,omitempty" yaml:"load_balancer_listener_id,omitempty"`
}
type AddRemoveLoadBalancerListenerInputCollection struct {
Collection
Data []AddRemoveLoadBalancerListenerInput `json:"data,omitempty"`
}
type AddRemoveLoadBalancerListenerInputClient struct {
rancherClient *RancherClient
}
type AddRemoveLoadBalancerListenerInputOperations interface {
List(opts *ListOpts) (*AddRemoveLoadBalancerListenerInputCollection, error)
Create(opts *AddRemoveLoadBalancerListenerInput) (*AddRemoveLoadBalancerListenerInput, error)
Update(existing *AddRemoveLoadBalancerListenerInput, updates interface{}) (*AddRemoveLoadBalancerListenerInput, error)
ById(id string) (*AddRemoveLoadBalancerListenerInput, error)
Delete(container *AddRemoveLoadBalancerListenerInput) error
}
func newAddRemoveLoadBalancerListenerInputClient(rancherClient *RancherClient) *AddRemoveLoadBalancerListenerInputClient {
return &AddRemoveLoadBalancerListenerInputClient{
rancherClient: rancherClient,
}
}
func (c *AddRemoveLoadBalancerListenerInputClient) Create(container *AddRemoveLoadBalancerListenerInput) (*AddRemoveLoadBalancerListenerInput, error) {
resp := &AddRemoveLoadBalancerListenerInput{}
err := c.rancherClient.doCreate(ADD_REMOVE_LOAD_BALANCER_LISTENER_INPUT_TYPE, container, resp)
return resp, err
}
func (c *AddRemoveLoadBalancerListenerInputClient) Update(existing *AddRemoveLoadBalancerListenerInput, updates interface{}) (*AddRemoveLoadBalancerListenerInput, error) {
resp := &AddRemoveLoadBalancerListenerInput{}
err := c.rancherClient.doUpdate(ADD_REMOVE_LOAD_BALANCER_LISTENER_INPUT_TYPE, &existing.Resource, updates, resp)
return resp, err
}
func (c *AddRemoveLoadBalancerListenerInputClient) List(opts *ListOpts) (*AddRemoveLoadBalancerListenerInputCollection, error) {
resp := &AddRemoveLoadBalancerListenerInputCollection{}
err := c.rancherClient.doList(ADD_REMOVE_LOAD_BALANCER_LISTENER_INPUT_TYPE, opts, resp)
return resp, err
}
func (c *AddRemoveLoadBalancerListenerInputClient) ById(id string) (*AddRemoveLoadBalancerListenerInput, error) {
resp := &AddRemoveLoadBalancerListenerInput{}
err := c.rancherClient.doById(ADD_REMOVE_LOAD_BALANCER_LISTENER_INPUT_TYPE, id, resp)
if apiError, ok := err.(*ApiError); ok {
if apiError.StatusCode == 404 {
return nil, nil
}
}
return resp, err
}
func (c *AddRemoveLoadBalancerListenerInputClient) Delete(container *AddRemoveLoadBalancerListenerInput) error {
return c.rancherClient.doResourceDelete(ADD_REMOVE_LOAD_BALANCER_LISTENER_INPUT_TYPE, &container.Resource)
}
@@ -0,0 +1,67 @@
package client
const (
ADD_REMOVE_LOAD_BALANCER_SERVICE_LINK_INPUT_TYPE = "addRemoveLoadBalancerServiceLinkInput"
)
type AddRemoveLoadBalancerServiceLinkInput struct {
Resource
ServiceLink LoadBalancerServiceLink `json:"serviceLink,omitempty" yaml:"service_link,omitempty"`
}
type AddRemoveLoadBalancerServiceLinkInputCollection struct {
Collection
Data []AddRemoveLoadBalancerServiceLinkInput `json:"data,omitempty"`
}
type AddRemoveLoadBalancerServiceLinkInputClient struct {
rancherClient *RancherClient
}
type AddRemoveLoadBalancerServiceLinkInputOperations interface {
List(opts *ListOpts) (*AddRemoveLoadBalancerServiceLinkInputCollection, error)
Create(opts *AddRemoveLoadBalancerServiceLinkInput) (*AddRemoveLoadBalancerServiceLinkInput, error)
Update(existing *AddRemoveLoadBalancerServiceLinkInput, updates interface{}) (*AddRemoveLoadBalancerServiceLinkInput, error)
ById(id string) (*AddRemoveLoadBalancerServiceLinkInput, error)
Delete(container *AddRemoveLoadBalancerServiceLinkInput) error
}
func newAddRemoveLoadBalancerServiceLinkInputClient(rancherClient *RancherClient) *AddRemoveLoadBalancerServiceLinkInputClient {
return &AddRemoveLoadBalancerServiceLinkInputClient{
rancherClient: rancherClient,
}
}
func (c *AddRemoveLoadBalancerServiceLinkInputClient) Create(container *AddRemoveLoadBalancerServiceLinkInput) (*AddRemoveLoadBalancerServiceLinkInput, error) {
resp := &AddRemoveLoadBalancerServiceLinkInput{}
err := c.rancherClient.doCreate(ADD_REMOVE_LOAD_BALANCER_SERVICE_LINK_INPUT_TYPE, container, resp)
return resp, err
}
func (c *AddRemoveLoadBalancerServiceLinkInputClient) Update(existing *AddRemoveLoadBalancerServiceLinkInput, updates interface{}) (*AddRemoveLoadBalancerServiceLinkInput, error) {
resp := &AddRemoveLoadBalancerServiceLinkInput{}
err := c.rancherClient.doUpdate(ADD_REMOVE_LOAD_BALANCER_SERVICE_LINK_INPUT_TYPE, &existing.Resource, updates, resp)
return resp, err
}
func (c *AddRemoveLoadBalancerServiceLinkInputClient) List(opts *ListOpts) (*AddRemoveLoadBalancerServiceLinkInputCollection, error) {
resp := &AddRemoveLoadBalancerServiceLinkInputCollection{}
err := c.rancherClient.doList(ADD_REMOVE_LOAD_BALANCER_SERVICE_LINK_INPUT_TYPE, opts, resp)
return resp, err
}
func (c *AddRemoveLoadBalancerServiceLinkInputClient) ById(id string) (*AddRemoveLoadBalancerServiceLinkInput, error) {
resp := &AddRemoveLoadBalancerServiceLinkInput{}
err := c.rancherClient.doById(ADD_REMOVE_LOAD_BALANCER_SERVICE_LINK_INPUT_TYPE, id, resp)
if apiError, ok := err.(*ApiError); ok {
if apiError.StatusCode == 404 {
return nil, nil
}
}
return resp, err
}
func (c *AddRemoveLoadBalancerServiceLinkInputClient) Delete(container *AddRemoveLoadBalancerServiceLinkInput) error {
return c.rancherClient.doResourceDelete(ADD_REMOVE_LOAD_BALANCER_SERVICE_LINK_INPUT_TYPE, &container.Resource)
}
@@ -0,0 +1,67 @@
package client
const (
ADD_REMOVE_LOAD_BALANCER_TARGET_INPUT_TYPE = "addRemoveLoadBalancerTargetInput"
)
type AddRemoveLoadBalancerTargetInput struct {
Resource
LoadBalancerTarget LoadBalancerTarget `json:"loadBalancerTarget,omitempty" yaml:"load_balancer_target,omitempty"`
}
type AddRemoveLoadBalancerTargetInputCollection struct {
Collection
Data []AddRemoveLoadBalancerTargetInput `json:"data,omitempty"`
}
type AddRemoveLoadBalancerTargetInputClient struct {
rancherClient *RancherClient
}
type AddRemoveLoadBalancerTargetInputOperations interface {
List(opts *ListOpts) (*AddRemoveLoadBalancerTargetInputCollection, error)
Create(opts *AddRemoveLoadBalancerTargetInput) (*AddRemoveLoadBalancerTargetInput, error)
Update(existing *AddRemoveLoadBalancerTargetInput, updates interface{}) (*AddRemoveLoadBalancerTargetInput, error)
ById(id string) (*AddRemoveLoadBalancerTargetInput, error)
Delete(container *AddRemoveLoadBalancerTargetInput) error
}
func newAddRemoveLoadBalancerTargetInputClient(rancherClient *RancherClient) *AddRemoveLoadBalancerTargetInputClient {
return &AddRemoveLoadBalancerTargetInputClient{
rancherClient: rancherClient,
}
}
func (c *AddRemoveLoadBalancerTargetInputClient) Create(container *AddRemoveLoadBalancerTargetInput) (*AddRemoveLoadBalancerTargetInput, error) {
resp := &AddRemoveLoadBalancerTargetInput{}
err := c.rancherClient.doCreate(ADD_REMOVE_LOAD_BALANCER_TARGET_INPUT_TYPE, container, resp)
return resp, err
}
func (c *AddRemoveLoadBalancerTargetInputClient) Update(existing *AddRemoveLoadBalancerTargetInput, updates interface{}) (*AddRemoveLoadBalancerTargetInput, error) {
resp := &AddRemoveLoadBalancerTargetInput{}
err := c.rancherClient.doUpdate(ADD_REMOVE_LOAD_BALANCER_TARGET_INPUT_TYPE, &existing.Resource, updates, resp)
return resp, err
}
func (c *AddRemoveLoadBalancerTargetInputClient) List(opts *ListOpts) (*AddRemoveLoadBalancerTargetInputCollection, error) {
resp := &AddRemoveLoadBalancerTargetInputCollection{}
err := c.rancherClient.doList(ADD_REMOVE_LOAD_BALANCER_TARGET_INPUT_TYPE, opts, resp)
return resp, err
}
func (c *AddRemoveLoadBalancerTargetInputClient) ById(id string) (*AddRemoveLoadBalancerTargetInput, error) {
resp := &AddRemoveLoadBalancerTargetInput{}
err := c.rancherClient.doById(ADD_REMOVE_LOAD_BALANCER_TARGET_INPUT_TYPE, id, resp)
if apiError, ok := err.(*ApiError); ok {
if apiError.StatusCode == 404 {
return nil, nil
}
}
return resp, err
}
func (c *AddRemoveLoadBalancerTargetInputClient) Delete(container *AddRemoveLoadBalancerTargetInput) error {
return c.rancherClient.doResourceDelete(ADD_REMOVE_LOAD_BALANCER_TARGET_INPUT_TYPE, &container.Resource)
}
@@ -12,8 +12,7 @@ type AddRemoveServiceLinkInput struct {
type AddRemoveServiceLinkInputCollection struct {
Collection
Data []AddRemoveServiceLinkInput `json:"data,omitempty"`
client *AddRemoveServiceLinkInputClient
Data []AddRemoveServiceLinkInput `json:"data,omitempty"`
}
type AddRemoveServiceLinkInputClient struct {
@@ -49,20 +48,9 @@ func (c *AddRemoveServiceLinkInputClient) Update(existing *AddRemoveServiceLinkI
func (c *AddRemoveServiceLinkInputClient) List(opts *ListOpts) (*AddRemoveServiceLinkInputCollection, error) {
resp := &AddRemoveServiceLinkInputCollection{}
err := c.rancherClient.doList(ADD_REMOVE_SERVICE_LINK_INPUT_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *AddRemoveServiceLinkInputCollection) Next() (*AddRemoveServiceLinkInputCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &AddRemoveServiceLinkInputCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *AddRemoveServiceLinkInputClient) ById(id string) (*AddRemoveServiceLinkInput, error) {
resp := &AddRemoveServiceLinkInput{}
err := c.rancherClient.doById(ADD_REMOVE_SERVICE_LINK_INPUT_TYPE, id, resp)
@@ -40,8 +40,7 @@ type Agent struct {
type AgentCollection struct {
Collection
Data []Agent `json:"data,omitempty"`
client *AgentClient
Data []Agent `json:"data,omitempty"`
}
type AgentClient struct {
@@ -61,16 +60,14 @@ type AgentOperations interface {
ActionDeactivate(*Agent) (*Agent, error)
ActionDisconnect(*Agent) (*Agent, error)
ActionFinishreconnect(*Agent) (*Agent, error)
ActionPurge(*Agent) (*Agent, error)
ActionReconnect(*Agent) (*Agent, error)
ActionRemove(*Agent) (*Agent, error)
ActionRestore(*Agent) (*Agent, error)
ActionUpdate(*Agent) (*Agent, error)
}
@@ -95,20 +92,9 @@ func (c *AgentClient) Update(existing *Agent, updates interface{}) (*Agent, erro
func (c *AgentClient) List(opts *ListOpts) (*AgentCollection, error) {
resp := &AgentCollection{}
err := c.rancherClient.doList(AGENT_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *AgentCollection) Next() (*AgentCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &AgentCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *AgentClient) ById(id string) (*Agent, error) {
resp := &Agent{}
err := c.rancherClient.doById(AGENT_TYPE, id, resp)
@@ -151,24 +137,6 @@ func (c *AgentClient) ActionDeactivate(resource *Agent) (*Agent, error) {
return resp, err
}
func (c *AgentClient) ActionDisconnect(resource *Agent) (*Agent, error) {
resp := &Agent{}
err := c.rancherClient.doAction(AGENT_TYPE, "disconnect", &resource.Resource, nil, resp)
return resp, err
}
func (c *AgentClient) ActionFinishreconnect(resource *Agent) (*Agent, error) {
resp := &Agent{}
err := c.rancherClient.doAction(AGENT_TYPE, "finishreconnect", &resource.Resource, nil, resp)
return resp, err
}
func (c *AgentClient) ActionPurge(resource *Agent) (*Agent, error) {
resp := &Agent{}
@@ -196,6 +164,15 @@ func (c *AgentClient) ActionRemove(resource *Agent) (*Agent, error) {
return resp, err
}
func (c *AgentClient) ActionRestore(resource *Agent) (*Agent, error) {
resp := &Agent{}
err := c.rancherClient.doAction(AGENT_TYPE, "restore", &resource.Resource, nil, resp)
return resp, err
}
func (c *AgentClient) ActionUpdate(resource *Agent) (*Agent, error) {
resp := &Agent{}
@@ -11,58 +11,34 @@ type Amazonec2Config struct {
Ami string `json:"ami,omitempty" yaml:"ami,omitempty"`
BlockDurationMinutes string `json:"blockDurationMinutes,omitempty" yaml:"block_duration_minutes,omitempty"`
DeviceName string `json:"deviceName,omitempty" yaml:"device_name,omitempty"`
Endpoint string `json:"endpoint,omitempty" yaml:"endpoint,omitempty"`
IamInstanceProfile string `json:"iamInstanceProfile,omitempty" yaml:"iam_instance_profile,omitempty"`
InsecureTransport bool `json:"insecureTransport,omitempty" yaml:"insecure_transport,omitempty"`
InstanceType string `json:"instanceType,omitempty" yaml:"instance_type,omitempty"`
KeypairName string `json:"keypairName,omitempty" yaml:"keypair_name,omitempty"`
Monitoring bool `json:"monitoring,omitempty" yaml:"monitoring,omitempty"`
OpenPort []string `json:"openPort,omitempty" yaml:"open_port,omitempty"`
PrivateAddressOnly bool `json:"privateAddressOnly,omitempty" yaml:"private_address_only,omitempty"`
Region string `json:"region,omitempty" yaml:"region,omitempty"`
RequestSpotInstance bool `json:"requestSpotInstance,omitempty" yaml:"request_spot_instance,omitempty"`
Retries string `json:"retries,omitempty" yaml:"retries,omitempty"`
RootSize string `json:"rootSize,omitempty" yaml:"root_size,omitempty"`
SecretKey string `json:"secretKey,omitempty" yaml:"secret_key,omitempty"`
SecurityGroup []string `json:"securityGroup,omitempty" yaml:"security_group,omitempty"`
SecurityGroup string `json:"securityGroup,omitempty" yaml:"security_group,omitempty"`
SessionToken string `json:"sessionToken,omitempty" yaml:"session_token,omitempty"`
SpotPrice string `json:"spotPrice,omitempty" yaml:"spot_price,omitempty"`
SshKeypath string `json:"sshKeypath,omitempty" yaml:"ssh_keypath,omitempty"`
SshUser string `json:"sshUser,omitempty" yaml:"ssh_user,omitempty"`
SubnetId string `json:"subnetId,omitempty" yaml:"subnet_id,omitempty"`
Tags string `json:"tags,omitempty" yaml:"tags,omitempty"`
UseEbsOptimizedInstance bool `json:"useEbsOptimizedInstance,omitempty" yaml:"use_ebs_optimized_instance,omitempty"`
UsePrivateAddress bool `json:"usePrivateAddress,omitempty" yaml:"use_private_address,omitempty"`
Userdata string `json:"userdata,omitempty" yaml:"userdata,omitempty"`
VolumeType string `json:"volumeType,omitempty" yaml:"volume_type,omitempty"`
VpcId string `json:"vpcId,omitempty" yaml:"vpc_id,omitempty"`
Zone string `json:"zone,omitempty" yaml:"zone,omitempty"`
@@ -70,8 +46,7 @@ type Amazonec2Config struct {
type Amazonec2ConfigCollection struct {
Collection
Data []Amazonec2Config `json:"data,omitempty"`
client *Amazonec2ConfigClient
Data []Amazonec2Config `json:"data,omitempty"`
}
type Amazonec2ConfigClient struct {
@@ -107,20 +82,9 @@ func (c *Amazonec2ConfigClient) Update(existing *Amazonec2Config, updates interf
func (c *Amazonec2ConfigClient) List(opts *ListOpts) (*Amazonec2ConfigCollection, error) {
resp := &Amazonec2ConfigCollection{}
err := c.rancherClient.doList(AMAZONEC2CONFIG_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *Amazonec2ConfigCollection) Next() (*Amazonec2ConfigCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &Amazonec2ConfigCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *Amazonec2ConfigClient) ById(id string) (*Amazonec2Config, error) {
resp := &Amazonec2Config{}
err := c.rancherClient.doById(AMAZONEC2CONFIG_TYPE, id, resp)
@@ -40,8 +40,7 @@ type ApiKey struct {
type ApiKeyCollection struct {
Collection
Data []ApiKey `json:"data,omitempty"`
client *ApiKeyClient
Data []ApiKey `json:"data,omitempty"`
}
type ApiKeyClient struct {
@@ -89,20 +88,9 @@ func (c *ApiKeyClient) Update(existing *ApiKey, updates interface{}) (*ApiKey, e
func (c *ApiKeyClient) List(opts *ListOpts) (*ApiKeyCollection, error) {
resp := &ApiKeyCollection{}
err := c.rancherClient.doList(API_KEY_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *ApiKeyCollection) Next() (*ApiKeyCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &ApiKeyCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *ApiKeyClient) ById(id string) (*ApiKey, error) {
resp := &ApiKey{}
err := c.rancherClient.doById(API_KEY_TYPE, id, resp)
@@ -38,8 +38,7 @@ type AuditLog struct {
type AuditLogCollection struct {
Collection
Data []AuditLog `json:"data,omitempty"`
client *AuditLogClient
Data []AuditLog `json:"data,omitempty"`
}
type AuditLogClient struct {
@@ -75,20 +74,9 @@ func (c *AuditLogClient) Update(existing *AuditLog, updates interface{}) (*Audit
func (c *AuditLogClient) List(opts *ListOpts) (*AuditLogCollection, error) {
resp := &AuditLogCollection{}
err := c.rancherClient.doList(AUDIT_LOG_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *AuditLogCollection) Next() (*AuditLogCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &AuditLogCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *AuditLogClient) ById(id string) (*AuditLog, error) {
resp := &AuditLog{}
err := c.rancherClient.doById(AUDIT_LOG_TYPE, id, resp)
@@ -7,55 +7,32 @@ const (
type AzureConfig struct {
Resource
AvailabilitySet string `json:"availabilitySet,omitempty" yaml:"availability_set,omitempty"`
ClientId string `json:"clientId,omitempty" yaml:"client_id,omitempty"`
ClientSecret string `json:"clientSecret,omitempty" yaml:"client_secret,omitempty"`
CustomData string `json:"customData,omitempty" yaml:"custom_data,omitempty"`
Dns string `json:"dns,omitempty" yaml:"dns,omitempty"`
DockerPort string `json:"dockerPort,omitempty" yaml:"docker_port,omitempty"`
Environment string `json:"environment,omitempty" yaml:"environment,omitempty"`
DockerSwarmMasterPort string `json:"dockerSwarmMasterPort,omitempty" yaml:"docker_swarm_master_port,omitempty"`
Image string `json:"image,omitempty" yaml:"image,omitempty"`
Location string `json:"location,omitempty" yaml:"location,omitempty"`
NoPublicIp bool `json:"noPublicIp,omitempty" yaml:"no_public_ip,omitempty"`
Password string `json:"password,omitempty" yaml:"password,omitempty"`
OpenPort []string `json:"openPort,omitempty" yaml:"open_port,omitempty"`
PrivateIpAddress string `json:"privateIpAddress,omitempty" yaml:"private_ip_address,omitempty"`
ResourceGroup string `json:"resourceGroup,omitempty" yaml:"resource_group,omitempty"`
PublishSettingsFile string `json:"publishSettingsFile,omitempty" yaml:"publish_settings_file,omitempty"`
Size string `json:"size,omitempty" yaml:"size,omitempty"`
SshUser string `json:"sshUser,omitempty" yaml:"ssh_user,omitempty"`
SshPort string `json:"sshPort,omitempty" yaml:"ssh_port,omitempty"`
StaticPublicIp bool `json:"staticPublicIp,omitempty" yaml:"static_public_ip,omitempty"`
StorageType string `json:"storageType,omitempty" yaml:"storage_type,omitempty"`
Subnet string `json:"subnet,omitempty" yaml:"subnet,omitempty"`
SubnetPrefix string `json:"subnetPrefix,omitempty" yaml:"subnet_prefix,omitempty"`
SubscriptionCert string `json:"subscriptionCert,omitempty" yaml:"subscription_cert,omitempty"`
SubscriptionId string `json:"subscriptionId,omitempty" yaml:"subscription_id,omitempty"`
UsePrivateIp bool `json:"usePrivateIp,omitempty" yaml:"use_private_ip,omitempty"`
Vnet string `json:"vnet,omitempty" yaml:"vnet,omitempty"`
Username string `json:"username,omitempty" yaml:"username,omitempty"`
}
type AzureConfigCollection struct {
Collection
Data []AzureConfig `json:"data,omitempty"`
client *AzureConfigClient
Data []AzureConfig `json:"data,omitempty"`
}
type AzureConfigClient struct {
@@ -91,20 +68,9 @@ func (c *AzureConfigClient) Update(existing *AzureConfig, updates interface{}) (
func (c *AzureConfigClient) List(opts *ListOpts) (*AzureConfigCollection, error) {
resp := &AzureConfigCollection{}
err := c.rancherClient.doList(AZURE_CONFIG_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *AzureConfigCollection) Next() (*AzureConfigCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &AzureConfigCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *AzureConfigClient) ById(id string) (*AzureConfig, error) {
resp := &AzureConfig{}
err := c.rancherClient.doById(AZURE_CONFIG_TYPE, id, resp)
@@ -44,8 +44,7 @@ type Backup struct {
type BackupCollection struct {
Collection
Data []Backup `json:"data,omitempty"`
client *BackupClient
Data []Backup `json:"data,omitempty"`
}
type BackupClient struct {
@@ -85,20 +84,9 @@ func (c *BackupClient) Update(existing *Backup, updates interface{}) (*Backup, e
func (c *BackupClient) List(opts *ListOpts) (*BackupCollection, error) {
resp := &BackupCollection{}
err := c.rancherClient.doList(BACKUP_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *BackupCollection) Next() (*BackupCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &BackupCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *BackupClient) ById(id string) (*Backup, error) {
resp := &Backup{}
err := c.rancherClient.doById(BACKUP_TYPE, id, resp)
@@ -38,8 +38,7 @@ type BackupTarget struct {
type BackupTargetCollection struct {
Collection
Data []BackupTarget `json:"data,omitempty"`
client *BackupTargetClient
Data []BackupTarget `json:"data,omitempty"`
}
type BackupTargetClient struct {
@@ -79,20 +78,9 @@ func (c *BackupTargetClient) Update(existing *BackupTarget, updates interface{})
func (c *BackupTargetClient) List(opts *ListOpts) (*BackupTargetCollection, error) {
resp := &BackupTargetCollection{}
err := c.rancherClient.doList(BACKUP_TARGET_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *BackupTargetCollection) Next() (*BackupTargetCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &BackupTargetCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *BackupTargetClient) ById(id string) (*BackupTarget, error) {
resp := &BackupTarget{}
err := c.rancherClient.doById(BACKUP_TARGET_TYPE, id, resp)
@@ -10,8 +10,7 @@ type BaseMachineConfig struct {
type BaseMachineConfigCollection struct {
Collection
Data []BaseMachineConfig `json:"data,omitempty"`
client *BaseMachineConfigClient
Data []BaseMachineConfig `json:"data,omitempty"`
}
type BaseMachineConfigClient struct {
@@ -47,20 +46,9 @@ func (c *BaseMachineConfigClient) Update(existing *BaseMachineConfig, updates in
func (c *BaseMachineConfigClient) List(opts *ListOpts) (*BaseMachineConfigCollection, error) {
resp := &BaseMachineConfigCollection{}
err := c.rancherClient.doList(BASE_MACHINE_CONFIG_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *BaseMachineConfigCollection) Next() (*BaseMachineConfigCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &BaseMachineConfigCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *BaseMachineConfigClient) ById(id string) (*BaseMachineConfig, error) {
resp := &BaseMachineConfig{}
err := c.rancherClient.doById(BASE_MACHINE_CONFIG_TYPE, id, resp)
@@ -20,8 +20,7 @@ type BlkioDeviceOption struct {
type BlkioDeviceOptionCollection struct {
Collection
Data []BlkioDeviceOption `json:"data,omitempty"`
client *BlkioDeviceOptionClient
Data []BlkioDeviceOption `json:"data,omitempty"`
}
type BlkioDeviceOptionClient struct {
@@ -57,20 +56,9 @@ func (c *BlkioDeviceOptionClient) Update(existing *BlkioDeviceOption, updates in
func (c *BlkioDeviceOptionClient) List(opts *ListOpts) (*BlkioDeviceOptionCollection, error) {
resp := &BlkioDeviceOptionCollection{}
err := c.rancherClient.doList(BLKIO_DEVICE_OPTION_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *BlkioDeviceOptionCollection) Next() (*BlkioDeviceOptionCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &BlkioDeviceOptionCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *BlkioDeviceOptionClient) ById(id string) (*BlkioDeviceOption, error) {
resp := &BlkioDeviceOption{}
err := c.rancherClient.doById(BLKIO_DEVICE_OPTION_TYPE, id, resp)
@@ -62,8 +62,7 @@ type Certificate struct {
type CertificateCollection struct {
Collection
Data []Certificate `json:"data,omitempty"`
client *CertificateClient
Data []Certificate `json:"data,omitempty"`
}
type CertificateClient struct {
@@ -105,20 +104,9 @@ func (c *CertificateClient) Update(existing *Certificate, updates interface{}) (
func (c *CertificateClient) List(opts *ListOpts) (*CertificateCollection, error) {
resp := &CertificateCollection{}
err := c.rancherClient.doList(CERTIFICATE_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *CertificateCollection) Next() (*CertificateCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &CertificateCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *CertificateClient) ById(id string) (*Certificate, error) {
resp := &Certificate{}
err := c.rancherClient.doById(CERTIFICATE_TYPE, id, resp)
@@ -14,8 +14,7 @@ type ChangeSecretInput struct {
type ChangeSecretInputCollection struct {
Collection
Data []ChangeSecretInput `json:"data,omitempty"`
client *ChangeSecretInputClient
Data []ChangeSecretInput `json:"data,omitempty"`
}
type ChangeSecretInputClient struct {
@@ -51,20 +50,9 @@ func (c *ChangeSecretInputClient) Update(existing *ChangeSecretInput, updates in
func (c *ChangeSecretInputClient) List(opts *ListOpts) (*ChangeSecretInputCollection, error) {
resp := &ChangeSecretInputCollection{}
err := c.rancherClient.doList(CHANGE_SECRET_INPUT_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *ChangeSecretInputCollection) Next() (*ChangeSecretInputCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &ChangeSecretInputCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *ChangeSecretInputClient) ById(id string) (*ChangeSecretInput, error) {
resp := &ChangeSecretInput{}
err := c.rancherClient.doById(CHANGE_SECRET_INPUT_TYPE, id, resp)
@@ -6,22 +6,17 @@ type RancherClient struct {
Account AccountOperations
ActiveSetting ActiveSettingOperations
AddOutputsInput AddOutputsInputOperations
AddRemoveLoadBalancerServiceLinkInput AddRemoveLoadBalancerServiceLinkInputOperations
AddRemoveServiceLinkInput AddRemoveServiceLinkInputOperations
Agent AgentOperations
Amazonec2Config Amazonec2ConfigOperations
ApiKey ApiKeyOperations
AuditLog AuditLogOperations
AzureConfig AzureConfigOperations
Azureadconfig AzureadconfigOperations
Backup BackupOperations
BackupTarget BackupTargetOperations
BaseMachineConfig BaseMachineConfigOperations
Binding BindingOperations
BlkioDeviceOption BlkioDeviceOptionOperations
CatalogTemplate CatalogTemplateOperations
Certificate CertificateOperations
ChangeSecretInput ChangeSecretInputOperations
ClusterMembership ClusterMembershipOperations
ComposeConfig ComposeConfigOperations
ComposeConfigInput ComposeConfigInputOperations
ComposeProject ComposeProjectOperations
@@ -36,10 +31,11 @@ type RancherClient struct {
Credential CredentialOperations
Databasechangelog DatabasechangelogOperations
Databasechangeloglock DatabasechangeloglockOperations
DefaultNetwork DefaultNetworkOperations
DigitaloceanConfig DigitaloceanConfigOperations
DnsService DnsServiceOperations
DockerBuild DockerBuildOperations
DynamicSchema DynamicSchemaOperations
Environment EnvironmentOperations
EnvironmentUpgrade EnvironmentUpgradeOperations
ExtensionImplementation ExtensionImplementationOperations
ExtensionPoint ExtensionPointOperations
ExternalDnsEvent ExternalDnsEventOperations
@@ -54,14 +50,14 @@ type RancherClient struct {
ExternalStoragePoolEvent ExternalStoragePoolEventOperations
ExternalVolumeEvent ExternalVolumeEventOperations
FieldDocumentation FieldDocumentationOperations
GenericObject GenericObjectOperations
Githubconfig GithubconfigOperations
HaConfig HaConfigOperations
HaConfigInput HaConfigInputOperations
HaproxyConfig HaproxyConfigOperations
HealthcheckInstanceHostMap HealthcheckInstanceHostMapOperations
Host HostOperations
HostAccess HostAccessOperations
HostApiProxyToken HostApiProxyTokenOperations
HostTemplate HostTemplateOperations
Identity IdentityOperations
Image ImageOperations
InServiceUpgradeStrategy InServiceUpgradeStrategyOperations
@@ -72,43 +68,32 @@ type RancherClient struct {
InstanceLink InstanceLinkOperations
InstanceStop InstanceStopOperations
IpAddress IpAddressOperations
IpAddressAssociateInput IpAddressAssociateInputOperations
KubernetesService KubernetesServiceOperations
KubernetesStack KubernetesStackOperations
KubernetesStackUpgrade KubernetesStackUpgradeOperations
Label LabelOperations
LaunchConfig LaunchConfigOperations
LbConfig LbConfigOperations
LbTargetConfig LbTargetConfigOperations
Ldapconfig LdapconfigOperations
LoadBalancerAppCookieStickinessPolicy LoadBalancerAppCookieStickinessPolicyOperations
LoadBalancerConfig LoadBalancerConfigOperations
LoadBalancerCookieStickinessPolicy LoadBalancerCookieStickinessPolicyOperations
LoadBalancerService LoadBalancerServiceOperations
LoadBalancerServiceLink LoadBalancerServiceLinkOperations
LocalAuthConfig LocalAuthConfigOperations
LogConfig LogConfigOperations
Machine MachineOperations
MachineDriver MachineDriverOperations
Mount MountOperations
MountEntry MountEntryOperations
Network NetworkOperations
NetworkDriver NetworkDriverOperations
NetworkDriverService NetworkDriverServiceOperations
NetworkPolicyRule NetworkPolicyRuleOperations
NetworkPolicyRuleBetween NetworkPolicyRuleBetweenOperations
NetworkPolicyRuleMember NetworkPolicyRuleMemberOperations
NetworkPolicyRuleWithin NetworkPolicyRuleWithinOperations
NfsConfig NfsConfigOperations
Openldapconfig OpenldapconfigOperations
PacketConfig PacketConfigOperations
Password PasswordOperations
PhysicalHost PhysicalHostOperations
Port PortOperations
PortRule PortRuleOperations
ProcessDefinition ProcessDefinitionOperations
ProcessExecution ProcessExecutionOperations
ProcessInstance ProcessInstanceOperations
ProcessPool ProcessPoolOperations
ProcessSummary ProcessSummaryOperations
Project ProjectOperations
ProjectMember ProjectMemberOperations
ProjectTemplate ProjectTemplateOperations
PublicEndpoint PublicEndpointOperations
Publish PublishOperations
PullTask PullTaskOperations
@@ -122,75 +107,59 @@ type RancherClient struct {
RestoreFromBackupInput RestoreFromBackupInputOperations
RevertToSnapshotInput RevertToSnapshotInputOperations
RollingRestartStrategy RollingRestartStrategyOperations
ScalePolicy ScalePolicyOperations
ScheduledUpgrade ScheduledUpgradeOperations
SecondaryLaunchConfig SecondaryLaunchConfigOperations
Secret SecretOperations
SecretReference SecretReferenceOperations
Service ServiceOperations
ServiceBinding ServiceBindingOperations
ServiceConsumeMap ServiceConsumeMapOperations
ServiceEvent ServiceEventOperations
ServiceExposeMap ServiceExposeMapOperations
ServiceLink ServiceLinkOperations
ServiceLog ServiceLogOperations
ServiceProxy ServiceProxyOperations
ServiceRestart ServiceRestartOperations
ServiceUpgrade ServiceUpgradeOperations
ServiceUpgradeStrategy ServiceUpgradeStrategyOperations
ServicesPortRange ServicesPortRangeOperations
SetLabelsInput SetLabelsInputOperations
SetLoadBalancerServiceLinksInput SetLoadBalancerServiceLinksInputOperations
SetProjectMembersInput SetProjectMembersInputOperations
SetServiceLinksInput SetServiceLinksInputOperations
Setting SettingOperations
Snapshot SnapshotOperations
SnapshotBackupInput SnapshotBackupInputOperations
Stack StackOperations
StackUpgrade StackUpgradeOperations
StateTransition StateTransitionOperations
StatsAccess StatsAccessOperations
StorageDriver StorageDriverOperations
StorageDriverService StorageDriverServiceOperations
StoragePool StoragePoolOperations
Subnet SubnetOperations
TargetPortRule TargetPortRuleOperations
Subscribe SubscribeOperations
Task TaskOperations
TaskInstance TaskInstanceOperations
ToServiceUpgradeStrategy ToServiceUpgradeStrategyOperations
TypeDocumentation TypeDocumentationOperations
Ulimit UlimitOperations
UserPreference UserPreferenceOperations
VirtualMachine VirtualMachineOperations
VirtualMachineDisk VirtualMachineDiskOperations
Volume VolumeOperations
VolumeActivateInput VolumeActivateInputOperations
VolumeSnapshotInput VolumeSnapshotInputOperations
VolumeTemplate VolumeTemplateOperations
}
func constructClient(rancherBaseClient *RancherBaseClientImpl) *RancherClient {
func constructClient() *RancherClient {
client := &RancherClient{
RancherBaseClient: rancherBaseClient,
RancherBaseClient: RancherBaseClient{
Types: map[string]Schema{},
},
}
client.Account = newAccountClient(client)
client.ActiveSetting = newActiveSettingClient(client)
client.AddOutputsInput = newAddOutputsInputClient(client)
client.AddRemoveLoadBalancerServiceLinkInput = newAddRemoveLoadBalancerServiceLinkInputClient(client)
client.AddRemoveServiceLinkInput = newAddRemoveServiceLinkInputClient(client)
client.Agent = newAgentClient(client)
client.Amazonec2Config = newAmazonec2ConfigClient(client)
client.ApiKey = newApiKeyClient(client)
client.AuditLog = newAuditLogClient(client)
client.AzureConfig = newAzureConfigClient(client)
client.Azureadconfig = newAzureadconfigClient(client)
client.Backup = newBackupClient(client)
client.BackupTarget = newBackupTargetClient(client)
client.BaseMachineConfig = newBaseMachineConfigClient(client)
client.Binding = newBindingClient(client)
client.BlkioDeviceOption = newBlkioDeviceOptionClient(client)
client.CatalogTemplate = newCatalogTemplateClient(client)
client.Certificate = newCertificateClient(client)
client.ChangeSecretInput = newChangeSecretInputClient(client)
client.ClusterMembership = newClusterMembershipClient(client)
client.ComposeConfig = newComposeConfigClient(client)
client.ComposeConfigInput = newComposeConfigInputClient(client)
client.ComposeProject = newComposeProjectClient(client)
@@ -205,10 +174,11 @@ func constructClient(rancherBaseClient *RancherBaseClientImpl) *RancherClient {
client.Credential = newCredentialClient(client)
client.Databasechangelog = newDatabasechangelogClient(client)
client.Databasechangeloglock = newDatabasechangeloglockClient(client)
client.DefaultNetwork = newDefaultNetworkClient(client)
client.DigitaloceanConfig = newDigitaloceanConfigClient(client)
client.DnsService = newDnsServiceClient(client)
client.DockerBuild = newDockerBuildClient(client)
client.DynamicSchema = newDynamicSchemaClient(client)
client.Environment = newEnvironmentClient(client)
client.EnvironmentUpgrade = newEnvironmentUpgradeClient(client)
client.ExtensionImplementation = newExtensionImplementationClient(client)
client.ExtensionPoint = newExtensionPointClient(client)
client.ExternalDnsEvent = newExternalDnsEventClient(client)
@@ -223,14 +193,14 @@ func constructClient(rancherBaseClient *RancherBaseClientImpl) *RancherClient {
client.ExternalStoragePoolEvent = newExternalStoragePoolEventClient(client)
client.ExternalVolumeEvent = newExternalVolumeEventClient(client)
client.FieldDocumentation = newFieldDocumentationClient(client)
client.GenericObject = newGenericObjectClient(client)
client.Githubconfig = newGithubconfigClient(client)
client.HaConfig = newHaConfigClient(client)
client.HaConfigInput = newHaConfigInputClient(client)
client.HaproxyConfig = newHaproxyConfigClient(client)
client.HealthcheckInstanceHostMap = newHealthcheckInstanceHostMapClient(client)
client.Host = newHostClient(client)
client.HostAccess = newHostAccessClient(client)
client.HostApiProxyToken = newHostApiProxyTokenClient(client)
client.HostTemplate = newHostTemplateClient(client)
client.Identity = newIdentityClient(client)
client.Image = newImageClient(client)
client.InServiceUpgradeStrategy = newInServiceUpgradeStrategyClient(client)
@@ -241,43 +211,32 @@ func constructClient(rancherBaseClient *RancherBaseClientImpl) *RancherClient {
client.InstanceLink = newInstanceLinkClient(client)
client.InstanceStop = newInstanceStopClient(client)
client.IpAddress = newIpAddressClient(client)
client.IpAddressAssociateInput = newIpAddressAssociateInputClient(client)
client.KubernetesService = newKubernetesServiceClient(client)
client.KubernetesStack = newKubernetesStackClient(client)
client.KubernetesStackUpgrade = newKubernetesStackUpgradeClient(client)
client.Label = newLabelClient(client)
client.LaunchConfig = newLaunchConfigClient(client)
client.LbConfig = newLbConfigClient(client)
client.LbTargetConfig = newLbTargetConfigClient(client)
client.Ldapconfig = newLdapconfigClient(client)
client.LoadBalancerAppCookieStickinessPolicy = newLoadBalancerAppCookieStickinessPolicyClient(client)
client.LoadBalancerConfig = newLoadBalancerConfigClient(client)
client.LoadBalancerCookieStickinessPolicy = newLoadBalancerCookieStickinessPolicyClient(client)
client.LoadBalancerService = newLoadBalancerServiceClient(client)
client.LoadBalancerServiceLink = newLoadBalancerServiceLinkClient(client)
client.LocalAuthConfig = newLocalAuthConfigClient(client)
client.LogConfig = newLogConfigClient(client)
client.Machine = newMachineClient(client)
client.MachineDriver = newMachineDriverClient(client)
client.Mount = newMountClient(client)
client.MountEntry = newMountEntryClient(client)
client.Network = newNetworkClient(client)
client.NetworkDriver = newNetworkDriverClient(client)
client.NetworkDriverService = newNetworkDriverServiceClient(client)
client.NetworkPolicyRule = newNetworkPolicyRuleClient(client)
client.NetworkPolicyRuleBetween = newNetworkPolicyRuleBetweenClient(client)
client.NetworkPolicyRuleMember = newNetworkPolicyRuleMemberClient(client)
client.NetworkPolicyRuleWithin = newNetworkPolicyRuleWithinClient(client)
client.NfsConfig = newNfsConfigClient(client)
client.Openldapconfig = newOpenldapconfigClient(client)
client.PacketConfig = newPacketConfigClient(client)
client.Password = newPasswordClient(client)
client.PhysicalHost = newPhysicalHostClient(client)
client.Port = newPortClient(client)
client.PortRule = newPortRuleClient(client)
client.ProcessDefinition = newProcessDefinitionClient(client)
client.ProcessExecution = newProcessExecutionClient(client)
client.ProcessInstance = newProcessInstanceClient(client)
client.ProcessPool = newProcessPoolClient(client)
client.ProcessSummary = newProcessSummaryClient(client)
client.Project = newProjectClient(client)
client.ProjectMember = newProjectMemberClient(client)
client.ProjectTemplate = newProjectTemplateClient(client)
client.PublicEndpoint = newPublicEndpointClient(client)
client.Publish = newPublishClient(client)
client.PullTask = newPullTaskClient(client)
@@ -291,60 +250,44 @@ func constructClient(rancherBaseClient *RancherBaseClientImpl) *RancherClient {
client.RestoreFromBackupInput = newRestoreFromBackupInputClient(client)
client.RevertToSnapshotInput = newRevertToSnapshotInputClient(client)
client.RollingRestartStrategy = newRollingRestartStrategyClient(client)
client.ScalePolicy = newScalePolicyClient(client)
client.ScheduledUpgrade = newScheduledUpgradeClient(client)
client.SecondaryLaunchConfig = newSecondaryLaunchConfigClient(client)
client.Secret = newSecretClient(client)
client.SecretReference = newSecretReferenceClient(client)
client.Service = newServiceClient(client)
client.ServiceBinding = newServiceBindingClient(client)
client.ServiceConsumeMap = newServiceConsumeMapClient(client)
client.ServiceEvent = newServiceEventClient(client)
client.ServiceExposeMap = newServiceExposeMapClient(client)
client.ServiceLink = newServiceLinkClient(client)
client.ServiceLog = newServiceLogClient(client)
client.ServiceProxy = newServiceProxyClient(client)
client.ServiceRestart = newServiceRestartClient(client)
client.ServiceUpgrade = newServiceUpgradeClient(client)
client.ServiceUpgradeStrategy = newServiceUpgradeStrategyClient(client)
client.ServicesPortRange = newServicesPortRangeClient(client)
client.SetLabelsInput = newSetLabelsInputClient(client)
client.SetLoadBalancerServiceLinksInput = newSetLoadBalancerServiceLinksInputClient(client)
client.SetProjectMembersInput = newSetProjectMembersInputClient(client)
client.SetServiceLinksInput = newSetServiceLinksInputClient(client)
client.Setting = newSettingClient(client)
client.Snapshot = newSnapshotClient(client)
client.SnapshotBackupInput = newSnapshotBackupInputClient(client)
client.Stack = newStackClient(client)
client.StackUpgrade = newStackUpgradeClient(client)
client.StateTransition = newStateTransitionClient(client)
client.StatsAccess = newStatsAccessClient(client)
client.StorageDriver = newStorageDriverClient(client)
client.StorageDriverService = newStorageDriverServiceClient(client)
client.StoragePool = newStoragePoolClient(client)
client.Subnet = newSubnetClient(client)
client.TargetPortRule = newTargetPortRuleClient(client)
client.Subscribe = newSubscribeClient(client)
client.Task = newTaskClient(client)
client.TaskInstance = newTaskInstanceClient(client)
client.ToServiceUpgradeStrategy = newToServiceUpgradeStrategyClient(client)
client.TypeDocumentation = newTypeDocumentationClient(client)
client.Ulimit = newUlimitClient(client)
client.UserPreference = newUserPreferenceClient(client)
client.VirtualMachine = newVirtualMachineClient(client)
client.VirtualMachineDisk = newVirtualMachineDiskClient(client)
client.Volume = newVolumeClient(client)
client.VolumeActivateInput = newVolumeActivateInputClient(client)
client.VolumeSnapshotInput = newVolumeSnapshotInputClient(client)
client.VolumeTemplate = newVolumeTemplateClient(client)
return client
}
func NewRancherClient(opts *ClientOpts) (*RancherClient, error) {
rancherBaseClient := &RancherBaseClientImpl{
Types: map[string]Schema{},
}
client := constructClient(rancherBaseClient)
client := constructClient()
err := setupRancherBaseClient(rancherBaseClient, opts)
err := setupRancherBaseClient(&client.RancherBaseClient, opts)
if err != nil {
return nil, err
}
+223
View File
@@ -0,0 +1,223 @@
package client
const (
CLUSTER_TYPE = "cluster"
)
type Cluster struct {
Resource
AccountId string `json:"accountId,omitempty" yaml:"account_id,omitempty"`
AgentId string `json:"agentId,omitempty" yaml:"agent_id,omitempty"`
AgentState string `json:"agentState,omitempty" yaml:"agent_state,omitempty"`
ApiProxy string `json:"apiProxy,omitempty" yaml:"api_proxy,omitempty"`
ComputeTotal int64 `json:"computeTotal,omitempty" yaml:"compute_total,omitempty"`
Created string `json:"created,omitempty" yaml:"created,omitempty"`
Data map[string]interface{} `json:"data,omitempty" yaml:"data,omitempty"`
Description string `json:"description,omitempty" yaml:"description,omitempty"`
DiscoverySpec string `json:"discoverySpec,omitempty" yaml:"discovery_spec,omitempty"`
Hostname string `json:"hostname,omitempty" yaml:"hostname,omitempty"`
Info interface{} `json:"info,omitempty" yaml:"info,omitempty"`
Kind string `json:"kind,omitempty" yaml:"kind,omitempty"`
Labels map[string]interface{} `json:"labels,omitempty" yaml:"labels,omitempty"`
Name string `json:"name,omitempty" yaml:"name,omitempty"`
PhysicalHostId string `json:"physicalHostId,omitempty" yaml:"physical_host_id,omitempty"`
Port int64 `json:"port,omitempty" yaml:"port,omitempty"`
PublicEndpoints []interface{} `json:"publicEndpoints,omitempty" yaml:"public_endpoints,omitempty"`
RemoveTime string `json:"removeTime,omitempty" yaml:"remove_time,omitempty"`
Removed string `json:"removed,omitempty" yaml:"removed,omitempty"`
State string `json:"state,omitempty" yaml:"state,omitempty"`
Transitioning string `json:"transitioning,omitempty" yaml:"transitioning,omitempty"`
TransitioningMessage string `json:"transitioningMessage,omitempty" yaml:"transitioning_message,omitempty"`
TransitioningProgress int64 `json:"transitioningProgress,omitempty" yaml:"transitioning_progress,omitempty"`
Uuid string `json:"uuid,omitempty" yaml:"uuid,omitempty"`
}
type ClusterCollection struct {
Collection
Data []Cluster `json:"data,omitempty"`
}
type ClusterClient struct {
rancherClient *RancherClient
}
type ClusterOperations interface {
List(opts *ListOpts) (*ClusterCollection, error)
Create(opts *Cluster) (*Cluster, error)
Update(existing *Cluster, updates interface{}) (*Cluster, error)
ById(id string) (*Cluster, error)
Delete(container *Cluster) error
ActionActivate(*Cluster) (*Host, error)
ActionAddhost(*Cluster, *AddRemoveClusterHostInput) (*Cluster, error)
ActionCreate(*Cluster) (*Host, error)
ActionDeactivate(*Cluster) (*Host, error)
ActionDockersocket(*Cluster) (*HostAccess, error)
ActionPurge(*Cluster) (*Host, error)
ActionRemove(*Cluster) (*Host, error)
ActionRemovehost(*Cluster, *AddRemoveClusterHostInput) (*Cluster, error)
ActionRestore(*Cluster) (*Host, error)
ActionUpdate(*Cluster) (*Host, error)
}
func newClusterClient(rancherClient *RancherClient) *ClusterClient {
return &ClusterClient{
rancherClient: rancherClient,
}
}
func (c *ClusterClient) Create(container *Cluster) (*Cluster, error) {
resp := &Cluster{}
err := c.rancherClient.doCreate(CLUSTER_TYPE, container, resp)
return resp, err
}
func (c *ClusterClient) Update(existing *Cluster, updates interface{}) (*Cluster, error) {
resp := &Cluster{}
err := c.rancherClient.doUpdate(CLUSTER_TYPE, &existing.Resource, updates, resp)
return resp, err
}
func (c *ClusterClient) List(opts *ListOpts) (*ClusterCollection, error) {
resp := &ClusterCollection{}
err := c.rancherClient.doList(CLUSTER_TYPE, opts, resp)
return resp, err
}
func (c *ClusterClient) ById(id string) (*Cluster, error) {
resp := &Cluster{}
err := c.rancherClient.doById(CLUSTER_TYPE, id, resp)
if apiError, ok := err.(*ApiError); ok {
if apiError.StatusCode == 404 {
return nil, nil
}
}
return resp, err
}
func (c *ClusterClient) Delete(container *Cluster) error {
return c.rancherClient.doResourceDelete(CLUSTER_TYPE, &container.Resource)
}
func (c *ClusterClient) ActionActivate(resource *Cluster) (*Host, error) {
resp := &Host{}
err := c.rancherClient.doAction(CLUSTER_TYPE, "activate", &resource.Resource, nil, resp)
return resp, err
}
func (c *ClusterClient) ActionAddhost(resource *Cluster, input *AddRemoveClusterHostInput) (*Cluster, error) {
resp := &Cluster{}
err := c.rancherClient.doAction(CLUSTER_TYPE, "addhost", &resource.Resource, input, resp)
return resp, err
}
func (c *ClusterClient) ActionCreate(resource *Cluster) (*Host, error) {
resp := &Host{}
err := c.rancherClient.doAction(CLUSTER_TYPE, "create", &resource.Resource, nil, resp)
return resp, err
}
func (c *ClusterClient) ActionDeactivate(resource *Cluster) (*Host, error) {
resp := &Host{}
err := c.rancherClient.doAction(CLUSTER_TYPE, "deactivate", &resource.Resource, nil, resp)
return resp, err
}
func (c *ClusterClient) ActionDockersocket(resource *Cluster) (*HostAccess, error) {
resp := &HostAccess{}
err := c.rancherClient.doAction(CLUSTER_TYPE, "dockersocket", &resource.Resource, nil, resp)
return resp, err
}
func (c *ClusterClient) ActionPurge(resource *Cluster) (*Host, error) {
resp := &Host{}
err := c.rancherClient.doAction(CLUSTER_TYPE, "purge", &resource.Resource, nil, resp)
return resp, err
}
func (c *ClusterClient) ActionRemove(resource *Cluster) (*Host, error) {
resp := &Host{}
err := c.rancherClient.doAction(CLUSTER_TYPE, "remove", &resource.Resource, nil, resp)
return resp, err
}
func (c *ClusterClient) ActionRemovehost(resource *Cluster, input *AddRemoveClusterHostInput) (*Cluster, error) {
resp := &Cluster{}
err := c.rancherClient.doAction(CLUSTER_TYPE, "removehost", &resource.Resource, input, resp)
return resp, err
}
func (c *ClusterClient) ActionRestore(resource *Cluster) (*Host, error) {
resp := &Host{}
err := c.rancherClient.doAction(CLUSTER_TYPE, "restore", &resource.Resource, nil, resp)
return resp, err
}
func (c *ClusterClient) ActionUpdate(resource *Cluster) (*Host, error) {
resp := &Host{}
err := c.rancherClient.doAction(CLUSTER_TYPE, "update", &resource.Resource, nil, resp)
return resp, err
}
@@ -14,8 +14,7 @@ type ComposeConfig struct {
type ComposeConfigCollection struct {
Collection
Data []ComposeConfig `json:"data,omitempty"`
client *ComposeConfigClient
Data []ComposeConfig `json:"data,omitempty"`
}
type ComposeConfigClient struct {
@@ -51,20 +50,9 @@ func (c *ComposeConfigClient) Update(existing *ComposeConfig, updates interface{
func (c *ComposeConfigClient) List(opts *ListOpts) (*ComposeConfigCollection, error) {
resp := &ComposeConfigCollection{}
err := c.rancherClient.doList(COMPOSE_CONFIG_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *ComposeConfigCollection) Next() (*ComposeConfigCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &ComposeConfigCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *ComposeConfigClient) ById(id string) (*ComposeConfig, error) {
resp := &ComposeConfig{}
err := c.rancherClient.doById(COMPOSE_CONFIG_TYPE, id, resp)
@@ -12,8 +12,7 @@ type ComposeConfigInput struct {
type ComposeConfigInputCollection struct {
Collection
Data []ComposeConfigInput `json:"data,omitempty"`
client *ComposeConfigInputClient
Data []ComposeConfigInput `json:"data,omitempty"`
}
type ComposeConfigInputClient struct {
@@ -49,20 +48,9 @@ func (c *ComposeConfigInputClient) Update(existing *ComposeConfigInput, updates
func (c *ComposeConfigInputClient) List(opts *ListOpts) (*ComposeConfigInputCollection, error) {
resp := &ComposeConfigInputCollection{}
err := c.rancherClient.doList(COMPOSE_CONFIG_INPUT_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *ComposeConfigInputCollection) Next() (*ComposeConfigInputCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &ComposeConfigInputCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *ComposeConfigInputClient) ById(id string) (*ComposeConfigInput, error) {
resp := &ComposeConfigInput{}
err := c.rancherClient.doById(COMPOSE_CONFIG_INPUT_TYPE, id, resp)
@@ -9,10 +9,6 @@ type ComposeProject struct {
AccountId string `json:"accountId,omitempty" yaml:"account_id,omitempty"`
Answers map[string]interface{} `json:"answers,omitempty" yaml:"answers,omitempty"`
Binding *Binding `json:"binding,omitempty" yaml:"binding,omitempty"`
Created string `json:"created,omitempty" yaml:"created,omitempty"`
Data map[string]interface{} `json:"data,omitempty" yaml:"data,omitempty"`
@@ -23,8 +19,6 @@ type ComposeProject struct {
ExternalId string `json:"externalId,omitempty" yaml:"external_id,omitempty"`
Group string `json:"group,omitempty" yaml:"group,omitempty"`
HealthState string `json:"healthState,omitempty" yaml:"health_state,omitempty"`
Kind string `json:"kind,omitempty" yaml:"kind,omitempty"`
@@ -39,12 +33,8 @@ type ComposeProject struct {
Removed string `json:"removed,omitempty" yaml:"removed,omitempty"`
ServiceIds []string `json:"serviceIds,omitempty" yaml:"service_ids,omitempty"`
State string `json:"state,omitempty" yaml:"state,omitempty"`
System bool `json:"system,omitempty" yaml:"system,omitempty"`
Templates map[string]interface{} `json:"templates,omitempty" yaml:"templates,omitempty"`
Transitioning string `json:"transitioning,omitempty" yaml:"transitioning,omitempty"`
@@ -58,8 +48,7 @@ type ComposeProject struct {
type ComposeProjectCollection struct {
Collection
Data []ComposeProject `json:"data,omitempty"`
client *ComposeProjectClient
Data []ComposeProject `json:"data,omitempty"`
}
type ComposeProjectClient struct {
@@ -73,17 +62,31 @@ type ComposeProjectOperations interface {
ById(id string) (*ComposeProject, error)
Delete(container *ComposeProject) error
ActionCancelupgrade(*ComposeProject) (*Stack, error)
ActionActivateservices(*ComposeProject) (*Environment, error)
ActionCreate(*ComposeProject) (*Stack, error)
ActionAddoutputs(*ComposeProject, *AddOutputsInput) (*Environment, error)
ActionError(*ComposeProject) (*Stack, error)
ActionCancelrollback(*ComposeProject) (*Environment, error)
ActionFinishupgrade(*ComposeProject) (*Stack, error)
ActionCancelupgrade(*ComposeProject) (*Environment, error)
ActionRemove(*ComposeProject) (*Stack, error)
ActionCreate(*ComposeProject) (*Environment, error)
ActionRollback(*ComposeProject) (*Stack, error)
ActionDeactivateservices(*ComposeProject) (*Environment, error)
ActionError(*ComposeProject) (*Environment, error)
ActionExportconfig(*ComposeProject, *ComposeConfigInput) (*ComposeConfig, error)
ActionFinishupgrade(*ComposeProject) (*Environment, error)
ActionRemove(*ComposeProject) (*Environment, error)
ActionRollback(*ComposeProject) (*Environment, error)
ActionUpdate(*ComposeProject) (*Environment, error)
ActionUpgrade(*ComposeProject, *EnvironmentUpgrade) (*Environment, error)
}
func newComposeProjectClient(rancherClient *RancherClient) *ComposeProjectClient {
@@ -107,20 +110,9 @@ func (c *ComposeProjectClient) Update(existing *ComposeProject, updates interfac
func (c *ComposeProjectClient) List(opts *ListOpts) (*ComposeProjectCollection, error) {
resp := &ComposeProjectCollection{}
err := c.rancherClient.doList(COMPOSE_PROJECT_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *ComposeProjectCollection) Next() (*ComposeProjectCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &ComposeProjectCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *ComposeProjectClient) ById(id string) (*ComposeProject, error) {
resp := &ComposeProject{}
err := c.rancherClient.doById(COMPOSE_PROJECT_TYPE, id, resp)
@@ -136,56 +128,119 @@ func (c *ComposeProjectClient) Delete(container *ComposeProject) error {
return c.rancherClient.doResourceDelete(COMPOSE_PROJECT_TYPE, &container.Resource)
}
func (c *ComposeProjectClient) ActionCancelupgrade(resource *ComposeProject) (*Stack, error) {
func (c *ComposeProjectClient) ActionActivateservices(resource *ComposeProject) (*Environment, error) {
resp := &Stack{}
resp := &Environment{}
err := c.rancherClient.doAction(COMPOSE_PROJECT_TYPE, "activateservices", &resource.Resource, nil, resp)
return resp, err
}
func (c *ComposeProjectClient) ActionAddoutputs(resource *ComposeProject, input *AddOutputsInput) (*Environment, error) {
resp := &Environment{}
err := c.rancherClient.doAction(COMPOSE_PROJECT_TYPE, "addoutputs", &resource.Resource, input, resp)
return resp, err
}
func (c *ComposeProjectClient) ActionCancelrollback(resource *ComposeProject) (*Environment, error) {
resp := &Environment{}
err := c.rancherClient.doAction(COMPOSE_PROJECT_TYPE, "cancelrollback", &resource.Resource, nil, resp)
return resp, err
}
func (c *ComposeProjectClient) ActionCancelupgrade(resource *ComposeProject) (*Environment, error) {
resp := &Environment{}
err := c.rancherClient.doAction(COMPOSE_PROJECT_TYPE, "cancelupgrade", &resource.Resource, nil, resp)
return resp, err
}
func (c *ComposeProjectClient) ActionCreate(resource *ComposeProject) (*Stack, error) {
func (c *ComposeProjectClient) ActionCreate(resource *ComposeProject) (*Environment, error) {
resp := &Stack{}
resp := &Environment{}
err := c.rancherClient.doAction(COMPOSE_PROJECT_TYPE, "create", &resource.Resource, nil, resp)
return resp, err
}
func (c *ComposeProjectClient) ActionError(resource *ComposeProject) (*Stack, error) {
func (c *ComposeProjectClient) ActionDeactivateservices(resource *ComposeProject) (*Environment, error) {
resp := &Stack{}
resp := &Environment{}
err := c.rancherClient.doAction(COMPOSE_PROJECT_TYPE, "deactivateservices", &resource.Resource, nil, resp)
return resp, err
}
func (c *ComposeProjectClient) ActionError(resource *ComposeProject) (*Environment, error) {
resp := &Environment{}
err := c.rancherClient.doAction(COMPOSE_PROJECT_TYPE, "error", &resource.Resource, nil, resp)
return resp, err
}
func (c *ComposeProjectClient) ActionFinishupgrade(resource *ComposeProject) (*Stack, error) {
func (c *ComposeProjectClient) ActionExportconfig(resource *ComposeProject, input *ComposeConfigInput) (*ComposeConfig, error) {
resp := &Stack{}
resp := &ComposeConfig{}
err := c.rancherClient.doAction(COMPOSE_PROJECT_TYPE, "exportconfig", &resource.Resource, input, resp)
return resp, err
}
func (c *ComposeProjectClient) ActionFinishupgrade(resource *ComposeProject) (*Environment, error) {
resp := &Environment{}
err := c.rancherClient.doAction(COMPOSE_PROJECT_TYPE, "finishupgrade", &resource.Resource, nil, resp)
return resp, err
}
func (c *ComposeProjectClient) ActionRemove(resource *ComposeProject) (*Stack, error) {
func (c *ComposeProjectClient) ActionRemove(resource *ComposeProject) (*Environment, error) {
resp := &Stack{}
resp := &Environment{}
err := c.rancherClient.doAction(COMPOSE_PROJECT_TYPE, "remove", &resource.Resource, nil, resp)
return resp, err
}
func (c *ComposeProjectClient) ActionRollback(resource *ComposeProject) (*Stack, error) {
func (c *ComposeProjectClient) ActionRollback(resource *ComposeProject) (*Environment, error) {
resp := &Stack{}
resp := &Environment{}
err := c.rancherClient.doAction(COMPOSE_PROJECT_TYPE, "rollback", &resource.Resource, nil, resp)
return resp, err
}
func (c *ComposeProjectClient) ActionUpdate(resource *ComposeProject) (*Environment, error) {
resp := &Environment{}
err := c.rancherClient.doAction(COMPOSE_PROJECT_TYPE, "update", &resource.Resource, nil, resp)
return resp, err
}
func (c *ComposeProjectClient) ActionUpgrade(resource *ComposeProject, input *EnvironmentUpgrade) (*Environment, error) {
resp := &Environment{}
err := c.rancherClient.doAction(COMPOSE_PROJECT_TYPE, "upgrade", &resource.Resource, input, resp)
return resp, err
}
@@ -11,29 +11,25 @@ type ComposeService struct {
Created string `json:"created,omitempty" yaml:"created,omitempty"`
CurrentScale int64 `json:"currentScale,omitempty" yaml:"current_scale,omitempty"`
Data map[string]interface{} `json:"data,omitempty" yaml:"data,omitempty"`
Description string `json:"description,omitempty" yaml:"description,omitempty"`
EnvironmentId string `json:"environmentId,omitempty" yaml:"environment_id,omitempty"`
ExternalId string `json:"externalId,omitempty" yaml:"external_id,omitempty"`
Fqdn string `json:"fqdn,omitempty" yaml:"fqdn,omitempty"`
HealthState string `json:"healthState,omitempty" yaml:"health_state,omitempty"`
InstanceIds []string `json:"instanceIds,omitempty" yaml:"instance_ids,omitempty"`
Kind string `json:"kind,omitempty" yaml:"kind,omitempty"`
LaunchConfig *LaunchConfig `json:"launchConfig,omitempty" yaml:"launch_config,omitempty"`
LinkedServices map[string]interface{} `json:"linkedServices,omitempty" yaml:"linked_services,omitempty"`
Name string `json:"name,omitempty" yaml:"name,omitempty"`
PublicEndpoints []PublicEndpoint `json:"publicEndpoints,omitempty" yaml:"public_endpoints,omitempty"`
PublicEndpoints []interface{} `json:"publicEndpoints,omitempty" yaml:"public_endpoints,omitempty"`
RemoveTime string `json:"removeTime,omitempty" yaml:"remove_time,omitempty"`
@@ -41,20 +37,14 @@ type ComposeService struct {
Scale int64 `json:"scale,omitempty" yaml:"scale,omitempty"`
ScalePolicy *ScalePolicy `json:"scalePolicy,omitempty" yaml:"scale_policy,omitempty"`
SelectorContainer string `json:"selectorContainer,omitempty" yaml:"selector_container,omitempty"`
SelectorLink string `json:"selectorLink,omitempty" yaml:"selector_link,omitempty"`
StackId string `json:"stackId,omitempty" yaml:"stack_id,omitempty"`
StartOnCreate bool `json:"startOnCreate,omitempty" yaml:"start_on_create,omitempty"`
State string `json:"state,omitempty" yaml:"state,omitempty"`
System bool `json:"system,omitempty" yaml:"system,omitempty"`
Transitioning string `json:"transitioning,omitempty" yaml:"transitioning,omitempty"`
TransitioningMessage string `json:"transitioningMessage,omitempty" yaml:"transitioning_message,omitempty"`
@@ -68,8 +58,7 @@ type ComposeService struct {
type ComposeServiceCollection struct {
Collection
Data []ComposeService `json:"data,omitempty"`
client *ComposeServiceClient
Data []ComposeService `json:"data,omitempty"`
}
type ComposeServiceClient struct {
@@ -85,17 +74,31 @@ type ComposeServiceOperations interface {
ActionActivate(*ComposeService) (*Service, error)
ActionAddservicelink(*ComposeService, *AddRemoveServiceLinkInput) (*Service, error)
ActionCancelrollback(*ComposeService) (*Service, error)
ActionCancelupgrade(*ComposeService) (*Service, error)
ActionContinueupgrade(*ComposeService) (*Service, error)
ActionCreate(*ComposeService) (*Service, error)
ActionDeactivate(*ComposeService) (*Service, error)
ActionFinishupgrade(*ComposeService) (*Service, error)
ActionRemove(*ComposeService) (*Service, error)
ActionRemoveservicelink(*ComposeService, *AddRemoveServiceLinkInput) (*Service, error)
ActionRestart(*ComposeService, *ServiceRestart) (*Service, error)
ActionRollback(*ComposeService) (*Service, error)
ActionSetservicelinks(*ComposeService, *SetServiceLinksInput) (*Service, error)
ActionUpdate(*ComposeService) (*Service, error)
ActionUpgrade(*ComposeService, *ServiceUpgrade) (*Service, error)
}
func newComposeServiceClient(rancherClient *RancherClient) *ComposeServiceClient {
@@ -119,20 +122,9 @@ func (c *ComposeServiceClient) Update(existing *ComposeService, updates interfac
func (c *ComposeServiceClient) List(opts *ListOpts) (*ComposeServiceCollection, error) {
resp := &ComposeServiceCollection{}
err := c.rancherClient.doList(COMPOSE_SERVICE_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *ComposeServiceCollection) Next() (*ComposeServiceCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &ComposeServiceCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *ComposeServiceClient) ById(id string) (*ComposeService, error) {
resp := &ComposeService{}
err := c.rancherClient.doById(COMPOSE_SERVICE_TYPE, id, resp)
@@ -157,6 +149,24 @@ func (c *ComposeServiceClient) ActionActivate(resource *ComposeService) (*Servic
return resp, err
}
func (c *ComposeServiceClient) ActionAddservicelink(resource *ComposeService, input *AddRemoveServiceLinkInput) (*Service, error) {
resp := &Service{}
err := c.rancherClient.doAction(COMPOSE_SERVICE_TYPE, "addservicelink", &resource.Resource, input, resp)
return resp, err
}
func (c *ComposeServiceClient) ActionCancelrollback(resource *ComposeService) (*Service, error) {
resp := &Service{}
err := c.rancherClient.doAction(COMPOSE_SERVICE_TYPE, "cancelrollback", &resource.Resource, nil, resp)
return resp, err
}
func (c *ComposeServiceClient) ActionCancelupgrade(resource *ComposeService) (*Service, error) {
resp := &Service{}
@@ -166,15 +176,6 @@ func (c *ComposeServiceClient) ActionCancelupgrade(resource *ComposeService) (*S
return resp, err
}
func (c *ComposeServiceClient) ActionContinueupgrade(resource *ComposeService) (*Service, error) {
resp := &Service{}
err := c.rancherClient.doAction(COMPOSE_SERVICE_TYPE, "continueupgrade", &resource.Resource, nil, resp)
return resp, err
}
func (c *ComposeServiceClient) ActionCreate(resource *ComposeService) (*Service, error) {
resp := &Service{}
@@ -184,6 +185,15 @@ func (c *ComposeServiceClient) ActionCreate(resource *ComposeService) (*Service,
return resp, err
}
func (c *ComposeServiceClient) ActionDeactivate(resource *ComposeService) (*Service, error) {
resp := &Service{}
err := c.rancherClient.doAction(COMPOSE_SERVICE_TYPE, "deactivate", &resource.Resource, nil, resp)
return resp, err
}
func (c *ComposeServiceClient) ActionFinishupgrade(resource *ComposeService) (*Service, error) {
resp := &Service{}
@@ -202,6 +212,24 @@ func (c *ComposeServiceClient) ActionRemove(resource *ComposeService) (*Service,
return resp, err
}
func (c *ComposeServiceClient) ActionRemoveservicelink(resource *ComposeService, input *AddRemoveServiceLinkInput) (*Service, error) {
resp := &Service{}
err := c.rancherClient.doAction(COMPOSE_SERVICE_TYPE, "removeservicelink", &resource.Resource, input, resp)
return resp, err
}
func (c *ComposeServiceClient) ActionRestart(resource *ComposeService, input *ServiceRestart) (*Service, error) {
resp := &Service{}
err := c.rancherClient.doAction(COMPOSE_SERVICE_TYPE, "restart", &resource.Resource, input, resp)
return resp, err
}
func (c *ComposeServiceClient) ActionRollback(resource *ComposeService) (*Service, error) {
resp := &Service{}
@@ -210,3 +238,30 @@ func (c *ComposeServiceClient) ActionRollback(resource *ComposeService) (*Servic
return resp, err
}
func (c *ComposeServiceClient) ActionSetservicelinks(resource *ComposeService, input *SetServiceLinksInput) (*Service, error) {
resp := &Service{}
err := c.rancherClient.doAction(COMPOSE_SERVICE_TYPE, "setservicelinks", &resource.Resource, input, resp)
return resp, err
}
func (c *ComposeServiceClient) ActionUpdate(resource *ComposeService) (*Service, error) {
resp := &Service{}
err := c.rancherClient.doAction(COMPOSE_SERVICE_TYPE, "update", &resource.Resource, nil, resp)
return resp, err
}
func (c *ComposeServiceClient) ActionUpgrade(resource *ComposeService, input *ServiceUpgrade) (*Service, error) {
resp := &Service{}
err := c.rancherClient.doAction(COMPOSE_SERVICE_TYPE, "upgrade", &resource.Resource, input, resp)
return resp, err
}
@@ -14,8 +14,7 @@ type ConfigItem struct {
type ConfigItemCollection struct {
Collection
Data []ConfigItem `json:"data,omitempty"`
client *ConfigItemClient
Data []ConfigItem `json:"data,omitempty"`
}
type ConfigItemClient struct {
@@ -51,20 +50,9 @@ func (c *ConfigItemClient) Update(existing *ConfigItem, updates interface{}) (*C
func (c *ConfigItemClient) List(opts *ListOpts) (*ConfigItemCollection, error) {
resp := &ConfigItemCollection{}
err := c.rancherClient.doList(CONFIG_ITEM_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *ConfigItemCollection) Next() (*ConfigItemCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &ConfigItemCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *ConfigItemClient) ById(id string) (*ConfigItem, error) {
resp := &ConfigItem{}
err := c.rancherClient.doById(CONFIG_ITEM_TYPE, id, resp)
@@ -26,8 +26,7 @@ type ConfigItemStatus struct {
type ConfigItemStatusCollection struct {
Collection
Data []ConfigItemStatus `json:"data,omitempty"`
client *ConfigItemStatusClient
Data []ConfigItemStatus `json:"data,omitempty"`
}
type ConfigItemStatusClient struct {
@@ -63,20 +62,9 @@ func (c *ConfigItemStatusClient) Update(existing *ConfigItemStatus, updates inte
func (c *ConfigItemStatusClient) List(opts *ListOpts) (*ConfigItemStatusCollection, error) {
resp := &ConfigItemStatusCollection{}
err := c.rancherClient.doList(CONFIG_ITEM_STATUS_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *ConfigItemStatusCollection) Next() (*ConfigItemStatusCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &ConfigItemStatusCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *ConfigItemStatusClient) ById(id string) (*ConfigItemStatus, error) {
resp := &ConfigItemStatus{}
err := c.rancherClient.doById(CONFIG_ITEM_STATUS_TYPE, id, resp)
@@ -15,36 +15,18 @@ type Container struct {
BlkioDeviceOptions map[string]interface{} `json:"blkioDeviceOptions,omitempty" yaml:"blkio_device_options,omitempty"`
BlkioWeight int64 `json:"blkioWeight,omitempty" yaml:"blkio_weight,omitempty"`
Build *DockerBuild `json:"build,omitempty" yaml:"build,omitempty"`
CapAdd []string `json:"capAdd,omitempty" yaml:"cap_add,omitempty"`
CapDrop []string `json:"capDrop,omitempty" yaml:"cap_drop,omitempty"`
CgroupParent string `json:"cgroupParent,omitempty" yaml:"cgroup_parent,omitempty"`
Command []string `json:"command,omitempty" yaml:"command,omitempty"`
Count int64 `json:"count,omitempty" yaml:"count,omitempty"`
CpuCount int64 `json:"cpuCount,omitempty" yaml:"cpu_count,omitempty"`
CpuPercent int64 `json:"cpuPercent,omitempty" yaml:"cpu_percent,omitempty"`
CpuPeriod int64 `json:"cpuPeriod,omitempty" yaml:"cpu_period,omitempty"`
CpuQuota int64 `json:"cpuQuota,omitempty" yaml:"cpu_quota,omitempty"`
CpuRealtimePeriod int64 `json:"cpuRealtimePeriod,omitempty" yaml:"cpu_realtime_period,omitempty"`
CpuRealtimeRuntime int64 `json:"cpuRealtimeRuntime,omitempty" yaml:"cpu_realtime_runtime,omitempty"`
CpuSet string `json:"cpuSet,omitempty" yaml:"cpu_set,omitempty"`
CpuSetMems string `json:"cpuSetMems,omitempty" yaml:"cpu_set_mems,omitempty"`
CpuShares int64 `json:"cpuShares,omitempty" yaml:"cpu_shares,omitempty"`
CreateIndex int64 `json:"createIndex,omitempty" yaml:"create_index,omitempty"`
@@ -65,12 +47,8 @@ type Container struct {
Devices []string `json:"devices,omitempty" yaml:"devices,omitempty"`
DiskQuota int64 `json:"diskQuota,omitempty" yaml:"disk_quota,omitempty"`
Dns []string `json:"dns,omitempty" yaml:"dns,omitempty"`
DnsOpt []string `json:"dnsOpt,omitempty" yaml:"dns_opt,omitempty"`
DnsSearch []string `json:"dnsSearch,omitempty" yaml:"dns_search,omitempty"`
DomainName string `json:"domainName,omitempty" yaml:"domain_name,omitempty"`
@@ -87,20 +65,10 @@ type Container struct {
FirstRunning string `json:"firstRunning,omitempty" yaml:"first_running,omitempty"`
GroupAdd []string `json:"groupAdd,omitempty" yaml:"group_add,omitempty"`
HealthCheck *InstanceHealthCheck `json:"healthCheck,omitempty" yaml:"health_check,omitempty"`
HealthCmd []string `json:"healthCmd,omitempty" yaml:"health_cmd,omitempty"`
HealthInterval int64 `json:"healthInterval,omitempty" yaml:"health_interval,omitempty"`
HealthRetries int64 `json:"healthRetries,omitempty" yaml:"health_retries,omitempty"`
HealthState string `json:"healthState,omitempty" yaml:"health_state,omitempty"`
HealthTimeout int64 `json:"healthTimeout,omitempty" yaml:"health_timeout,omitempty"`
HostId string `json:"hostId,omitempty" yaml:"host_id,omitempty"`
Hostname string `json:"hostname,omitempty" yaml:"hostname,omitempty"`
@@ -109,22 +77,6 @@ type Container struct {
InstanceLinks map[string]interface{} `json:"instanceLinks,omitempty" yaml:"instance_links,omitempty"`
InstanceTriggeredStop string `json:"instanceTriggeredStop,omitempty" yaml:"instance_triggered_stop,omitempty"`
IoMaximumBandwidth int64 `json:"ioMaximumBandwidth,omitempty" yaml:"io_maximum_bandwidth,omitempty"`
IoMaximumIOps int64 `json:"ioMaximumIOps,omitempty" yaml:"io_maximum_iops,omitempty"`
Ip string `json:"ip,omitempty" yaml:"ip,omitempty"`
Ip6 string `json:"ip6,omitempty" yaml:"ip6,omitempty"`
IpcMode string `json:"ipcMode,omitempty" yaml:"ipc_mode,omitempty"`
Isolation string `json:"isolation,omitempty" yaml:"isolation,omitempty"`
KernelMemory int64 `json:"kernelMemory,omitempty" yaml:"kernel_memory,omitempty"`
Kind string `json:"kind,omitempty" yaml:"kind,omitempty"`
Labels map[string]interface{} `json:"labels,omitempty" yaml:"labels,omitempty"`
@@ -135,42 +87,24 @@ type Container struct {
Memory int64 `json:"memory,omitempty" yaml:"memory,omitempty"`
MemoryReservation int64 `json:"memoryReservation,omitempty" yaml:"memory_reservation,omitempty"`
MemorySwap int64 `json:"memorySwap,omitempty" yaml:"memory_swap,omitempty"`
MemorySwappiness int64 `json:"memorySwappiness,omitempty" yaml:"memory_swappiness,omitempty"`
MilliCpuReservation int64 `json:"milliCpuReservation,omitempty" yaml:"milli_cpu_reservation,omitempty"`
Mounts []MountEntry `json:"mounts,omitempty" yaml:"mounts,omitempty"`
Name string `json:"name,omitempty" yaml:"name,omitempty"`
NativeContainer bool `json:"nativeContainer,omitempty" yaml:"native_container,omitempty"`
NetAlias []string `json:"netAlias,omitempty" yaml:"net_alias,omitempty"`
NetworkContainerId string `json:"networkContainerId,omitempty" yaml:"network_container_id,omitempty"`
NetworkIds []string `json:"networkIds,omitempty" yaml:"network_ids,omitempty"`
NetworkMode string `json:"networkMode,omitempty" yaml:"network_mode,omitempty"`
OomKillDisable bool `json:"oomKillDisable,omitempty" yaml:"oom_kill_disable,omitempty"`
OomScoreAdj int64 `json:"oomScoreAdj,omitempty" yaml:"oom_score_adj,omitempty"`
PidMode string `json:"pidMode,omitempty" yaml:"pid_mode,omitempty"`
PidsLimit int64 `json:"pidsLimit,omitempty" yaml:"pids_limit,omitempty"`
Ports []string `json:"ports,omitempty" yaml:"ports,omitempty"`
PrimaryIpAddress string `json:"primaryIpAddress,omitempty" yaml:"primary_ip_address,omitempty"`
PrimaryNetworkId string `json:"primaryNetworkId,omitempty" yaml:"primary_network_id,omitempty"`
Privileged bool `json:"privileged,omitempty" yaml:"privileged,omitempty"`
PublishAllPorts bool `json:"publishAllPorts,omitempty" yaml:"publish_all_ports,omitempty"`
@@ -187,20 +121,8 @@ type Container struct {
RestartPolicy *RestartPolicy `json:"restartPolicy,omitempty" yaml:"restart_policy,omitempty"`
RunInit bool `json:"runInit,omitempty" yaml:"run_init,omitempty"`
Secrets []SecretReference `json:"secrets,omitempty" yaml:"secrets,omitempty"`
SecurityOpt []string `json:"securityOpt,omitempty" yaml:"security_opt,omitempty"`
ServiceId string `json:"serviceId,omitempty" yaml:"service_id,omitempty"`
ServiceIds []string `json:"serviceIds,omitempty" yaml:"service_ids,omitempty"`
ShmSize int64 `json:"shmSize,omitempty" yaml:"shm_size,omitempty"`
StackId string `json:"stackId,omitempty" yaml:"stack_id,omitempty"`
StartCount int64 `json:"startCount,omitempty" yaml:"start_count,omitempty"`
StartOnCreate bool `json:"startOnCreate,omitempty" yaml:"start_on_create,omitempty"`
@@ -209,17 +131,7 @@ type Container struct {
StdinOpen bool `json:"stdinOpen,omitempty" yaml:"stdin_open,omitempty"`
StopSignal string `json:"stopSignal,omitempty" yaml:"stop_signal,omitempty"`
StopTimeout int64 `json:"stopTimeout,omitempty" yaml:"stop_timeout,omitempty"`
StorageOpt map[string]interface{} `json:"storageOpt,omitempty" yaml:"storage_opt,omitempty"`
Sysctls map[string]interface{} `json:"sysctls,omitempty" yaml:"sysctls,omitempty"`
System bool `json:"system,omitempty" yaml:"system,omitempty"`
Tmpfs map[string]interface{} `json:"tmpfs,omitempty" yaml:"tmpfs,omitempty"`
SystemContainer string `json:"systemContainer,omitempty" yaml:"system_container,omitempty"`
Token string `json:"token,omitempty" yaml:"token,omitempty"`
@@ -231,16 +143,8 @@ type Container struct {
Tty bool `json:"tty,omitempty" yaml:"tty,omitempty"`
Ulimits []Ulimit `json:"ulimits,omitempty" yaml:"ulimits,omitempty"`
User string `json:"user,omitempty" yaml:"user,omitempty"`
UserPorts []string `json:"userPorts,omitempty" yaml:"user_ports,omitempty"`
UsernsMode string `json:"usernsMode,omitempty" yaml:"userns_mode,omitempty"`
Uts string `json:"uts,omitempty" yaml:"uts,omitempty"`
Uuid string `json:"uuid,omitempty" yaml:"uuid,omitempty"`
Version string `json:"version,omitempty" yaml:"version,omitempty"`
@@ -252,8 +156,7 @@ type Container struct {
type ContainerCollection struct {
Collection
Data []Container `json:"data,omitempty"`
client *ContainerClient
Data []Container `json:"data,omitempty"`
}
type ContainerClient struct {
@@ -291,6 +194,10 @@ type ContainerOperations interface {
ActionRestart(*Container) (*Instance, error)
ActionRestore(*Container) (*Instance, error)
ActionSetlabels(*Container, *SetLabelsInput) (*Container, error)
ActionStart(*Container) (*Instance, error)
ActionStop(*Container, *InstanceStop) (*Instance, error)
@@ -325,20 +232,9 @@ func (c *ContainerClient) Update(existing *Container, updates interface{}) (*Con
func (c *ContainerClient) List(opts *ListOpts) (*ContainerCollection, error) {
resp := &ContainerCollection{}
err := c.rancherClient.doList(CONTAINER_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *ContainerCollection) Next() (*ContainerCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &ContainerCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *ContainerClient) ById(id string) (*Container, error) {
resp := &Container{}
err := c.rancherClient.doById(CONTAINER_TYPE, id, resp)
@@ -462,6 +358,24 @@ func (c *ContainerClient) ActionRestart(resource *Container) (*Instance, error)
return resp, err
}
func (c *ContainerClient) ActionRestore(resource *Container) (*Instance, error) {
resp := &Instance{}
err := c.rancherClient.doAction(CONTAINER_TYPE, "restore", &resource.Resource, nil, resp)
return resp, err
}
func (c *ContainerClient) ActionSetlabels(resource *Container, input *SetLabelsInput) (*Container, error) {
resp := &Container{}
err := c.rancherClient.doAction(CONTAINER_TYPE, "setlabels", &resource.Resource, input, resp)
return resp, err
}
func (c *ContainerClient) ActionStart(resource *Container) (*Instance, error) {
resp := &Instance{}
@@ -40,8 +40,7 @@ type ContainerEvent struct {
type ContainerEventCollection struct {
Collection
Data []ContainerEvent `json:"data,omitempty"`
client *ContainerEventClient
Data []ContainerEvent `json:"data,omitempty"`
}
type ContainerEventClient struct {
@@ -81,20 +80,9 @@ func (c *ContainerEventClient) Update(existing *ContainerEvent, updates interfac
func (c *ContainerEventClient) List(opts *ListOpts) (*ContainerEventCollection, error) {
resp := &ContainerEventCollection{}
err := c.rancherClient.doList(CONTAINER_EVENT_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *ContainerEventCollection) Next() (*ContainerEventCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &ContainerEventCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *ContainerEventClient) ById(id string) (*ContainerEvent, error) {
resp := &ContainerEvent{}
err := c.rancherClient.doById(CONTAINER_EVENT_TYPE, id, resp)
@@ -18,8 +18,7 @@ type ContainerExec struct {
type ContainerExecCollection struct {
Collection
Data []ContainerExec `json:"data,omitempty"`
client *ContainerExecClient
Data []ContainerExec `json:"data,omitempty"`
}
type ContainerExecClient struct {
@@ -55,20 +54,9 @@ func (c *ContainerExecClient) Update(existing *ContainerExec, updates interface{
func (c *ContainerExecClient) List(opts *ListOpts) (*ContainerExecCollection, error) {
resp := &ContainerExecCollection{}
err := c.rancherClient.doList(CONTAINER_EXEC_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *ContainerExecCollection) Next() (*ContainerExecCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &ContainerExecCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *ContainerExecClient) ById(id string) (*ContainerExec, error) {
resp := &ContainerExec{}
err := c.rancherClient.doById(CONTAINER_EXEC_TYPE, id, resp)
@@ -14,8 +14,7 @@ type ContainerLogs struct {
type ContainerLogsCollection struct {
Collection
Data []ContainerLogs `json:"data,omitempty"`
client *ContainerLogsClient
Data []ContainerLogs `json:"data,omitempty"`
}
type ContainerLogsClient struct {
@@ -51,20 +50,9 @@ func (c *ContainerLogsClient) Update(existing *ContainerLogs, updates interface{
func (c *ContainerLogsClient) List(opts *ListOpts) (*ContainerLogsCollection, error) {
resp := &ContainerLogsCollection{}
err := c.rancherClient.doList(CONTAINER_LOGS_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *ContainerLogsCollection) Next() (*ContainerLogsCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &ContainerLogsCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *ContainerLogsClient) ById(id string) (*ContainerLogs, error) {
resp := &ContainerLogs{}
err := c.rancherClient.doById(CONTAINER_LOGS_TYPE, id, resp)
@@ -14,8 +14,7 @@ type ContainerProxy struct {
type ContainerProxyCollection struct {
Collection
Data []ContainerProxy `json:"data,omitempty"`
client *ContainerProxyClient
Data []ContainerProxy `json:"data,omitempty"`
}
type ContainerProxyClient struct {
@@ -51,20 +50,9 @@ func (c *ContainerProxyClient) Update(existing *ContainerProxy, updates interfac
func (c *ContainerProxyClient) List(opts *ListOpts) (*ContainerProxyCollection, error) {
resp := &ContainerProxyCollection{}
err := c.rancherClient.doList(CONTAINER_PROXY_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *ContainerProxyCollection) Next() (*ContainerProxyCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &ContainerProxyCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *ContainerProxyClient) ById(id string) (*ContainerProxy, error) {
resp := &ContainerProxy{}
err := c.rancherClient.doById(CONTAINER_PROXY_TYPE, id, resp)
@@ -40,8 +40,7 @@ type Credential struct {
type CredentialCollection struct {
Collection
Data []Credential `json:"data,omitempty"`
client *CredentialClient
Data []Credential `json:"data,omitempty"`
}
type CredentialClient struct {
@@ -89,20 +88,9 @@ func (c *CredentialClient) Update(existing *Credential, updates interface{}) (*C
func (c *CredentialClient) List(opts *ListOpts) (*CredentialCollection, error) {
resp := &CredentialCollection{}
err := c.rancherClient.doList(CREDENTIAL_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *CredentialCollection) Next() (*CredentialCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &CredentialCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *CredentialClient) ById(id string) (*Credential, error) {
resp := &Credential{}
err := c.rancherClient.doById(CREDENTIAL_TYPE, id, resp)
@@ -30,8 +30,7 @@ type Databasechangelog struct {
type DatabasechangelogCollection struct {
Collection
Data []Databasechangelog `json:"data,omitempty"`
client *DatabasechangelogClient
Data []Databasechangelog `json:"data,omitempty"`
}
type DatabasechangelogClient struct {
@@ -67,20 +66,9 @@ func (c *DatabasechangelogClient) Update(existing *Databasechangelog, updates in
func (c *DatabasechangelogClient) List(opts *ListOpts) (*DatabasechangelogCollection, error) {
resp := &DatabasechangelogCollection{}
err := c.rancherClient.doList(DATABASECHANGELOG_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *DatabasechangelogCollection) Next() (*DatabasechangelogCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &DatabasechangelogCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *DatabasechangelogClient) ById(id string) (*Databasechangelog, error) {
resp := &Databasechangelog{}
err := c.rancherClient.doById(DATABASECHANGELOG_TYPE, id, resp)
@@ -16,8 +16,7 @@ type Databasechangeloglock struct {
type DatabasechangeloglockCollection struct {
Collection
Data []Databasechangeloglock `json:"data,omitempty"`
client *DatabasechangeloglockClient
Data []Databasechangeloglock `json:"data,omitempty"`
}
type DatabasechangeloglockClient struct {
@@ -53,20 +52,9 @@ func (c *DatabasechangeloglockClient) Update(existing *Databasechangeloglock, up
func (c *DatabasechangeloglockClient) List(opts *ListOpts) (*DatabasechangeloglockCollection, error) {
resp := &DatabasechangeloglockCollection{}
err := c.rancherClient.doList(DATABASECHANGELOGLOCK_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *DatabasechangeloglockCollection) Next() (*DatabasechangeloglockCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &DatabasechangeloglockCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *DatabasechangeloglockClient) ById(id string) (*Databasechangeloglock, error) {
resp := &Databasechangeloglock{}
err := c.rancherClient.doById(DATABASECHANGELOGLOCK_TYPE, id, resp)
@@ -21,21 +21,12 @@ type DigitaloceanConfig struct {
Size string `json:"size,omitempty" yaml:"size,omitempty"`
SshKeyFingerprint string `json:"sshKeyFingerprint,omitempty" yaml:"ssh_key_fingerprint,omitempty"`
SshKeyPath string `json:"sshKeyPath,omitempty" yaml:"ssh_key_path,omitempty"`
SshPort string `json:"sshPort,omitempty" yaml:"ssh_port,omitempty"`
SshUser string `json:"sshUser,omitempty" yaml:"ssh_user,omitempty"`
Userdata string `json:"userdata,omitempty" yaml:"userdata,omitempty"`
}
type DigitaloceanConfigCollection struct {
Collection
Data []DigitaloceanConfig `json:"data,omitempty"`
client *DigitaloceanConfigClient
Data []DigitaloceanConfig `json:"data,omitempty"`
}
type DigitaloceanConfigClient struct {
@@ -71,20 +62,9 @@ func (c *DigitaloceanConfigClient) Update(existing *DigitaloceanConfig, updates
func (c *DigitaloceanConfigClient) List(opts *ListOpts) (*DigitaloceanConfigCollection, error) {
resp := &DigitaloceanConfigCollection{}
err := c.rancherClient.doList(DIGITALOCEAN_CONFIG_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *DigitaloceanConfigCollection) Next() (*DigitaloceanConfigCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &DigitaloceanConfigCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *DigitaloceanConfigClient) ById(id string) (*DigitaloceanConfig, error) {
resp := &DigitaloceanConfig{}
err := c.rancherClient.doById(DIGITALOCEAN_CONFIG_TYPE, id, resp)
@@ -17,20 +17,18 @@ type DnsService struct {
Description string `json:"description,omitempty" yaml:"description,omitempty"`
EnvironmentId string `json:"environmentId,omitempty" yaml:"environment_id,omitempty"`
ExternalId string `json:"externalId,omitempty" yaml:"external_id,omitempty"`
Fqdn string `json:"fqdn,omitempty" yaml:"fqdn,omitempty"`
HealthState string `json:"healthState,omitempty" yaml:"health_state,omitempty"`
InstanceIds []string `json:"instanceIds,omitempty" yaml:"instance_ids,omitempty"`
Kind string `json:"kind,omitempty" yaml:"kind,omitempty"`
LaunchConfig *LaunchConfig `json:"launchConfig,omitempty" yaml:"launch_config,omitempty"`
LinkedServices map[string]interface{} `json:"linkedServices,omitempty" yaml:"linked_services,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty" yaml:"metadata,omitempty"`
Name string `json:"name,omitempty" yaml:"name,omitempty"`
@@ -43,14 +41,10 @@ type DnsService struct {
SelectorLink string `json:"selectorLink,omitempty" yaml:"selector_link,omitempty"`
StackId string `json:"stackId,omitempty" yaml:"stack_id,omitempty"`
StartOnCreate bool `json:"startOnCreate,omitempty" yaml:"start_on_create,omitempty"`
State string `json:"state,omitempty" yaml:"state,omitempty"`
System bool `json:"system,omitempty" yaml:"system,omitempty"`
Transitioning string `json:"transitioning,omitempty" yaml:"transitioning,omitempty"`
TransitioningMessage string `json:"transitioningMessage,omitempty" yaml:"transitioning_message,omitempty"`
@@ -64,8 +58,7 @@ type DnsService struct {
type DnsServiceCollection struct {
Collection
Data []DnsService `json:"data,omitempty"`
client *DnsServiceClient
Data []DnsService `json:"data,omitempty"`
}
type DnsServiceClient struct {
@@ -83,9 +76,9 @@ type DnsServiceOperations interface {
ActionAddservicelink(*DnsService, *AddRemoveServiceLinkInput) (*Service, error)
ActionCancelupgrade(*DnsService) (*Service, error)
ActionCancelrollback(*DnsService) (*Service, error)
ActionContinueupgrade(*DnsService) (*Service, error)
ActionCancelupgrade(*DnsService) (*Service, error)
ActionCreate(*DnsService) (*Service, error)
@@ -129,20 +122,9 @@ func (c *DnsServiceClient) Update(existing *DnsService, updates interface{}) (*D
func (c *DnsServiceClient) List(opts *ListOpts) (*DnsServiceCollection, error) {
resp := &DnsServiceCollection{}
err := c.rancherClient.doList(DNS_SERVICE_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *DnsServiceCollection) Next() (*DnsServiceCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &DnsServiceCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *DnsServiceClient) ById(id string) (*DnsService, error) {
resp := &DnsService{}
err := c.rancherClient.doById(DNS_SERVICE_TYPE, id, resp)
@@ -176,6 +158,15 @@ func (c *DnsServiceClient) ActionAddservicelink(resource *DnsService, input *Add
return resp, err
}
func (c *DnsServiceClient) ActionCancelrollback(resource *DnsService) (*Service, error) {
resp := &Service{}
err := c.rancherClient.doAction(DNS_SERVICE_TYPE, "cancelrollback", &resource.Resource, nil, resp)
return resp, err
}
func (c *DnsServiceClient) ActionCancelupgrade(resource *DnsService) (*Service, error) {
resp := &Service{}
@@ -185,15 +176,6 @@ func (c *DnsServiceClient) ActionCancelupgrade(resource *DnsService) (*Service,
return resp, err
}
func (c *DnsServiceClient) ActionContinueupgrade(resource *DnsService) (*Service, error) {
resp := &Service{}
err := c.rancherClient.doAction(DNS_SERVICE_TYPE, "continueupgrade", &resource.Resource, nil, resp)
return resp, err
}
func (c *DnsServiceClient) ActionCreate(resource *DnsService) (*Service, error) {
resp := &Service{}
@@ -22,8 +22,7 @@ type DockerBuild struct {
type DockerBuildCollection struct {
Collection
Data []DockerBuild `json:"data,omitempty"`
client *DockerBuildClient
Data []DockerBuild `json:"data,omitempty"`
}
type DockerBuildClient struct {
@@ -59,20 +58,9 @@ func (c *DockerBuildClient) Update(existing *DockerBuild, updates interface{}) (
func (c *DockerBuildClient) List(opts *ListOpts) (*DockerBuildCollection, error) {
resp := &DockerBuildCollection{}
err := c.rancherClient.doList(DOCKER_BUILD_TYPE, opts, resp)
resp.client = c
return resp, err
}
func (cc *DockerBuildCollection) Next() (*DockerBuildCollection, error) {
if cc != nil && cc.Pagination != nil && cc.Pagination.Next != "" {
resp := &DockerBuildCollection{}
err := cc.client.rancherClient.doNext(cc.Pagination.Next, resp)
resp.client = cc.client
return resp, err
}
return nil, nil
}
func (c *DockerBuildClient) ById(id string) (*DockerBuild, error) {
resp := &DockerBuild{}
err := c.rancherClient.doById(DOCKER_BUILD_TYPE, id, resp)
+117
View File
@@ -0,0 +1,117 @@
package client
const (
DYNAMIC_SCHEMA_TYPE = "dynamicSchema"
)
type DynamicSchema struct {
Resource
AccountId string `json:"accountId,omitempty" yaml:"account_id,omitempty"`
Created string `json:"created,omitempty" yaml:"created,omitempty"`
Data map[string]interface{} `json:"data,omitempty" yaml:"data,omitempty"`
Definition string `json:"definition,omitempty" yaml:"definition,omitempty"`
Description string `json:"description,omitempty" yaml:"description,omitempty"`
Kind string `json:"kind,omitempty" yaml:"kind,omitempty"`
Name string `json:"name,omitempty" yaml:"name,omitempty"`
Parent string `json:"parent,omitempty" yaml:"parent,omitempty"`
Removed string `json:"removed,omitempty" yaml:"removed,omitempty"`
Roles []string `json:"roles,omitempty" yaml:"roles,omitempty"`
State string `json:"state,omitempty" yaml:"state,omitempty"`
Transitioning string `json:"transitioning,omitempty" yaml:"transitioning,omitempty"`
TransitioningMessage string `json:"transitioningMessage,omitempty" yaml:"transitioning_message,omitempty"`
TransitioningProgress int64 `json:"transitioningProgress,omitempty" yaml:"transitioning_progress,omitempty"`
Uuid string `json:"uuid,omitempty" yaml:"uuid,omitempty"`
}
type DynamicSchemaCollection struct {
Collection
Data []DynamicSchema `json:"data,omitempty"`
}
type DynamicSchemaClient struct {
rancherClient *RancherClient
}
type DynamicSchemaOperations interface {
List(opts *ListOpts) (*DynamicSchemaCollection, error)
Create(opts *DynamicSchema) (*DynamicSchema, error)
Update(existing *DynamicSchema, updates interface{}) (*DynamicSchema, error)
ById(id string) (*DynamicSchema, error)
Delete(container *DynamicSchema) error
ActionCreate(*DynamicSchema) (*DynamicSchema, error)
ActionRemove(*DynamicSchema) (*DynamicSchema, error)
}
func newDynamicSchemaClient(rancherClient *RancherClient) *DynamicSchemaClient {
return &DynamicSchemaClient{
rancherClient: rancherClient,
}
}
func (c *DynamicSchemaClient) Create(container *DynamicSchema) (*DynamicSchema, error) {
resp := &DynamicSchema{}
err := c.rancherClient.doCreate(DYNAMIC_SCHEMA_TYPE, container, resp)
return resp, err
}
func (c *DynamicSchemaClient) Update(existing *DynamicSchema, updates interface{}) (*DynamicSchema, error) {
resp := &DynamicSchema{}
err := c.rancherClient.doUpdate(DYNAMIC_SCHEMA_TYPE, &existing.Resource, updates, resp)
return resp, err
}
func (c *DynamicSchemaClient) List(opts *ListOpts) (*DynamicSchemaCollection, error) {
resp := &DynamicSchemaCollection{}
err := c.rancherClient.doList(DYNAMIC_SCHEMA_TYPE, opts, resp)
return resp, err
}
func (c *DynamicSchemaClient) ById(id string) (*DynamicSchema, error) {
resp := &DynamicSchema{}
err := c.rancherClient.doById(DYNAMIC_SCHEMA_TYPE, id, resp)
if apiError, ok := err.(*ApiError); ok {
if apiError.StatusCode == 404 {
return nil, nil
}
}
return resp, err
}
func (c *DynamicSchemaClient) Delete(container *DynamicSchema) error {
return c.rancherClient.doResourceDelete(DYNAMIC_SCHEMA_TYPE, &container.Resource)
}
func (c *DynamicSchemaClient) ActionCreate(resource *DynamicSchema) (*DynamicSchema, error) {
resp := &DynamicSchema{}
err := c.rancherClient.doAction(DYNAMIC_SCHEMA_TYPE, "create", &resource.Resource, nil, resp)
return resp, err
}
func (c *DynamicSchemaClient) ActionRemove(resource *DynamicSchema) (*DynamicSchema, error) {
resp := &DynamicSchema{}
err := c.rancherClient.doAction(DYNAMIC_SCHEMA_TYPE, "remove", &resource.Resource, nil, resp)
return resp, err
}

Some files were not shown because too many files have changed in this diff Show More