Unverified Commit 1b9698bb authored by Erik Wilson's avatar Erik Wilson Committed by GitHub

Merge pull request #850 from chenrui333/go-1.13

Upgrade to go v1.13.1
parents cac41db0 ca70e11d
FROM golang:1.12.9-alpine3.10 FROM golang:1.13.1-alpine3.10
RUN apk -U --no-cache add bash git gcc musl-dev docker vim less file curl wget ca-certificates jq linux-headers zlib-dev tar zip squashfs-tools npm coreutils \ RUN apk -U --no-cache add bash git gcc musl-dev docker vim less file curl wget ca-certificates jq linux-headers zlib-dev tar zip squashfs-tools npm coreutils \
python3 py3-pip python3-dev openssl-dev libffi-dev libseccomp libseccomp-dev make python3 py3-pip python3-dev openssl-dev libffi-dev libseccomp libseccomp-dev make
...@@ -29,4 +29,3 @@ WORKDIR ${DAPPER_SOURCE} ...@@ -29,4 +29,3 @@ WORKDIR ${DAPPER_SOURCE}
ENTRYPOINT ["./scripts/entry.sh"] ENTRYPOINT ["./scripts/entry.sh"]
CMD ["ci"] CMD ["ci"]
FROM golang:1.12.9-alpine3.10 FROM golang:1.13.1-alpine3.10
RUN apk -U --no-cache add bash git gcc musl-dev docker curl jq coreutils RUN apk -U --no-cache add bash git gcc musl-dev docker curl jq coreutils
RUN go get -d github.com/heptio/sonobuoy && \ RUN go get -d github.com/heptio/sonobuoy && \
......
module github.com/rancher/k3s module github.com/rancher/k3s
go 1.12 go 1.13
replace ( replace (
github.com/Microsoft/hcsshim => github.com/Microsoft/hcsshim v0.8.7-0.20190926181021-82c7525d98c8
github.com/containerd/btrfs => github.com/containerd/btrfs v0.0.0-20181101203652-af5082808c83 github.com/containerd/btrfs => github.com/containerd/btrfs v0.0.0-20181101203652-af5082808c83
github.com/containerd/cgroups => github.com/containerd/cgroups v0.0.0-20190717030353-c4b9ac5c7601 github.com/containerd/cgroups => github.com/containerd/cgroups v0.0.0-20190717030353-c4b9ac5c7601
github.com/containerd/console => github.com/containerd/console v0.0.0-20181022165439-0650fd9eeb50 github.com/containerd/console => github.com/containerd/console v0.0.0-20181022165439-0650fd9eeb50
...@@ -16,6 +17,13 @@ replace ( ...@@ -16,6 +17,13 @@ replace (
github.com/coreos/go-systemd => github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7 github.com/coreos/go-systemd => github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7
github.com/docker/distribution => github.com/docker/distribution v0.0.0-20190205005809-0d3efadf0154 github.com/docker/distribution => github.com/docker/distribution v0.0.0-20190205005809-0d3efadf0154
github.com/docker/libnetwork => github.com/docker/libnetwork v0.8.0-dev.2.0.20190624125649-f0e46a78ea34 github.com/docker/libnetwork => github.com/docker/libnetwork v0.8.0-dev.2.0.20190624125649-f0e46a78ea34
github.com/go-critic/go-critic => github.com/go-critic/go-critic v0.3.5-0.20190526074819-1df300866540
github.com/golangci/errcheck => github.com/golangci/errcheck v0.0.0-20181223084120-ef45e06d44b6
github.com/golangci/go-tools => github.com/golangci/go-tools v0.0.0-20190318060251-af6baa5dc196
github.com/golangci/gofmt => github.com/golangci/gofmt v0.0.0-20181222123516-0b8337e80d98
github.com/golangci/gosec => github.com/golangci/gosec v0.0.0-20190211064107-66fb7fc33547
github.com/golangci/ineffassign => github.com/golangci/ineffassign v0.0.0-20190609212857-42439a7714cc
github.com/golangci/lint-1 => github.com/golangci/lint-1 v0.0.0-20190420132249-ee948d087217
github.com/kubernetes-sigs/cri-tools => github.com/rancher/cri-tools v1.16.0-k3s.1 github.com/kubernetes-sigs/cri-tools => github.com/rancher/cri-tools v1.16.0-k3s.1
github.com/matryer/moq => github.com/rancher/moq v0.0.0-20190404221404-ee5226d43009 github.com/matryer/moq => github.com/rancher/moq v0.0.0-20190404221404-ee5226d43009
github.com/opencontainers/runtime-spec => github.com/opencontainers/runtime-spec v0.0.0-20180911193056-5684b8af48c1 github.com/opencontainers/runtime-spec => github.com/opencontainers/runtime-spec v0.0.0-20180911193056-5684b8af48c1
...@@ -49,17 +57,16 @@ replace ( ...@@ -49,17 +57,16 @@ replace (
k8s.io/sample-apiserver => github.com/rancher/kubernetes/staging/src/k8s.io/sample-apiserver v1.16.0-k3s.1 k8s.io/sample-apiserver => github.com/rancher/kubernetes/staging/src/k8s.io/sample-apiserver v1.16.0-k3s.1
k8s.io/sample-cli-plugin => github.com/rancher/kubernetes/staging/src/k8s.io/sample-cli-plugin v1.16.0-k3s.1 k8s.io/sample-cli-plugin => github.com/rancher/kubernetes/staging/src/k8s.io/sample-cli-plugin v1.16.0-k3s.1
k8s.io/sample-controller => github.com/rancher/kubernetes/staging/src/k8s.io/sample-controller v1.16.0-k3s.1 k8s.io/sample-controller => github.com/rancher/kubernetes/staging/src/k8s.io/sample-controller v1.16.0-k3s.1
mvdan.cc/unparam => mvdan.cc/unparam v0.0.0-20190209190245-fbb59629db34
) )
require ( require (
github.com/Microsoft/go-winio v0.4.14 // indirect
github.com/NYTimes/gziphandler v1.1.1 // indirect github.com/NYTimes/gziphandler v1.1.1 // indirect
github.com/bhendo/go-powershell v0.0.0-20190719160123-219e7fb4e41e // indirect github.com/bhendo/go-powershell v0.0.0-20190719160123-219e7fb4e41e // indirect
github.com/bronze1man/goStrongswanVici v0.0.0-20190828090544-27d02f80ba40 // indirect github.com/bronze1man/goStrongswanVici v0.0.0-20190828090544-27d02f80ba40 // indirect
github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23 // indirect github.com/buger/jsonparser v0.0.0-20181115193947-bf1c66bbce23 // indirect
github.com/containerd/cgroups v0.0.0-20190923161937-abd0b19954a6 // indirect github.com/containerd/cgroups v0.0.0-20190923161937-abd0b19954a6 // indirect
github.com/containerd/containerd v1.2.8 github.com/containerd/containerd v1.3.0-beta.2.0.20190828155532-0293cbd26c69
github.com/containerd/continuity v0.0.0-20190827140505-75bee3e2ccb6 // indirect github.com/containerd/continuity v0.0.0-20190827140505-75bee3e2ccb6 // indirect
github.com/containerd/cri v1.11.1-0.20190909171321-f4d75d321c89 github.com/containerd/cri v1.11.1-0.20190909171321-f4d75d321c89
github.com/containerd/fifo v0.0.0-20190816180239-bda0ff6ed73c // indirect github.com/containerd/fifo v0.0.0-20190816180239-bda0ff6ed73c // indirect
...@@ -70,7 +77,6 @@ require ( ...@@ -70,7 +77,6 @@ require (
github.com/coreos/flannel v0.11.0 github.com/coreos/flannel v0.11.0
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e
github.com/docker/docker v0.7.3-0.20190731001754-589f1dad8dad github.com/docker/docker v0.7.3-0.20190731001754-589f1dad8dad
github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c // indirect
github.com/docker/go-metrics v0.0.1 // indirect github.com/docker/go-metrics v0.0.1 // indirect
github.com/docker/libnetwork v0.8.0-dev.2.0.20190624125649-f0e46a78ea34 // indirect github.com/docker/libnetwork v0.8.0-dev.2.0.20190624125649-f0e46a78ea34 // indirect
github.com/go-bindata/go-bindata v3.1.2+incompatible github.com/go-bindata/go-bindata v3.1.2+incompatible
...@@ -105,7 +111,7 @@ require ( ...@@ -105,7 +111,7 @@ require (
github.com/urfave/cli v1.21.0 github.com/urfave/cli v1.21.0
go.etcd.io/bbolt v1.3.3 // indirect go.etcd.io/bbolt v1.3.3 // indirect
golang.org/x/net v0.0.0-20190812203447-cdfb69ac37fc golang.org/x/net v0.0.0-20190812203447-cdfb69ac37fc
golang.org/x/sys v0.0.0-20190812073006-9eafafc0a87e golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3
google.golang.org/grpc v1.23.0 google.golang.org/grpc v1.23.0
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22 // indirect gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22 // indirect
k8s.io/api v0.0.0 k8s.io/api v0.0.0
......
...@@ -5,5 +5,5 @@ go 1.12 ...@@ -5,5 +5,5 @@ go 1.12
require ( require (
github.com/pkg/errors v0.8.1 github.com/pkg/errors v0.8.1
github.com/sirupsen/logrus v1.4.1 github.com/sirupsen/logrus v1.4.1
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3
) )
...@@ -14,3 +14,5 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf ...@@ -14,3 +14,5 @@ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXf
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b h1:ag/x1USPSsqHud38I9BAC88qdNLDHHtQ4mlgQIZPPNA= golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b h1:ag/x1USPSsqHud38I9BAC88qdNLDHHtQ4mlgQIZPPNA=
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3 h1:7TYNF4UdlohbFwpNH04CoPMp1cHUZgO1Ebq5r2hIjfo=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
version = "unstable"
generator = "gogoctrd"
plugins = ["grpc", "fieldpath"]
# Control protoc include paths. Below are usually some good defaults, but feel
# free to try it without them if it works for your project.
[includes]
# Include paths that will be added before all others. Typically, you want to
# treat the root of the project as an include, but this may not be necessary.
before = ["./protobuf"]
# Paths that should be treated as include roots in relation to the vendor
# directory. These will be calculated with the vendor directory nearest the
# target package.
packages = ["github.com/gogo/protobuf"]
# Paths that will be added untouched to the end of the includes. We use
# `/usr/local/include` to pickup the common install location of protobuf.
# This is the default.
after = ["/usr/local/include"]
# This section maps protobuf imports to Go packages. These will become
# `-M` directives in the call to the go protobuf generator.
[packages]
"gogoproto/gogo.proto" = "github.com/gogo/protobuf/gogoproto"
"google/protobuf/any.proto" = "github.com/gogo/protobuf/types"
"google/protobuf/empty.proto" = "github.com/gogo/protobuf/types"
"google/protobuf/descriptor.proto" = "github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
"google/protobuf/field_mask.proto" = "github.com/gogo/protobuf/types"
"google/protobuf/timestamp.proto" = "github.com/gogo/protobuf/types"
"google/protobuf/duration.proto" = "github.com/gogo/protobuf/types"
[[overrides]]
prefixes = ["github.com/Microsoft/hcsshim/internal/shimdiag"]
plugins = ["ttrpc"]
# Lock down runhcs config
[[descriptors]]
prefix = "github.com/Microsoft/hcsshim/cmd/containerd-shim-runhcs-v1/options"
target = "cmd/containerd-shim-runhcs-v1/options/next.pb.txt"
ignore_files = [
"google/protobuf/descriptor.proto",
"gogoproto/gogo.proto"
]
[[descriptors]]
prefix = "github.com/Microsoft/hcsshim/cmd/containerd-shim-runhcs-v1/stats"
target = "cmd/containerd-shim-runhcs-v1/stats/next.pb.txt"
ignore_files = [
"google/protobuf/descriptor.proto",
"gogoproto/gogo.proto"
]
\ No newline at end of file
...@@ -8,22 +8,34 @@ environment: ...@@ -8,22 +8,34 @@ environment:
GOPATH: c:\gopath GOPATH: c:\gopath
PATH: C:\mingw-w64\x86_64-7.2.0-posix-seh-rt_v5-rev1\mingw64\bin;%GOPATH%\bin;C:\gometalinter-2.0.12-windows-amd64;%PATH% PATH: C:\mingw-w64\x86_64-7.2.0-posix-seh-rt_v5-rev1\mingw64\bin;%GOPATH%\bin;C:\gometalinter-2.0.12-windows-amd64;%PATH%
stack: go 1.11 stack: go 1.12.9
build_script: build_script:
- appveyor DownloadFile https://github.com/alecthomas/gometalinter/releases/download/v2.0.12/gometalinter-2.0.12-windows-amd64.zip - appveyor DownloadFile https://github.com/alecthomas/gometalinter/releases/download/v2.0.12/gometalinter-2.0.12-windows-amd64.zip
- 7z x gometalinter-2.0.12-windows-amd64.zip -y -oC:\ > NUL - 7z x gometalinter-2.0.12-windows-amd64.zip -y -oC:\ > NUL
- gometalinter.exe --config .gometalinter.json ./... - gometalinter.exe --config .gometalinter.json ./...
- go build ./cmd/wclayer - go build ./cmd/containerd-shim-runhcs-v1
- go build ./cmd/runhcs - go build ./cmd/runhcs
- go build ./cmd/tar2ext4 - go build ./cmd/tar2ext4
- go build ./cmd/wclayer
- go build ./internal/tools/grantvmgroupaccess
- go build ./internal/tools/uvmboot
- go build ./internal/tools/zapdir
- go test -v ./... -tags admin - go test -v ./... -tags admin
- go test -c ./test/containerd-shim-runhcs-v1/ -tags functional
- go test -c ./test/cri-containerd/ -tags functional
- go test -c ./test/functional/ -tags functional - go test -c ./test/functional/ -tags functional
- go test -c ./test/runhcs/ -tags integration - go test -c ./test/runhcs/ -tags functional
artifacts: artifacts:
- path: 'wclayer.exe' - path: 'containerd-shim-runhcs-v1.exe'
- path: 'runhcs.exe' - path: 'runhcs.exe'
- path: 'tar2ext4.exe' - path: 'tar2ext4.exe'
- path: 'wclayer.exe'
- path: 'grantvmgroupaccess.exe'
- path: 'uvmboot.exe'
- path: 'zapdir.exe'
- path: 'containerd-shim-runhcs-v1.test.exe'
- path: 'cri-containerd.test.exe'
- path: 'functional.test.exe' - path: 'functional.test.exe'
- path: 'runhcs.test.exe' - path: 'runhcs.test.exe'
\ No newline at end of file
syntax = "proto3";
package containerd.runhcs.v1;
import weak "gogoproto/gogo.proto";
import "google/protobuf/timestamp.proto";
option go_package = "github.com/Microsoft/hcsshim/cmd/containerd-shim-runhcs-v1/options;options";
// Options are the set of customizations that can be passed at Create time.
message Options {
// enable debug tracing
bool debug = 1;
enum DebugType {
NPIPE = 0;
FILE = 1;
ETW = 2;
}
// debug tracing output type
DebugType debug_type = 2;
// registry key root for storage of the runhcs container state
string registry_root = 3;
// sandbox_image is the image to use for the sandbox that matches the
// sandbox_platform.
string sandbox_image = 4;
// sandbox_platform is a CRI setting that specifies the platform
// architecture for all sandbox's in this runtime. Values are
// 'windows/amd64' and 'linux/amd64'.
string sandbox_platform = 5;
enum SandboxIsolation {
PROCESS = 0;
HYPERVISOR = 1;
}
// sandbox_isolation is a CRI setting that specifies the isolation level of
// the sandbox. For Windows runtime PROCESS and HYPERVISOR are valid. For
// LCOW only HYPERVISOR is valid and default if omitted.
SandboxIsolation sandbox_isolation = 6;
// boot_files_root_path is the path to the directory containing the LCOW
// kernel and root FS files.
string boot_files_root_path = 7;
}
// ProcessDetails contains additional information about a process. This is the additional
// info returned in the Pids query.
message ProcessDetails {
string image_name = 1;
google.protobuf.Timestamp created_at = 2 [(gogoproto.stdtime) = true, (gogoproto.nullable) = false];
uint64 kernel_time_100_ns = 3;
uint64 memory_commit_bytes = 4;
uint64 memory_working_set_private_bytes = 5;
uint64 memory_working_set_shared_bytes = 6;
uint32 process_id = 7;
uint64 user_time_100_ns = 8;
string exec_id = 9;
}
package hcsshim package hcsshim
import ( import (
"context"
"fmt" "fmt"
"os" "os"
"sync"
"time" "time"
"github.com/Microsoft/hcsshim/internal/hcs" "github.com/Microsoft/hcsshim/internal/hcs"
...@@ -52,7 +54,10 @@ const ( ...@@ -52,7 +54,10 @@ const (
type ResourceModificationRequestResponse = schema1.ResourceModificationRequestResponse type ResourceModificationRequestResponse = schema1.ResourceModificationRequestResponse
type container struct { type container struct {
system *hcs.System system *hcs.System
waitOnce sync.Once
waitErr error
waitCh chan struct{}
} }
// createComputeSystemAdditionalJSON is read from the environment at initialisation // createComputeSystemAdditionalJSON is read from the environment at initialisation
...@@ -71,61 +76,87 @@ func CreateContainer(id string, c *ContainerConfig) (Container, error) { ...@@ -71,61 +76,87 @@ func CreateContainer(id string, c *ContainerConfig) (Container, error) {
return nil, fmt.Errorf("failed to merge additional JSON '%s': %s", createContainerAdditionalJSON, err) return nil, fmt.Errorf("failed to merge additional JSON '%s': %s", createContainerAdditionalJSON, err)
} }
system, err := hcs.CreateComputeSystem(id, fullConfig) system, err := hcs.CreateComputeSystem(context.Background(), id, fullConfig)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &container{system}, err return &container{system: system}, err
} }
// OpenContainer opens an existing container by ID. // OpenContainer opens an existing container by ID.
func OpenContainer(id string) (Container, error) { func OpenContainer(id string) (Container, error) {
system, err := hcs.OpenComputeSystem(id) system, err := hcs.OpenComputeSystem(context.Background(), id)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &container{system}, err return &container{system: system}, err
} }
// GetContainers gets a list of the containers on the system that match the query // GetContainers gets a list of the containers on the system that match the query
func GetContainers(q ComputeSystemQuery) ([]ContainerProperties, error) { func GetContainers(q ComputeSystemQuery) ([]ContainerProperties, error) {
return hcs.GetComputeSystems(q) return hcs.GetComputeSystems(context.Background(), q)
} }
// Start synchronously starts the container. // Start synchronously starts the container.
func (container *container) Start() error { func (container *container) Start() error {
return convertSystemError(container.system.Start(), container) return convertSystemError(container.system.Start(context.Background()), container)
} }
// Shutdown requests a container shutdown, but it may not actually be shutdown until Wait() succeeds. // Shutdown requests a container shutdown, but it may not actually be shutdown until Wait() succeeds.
func (container *container) Shutdown() error { func (container *container) Shutdown() error {
return convertSystemError(container.system.Shutdown(), container) err := container.system.Shutdown(context.Background())
if err != nil {
return convertSystemError(err, container)
}
return &ContainerError{Container: container, Err: ErrVmcomputeOperationPending, Operation: "hcsshim::ComputeSystem::Shutdown"}
} }
// Terminate requests a container terminate, but it may not actually be terminated until Wait() succeeds. // Terminate requests a container terminate, but it may not actually be terminated until Wait() succeeds.
func (container *container) Terminate() error { func (container *container) Terminate() error {
return convertSystemError(container.system.Terminate(), container) err := container.system.Terminate(context.Background())
if err != nil {
return convertSystemError(err, container)
}
return &ContainerError{Container: container, Err: ErrVmcomputeOperationPending, Operation: "hcsshim::ComputeSystem::Terminate"}
} }
// Waits synchronously waits for the container to shutdown or terminate. // Waits synchronously waits for the container to shutdown or terminate.
func (container *container) Wait() error { func (container *container) Wait() error {
return convertSystemError(container.system.Wait(), container) err := container.system.Wait()
if err == nil {
err = container.system.ExitError()
}
return convertSystemError(err, container)
} }
// WaitTimeout synchronously waits for the container to terminate or the duration to elapse. It // WaitTimeout synchronously waits for the container to terminate or the duration to elapse. It
// returns false if timeout occurs. // returns false if timeout occurs.
func (container *container) WaitTimeout(t time.Duration) error { func (container *container) WaitTimeout(timeout time.Duration) error {
return convertSystemError(container.system.WaitTimeout(t), container) container.waitOnce.Do(func() {
container.waitCh = make(chan struct{})
go func() {
container.waitErr = container.Wait()
close(container.waitCh)
}()
})
t := time.NewTimer(timeout)
defer t.Stop()
select {
case <-t.C:
return &ContainerError{Container: container, Err: ErrTimeout, Operation: "hcsshim::ComputeSystem::Wait"}
case <-container.waitCh:
return container.waitErr
}
} }
// Pause pauses the execution of a container. // Pause pauses the execution of a container.
func (container *container) Pause() error { func (container *container) Pause() error {
return convertSystemError(container.system.Pause(), container) return convertSystemError(container.system.Pause(context.Background()), container)
} }
// Resume resumes the execution of a container. // Resume resumes the execution of a container.
func (container *container) Resume() error { func (container *container) Resume() error {
return convertSystemError(container.system.Resume(), container) return convertSystemError(container.system.Resume(context.Background()), container)
} }
// HasPendingUpdates returns true if the container has updates pending to install // HasPendingUpdates returns true if the container has updates pending to install
...@@ -135,7 +166,7 @@ func (container *container) HasPendingUpdates() (bool, error) { ...@@ -135,7 +166,7 @@ func (container *container) HasPendingUpdates() (bool, error) {
// Statistics returns statistics for the container. This is a legacy v1 call // Statistics returns statistics for the container. This is a legacy v1 call
func (container *container) Statistics() (Statistics, error) { func (container *container) Statistics() (Statistics, error) {
properties, err := container.system.Properties(schema1.PropertyTypeStatistics) properties, err := container.system.Properties(context.Background(), schema1.PropertyTypeStatistics)
if err != nil { if err != nil {
return Statistics{}, convertSystemError(err, container) return Statistics{}, convertSystemError(err, container)
} }
...@@ -145,7 +176,7 @@ func (container *container) Statistics() (Statistics, error) { ...@@ -145,7 +176,7 @@ func (container *container) Statistics() (Statistics, error) {
// ProcessList returns an array of ProcessListItems for the container. This is a legacy v1 call // ProcessList returns an array of ProcessListItems for the container. This is a legacy v1 call
func (container *container) ProcessList() ([]ProcessListItem, error) { func (container *container) ProcessList() ([]ProcessListItem, error) {
properties, err := container.system.Properties(schema1.PropertyTypeProcessList) properties, err := container.system.Properties(context.Background(), schema1.PropertyTypeProcessList)
if err != nil { if err != nil {
return nil, convertSystemError(err, container) return nil, convertSystemError(err, container)
} }
...@@ -155,7 +186,7 @@ func (container *container) ProcessList() ([]ProcessListItem, error) { ...@@ -155,7 +186,7 @@ func (container *container) ProcessList() ([]ProcessListItem, error) {
// This is a legacy v1 call // This is a legacy v1 call
func (container *container) MappedVirtualDisks() (map[int]MappedVirtualDiskController, error) { func (container *container) MappedVirtualDisks() (map[int]MappedVirtualDiskController, error) {
properties, err := container.system.Properties(schema1.PropertyTypeMappedVirtualDisk) properties, err := container.system.Properties(context.Background(), schema1.PropertyTypeMappedVirtualDisk)
if err != nil { if err != nil {
return nil, convertSystemError(err, container) return nil, convertSystemError(err, container)
} }
...@@ -165,20 +196,20 @@ func (container *container) MappedVirtualDisks() (map[int]MappedVirtualDiskContr ...@@ -165,20 +196,20 @@ func (container *container) MappedVirtualDisks() (map[int]MappedVirtualDiskContr
// CreateProcess launches a new process within the container. // CreateProcess launches a new process within the container.
func (container *container) CreateProcess(c *ProcessConfig) (Process, error) { func (container *container) CreateProcess(c *ProcessConfig) (Process, error) {
p, err := container.system.CreateProcess(c) p, err := container.system.CreateProcessNoStdio(c)
if err != nil { if err != nil {
return nil, convertSystemError(err, container) return nil, convertSystemError(err, container)
} }
return &process{p}, nil return &process{p: p.(*hcs.Process)}, nil
} }
// OpenProcess gets an interface to an existing process within the container. // OpenProcess gets an interface to an existing process within the container.
func (container *container) OpenProcess(pid int) (Process, error) { func (container *container) OpenProcess(pid int) (Process, error) {
p, err := container.system.OpenProcess(pid) p, err := container.system.OpenProcess(context.Background(), pid)
if err != nil { if err != nil {
return nil, convertSystemError(err, container) return nil, convertSystemError(err, container)
} }
return &process{p}, nil return &process{p: p}, nil
} }
// Close cleans up any state associated with the container but does not terminate or wait for it. // Close cleans up any state associated with the container but does not terminate or wait for it.
...@@ -188,5 +219,5 @@ func (container *container) Close() error { ...@@ -188,5 +219,5 @@ func (container *container) Close() error {
// Modify the System // Modify the System
func (container *container) Modify(config *ResourceModificationRequestResponse) error { func (container *container) Modify(config *ResourceModificationRequestResponse) error {
return convertSystemError(container.system.Modify(config), container) return convertSystemError(container.system.Modify(context.Background(), config), container)
} }
module github.com/Microsoft/hcsshim
go 1.12
require (
github.com/Microsoft/go-winio v0.4.15-0.20190919025122-fc70bd9a86b5
github.com/blang/semver v3.1.0+incompatible // indirect
github.com/containerd/console v0.0.0-20180822173158-c12b1e7919c1
github.com/containerd/containerd v1.3.0-beta.2.0.20190828155532-0293cbd26c69
github.com/containerd/continuity v0.0.0-20190426062206-aaeac12a7ffc // indirect
github.com/containerd/fifo v0.0.0-20190226154929-a9fb20d87448 // indirect
github.com/containerd/go-runc v0.0.0-20180907222934-5a6d9f37cfa3
github.com/containerd/ttrpc v0.0.0-20190828154514-0e0f228740de
github.com/containerd/typeurl v0.0.0-20180627222232-a93fcdb778cd
github.com/docker/distribution v2.7.1+incompatible // indirect
github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c // indirect
github.com/gogo/googleapis v1.2.0 // indirect
github.com/gogo/protobuf v1.2.1
github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce // indirect
github.com/hashicorp/go-multierror v0.0.0-20161216184304-ed905158d874 // indirect
github.com/opencontainers/go-digest v0.0.0-20180430190053-c9281466c8b2 // indirect
github.com/opencontainers/image-spec v1.0.1 // indirect
github.com/opencontainers/runc v0.0.0-20190115041553-12f6a991201f // indirect
github.com/opencontainers/runtime-spec v0.0.0-20190207185410-29686dbc5559
github.com/opencontainers/runtime-tools v0.0.0-20181011054405-1d69bd0f9c39
github.com/pkg/errors v0.8.1
github.com/sirupsen/logrus v1.4.1
github.com/syndtr/gocapability v0.0.0-20170704070218-db04d3cc01c8 // indirect
github.com/urfave/cli v0.0.0-20171014202726-7bc6a0acffa5
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect
github.com/xeipuuv/gojsonschema v0.0.0-20180618132009-1d523034197f // indirect
go.opencensus.io v0.22.0
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3
google.golang.org/grpc v1.20.1
gotest.tools v2.2.0+incompatible // indirect
k8s.io/kubernetes v1.13.0
)
...@@ -7,7 +7,7 @@ import ( ...@@ -7,7 +7,7 @@ import (
"fmt" "fmt"
"syscall" "syscall"
"github.com/Microsoft/hcsshim/internal/guid" "github.com/Microsoft/go-winio/pkg/guid"
) )
//go:generate go run ../mksyscall_windows.go -output zsyscall_windows.go hcn.go //go:generate go run ../mksyscall_windows.go -output zsyscall_windows.go hcn.go
......
...@@ -2,8 +2,9 @@ package hcn ...@@ -2,8 +2,9 @@ package hcn
import ( import (
"encoding/json" "encoding/json"
"errors"
"github.com/Microsoft/hcsshim/internal/guid" "github.com/Microsoft/go-winio/pkg/guid"
"github.com/Microsoft/hcsshim/internal/interop" "github.com/Microsoft/hcsshim/internal/interop"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
...@@ -121,7 +122,10 @@ func enumerateEndpoints(query string) ([]HostComputeEndpoint, error) { ...@@ -121,7 +122,10 @@ func enumerateEndpoints(query string) ([]HostComputeEndpoint, error) {
} }
func createEndpoint(networkId string, endpointSettings string) (*HostComputeEndpoint, error) { func createEndpoint(networkId string, endpointSettings string) (*HostComputeEndpoint, error) {
networkGuid := guid.FromString(networkId) networkGuid, err := guid.FromString(networkId)
if err != nil {
return nil, errInvalidNetworkID
}
// Open network. // Open network.
var networkHandle hcnNetwork var networkHandle hcnNetwork
var resultBuffer *uint16 var resultBuffer *uint16
...@@ -167,7 +171,10 @@ func createEndpoint(networkId string, endpointSettings string) (*HostComputeEndp ...@@ -167,7 +171,10 @@ func createEndpoint(networkId string, endpointSettings string) (*HostComputeEndp
} }
func modifyEndpoint(endpointId string, settings string) (*HostComputeEndpoint, error) { func modifyEndpoint(endpointId string, settings string) (*HostComputeEndpoint, error) {
endpointGuid := guid.FromString(endpointId) endpointGuid, err := guid.FromString(endpointId)
if err != nil {
return nil, errInvalidEndpointID
}
// Open endpoint // Open endpoint
var ( var (
endpointHandle hcnEndpoint endpointHandle hcnEndpoint
...@@ -208,7 +215,10 @@ func modifyEndpoint(endpointId string, settings string) (*HostComputeEndpoint, e ...@@ -208,7 +215,10 @@ func modifyEndpoint(endpointId string, settings string) (*HostComputeEndpoint, e
} }
func deleteEndpoint(endpointId string) error { func deleteEndpoint(endpointId string) error {
endpointGuid := guid.FromString(endpointId) endpointGuid, err := guid.FromString(endpointId)
if err != nil {
return errInvalidEndpointID
}
var resultBuffer *uint16 var resultBuffer *uint16
hr := hcnDeleteEndpoint(&endpointGuid, &resultBuffer) hr := hcnDeleteEndpoint(&endpointGuid, &resultBuffer)
if err := checkForErrors("hcnDeleteEndpoint", hr, resultBuffer); err != nil { if err := checkForErrors("hcnDeleteEndpoint", hr, resultBuffer); err != nil {
...@@ -299,6 +309,10 @@ func GetEndpointByName(endpointName string) (*HostComputeEndpoint, error) { ...@@ -299,6 +309,10 @@ func GetEndpointByName(endpointName string) (*HostComputeEndpoint, error) {
func (endpoint *HostComputeEndpoint) Create() (*HostComputeEndpoint, error) { func (endpoint *HostComputeEndpoint) Create() (*HostComputeEndpoint, error) {
logrus.Debugf("hcn::HostComputeEndpoint::Create id=%s", endpoint.Id) logrus.Debugf("hcn::HostComputeEndpoint::Create id=%s", endpoint.Id)
if endpoint.HostComputeNamespace != "" {
return nil, errors.New("endpoint create error, endpoint json HostComputeNamespace is read only and should not be set")
}
jsonString, err := json.Marshal(endpoint) jsonString, err := json.Marshal(endpoint)
if err != nil { if err != nil {
return nil, err return nil, err
...@@ -339,7 +353,7 @@ func ModifyEndpointSettings(endpointId string, request *ModifyEndpointSettingReq ...@@ -339,7 +353,7 @@ func ModifyEndpointSettings(endpointId string, request *ModifyEndpointSettingReq
} }
// ApplyPolicy applies a Policy (ex: ACL) on the Endpoint. // ApplyPolicy applies a Policy (ex: ACL) on the Endpoint.
func (endpoint *HostComputeEndpoint) ApplyPolicy(endpointPolicy PolicyEndpointRequest) error { func (endpoint *HostComputeEndpoint) ApplyPolicy(requestType RequestType, endpointPolicy PolicyEndpointRequest) error {
logrus.Debugf("hcn::HostComputeEndpoint::ApplyPolicy id=%s", endpoint.Id) logrus.Debugf("hcn::HostComputeEndpoint::ApplyPolicy id=%s", endpoint.Id)
settingsJson, err := json.Marshal(endpointPolicy) settingsJson, err := json.Marshal(endpointPolicy)
...@@ -348,7 +362,7 @@ func (endpoint *HostComputeEndpoint) ApplyPolicy(endpointPolicy PolicyEndpointRe ...@@ -348,7 +362,7 @@ func (endpoint *HostComputeEndpoint) ApplyPolicy(endpointPolicy PolicyEndpointRe
} }
requestMessage := &ModifyEndpointSettingRequest{ requestMessage := &ModifyEndpointSettingRequest{
ResourceType: EndpointResourceTypePolicy, ResourceType: EndpointResourceTypePolicy,
RequestType: RequestTypeUpdate, RequestType: requestType,
Settings: settingsJson, Settings: settingsJson,
} }
......
...@@ -3,13 +3,22 @@ ...@@ -3,13 +3,22 @@
package hcn package hcn
import ( import (
"errors"
"fmt" "fmt"
"github.com/Microsoft/hcsshim/internal/hcs"
"github.com/Microsoft/hcsshim/internal/hcserror" "github.com/Microsoft/hcsshim/internal/hcserror"
"github.com/Microsoft/hcsshim/internal/interop" "github.com/Microsoft/hcsshim/internal/interop"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
var (
errInvalidNetworkID = errors.New("invalid network ID")
errInvalidEndpointID = errors.New("invalid endpoint ID")
errInvalidNamespaceID = errors.New("invalid namespace ID")
errInvalidLoadBalancerID = errors.New("invalid load balancer ID")
)
func checkForErrors(methodName string, hr error, resultBuffer *uint16) error { func checkForErrors(methodName string, hr error, resultBuffer *uint16) error {
errorFound := false errorFound := false
...@@ -81,7 +90,7 @@ func (e LoadBalancerNotFoundError) Error() string { ...@@ -81,7 +90,7 @@ func (e LoadBalancerNotFoundError) Error() string {
// IsNotFoundError returns a boolean indicating whether the error was caused by // IsNotFoundError returns a boolean indicating whether the error was caused by
// a resource not being found. // a resource not being found.
func IsNotFoundError(err error) bool { func IsNotFoundError(err error) bool {
switch err.(type) { switch pe := err.(type) {
case NetworkNotFoundError: case NetworkNotFoundError:
return true return true
case EndpointNotFoundError: case EndpointNotFoundError:
...@@ -90,6 +99,8 @@ func IsNotFoundError(err error) bool { ...@@ -90,6 +99,8 @@ func IsNotFoundError(err error) bool {
return true return true
case LoadBalancerNotFoundError: case LoadBalancerNotFoundError:
return true return true
case *hcserror.HcsError:
return pe.Err == hcs.ErrElementNotFound
} }
return false return false
} }
...@@ -24,7 +24,7 @@ var ( ...@@ -24,7 +24,7 @@ var (
// HNSVersion1803 added ACL functionality. // HNSVersion1803 added ACL functionality.
HNSVersion1803 = Version{Major: 7, Minor: 2} HNSVersion1803 = Version{Major: 7, Minor: 2}
// V2ApiSupport allows the use of V2 Api calls and V2 Schema. // V2ApiSupport allows the use of V2 Api calls and V2 Schema.
V2ApiSupport = Version{Major: 9, Minor: 1} V2ApiSupport = Version{Major: 9, Minor: 2}
// Remote Subnet allows for Remote Subnet policies on Overlay networks // Remote Subnet allows for Remote Subnet policies on Overlay networks
RemoteSubnetVersion = Version{Major: 9, Minor: 2} RemoteSubnetVersion = Version{Major: 9, Minor: 2}
// A Host Route policy allows for local container to local host communication Overlay networks // A Host Route policy allows for local container to local host communication Overlay networks
......
...@@ -3,7 +3,7 @@ package hcn ...@@ -3,7 +3,7 @@ package hcn
import ( import (
"encoding/json" "encoding/json"
"github.com/Microsoft/hcsshim/internal/guid" "github.com/Microsoft/go-winio/pkg/guid"
"github.com/Microsoft/hcsshim/internal/interop" "github.com/Microsoft/hcsshim/internal/interop"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
...@@ -148,7 +148,10 @@ func createLoadBalancer(settings string) (*HostComputeLoadBalancer, error) { ...@@ -148,7 +148,10 @@ func createLoadBalancer(settings string) (*HostComputeLoadBalancer, error) {
} }
func modifyLoadBalancer(loadBalancerId string, settings string) (*HostComputeLoadBalancer, error) { func modifyLoadBalancer(loadBalancerId string, settings string) (*HostComputeLoadBalancer, error) {
loadBalancerGuid := guid.FromString(loadBalancerId) loadBalancerGuid, err := guid.FromString(loadBalancerId)
if err != nil {
return nil, errInvalidLoadBalancerID
}
// Open loadBalancer. // Open loadBalancer.
var ( var (
loadBalancerHandle hcnLoadBalancer loadBalancerHandle hcnLoadBalancer
...@@ -189,7 +192,10 @@ func modifyLoadBalancer(loadBalancerId string, settings string) (*HostComputeLoa ...@@ -189,7 +192,10 @@ func modifyLoadBalancer(loadBalancerId string, settings string) (*HostComputeLoa
} }
func deleteLoadBalancer(loadBalancerId string) error { func deleteLoadBalancer(loadBalancerId string) error {
loadBalancerGuid := guid.FromString(loadBalancerId) loadBalancerGuid, err := guid.FromString(loadBalancerId)
if err != nil {
return errInvalidLoadBalancerID
}
var resultBuffer *uint16 var resultBuffer *uint16
hr := hcnDeleteLoadBalancer(&loadBalancerGuid, &resultBuffer) hr := hcnDeleteLoadBalancer(&loadBalancerGuid, &resultBuffer)
if err := checkForErrors("hcnDeleteLoadBalancer", hr, resultBuffer); err != nil { if err := checkForErrors("hcnDeleteLoadBalancer", hr, resultBuffer); err != nil {
......
...@@ -5,8 +5,8 @@ import ( ...@@ -5,8 +5,8 @@ import (
"os" "os"
"syscall" "syscall"
"github.com/Microsoft/go-winio/pkg/guid"
icni "github.com/Microsoft/hcsshim/internal/cni" icni "github.com/Microsoft/hcsshim/internal/cni"
"github.com/Microsoft/hcsshim/internal/guid"
"github.com/Microsoft/hcsshim/internal/interop" "github.com/Microsoft/hcsshim/internal/interop"
"github.com/Microsoft/hcsshim/internal/regstate" "github.com/Microsoft/hcsshim/internal/regstate"
"github.com/Microsoft/hcsshim/internal/runhcs" "github.com/Microsoft/hcsshim/internal/runhcs"
...@@ -165,7 +165,10 @@ func createNamespace(settings string) (*HostComputeNamespace, error) { ...@@ -165,7 +165,10 @@ func createNamespace(settings string) (*HostComputeNamespace, error) {
} }
func modifyNamespace(namespaceId string, settings string) (*HostComputeNamespace, error) { func modifyNamespace(namespaceId string, settings string) (*HostComputeNamespace, error) {
namespaceGuid := guid.FromString(namespaceId) namespaceGuid, err := guid.FromString(namespaceId)
if err != nil {
return nil, errInvalidNamespaceID
}
// Open namespace. // Open namespace.
var ( var (
namespaceHandle hcnNamespace namespaceHandle hcnNamespace
...@@ -206,7 +209,10 @@ func modifyNamespace(namespaceId string, settings string) (*HostComputeNamespace ...@@ -206,7 +209,10 @@ func modifyNamespace(namespaceId string, settings string) (*HostComputeNamespace
} }
func deleteNamespace(namespaceId string) error { func deleteNamespace(namespaceId string) error {
namespaceGuid := guid.FromString(namespaceId) namespaceGuid, err := guid.FromString(namespaceId)
if err != nil {
return errInvalidNamespaceID
}
var resultBuffer *uint16 var resultBuffer *uint16
hr := hcnDeleteNamespace(&namespaceGuid, &resultBuffer) hr := hcnDeleteNamespace(&namespaceGuid, &resultBuffer)
if err := checkForErrors("hcnDeleteNamespace", hr, resultBuffer); err != nil { if err := checkForErrors("hcnDeleteNamespace", hr, resultBuffer); err != nil {
...@@ -241,7 +247,11 @@ func ListNamespacesQuery(query HostComputeQuery) ([]HostComputeNamespace, error) ...@@ -241,7 +247,11 @@ func ListNamespacesQuery(query HostComputeQuery) ([]HostComputeNamespace, error)
// GetNamespaceByID returns the Namespace specified by Id. // GetNamespaceByID returns the Namespace specified by Id.
func GetNamespaceByID(namespaceId string) (*HostComputeNamespace, error) { func GetNamespaceByID(namespaceId string) (*HostComputeNamespace, error) {
return getNamespace(guid.FromString(namespaceId), defaultQueryJson()) g, err := guid.FromString(namespaceId)
if err != nil {
return nil, errInvalidNamespaceID
}
return getNamespace(g, defaultQueryJson())
} }
// GetNamespaceEndpointIds returns the endpoints of the Namespace specified by Id. // GetNamespaceEndpointIds returns the endpoints of the Namespace specified by Id.
......
...@@ -2,8 +2,9 @@ package hcn ...@@ -2,8 +2,9 @@ package hcn
import ( import (
"encoding/json" "encoding/json"
"errors"
"github.com/Microsoft/hcsshim/internal/guid" "github.com/Microsoft/go-winio/pkg/guid"
"github.com/Microsoft/hcsshim/internal/interop" "github.com/Microsoft/hcsshim/internal/interop"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
...@@ -132,6 +133,12 @@ func getNetwork(networkGuid guid.GUID, query string) (*HostComputeNetwork, error ...@@ -132,6 +133,12 @@ func getNetwork(networkGuid guid.GUID, query string) (*HostComputeNetwork, error
} }
// Convert output to HostComputeNetwork // Convert output to HostComputeNetwork
var outputNetwork HostComputeNetwork var outputNetwork HostComputeNetwork
// If HNS sets the network type to NAT (i.e. '0' in HNS.Schema.Network.NetworkMode),
// the value will be omitted from the JSON blob. We therefore need to initialize NAT here before
// unmarshaling the JSON blob.
outputNetwork.Type = NAT
if err := json.Unmarshal([]byte(properties), &outputNetwork); err != nil { if err := json.Unmarshal([]byte(properties), &outputNetwork); err != nil {
return nil, err return nil, err
} }
...@@ -196,6 +203,12 @@ func createNetwork(settings string) (*HostComputeNetwork, error) { ...@@ -196,6 +203,12 @@ func createNetwork(settings string) (*HostComputeNetwork, error) {
} }
// Convert output to HostComputeNetwork // Convert output to HostComputeNetwork
var outputNetwork HostComputeNetwork var outputNetwork HostComputeNetwork
// If HNS sets the network type to NAT (i.e. '0' in HNS.Schema.Network.NetworkMode),
// the value will be omitted from the JSON blob. We therefore need to initialize NAT here before
// unmarshaling the JSON blob.
outputNetwork.Type = NAT
if err := json.Unmarshal([]byte(properties), &outputNetwork); err != nil { if err := json.Unmarshal([]byte(properties), &outputNetwork); err != nil {
return nil, err return nil, err
} }
...@@ -203,7 +216,10 @@ func createNetwork(settings string) (*HostComputeNetwork, error) { ...@@ -203,7 +216,10 @@ func createNetwork(settings string) (*HostComputeNetwork, error) {
} }
func modifyNetwork(networkId string, settings string) (*HostComputeNetwork, error) { func modifyNetwork(networkId string, settings string) (*HostComputeNetwork, error) {
networkGuid := guid.FromString(networkId) networkGuid, err := guid.FromString(networkId)
if err != nil {
return nil, errInvalidNetworkID
}
// Open Network // Open Network
var ( var (
networkHandle hcnNetwork networkHandle hcnNetwork
...@@ -237,6 +253,12 @@ func modifyNetwork(networkId string, settings string) (*HostComputeNetwork, erro ...@@ -237,6 +253,12 @@ func modifyNetwork(networkId string, settings string) (*HostComputeNetwork, erro
} }
// Convert output to HostComputeNetwork // Convert output to HostComputeNetwork
var outputNetwork HostComputeNetwork var outputNetwork HostComputeNetwork
// If HNS sets the network type to NAT (i.e. '0' in HNS.Schema.Network.NetworkMode),
// the value will be omitted from the JSON blob. We therefore need to initialize NAT here before
// unmarshaling the JSON blob.
outputNetwork.Type = NAT
if err := json.Unmarshal([]byte(properties), &outputNetwork); err != nil { if err := json.Unmarshal([]byte(properties), &outputNetwork); err != nil {
return nil, err return nil, err
} }
...@@ -244,7 +266,10 @@ func modifyNetwork(networkId string, settings string) (*HostComputeNetwork, erro ...@@ -244,7 +266,10 @@ func modifyNetwork(networkId string, settings string) (*HostComputeNetwork, erro
} }
func deleteNetwork(networkId string) error { func deleteNetwork(networkId string) error {
networkGuid := guid.FromString(networkId) networkGuid, err := guid.FromString(networkId)
if err != nil {
return errInvalidNetworkID
}
var resultBuffer *uint16 var resultBuffer *uint16
hr := hcnDeleteNetwork(&networkGuid, &resultBuffer) hr := hcnDeleteNetwork(&networkGuid, &resultBuffer)
if err := checkForErrors("hcnDeleteNetwork", hr, resultBuffer); err != nil { if err := checkForErrors("hcnDeleteNetwork", hr, resultBuffer); err != nil {
...@@ -320,6 +345,24 @@ func GetNetworkByName(networkName string) (*HostComputeNetwork, error) { ...@@ -320,6 +345,24 @@ func GetNetworkByName(networkName string) (*HostComputeNetwork, error) {
// Create Network. // Create Network.
func (network *HostComputeNetwork) Create() (*HostComputeNetwork, error) { func (network *HostComputeNetwork) Create() (*HostComputeNetwork, error) {
logrus.Debugf("hcn::HostComputeNetwork::Create id=%s", network.Id) logrus.Debugf("hcn::HostComputeNetwork::Create id=%s", network.Id)
for _, ipam := range network.Ipams {
for _, subnet := range ipam.Subnets {
if subnet.IpAddressPrefix != "" {
hasDefault := false
for _, route := range subnet.Routes {
if route.NextHop == "" {
return nil, errors.New("network create error, subnet has address prefix but no gateway specified")
}
if route.DestinationPrefix == "0.0.0.0/0" || route.DestinationPrefix == "::/0" {
hasDefault = true
}
}
if !hasDefault {
return nil, errors.New("network create error, no default gateway")
}
}
}
}
jsonString, err := json.Marshal(network) jsonString, err := json.Marshal(network)
if err != nil { if err != nil {
......
package hcn package hcn
import "encoding/json" import (
"encoding/json"
)
// EndpointPolicyType are the potential Policies that apply to Endpoints. // EndpointPolicyType are the potential Policies that apply to Endpoints.
type EndpointPolicyType string type EndpointPolicyType string
...@@ -64,14 +66,18 @@ type SubnetPolicy struct { ...@@ -64,14 +66,18 @@ type SubnetPolicy struct {
Settings json.RawMessage `json:",omitempty"` Settings json.RawMessage `json:",omitempty"`
} }
// NatFlags are flags for portmappings.
type NatFlags uint32
/// Endpoint Policy objects /// Endpoint Policy objects
// PortMappingPolicySetting defines Port Mapping (NAT) // PortMappingPolicySetting defines Port Mapping (NAT)
type PortMappingPolicySetting struct { type PortMappingPolicySetting struct {
Protocol uint32 `json:",omitempty"` // EX: TCP = 6, UDP = 17 Protocol uint32 `json:",omitempty"` // EX: TCP = 6, UDP = 17
InternalPort uint16 `json:",omitempty"` InternalPort uint16 `json:",omitempty"`
ExternalPort uint16 `json:",omitempty"` ExternalPort uint16 `json:",omitempty"`
VIP string `json:",omitempty"` VIP string `json:",omitempty"`
Flags NatFlags `json:",omitempty"`
} }
// ActionType associated with ACLs. Value is either Allow or Block. // ActionType associated with ACLs. Value is either Allow or Block.
...@@ -131,6 +137,26 @@ type SDNRoutePolicySetting struct { ...@@ -131,6 +137,26 @@ type SDNRoutePolicySetting struct {
NeedEncap bool `json:",omitempty"` NeedEncap bool `json:",omitempty"`
} }
// A ProxyType is a type of proxy used by the L4 proxy policy.
type ProxyType int
const (
// ProxyTypeVFP specifies a Virtual Filtering Protocol proxy.
ProxyTypeVFP ProxyType = iota
// ProxyTypeWFP specifies a Windows Filtering Platform proxy.
ProxyTypeWFP
)
// FiveTuple is nested in L4ProxyPolicySetting for WFP support.
type FiveTuple struct {
Protocols string `json:",omitempty"`
LocalAddresses string `json:",omitempty"`
RemoteAddresses string `json:",omitempty"`
LocalPorts string `json:",omitempty"`
RemotePorts string `json:",omitempty"`
Priority uint16 `json:",omitempty"`
}
// L4ProxyPolicySetting sets Layer-4 Proxy on an endpoint. // L4ProxyPolicySetting sets Layer-4 Proxy on an endpoint.
type L4ProxyPolicySetting struct { type L4ProxyPolicySetting struct {
IP string `json:",omitempty"` IP string `json:",omitempty"`
...@@ -139,6 +165,12 @@ type L4ProxyPolicySetting struct { ...@@ -139,6 +165,12 @@ type L4ProxyPolicySetting struct {
ExceptionList []string `json:",omitempty"` ExceptionList []string `json:",omitempty"`
Destination string `json:","` Destination string `json:","`
OutboundNat bool `json:",omitempty"` OutboundNat bool `json:",omitempty"`
// For the WFP proxy
FilterTuple FiveTuple `json:",omitempty"`
ProxyType ProxyType `json:",omitempty"`
UserSID string `json:",omitempty"`
CompartmentID uint32 `json:",omitempty"`
} }
// PortnameEndpointPolicySetting sets the port name for an endpoint. // PortnameEndpointPolicySetting sets the port name for an endpoint.
......
...@@ -39,11 +39,21 @@ func HNSListEndpointRequest() ([]HNSEndpoint, error) { ...@@ -39,11 +39,21 @@ func HNSListEndpointRequest() ([]HNSEndpoint, error) {
// HotAttachEndpoint makes a HCS Call to attach the endpoint to the container // HotAttachEndpoint makes a HCS Call to attach the endpoint to the container
func HotAttachEndpoint(containerID string, endpointID string) error { func HotAttachEndpoint(containerID string, endpointID string) error {
endpoint, err := GetHNSEndpointByID(endpointID)
isAttached, err := endpoint.IsAttached(containerID)
if isAttached {
return err
}
return modifyNetworkEndpoint(containerID, endpointID, Add) return modifyNetworkEndpoint(containerID, endpointID, Add)
} }
// HotDetachEndpoint makes a HCS Call to detach the endpoint from the container // HotDetachEndpoint makes a HCS Call to detach the endpoint from the container
func HotDetachEndpoint(containerID string, endpointID string) error { func HotDetachEndpoint(containerID string, endpointID string) error {
endpoint, err := GetHNSEndpointByID(endpointID)
isAttached, err := endpoint.IsAttached(containerID)
if !isAttached {
return err
}
return modifyNetworkEndpoint(containerID, endpointID, Remove) return modifyNetworkEndpoint(containerID, endpointID, Remove)
} }
......
...@@ -3,7 +3,7 @@ package cni ...@@ -3,7 +3,7 @@ package cni
import ( import (
"errors" "errors"
"github.com/Microsoft/hcsshim/internal/guid" "github.com/Microsoft/go-winio/pkg/guid"
"github.com/Microsoft/hcsshim/internal/regstate" "github.com/Microsoft/hcsshim/internal/regstate"
) )
......
package cow
import (
"context"
"io"
"github.com/Microsoft/hcsshim/internal/schema1"
)
// Process is the interface for an OS process running in a container or utility VM.
type Process interface {
// Close releases resources associated with the process and closes the
// writer and readers returned by Stdio. Depending on the implementation,
// this may also terminate the process.
Close() error
// CloseStdin causes the process's stdin handle to receive EOF/EPIPE/whatever
// is appropriate to indicate that no more data is available.
CloseStdin(ctx context.Context) error
// Pid returns the process ID.
Pid() int
// Stdio returns the stdio streams for a process. These may be nil if a stream
// was not requested during CreateProcess.
Stdio() (_ io.Writer, _ io.Reader, _ io.Reader)
// ResizeConsole resizes the virtual terminal associated with the process.
ResizeConsole(ctx context.Context, width, height uint16) error
// Kill sends a SIGKILL or equivalent signal to the process and returns whether
// the signal was delivered. It does not wait for the process to terminate.
Kill(ctx context.Context) (bool, error)
// Signal sends a signal to the process and returns whether the signal was
// delivered. The input is OS specific (either
// guestrequest.SignalProcessOptionsWCOW or
// guestrequest.SignalProcessOptionsLCOW). It does not wait for the process
// to terminate.
Signal(ctx context.Context, options interface{}) (bool, error)
// Wait waits for the process to complete, or for a connection to the process to be
// terminated by some error condition (including calling Close).
Wait() error
// ExitCode returns the exit code of the process. Returns an error if the process is
// not running.
ExitCode() (int, error)
}
// ProcessHost is the interface for creating processes.
type ProcessHost interface {
// CreateProcess creates a process. The configuration is host specific
// (either hcsschema.ProcessParameters or lcow.ProcessParameters).
CreateProcess(ctx context.Context, config interface{}) (Process, error)
// OS returns the host's operating system, "linux" or "windows".
OS() string
// IsOCI specifies whether this is an OCI-compliant process host. If true,
// then the configuration passed to CreateProcess should have an OCI process
// spec (or nil if this is the initial process in an OCI container).
// Otherwise, it should have the HCS-specific process parameters.
IsOCI() bool
}
// Container is the interface for container objects, either running on the host or
// in a utility VM.
type Container interface {
ProcessHost
// Close releases the resources associated with the container. Depending on
// the implementation, this may also terminate the container.
Close() error
// ID returns the container ID.
ID() string
// Properties returns the requested container properties.
Properties(ctx context.Context, types ...schema1.PropertyType) (*schema1.ContainerProperties, error)
// Start starts a container.
Start(ctx context.Context) error
// Shutdown sends a shutdown request to the container (but does not wait for
// the shutdown to complete).
Shutdown(ctx context.Context) error
// Terminate sends a terminate request to the container (but does not wait
// for the terminate to complete).
Terminate(ctx context.Context) error
// Wait waits for the container to terminate, or for the connection to the
// container to be terminated by some error condition (including calling
// Close).
Wait() error
}
package guestrequest
import (
"github.com/Microsoft/hcsshim/internal/schema2"
)
// Arguably, many of these (at least CombinedLayers) should have been generated
// by swagger.
//
// This will also change package name due to an inbound breaking change.
// This class is used by a modify request to add or remove a combined layers
// structure in the guest. For windows, the GCS applies a filter in ContainerRootPath
// using the specified layers as the parent content. Ignores property ScratchPath
// since the container path is already the scratch path. For linux, the GCS unions
// the specified layers and ScratchPath together, placing the resulting union
// filesystem at ContainerRootPath.
type CombinedLayers struct {
ContainerRootPath string `json:"ContainerRootPath,omitempty"`
Layers []hcsschema.Layer `json:"Layers,omitempty"`
ScratchPath string `json:"ScratchPath,omitempty"`
}
// Defines the schema for hosted settings passed to GCS and/or OpenGCS
// SCSI. Scratch space for remote file-system commands, or R/W layer for containers
type LCOWMappedVirtualDisk struct {
MountPath string `json:"MountPath,omitempty"` // /tmp/scratch for an LCOW utility VM being used as a service VM
Lun uint8 `json:"Lun,omitempty"`
Controller uint8 `json:"Controller,omitempty"`
ReadOnly bool `json:"ReadOnly,omitempty"`
}
type WCOWMappedVirtualDisk struct {
ContainerPath string `json:"ContainerPath,omitempty"`
Lun int32 `json:"Lun,omitempty"`
}
type LCOWMappedDirectory struct {
MountPath string `json:"MountPath,omitempty"`
Port int32 `json:"Port,omitempty"`
ShareName string `json:"ShareName,omitempty"` // If empty not using ANames (not currently supported)
ReadOnly bool `json:"ReadOnly,omitempty"`
}
// Read-only layers over VPMem
type LCOWMappedVPMemDevice struct {
DeviceNumber uint32 `json:"DeviceNumber,omitempty"`
MountPath string `json:"MountPath,omitempty"` // /tmp/pN
}
type LCOWNetworkAdapter struct {
NamespaceID string `json:",omitempty"`
ID string `json:",omitempty"`
MacAddress string `json:",omitempty"`
IPAddress string `json:",omitempty"`
PrefixLength uint8 `json:",omitempty"`
GatewayAddress string `json:",omitempty"`
DNSSuffix string `json:",omitempty"`
DNSServerList string `json:",omitempty"`
EnableLowMetric bool `json:",omitempty"`
EncapOverhead uint16 `json:",omitempty"`
}
type ResourceType string
const (
// These are constants for v2 schema modify guest requests.
ResourceTypeMappedDirectory ResourceType = "MappedDirectory"
ResourceTypeMappedVirtualDisk ResourceType = "MappedVirtualDisk"
ResourceTypeNetwork ResourceType = "Network"
ResourceTypeNetworkNamespace ResourceType = "NetworkNamespace"
ResourceTypeCombinedLayers ResourceType = "CombinedLayers"
ResourceTypeVPMemDevice ResourceType = "VPMemDevice"
)
// GuestRequest is for modify commands passed to the guest.
type GuestRequest struct {
RequestType string `json:"RequestType,omitempty"`
ResourceType ResourceType `json:"ResourceType,omitempty"`
Settings interface{} `json:"Settings,omitempty"`
}
type NetworkModifyRequest struct {
AdapterId string `json:"AdapterId,omitempty"`
RequestType string `json:"RequestType,omitempty"`
Settings interface{} `json:"Settings,omitempty"`
}
type RS4NetworkModifyRequest struct {
AdapterInstanceId string `json:"AdapterInstanceId,omitempty"`
RequestType string `json:"RequestType,omitempty"`
Settings interface{} `json:"Settings,omitempty"`
}
// SignalProcessOptions is the options passed to either WCOW or LCOW
// to signal a given process.
type SignalProcessOptions struct {
Signal int `json:,omitempty`
}
package guid
import (
"crypto/rand"
"encoding/json"
"fmt"
"io"
"strconv"
"strings"
)
var _ = (json.Marshaler)(&GUID{})
var _ = (json.Unmarshaler)(&GUID{})
type GUID [16]byte
func New() GUID {
g := GUID{}
_, err := io.ReadFull(rand.Reader, g[:])
if err != nil {
panic(err)
}
return g
}
func (g GUID) String() string {
return fmt.Sprintf("%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x-%02x", g[3], g[2], g[1], g[0], g[5], g[4], g[7], g[6], g[8:10], g[10:])
}
func FromString(s string) GUID {
if len(s) != 36 {
panic(fmt.Sprintf("invalid GUID length: %d", len(s)))
}
if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' {
panic("invalid GUID format")
}
indexOrder := [16]int{
0, 2, 4, 6,
9, 11,
14, 16,
19, 21,
24, 26, 28, 30, 32, 34,
}
byteOrder := [16]int{
3, 2, 1, 0,
5, 4,
7, 6,
8, 9,
10, 11, 12, 13, 14, 15,
}
var g GUID
for i, x := range indexOrder {
b, err := strconv.ParseInt(s[x:x+2], 16, 16)
if err != nil {
panic(err)
}
g[byteOrder[i]] = byte(b)
}
return g
}
func (g GUID) MarshalJSON() ([]byte, error) {
return json.Marshal(g.String())
}
func (g *GUID) UnmarshalJSON(data []byte) error {
*g = FromString(strings.Trim(string(data), "\""))
return nil
}
package hcs package hcs
import ( import (
"fmt"
"sync" "sync"
"syscall" "syscall"
"github.com/Microsoft/hcsshim/internal/interop" "github.com/Microsoft/hcsshim/internal/interop"
"github.com/Microsoft/hcsshim/internal/logfields"
"github.com/Microsoft/hcsshim/internal/vmcompute"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
...@@ -40,35 +43,83 @@ var ( ...@@ -40,35 +43,83 @@ var (
) )
type hcsNotification uint32 type hcsNotification uint32
func (hn hcsNotification) String() string {
switch hn {
case hcsNotificationSystemExited:
return "SystemExited"
case hcsNotificationSystemCreateCompleted:
return "SystemCreateCompleted"
case hcsNotificationSystemStartCompleted:
return "SystemStartCompleted"
case hcsNotificationSystemPauseCompleted:
return "SystemPauseCompleted"
case hcsNotificationSystemResumeCompleted:
return "SystemResumeCompleted"
case hcsNotificationSystemCrashReport:
return "SystemCrashReport"
case hcsNotificationSystemSiloJobCreated:
return "SystemSiloJobCreated"
case hcsNotificationSystemSaveCompleted:
return "SystemSaveCompleted"
case hcsNotificationSystemRdpEnhancedModeStateChanged:
return "SystemRdpEnhancedModeStateChanged"
case hcsNotificationSystemShutdownFailed:
return "SystemShutdownFailed"
case hcsNotificationSystemGetPropertiesCompleted:
return "SystemGetPropertiesCompleted"
case hcsNotificationSystemModifyCompleted:
return "SystemModifyCompleted"
case hcsNotificationSystemCrashInitiated:
return "SystemCrashInitiated"
case hcsNotificationSystemGuestConnectionClosed:
return "SystemGuestConnectionClosed"
case hcsNotificationProcessExited:
return "ProcessExited"
case hcsNotificationInvalid:
return "Invalid"
case hcsNotificationServiceDisconnect:
return "ServiceDisconnect"
default:
return fmt.Sprintf("Unknown: %d", hn)
}
}
type notificationChannel chan error type notificationChannel chan error
type notifcationWatcherContext struct { type notifcationWatcherContext struct {
channels notificationChannels channels notificationChannels
handle hcsCallback handle vmcompute.HcsCallback
systemID string
processID int
} }
type notificationChannels map[hcsNotification]notificationChannel type notificationChannels map[hcsNotification]notificationChannel
func newChannels() notificationChannels { func newSystemChannels() notificationChannels {
channels := make(notificationChannels) channels := make(notificationChannels)
for _, notif := range []hcsNotification{
hcsNotificationServiceDisconnect,
hcsNotificationSystemExited,
hcsNotificationSystemCreateCompleted,
hcsNotificationSystemStartCompleted,
hcsNotificationSystemPauseCompleted,
hcsNotificationSystemResumeCompleted,
} {
channels[notif] = make(notificationChannel, 1)
}
return channels
}
channels[hcsNotificationSystemExited] = make(notificationChannel, 1) func newProcessChannels() notificationChannels {
channels[hcsNotificationSystemCreateCompleted] = make(notificationChannel, 1) channels := make(notificationChannels)
channels[hcsNotificationSystemStartCompleted] = make(notificationChannel, 1) for _, notif := range []hcsNotification{
channels[hcsNotificationSystemPauseCompleted] = make(notificationChannel, 1) hcsNotificationServiceDisconnect,
channels[hcsNotificationSystemResumeCompleted] = make(notificationChannel, 1) hcsNotificationProcessExited,
channels[hcsNotificationProcessExited] = make(notificationChannel, 1) } {
channels[hcsNotificationServiceDisconnect] = make(notificationChannel, 1) channels[notif] = make(notificationChannel, 1)
channels[hcsNotificationSystemCrashReport] = make(notificationChannel, 1) }
channels[hcsNotificationSystemSiloJobCreated] = make(notificationChannel, 1)
channels[hcsNotificationSystemSaveCompleted] = make(notificationChannel, 1)
channels[hcsNotificationSystemRdpEnhancedModeStateChanged] = make(notificationChannel, 1)
channels[hcsNotificationSystemShutdownFailed] = make(notificationChannel, 1)
channels[hcsNotificationSystemGetPropertiesCompleted] = make(notificationChannel, 1)
channels[hcsNotificationSystemModifyCompleted] = make(notificationChannel, 1)
channels[hcsNotificationSystemCrashInitiated] = make(notificationChannel, 1)
channels[hcsNotificationSystemGuestConnectionClosed] = make(notificationChannel, 1)
return channels return channels
} }
...@@ -92,12 +143,17 @@ func notificationWatcher(notificationType hcsNotification, callbackNumber uintpt ...@@ -92,12 +143,17 @@ func notificationWatcher(notificationType hcsNotification, callbackNumber uintpt
return 0 return 0
} }
log := logrus.WithFields(logrus.Fields{
"notification-type": notificationType.String(),
"system-id": context.systemID,
})
if context.processID != 0 {
log.Data[logfields.ProcessID] = context.processID
}
log.Debug("HCS notification")
if channel, ok := context.channels[notificationType]; ok { if channel, ok := context.channels[notificationType]; ok {
channel <- result channel <- result
} else {
logrus.WithFields(logrus.Fields{
"notification-type": notificationType,
}).Warn("Received a callback of an unsupported type")
} }
return 0 return 0
......
package hcs package hcs
import ( import (
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"net"
"syscall" "syscall"
"github.com/Microsoft/hcsshim/internal/interop" "github.com/Microsoft/hcsshim/internal/log"
"github.com/Microsoft/hcsshim/internal/logfields"
"github.com/sirupsen/logrus"
) )
var ( var (
...@@ -117,17 +117,11 @@ func (ev *ErrorEvent) String() string { ...@@ -117,17 +117,11 @@ func (ev *ErrorEvent) String() string {
return evs return evs
} }
func processHcsResult(resultp *uint16) []ErrorEvent { func processHcsResult(ctx context.Context, resultJSON string) []ErrorEvent {
if resultp != nil { if resultJSON != "" {
resultj := interop.ConvertAndFreeCoTaskMemString(resultp)
logrus.WithField(logfields.JSON, resultj).
Debug("HCS Result")
result := &hcsResult{} result := &hcsResult{}
if err := json.Unmarshal([]byte(resultj), result); err != nil { if err := json.Unmarshal([]byte(resultJSON), result); err != nil {
logrus.WithFields(logrus.Fields{ log.G(ctx).WithError(err).Warning("Could not unmarshal HCS result")
logfields.JSON: resultj,
logrus.ErrorKey: err,
}).Warning("Could not unmarshal HCS result")
return nil return nil
} }
return result.ErrorEvents return result.ErrorEvents
...@@ -141,6 +135,8 @@ type HcsError struct { ...@@ -141,6 +135,8 @@ type HcsError struct {
Events []ErrorEvent Events []ErrorEvent
} }
var _ net.Error = &HcsError{}
func (e *HcsError) Error() string { func (e *HcsError) Error() string {
s := e.Op + ": " + e.Err.Error() s := e.Op + ": " + e.Err.Error()
for _, ev := range e.Events { for _, ev := range e.Events {
...@@ -149,6 +145,16 @@ func (e *HcsError) Error() string { ...@@ -149,6 +145,16 @@ func (e *HcsError) Error() string {
return s return s
} }
func (e *HcsError) Temporary() bool {
err, ok := e.Err.(net.Error)
return ok && err.Temporary()
}
func (e *HcsError) Timeout() bool {
err, ok := e.Err.(net.Error)
return ok && err.Timeout()
}
// ProcessError is an error encountered in HCS during an operation on a Process object // ProcessError is an error encountered in HCS during an operation on a Process object
type ProcessError struct { type ProcessError struct {
SystemID string SystemID string
...@@ -158,6 +164,8 @@ type ProcessError struct { ...@@ -158,6 +164,8 @@ type ProcessError struct {
Events []ErrorEvent Events []ErrorEvent
} }
var _ net.Error = &ProcessError{}
// SystemError is an error encountered in HCS during an operation on a Container object // SystemError is an error encountered in HCS during an operation on a Container object
type SystemError struct { type SystemError struct {
ID string ID string
...@@ -167,6 +175,8 @@ type SystemError struct { ...@@ -167,6 +175,8 @@ type SystemError struct {
Events []ErrorEvent Events []ErrorEvent
} }
var _ net.Error = &SystemError{}
func (e *SystemError) Error() string { func (e *SystemError) Error() string {
s := e.Op + " " + e.ID + ": " + e.Err.Error() s := e.Op + " " + e.ID + ": " + e.Err.Error()
for _, ev := range e.Events { for _, ev := range e.Events {
...@@ -178,6 +188,16 @@ func (e *SystemError) Error() string { ...@@ -178,6 +188,16 @@ func (e *SystemError) Error() string {
return s return s
} }
func (e *SystemError) Temporary() bool {
err, ok := e.Err.(net.Error)
return ok && err.Temporary()
}
func (e *SystemError) Timeout() bool {
err, ok := e.Err.(net.Error)
return ok && err.Timeout()
}
func makeSystemError(system *System, op string, extra string, err error, events []ErrorEvent) error { func makeSystemError(system *System, op string, extra string, err error, events []ErrorEvent) error {
// Don't double wrap errors // Don't double wrap errors
if _, ok := err.(*SystemError); ok { if _, ok := err.(*SystemError); ok {
...@@ -200,6 +220,16 @@ func (e *ProcessError) Error() string { ...@@ -200,6 +220,16 @@ func (e *ProcessError) Error() string {
return s return s
} }
func (e *ProcessError) Temporary() bool {
err, ok := e.Err.(net.Error)
return ok && err.Temporary()
}
func (e *ProcessError) Timeout() bool {
err, ok := e.Err.(net.Error)
return ok && err.Timeout()
}
func makeProcessError(process *Process, op string, err error, events []ErrorEvent) error { func makeProcessError(process *Process, op string, err error, events []ErrorEvent) error {
// Don't double wrap errors // Don't double wrap errors
if _, ok := err.(*ProcessError); ok { if _, ok := err.(*ProcessError); ok {
...@@ -242,6 +272,9 @@ func IsPending(err error) bool { ...@@ -242,6 +272,9 @@ func IsPending(err error) bool {
// IsTimeout returns a boolean indicating whether the error is caused by // IsTimeout returns a boolean indicating whether the error is caused by
// a timeout waiting for the operation to complete. // a timeout waiting for the operation to complete.
func IsTimeout(err error) bool { func IsTimeout(err error) bool {
if err, ok := err.(net.Error); ok && err.Timeout() {
return true
}
err = getInnerError(err) err = getInnerError(err)
return err == ErrTimeout return err == ErrTimeout
} }
...@@ -272,6 +305,13 @@ func IsNotSupported(err error) bool { ...@@ -272,6 +305,13 @@ func IsNotSupported(err error) bool {
err == ErrVmcomputeUnknownMessage err == ErrVmcomputeUnknownMessage
} }
// IsOperationInvalidState returns true when err is caused by
// `ErrVmcomputeOperationInvalidState`.
func IsOperationInvalidState(err error) bool {
err = getInnerError(err)
return err == ErrVmcomputeOperationInvalidState
}
func getInnerError(err error) error { func getInnerError(err error) error {
switch pe := err.(type) { switch pe := err.(type) {
case nil: case nil:
...@@ -285,3 +325,12 @@ func getInnerError(err error) error { ...@@ -285,3 +325,12 @@ func getInnerError(err error) error {
} }
return err return err
} }
func getOperationLogResult(err error) (string, error) {
switch err {
case nil:
return "Success", nil
default:
return "Error", err
}
}
// Shim for the Host Compute Service (HCS) to manage Windows Server
// containers and Hyper-V containers.
package hcs
import (
"syscall"
)
//go:generate go run ../../mksyscall_windows.go -output zsyscall_windows.go hcs.go
//sys hcsEnumerateComputeSystems(query string, computeSystems **uint16, result **uint16) (hr error) = vmcompute.HcsEnumerateComputeSystems?
//sys hcsCreateComputeSystem(id string, configuration string, identity syscall.Handle, computeSystem *hcsSystem, result **uint16) (hr error) = vmcompute.HcsCreateComputeSystem?
//sys hcsOpenComputeSystem(id string, computeSystem *hcsSystem, result **uint16) (hr error) = vmcompute.HcsOpenComputeSystem?
//sys hcsCloseComputeSystem(computeSystem hcsSystem) (hr error) = vmcompute.HcsCloseComputeSystem?
//sys hcsStartComputeSystem(computeSystem hcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsStartComputeSystem?
//sys hcsShutdownComputeSystem(computeSystem hcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsShutdownComputeSystem?
//sys hcsTerminateComputeSystem(computeSystem hcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsTerminateComputeSystem?
//sys hcsPauseComputeSystem(computeSystem hcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsPauseComputeSystem?
//sys hcsResumeComputeSystem(computeSystem hcsSystem, options string, result **uint16) (hr error) = vmcompute.HcsResumeComputeSystem?
//sys hcsGetComputeSystemProperties(computeSystem hcsSystem, propertyQuery string, properties **uint16, result **uint16) (hr error) = vmcompute.HcsGetComputeSystemProperties?
//sys hcsModifyComputeSystem(computeSystem hcsSystem, configuration string, result **uint16) (hr error) = vmcompute.HcsModifyComputeSystem?
//sys hcsRegisterComputeSystemCallback(computeSystem hcsSystem, callback uintptr, context uintptr, callbackHandle *hcsCallback) (hr error) = vmcompute.HcsRegisterComputeSystemCallback?
//sys hcsUnregisterComputeSystemCallback(callbackHandle hcsCallback) (hr error) = vmcompute.HcsUnregisterComputeSystemCallback?
//sys hcsCreateProcess(computeSystem hcsSystem, processParameters string, processInformation *hcsProcessInformation, process *hcsProcess, result **uint16) (hr error) = vmcompute.HcsCreateProcess?
//sys hcsOpenProcess(computeSystem hcsSystem, pid uint32, process *hcsProcess, result **uint16) (hr error) = vmcompute.HcsOpenProcess?
//sys hcsCloseProcess(process hcsProcess) (hr error) = vmcompute.HcsCloseProcess?
//sys hcsTerminateProcess(process hcsProcess, result **uint16) (hr error) = vmcompute.HcsTerminateProcess?
//sys hcsSignalProcess(process hcsProcess, options string, result **uint16) (hr error) = vmcompute.HcsTerminateProcess?
//sys hcsGetProcessInfo(process hcsProcess, processInformation *hcsProcessInformation, result **uint16) (hr error) = vmcompute.HcsGetProcessInfo?
//sys hcsGetProcessProperties(process hcsProcess, processProperties **uint16, result **uint16) (hr error) = vmcompute.HcsGetProcessProperties?
//sys hcsModifyProcess(process hcsProcess, settings string, result **uint16) (hr error) = vmcompute.HcsModifyProcess?
//sys hcsGetServiceProperties(propertyQuery string, properties **uint16, result **uint16) (hr error) = vmcompute.HcsGetServiceProperties?
//sys hcsRegisterProcessCallback(process hcsProcess, callback uintptr, context uintptr, callbackHandle *hcsCallback) (hr error) = vmcompute.HcsRegisterProcessCallback?
//sys hcsUnregisterProcessCallback(callbackHandle hcsCallback) (hr error) = vmcompute.HcsUnregisterProcessCallback?
type hcsSystem syscall.Handle
type hcsProcess syscall.Handle
type hcsCallback syscall.Handle
type hcsProcessInformation struct {
ProcessId uint32
Reserved uint32
StdInput syscall.Handle
StdOutput syscall.Handle
StdError syscall.Handle
}
package hcs
import "github.com/sirupsen/logrus"
func logOperationBegin(ctx logrus.Fields, msg string) {
logrus.WithFields(ctx).Debug(msg)
}
func logOperationEnd(ctx logrus.Fields, msg string, err error) {
// Copy the log and fields first.
log := logrus.WithFields(ctx)
if err == nil {
log.Debug(msg)
} else {
// Edit only the copied field data to avoid race conditions on the
// write.
log.Data[logrus.ErrorKey] = err
log.Error(msg)
}
}
package hcs package hcs
import ( import (
"context"
"time" "time"
"github.com/sirupsen/logrus" "github.com/Microsoft/hcsshim/internal/log"
) )
func processAsyncHcsResult(err error, resultp *uint16, callbackNumber uintptr, expectedNotification hcsNotification, timeout *time.Duration) ([]ErrorEvent, error) { func processAsyncHcsResult(ctx context.Context, err error, resultJSON string, callbackNumber uintptr, expectedNotification hcsNotification, timeout *time.Duration) ([]ErrorEvent, error) {
events := processHcsResult(resultp) events := processHcsResult(ctx, resultJSON)
if IsPending(err) { if IsPending(err) {
return nil, waitForNotification(callbackNumber, expectedNotification, timeout) return nil, waitForNotification(ctx, callbackNumber, expectedNotification, timeout)
} }
return events, err return events, err
} }
func waitForNotification(callbackNumber uintptr, expectedNotification hcsNotification, timeout *time.Duration) error { func waitForNotification(ctx context.Context, callbackNumber uintptr, expectedNotification hcsNotification, timeout *time.Duration) error {
callbackMapLock.RLock() callbackMapLock.RLock()
if _, ok := callbackMap[callbackNumber]; !ok {
callbackMapLock.RUnlock()
log.G(ctx).WithField("callbackNumber", callbackNumber).Error("failed to waitForNotification: callbackNumber does not exist in callbackMap")
return ErrHandleClose
}
channels := callbackMap[callbackNumber].channels channels := callbackMap[callbackNumber].channels
callbackMapLock.RUnlock() callbackMapLock.RUnlock()
expectedChannel := channels[expectedNotification] expectedChannel := channels[expectedNotification]
if expectedChannel == nil { if expectedChannel == nil {
logrus.Errorf("unknown notification type in waitForNotification %x", expectedNotification) log.G(ctx).WithField("type", expectedNotification).Error("unknown notification type in waitForNotification")
return ErrInvalidNotificationType return ErrInvalidNotificationType
} }
......
package hcs
import (
"context"
"github.com/Microsoft/hcsshim/internal/logfields"
"github.com/Microsoft/hcsshim/internal/timeout"
"github.com/sirupsen/logrus"
)
// syscallWatcher is used as a very simple goroutine around calls into
// the platform. In some cases, we have seen HCS APIs not returning due to
// various bugs, and the goroutine making the syscall ends up not returning,
// prior to its async callback. By spinning up a syscallWatcher, it allows
// us to at least log a warning if a syscall doesn't complete in a reasonable
// amount of time.
//
// Usage is:
//
// syscallWatcher(logContext, func() {
// err = <syscall>(args...)
// })
//
func syscallWatcher(logContext logrus.Fields, syscallLambda func()) {
ctx, cancel := context.WithTimeout(context.Background(), timeout.SyscallWatcher)
defer cancel()
go watchFunc(ctx, logContext)
syscallLambda()
}
func watchFunc(ctx context.Context, logContext logrus.Fields) {
select {
case <-ctx.Done():
if ctx.Err() != context.Canceled {
logrus.WithFields(logContext).
WithField(logfields.Timeout, timeout.SyscallWatcher).
Warning("Syscall did not complete within operation timeout. This may indicate a platform issue. If it appears to be making no forward progress, obtain the stacks and see if there is a syscall stuck in the platform API for a significant length of time.")
}
}
}
...@@ -3,6 +3,7 @@ package hns ...@@ -3,6 +3,7 @@ package hns
import ( import (
"encoding/json" "encoding/json"
"net" "net"
"strings"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
...@@ -94,6 +95,27 @@ func GetHNSEndpointByName(endpointName string) (*HNSEndpoint, error) { ...@@ -94,6 +95,27 @@ func GetHNSEndpointByName(endpointName string) (*HNSEndpoint, error) {
return nil, EndpointNotFoundError{EndpointName: endpointName} return nil, EndpointNotFoundError{EndpointName: endpointName}
} }
type endpointAttachInfo struct {
SharedContainers json.RawMessage `json:",omitempty"`
}
func (endpoint *HNSEndpoint) IsAttached(vID string) (bool, error) {
attachInfo := endpointAttachInfo{}
err := hnsCall("GET", "/endpoints/"+endpoint.Id, "", &attachInfo)
// Return false allows us to just return the err
if err != nil {
return false, err
}
if strings.Contains(strings.ToLower(string(attachInfo.SharedContainers)), strings.ToLower(vID)) {
return true, nil
}
return false, nil
}
// Create Endpoint by sending EndpointRequest to HNS. TODO: Create a separate HNS interface to place all these methods // Create Endpoint by sending EndpointRequest to HNS. TODO: Create a separate HNS interface to place all these methods
func (endpoint *HNSEndpoint) Create() (*HNSEndpoint, error) { func (endpoint *HNSEndpoint) Create() (*HNSEndpoint, error) {
operation := "Create" operation := "Create"
......
...@@ -9,23 +9,30 @@ import ( ...@@ -9,23 +9,30 @@ import (
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
func hnsCall(method, path, request string, returnResponse interface{}) error { func hnsCallRawResponse(method, path, request string) (*hnsResponse, error) {
var responseBuffer *uint16 var responseBuffer *uint16
logrus.Debugf("[%s]=>[%s] Request : %s", method, path, request) logrus.Debugf("[%s]=>[%s] Request : %s", method, path, request)
err := _hnsCall(method, path, request, &responseBuffer) err := _hnsCall(method, path, request, &responseBuffer)
if err != nil { if err != nil {
return hcserror.New(err, "hnsCall ", "") return nil, hcserror.New(err, "hnsCall ", "")
} }
response := interop.ConvertAndFreeCoTaskMemString(responseBuffer) response := interop.ConvertAndFreeCoTaskMemString(responseBuffer)
hnsresponse := &hnsResponse{} hnsresponse := &hnsResponse{}
if err = json.Unmarshal([]byte(response), &hnsresponse); err != nil { if err = json.Unmarshal([]byte(response), &hnsresponse); err != nil {
return err return nil, err
} }
return hnsresponse, nil
}
func hnsCall(method, path, request string, returnResponse interface{}) error {
hnsresponse, err := hnsCallRawResponse(method, path, request)
if err != nil {
return fmt.Errorf("failed during hnsCallRawResponse: %v", err)
}
if !hnsresponse.Success { if !hnsresponse.Success {
return fmt.Errorf("HNS failed with error : %s", hnsresponse.Error) return fmt.Errorf("hns failed with error : %s", hnsresponse.Error)
} }
if len(hnsresponse.Output) == 0 { if len(hnsresponse.Output) == 0 {
......
...@@ -2,9 +2,9 @@ package hns ...@@ -2,9 +2,9 @@ package hns
import ( import (
"encoding/json" "encoding/json"
"net" "errors"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"net"
) )
// Subnet is assoicated with a network and represents a list // Subnet is assoicated with a network and represents a list
...@@ -98,6 +98,12 @@ func (network *HNSNetwork) Create() (*HNSNetwork, error) { ...@@ -98,6 +98,12 @@ func (network *HNSNetwork) Create() (*HNSNetwork, error) {
title := "hcsshim::HNSNetwork::" + operation title := "hcsshim::HNSNetwork::" + operation
logrus.Debugf(title+" id=%s", network.Id) logrus.Debugf(title+" id=%s", network.Id)
for _, subnet := range network.Subnets {
if (subnet.AddressPrefix != "") && (subnet.GatewayAddress == "") {
return nil, errors.New("network create error, subnet has address prefix but no gateway specified")
}
}
jsonString, err := json.Marshal(network) jsonString, err := json.Marshal(network)
if err != nil { if err != nil {
return nil, err return nil, err
......
...@@ -15,10 +15,6 @@ func ConvertAndFreeCoTaskMemString(buffer *uint16) string { ...@@ -15,10 +15,6 @@ func ConvertAndFreeCoTaskMemString(buffer *uint16) string {
return str return str
} }
func ConvertAndFreeCoTaskMemBytes(buffer *uint16) []byte {
return []byte(ConvertAndFreeCoTaskMemString(buffer))
}
func Win32FromHresult(hr uintptr) syscall.Errno { func Win32FromHresult(hr uintptr) syscall.Errno {
if hr&0x1fff0000 == 0x00070000 { if hr&0x1fff0000 == 0x00070000 {
return syscall.Errno(hr & 0xffff) return syscall.Errno(hr & 0xffff)
......
package log
import (
"context"
"github.com/sirupsen/logrus"
"go.opencensus.io/trace"
)
// G returns a `logrus.Entry` with the `TraceID, SpanID` from `ctx` if `ctx`
// contains an OpenCensus `trace.Span`.
func G(ctx context.Context) *logrus.Entry {
span := trace.FromContext(ctx)
if span != nil {
sctx := span.SpanContext()
return logrus.WithFields(logrus.Fields{
"traceID": sctx.TraceID.String(),
"spanID": sctx.SpanID.String(),
// "parentSpanID": TODO: JTERRY75 - Try to convince OC to export this?
})
}
return logrus.NewEntry(logrus.StandardLogger())
}
package oc
import (
"github.com/sirupsen/logrus"
"go.opencensus.io/trace"
)
var _ = (trace.Exporter)(&LogrusExporter{})
// LogrusExporter is an OpenCensus `trace.Exporter` that exports
// `trace.SpanData` to logrus output.
type LogrusExporter struct {
}
// ExportSpan exports `s` based on the the following rules:
//
// 1. All output will contain `s.Attributes`, `s.TraceID`, `s.SpanID`,
// `s.ParentSpanID` for correlation
//
// 2. Any calls to .Annotate will not be supported.
//
// 3. The span itself will be written at `logrus.InfoLevel` unless
// `s.Status.Code != 0` in which case it will be written at `logrus.ErrorLevel`
// providing `s.Status.Message` as the error value.
func (le *LogrusExporter) ExportSpan(s *trace.SpanData) {
// Combine all span annotations with traceID, spanID, parentSpanID
baseEntry := logrus.WithFields(logrus.Fields(s.Attributes))
baseEntry.Data["traceID"] = s.TraceID.String()
baseEntry.Data["spanID"] = s.SpanID.String()
baseEntry.Data["parentSpanID"] = s.ParentSpanID.String()
baseEntry.Data["startTime"] = s.StartTime
baseEntry.Data["endTime"] = s.EndTime
baseEntry.Data["duration"] = s.EndTime.Sub(s.StartTime).String()
baseEntry.Data["name"] = s.Name
baseEntry.Time = s.StartTime
level := logrus.InfoLevel
if s.Status.Code != 0 {
level = logrus.ErrorLevel
baseEntry.Data[logrus.ErrorKey] = s.Status.Message
}
baseEntry.Log(level, "Span")
}
package oc
import (
"go.opencensus.io/trace"
)
// SetSpanStatus sets `span.SetStatus` to the proper status depending on `err`. If
// `err` is `nil` assumes `trace.StatusCodeOk`.
func SetSpanStatus(span *trace.Span, err error) {
status := trace.Status{}
if err != nil {
// TODO: JTERRY75 - Handle errors in a non-generic way
status.Code = trace.StatusCodeUnknown
status.Message = err.Error()
}
span.SetStatus(status)
}
...@@ -10,7 +10,7 @@ import ( ...@@ -10,7 +10,7 @@ import (
"syscall" "syscall"
"time" "time"
"github.com/Microsoft/hcsshim/internal/guid" "github.com/Microsoft/go-winio/pkg/guid"
) )
// ContainerState represents the platform agnostic pieces relating to a // ContainerState represents the platform agnostic pieces relating to a
......
...@@ -4,7 +4,8 @@ import ( ...@@ -4,7 +4,8 @@ import (
"encoding/json" "encoding/json"
"time" "time"
"github.com/Microsoft/hcsshim/internal/schema2" "github.com/Microsoft/go-winio/pkg/guid"
hcsschema "github.com/Microsoft/hcsshim/internal/schema2"
) )
// ProcessConfig is used as both the input of Container.CreateProcess // ProcessConfig is used as both the input of Container.CreateProcess
...@@ -62,7 +63,7 @@ type MappedVirtualDisk struct { ...@@ -62,7 +63,7 @@ type MappedVirtualDisk struct {
CreateInUtilityVM bool `json:",omitempty"` CreateInUtilityVM bool `json:",omitempty"`
ReadOnly bool `json:",omitempty"` ReadOnly bool `json:",omitempty"`
Cache string `json:",omitempty"` // "" (Unspecified); "Disabled"; "Enabled"; "Private"; "PrivateAllowSharing" Cache string `json:",omitempty"` // "" (Unspecified); "Disabled"; "Enabled"; "Private"; "PrivateAllowSharing"
AttachOnly bool `json:",omitempty:` AttachOnly bool `json:",omitempty"`
} }
// AssignedDevice represents a device that has been directly assigned to a container // AssignedDevice represents a device that has been directly assigned to a container
...@@ -133,9 +134,10 @@ type ContainerProperties struct { ...@@ -133,9 +134,10 @@ type ContainerProperties struct {
State string State string
Name string Name string
SystemType string SystemType string
RuntimeOSType string `json:"RuntimeOsType,omitempty"`
Owner string Owner string
SiloGUID string `json:"SiloGuid,omitempty"` SiloGUID string `json:"SiloGuid,omitempty"`
RuntimeID string `json:"RuntimeId,omitempty"` RuntimeID guid.GUID `json:"RuntimeId,omitempty"`
IsRuntimeTemplate bool `json:",omitempty"` IsRuntimeTemplate bool `json:",omitempty"`
RuntimeImagePath string `json:",omitempty"` RuntimeImagePath string `json:",omitempty"`
Stopped bool `json:",omitempty"` Stopped bool `json:",omitempty"`
...@@ -214,6 +216,7 @@ type MappedVirtualDiskController struct { ...@@ -214,6 +216,7 @@ type MappedVirtualDiskController struct {
type GuestDefinedCapabilities struct { type GuestDefinedCapabilities struct {
NamespaceAddRequestSupported bool `json:",omitempty"` NamespaceAddRequestSupported bool `json:",omitempty"`
SignalProcessSupported bool `json:",omitempty"` SignalProcessSupported bool `json:",omitempty"`
DumpStacksSupported bool `json:",omitempty"`
} }
// GuestConnectionInfo is the structure of an iterm return by a GuestConnection call on a utility VM // GuestConnectionInfo is the structure of an iterm return by a GuestConnection call on a utility VM
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type Attachment struct { type Attachment struct {
Type_ string `json:"Type,omitempty"` Type_ string `json:"Type,omitempty"`
Path string `json:"Path,omitempty"` Path string `json:"Path,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type CacheQueryStatsResponse struct { type CacheQueryStatsResponse struct {
L3OccupancyBytes int32 `json:"L3OccupancyBytes,omitempty"` L3OccupancyBytes int32 `json:"L3OccupancyBytes,omitempty"`
L3TotalBwBytes int32 `json:"L3TotalBwBytes,omitempty"` L3TotalBwBytes int32 `json:"L3TotalBwBytes,omitempty"`
......
...@@ -10,6 +10,5 @@ ...@@ -10,6 +10,5 @@
package hcsschema package hcsschema
type CloseHandle struct { type CloseHandle struct {
Handle string `json:"Handle,omitempty"` Handle string `json:"Handle,omitempty"`
} }
...@@ -11,7 +11,6 @@ package hcsschema ...@@ -11,7 +11,6 @@ package hcsschema
// ComPort specifies the named pipe that will be used for the port, with empty string indicating a disconnected port. // ComPort specifies the named pipe that will be used for the port, with empty string indicating a disconnected port.
type ComPort struct { type ComPort struct {
NamedPipe string `json:"NamedPipe,omitempty"` NamedPipe string `json:"NamedPipe,omitempty"`
OptimizeForDebugger bool `json:"OptimizeForDebugger,omitempty"` OptimizeForDebugger bool `json:"OptimizeForDebugger,omitempty"`
......
...@@ -10,14 +10,13 @@ ...@@ -10,14 +10,13 @@
package hcsschema package hcsschema
type ComputeSystem struct { type ComputeSystem struct {
Owner string `json:"Owner,omitempty"` Owner string `json:"Owner,omitempty"`
SchemaVersion *Version `json:"SchemaVersion,omitempty"` SchemaVersion *Version `json:"SchemaVersion,omitempty"`
HostingSystemId string `json:"HostingSystemId,omitempty"` HostingSystemId string `json:"HostingSystemId,omitempty"`
HostedSystem *HostedSystem `json:"HostedSystem,omitempty"` HostedSystem interface{} `json:"HostedSystem,omitempty"`
Container *Container `json:"Container,omitempty"` Container *Container `json:"Container,omitempty"`
......
...@@ -25,37 +25,37 @@ func (c contextKey) String() string { ...@@ -25,37 +25,37 @@ func (c contextKey) String() string {
var ( var (
// ContextOAuth2 takes a oauth2.TokenSource as authentication for the request. // ContextOAuth2 takes a oauth2.TokenSource as authentication for the request.
ContextOAuth2 = contextKey("token") ContextOAuth2 = contextKey("token")
// ContextBasicAuth takes BasicAuth as authentication for the request. // ContextBasicAuth takes BasicAuth as authentication for the request.
ContextBasicAuth = contextKey("basic") ContextBasicAuth = contextKey("basic")
// ContextAccessToken takes a string oauth2 access token as authentication for the request. // ContextAccessToken takes a string oauth2 access token as authentication for the request.
ContextAccessToken = contextKey("accesstoken") ContextAccessToken = contextKey("accesstoken")
// ContextAPIKey takes an APIKey as authentication for the request // ContextAPIKey takes an APIKey as authentication for the request
ContextAPIKey = contextKey("apikey") ContextAPIKey = contextKey("apikey")
) )
// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth // BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth
type BasicAuth struct { type BasicAuth struct {
UserName string `json:"userName,omitempty"` UserName string `json:"userName,omitempty"`
Password string `json:"password,omitempty"` Password string `json:"password,omitempty"`
} }
// APIKey provides API key based authentication to a request passed via context using ContextAPIKey // APIKey provides API key based authentication to a request passed via context using ContextAPIKey
type APIKey struct { type APIKey struct {
Key string Key string
Prefix string Prefix string
} }
type Configuration struct { type Configuration struct {
BasePath string `json:"basePath,omitempty"` BasePath string `json:"basePath,omitempty"`
Host string `json:"host,omitempty"` Host string `json:"host,omitempty"`
Scheme string `json:"scheme,omitempty"` Scheme string `json:"scheme,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"` DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"` UserAgent string `json:"userAgent,omitempty"`
HTTPClient *http.Client HTTPClient *http.Client
} }
func NewConfiguration() *Configuration { func NewConfiguration() *Configuration {
...@@ -69,4 +69,4 @@ func NewConfiguration() *Configuration { ...@@ -69,4 +69,4 @@ func NewConfiguration() *Configuration {
func (c *Configuration) AddDefaultHeader(key string, value string) { func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value c.DefaultHeader[key] = value
} }
\ No newline at end of file
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type ConsoleSize struct { type ConsoleSize struct {
Height int32 `json:"Height,omitempty"` Height int32 `json:"Height,omitempty"`
Width int32 `json:"Width,omitempty"` Width int32 `json:"Width,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type Container struct { type Container struct {
GuestOs *GuestOs `json:"GuestOs,omitempty"` GuestOs *GuestOs `json:"GuestOs,omitempty"`
Storage *Storage `json:"Storage,omitempty"` Storage *Storage `json:"Storage,omitempty"`
......
...@@ -11,7 +11,6 @@ package hcsschema ...@@ -11,7 +11,6 @@ package hcsschema
// memory usage as viewed from within the container // memory usage as viewed from within the container
type ContainerMemoryInformation struct { type ContainerMemoryInformation struct {
TotalPhysicalBytes int32 `json:"TotalPhysicalBytes,omitempty"` TotalPhysicalBytes int32 `json:"TotalPhysicalBytes,omitempty"`
TotalUsage int32 `json:"TotalUsage,omitempty"` TotalUsage int32 `json:"TotalUsage,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type Devices struct { type Devices struct {
ComPorts map[string]ComPort `json:"ComPorts,omitempty"` ComPorts map[string]ComPort `json:"ComPorts,omitempty"`
Scsi map[string]Scsi `json:"Scsi,omitempty"` Scsi map[string]Scsi `json:"Scsi,omitempty"`
......
...@@ -10,6 +10,5 @@ ...@@ -10,6 +10,5 @@
package hcsschema package hcsschema
type EnhancedModeVideo struct { type EnhancedModeVideo struct {
ConnectionOptions *RdpConnectionOptions `json:"ConnectionOptions,omitempty"` ConnectionOptions *RdpConnectionOptions `json:"ConnectionOptions,omitempty"`
} }
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type FlexibleIoDevice struct { type FlexibleIoDevice struct {
EmulatorId string `json:"EmulatorId,omitempty"` EmulatorId string `json:"EmulatorId,omitempty"`
HostingModel string `json:"HostingModel,omitempty"` HostingModel string `json:"HostingModel,omitempty"`
......
...@@ -10,6 +10,5 @@ ...@@ -10,6 +10,5 @@
package hcsschema package hcsschema
type GuestCrashReporting struct { type GuestCrashReporting struct {
WindowsCrashSettings *WindowsCrashReporting `json:"WindowsCrashSettings,omitempty"` WindowsCrashSettings *WindowsCrashReporting `json:"WindowsCrashSettings,omitempty"`
} }
...@@ -10,6 +10,5 @@ ...@@ -10,6 +10,5 @@
package hcsschema package hcsschema
type GuestOs struct { type GuestOs struct {
HostName string `json:"HostName,omitempty"` HostName string `json:"HostName,omitempty"`
} }
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type HostedSystem struct { type HostedSystem struct {
SchemaVersion *Version `json:"SchemaVersion,omitempty"` SchemaVersion *Version `json:"SchemaVersion,omitempty"`
Container *Container `json:"Container,omitempty"` Container *Container `json:"Container,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type HvSocket struct { type HvSocket struct {
Config *HvSocketSystemConfig `json:"Config,omitempty"` Config *HvSocketSystemConfig `json:"Config,omitempty"`
EnablePowerShellDirect bool `json:"EnablePowerShellDirect,omitempty"` EnablePowerShellDirect bool `json:"EnablePowerShellDirect,omitempty"`
......
...@@ -11,6 +11,5 @@ package hcsschema ...@@ -11,6 +11,5 @@ package hcsschema
// HvSocket configuration for a VM // HvSocket configuration for a VM
type HvSocket2 struct { type HvSocket2 struct {
HvSocketConfig *HvSocketSystemConfig `json:"HvSocketConfig,omitempty"` HvSocketConfig *HvSocketSystemConfig `json:"HvSocketConfig,omitempty"`
} }
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type Layer struct { type Layer struct {
Id string `json:"Id,omitempty"` Id string `json:"Id,omitempty"`
Path string `json:"Path,omitempty"` Path string `json:"Path,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type MappedDirectory struct { type MappedDirectory struct {
HostPath string `json:"HostPath,omitempty"` HostPath string `json:"HostPath,omitempty"`
HostPathType string `json:"HostPathType,omitempty"` HostPathType string `json:"HostPathType,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type MappedPipe struct { type MappedPipe struct {
ContainerPipeName string `json:"ContainerPipeName,omitempty"` ContainerPipeName string `json:"ContainerPipeName,omitempty"`
HostPath string `json:"HostPath,omitempty"` HostPath string `json:"HostPath,omitempty"`
......
...@@ -10,6 +10,5 @@ ...@@ -10,6 +10,5 @@
package hcsschema package hcsschema
type Memory struct { type Memory struct {
SizeInMB int32 `json:"SizeInMB,omitempty"` SizeInMB int32 `json:"SizeInMB,omitempty"`
} }
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type MemoryInformationForVm struct { type MemoryInformationForVm struct {
VirtualNodeCount int32 `json:"VirtualNodeCount,omitempty"` VirtualNodeCount int32 `json:"VirtualNodeCount,omitempty"`
VirtualMachineMemory *VmMemory `json:"VirtualMachineMemory,omitempty"` VirtualMachineMemory *VmMemory `json:"VirtualMachineMemory,omitempty"`
......
...@@ -11,7 +11,6 @@ package hcsschema ...@@ -11,7 +11,6 @@ package hcsschema
// Memory runtime statistics // Memory runtime statistics
type MemoryStats struct { type MemoryStats struct {
MemoryUsageCommitBytes int32 `json:"MemoryUsageCommitBytes,omitempty"` MemoryUsageCommitBytes int32 `json:"MemoryUsageCommitBytes,omitempty"`
MemoryUsageCommitPeakBytes int32 `json:"MemoryUsageCommitPeakBytes,omitempty"` MemoryUsageCommitPeakBytes int32 `json:"MemoryUsageCommitPeakBytes,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type NetworkAdapter struct { type NetworkAdapter struct {
EndpointId string `json:"EndpointId,omitempty"` EndpointId string `json:"EndpointId,omitempty"`
MacAddress string `json:"MacAddress,omitempty"` MacAddress string `json:"MacAddress,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type Networking struct { type Networking struct {
AllowUnqualifiedDnsQuery bool `json:"AllowUnqualifiedDnsQuery,omitempty"` AllowUnqualifiedDnsQuery bool `json:"AllowUnqualifiedDnsQuery,omitempty"`
DnsSearchList string `json:"DnsSearchList,omitempty"` DnsSearchList string `json:"DnsSearchList,omitempty"`
......
...@@ -11,6 +11,5 @@ package hcsschema ...@@ -11,6 +11,5 @@ package hcsschema
// Notification data that is indicated to components running in the Virtual Machine. // Notification data that is indicated to components running in the Virtual Machine.
type PauseNotification struct { type PauseNotification struct {
Reason string `json:"Reason,omitempty"` Reason string `json:"Reason,omitempty"`
} }
...@@ -11,7 +11,6 @@ package hcsschema ...@@ -11,7 +11,6 @@ package hcsschema
// Options for HcsPauseComputeSystem // Options for HcsPauseComputeSystem
type PauseOptions struct { type PauseOptions struct {
SuspensionLevel string `json:"SuspensionLevel,omitempty"` SuspensionLevel string `json:"SuspensionLevel,omitempty"`
HostedNotification *PauseNotification `json:"HostedNotification,omitempty"` HostedNotification *PauseNotification `json:"HostedNotification,omitempty"`
......
...@@ -10,6 +10,5 @@ ...@@ -10,6 +10,5 @@
package hcsschema package hcsschema
type Plan9 struct { type Plan9 struct {
Shares []Plan9Share `json:"Shares,omitempty"` Shares []Plan9Share `json:"Shares,omitempty"`
} }
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type Plan9Share struct { type Plan9Share struct {
Name string `json:"Name,omitempty"` Name string `json:"Name,omitempty"`
// The name by which the guest operation system can access this share, via the aname parameter in the Plan9 protocol. // The name by which the guest operation system can access this share, via the aname parameter in the Plan9 protocol.
...@@ -30,4 +29,6 @@ type Plan9Share struct { ...@@ -30,4 +29,6 @@ type Plan9Share struct {
ReadOnly bool `json:"ReadOnly,omitempty"` ReadOnly bool `json:"ReadOnly,omitempty"`
UseShareRootIdentity bool `json:"UseShareRootIdentity,omitempty"` UseShareRootIdentity bool `json:"UseShareRootIdentity,omitempty"`
AllowedFiles []string `json:"AllowedFiles,omitempty"`
} }
...@@ -15,7 +15,6 @@ import ( ...@@ -15,7 +15,6 @@ import (
// Information about a process running in a container // Information about a process running in a container
type ProcessDetails struct { type ProcessDetails struct {
ProcessId int32 `json:"ProcessId,omitempty"` ProcessId int32 `json:"ProcessId,omitempty"`
ImageName string `json:"ImageName,omitempty"` ImageName string `json:"ImageName,omitempty"`
......
...@@ -11,7 +11,6 @@ package hcsschema ...@@ -11,7 +11,6 @@ package hcsschema
// Passed to HcsRpc_ModifyProcess // Passed to HcsRpc_ModifyProcess
type ProcessModifyRequest struct { type ProcessModifyRequest struct {
Operation string `json:"Operation,omitempty"` Operation string `json:"Operation,omitempty"`
ConsoleSize *ConsoleSize `json:"ConsoleSize,omitempty"` ConsoleSize *ConsoleSize `json:"ConsoleSize,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type ProcessParameters struct { type ProcessParameters struct {
ApplicationName string `json:"ApplicationName,omitempty"` ApplicationName string `json:"ApplicationName,omitempty"`
CommandLine string `json:"CommandLine,omitempty"` CommandLine string `json:"CommandLine,omitempty"`
......
...@@ -11,7 +11,6 @@ package hcsschema ...@@ -11,7 +11,6 @@ package hcsschema
// Status of a process running in a container // Status of a process running in a container
type ProcessStatus struct { type ProcessStatus struct {
ProcessId int32 `json:"ProcessId,omitempty"` ProcessId int32 `json:"ProcessId,omitempty"`
Exited bool `json:"Exited,omitempty"` Exited bool `json:"Exited,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type Processor struct { type Processor struct {
Count int32 `json:"Count,omitempty"` Count int32 `json:"Count,omitempty"`
Maximum int32 `json:"Maximum,omitempty"` Maximum int32 `json:"Maximum,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type Processor2 struct { type Processor2 struct {
Count int32 `json:"Count,omitempty"` Count int32 `json:"Count,omitempty"`
Limit int32 `json:"Limit,omitempty"` Limit int32 `json:"Limit,omitempty"`
......
...@@ -11,7 +11,6 @@ package hcsschema ...@@ -11,7 +11,6 @@ package hcsschema
// CPU runtime statistics // CPU runtime statistics
type ProcessorStats struct { type ProcessorStats struct {
TotalRuntime100ns int32 `json:"TotalRuntime100ns,omitempty"` TotalRuntime100ns int32 `json:"TotalRuntime100ns,omitempty"`
RuntimeUser100ns int32 `json:"RuntimeUser100ns,omitempty"` RuntimeUser100ns int32 `json:"RuntimeUser100ns,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type Properties struct { type Properties struct {
Id string `json:"Id,omitempty"` Id string `json:"Id,omitempty"`
SystemType string `json:"SystemType,omitempty"` SystemType string `json:"SystemType,omitempty"`
......
...@@ -9,8 +9,7 @@ ...@@ -9,8 +9,7 @@
package hcsschema package hcsschema
// By default the basic properties will be returned. This query provides a way to request specific properties. // By default the basic properties will be returned. This query provides a way to request specific properties.
type PropertyQuery struct { type PropertyQuery struct {
PropertyTypes []string `json:"PropertyTypes,omitempty"` PropertyTypes []string `json:"PropertyTypes,omitempty"`
} }
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type RdpConnectionOptions struct { type RdpConnectionOptions struct {
AccessSids []string `json:"AccessSids,omitempty"` AccessSids []string `json:"AccessSids,omitempty"`
NamedPipe string `json:"NamedPipe,omitempty"` NamedPipe string `json:"NamedPipe,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type RegistryChanges struct { type RegistryChanges struct {
AddValues []RegistryValue `json:"AddValues,omitempty"` AddValues []RegistryValue `json:"AddValues,omitempty"`
DeleteKeys []RegistryKey `json:"DeleteKeys,omitempty"` DeleteKeys []RegistryKey `json:"DeleteKeys,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type RegistryKey struct { type RegistryKey struct {
Hive string `json:"Hive,omitempty"` Hive string `json:"Hive,omitempty"`
Name string `json:"Name,omitempty"` Name string `json:"Name,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type RegistryValue struct { type RegistryValue struct {
Key *RegistryKey `json:"Key,omitempty"` Key *RegistryKey `json:"Key,omitempty"`
Name string `json:"Name,omitempty"` Name string `json:"Name,omitempty"`
......
...@@ -10,6 +10,5 @@ ...@@ -10,6 +10,5 @@
package hcsschema package hcsschema
type SharedMemoryConfiguration struct { type SharedMemoryConfiguration struct {
Regions []SharedMemoryRegion `json:"Regions,omitempty"` Regions []SharedMemoryRegion `json:"Regions,omitempty"`
} }
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type SharedMemoryRegion struct { type SharedMemoryRegion struct {
SectionName string `json:"SectionName,omitempty"` SectionName string `json:"SectionName,omitempty"`
StartOffset int32 `json:"StartOffset,omitempty"` StartOffset int32 `json:"StartOffset,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type SharedMemoryRegionInfo struct { type SharedMemoryRegionInfo struct {
SectionName string `json:"SectionName,omitempty"` SectionName string `json:"SectionName,omitempty"`
GuestPhysicalAddress int32 `json:"GuestPhysicalAddress,omitempty"` GuestPhysicalAddress int32 `json:"GuestPhysicalAddress,omitempty"`
......
...@@ -11,7 +11,6 @@ package hcsschema ...@@ -11,7 +11,6 @@ package hcsschema
// Silo job information // Silo job information
type SiloProperties struct { type SiloProperties struct {
Enabled bool `json:"Enabled,omitempty"` Enabled bool `json:"Enabled,omitempty"`
JobName string `json:"JobName,omitempty"` JobName string `json:"JobName,omitempty"`
......
...@@ -15,7 +15,6 @@ import ( ...@@ -15,7 +15,6 @@ import (
// Runtime statistics for a container // Runtime statistics for a container
type Statistics struct { type Statistics struct {
Timestamp time.Time `json:"Timestamp,omitempty"` Timestamp time.Time `json:"Timestamp,omitempty"`
ContainerStartTime time.Time `json:"ContainerStartTime,omitempty"` ContainerStartTime time.Time `json:"ContainerStartTime,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type StorageQoS struct { type StorageQoS struct {
IopsMaximum int32 `json:"IopsMaximum,omitempty"` IopsMaximum int32 `json:"IopsMaximum,omitempty"`
BandwidthMaximum int32 `json:"BandwidthMaximum,omitempty"` BandwidthMaximum int32 `json:"BandwidthMaximum,omitempty"`
......
...@@ -11,7 +11,6 @@ package hcsschema ...@@ -11,7 +11,6 @@ package hcsschema
// Storage runtime statistics // Storage runtime statistics
type StorageStats struct { type StorageStats struct {
ReadCountNormalized int32 `json:"ReadCountNormalized,omitempty"` ReadCountNormalized int32 `json:"ReadCountNormalized,omitempty"`
ReadSizeBytes int32 `json:"ReadSizeBytes,omitempty"` ReadSizeBytes int32 `json:"ReadSizeBytes,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type Topology struct { type Topology struct {
Memory *Memory2 `json:"Memory,omitempty"` Memory *Memory2 `json:"Memory,omitempty"`
Processor *Processor2 `json:"Processor,omitempty"` Processor *Processor2 `json:"Processor,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type Uefi struct { type Uefi struct {
EnableDebugger bool `json:"EnableDebugger,omitempty"` EnableDebugger bool `json:"EnableDebugger,omitempty"`
SecureBootTemplateId string `json:"SecureBootTemplateId,omitempty"` SecureBootTemplateId string `json:"SecureBootTemplateId,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type UefiBootEntry struct { type UefiBootEntry struct {
DeviceType string `json:"DeviceType,omitempty"` DeviceType string `json:"DeviceType,omitempty"`
DevicePath string `json:"DevicePath,omitempty"` DevicePath string `json:"DevicePath,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type Version struct { type Version struct {
Major int32 `json:"Major,omitempty"` Major int32 `json:"Major,omitempty"`
Minor int32 `json:"Minor,omitempty"` Minor int32 `json:"Minor,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type VideoMonitor struct { type VideoMonitor struct {
HorizontalResolution int32 `json:"HorizontalResolution,omitempty"` HorizontalResolution int32 `json:"HorizontalResolution,omitempty"`
VerticalResolution int32 `json:"VerticalResolution,omitempty"` VerticalResolution int32 `json:"VerticalResolution,omitempty"`
......
...@@ -10,7 +10,6 @@ ...@@ -10,7 +10,6 @@
package hcsschema package hcsschema
type VirtualNodeInfo struct { type VirtualNodeInfo struct {
VirtualNodeIndex int32 `json:"VirtualNodeIndex,omitempty"` VirtualNodeIndex int32 `json:"VirtualNodeIndex,omitempty"`
PhysicalNodeNumber int32 `json:"PhysicalNodeNumber,omitempty"` PhysicalNodeNumber int32 `json:"PhysicalNodeNumber,omitempty"`
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment