Merge pull request #21 from mikebrow/image-management
Initial implementation for image management
This commit is contained in:
commit
cdfdc8d33b
@ -1,6 +1,5 @@
|
|||||||
language: go
|
language: go
|
||||||
go:
|
go:
|
||||||
- 1.6.x
|
|
||||||
- 1.7.x
|
- 1.7.x
|
||||||
- 1.8.x
|
- 1.8.x
|
||||||
- tip
|
- tip
|
||||||
|
141
Godeps/Godeps.json
generated
141
Godeps/Godeps.json
generated
@ -6,11 +6,26 @@
|
|||||||
"./..."
|
"./..."
|
||||||
],
|
],
|
||||||
"Deps": [
|
"Deps": [
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/Microsoft/go-winio",
|
||||||
|
"Comment": "v0.3.8",
|
||||||
|
"Rev": "fff283ad5116362ca252298cfc9b95828956d85d"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/Sirupsen/logrus",
|
||||||
|
"Comment": "v0.11.0",
|
||||||
|
"Rev": "d26492970760ca5d33129d2d799e34be5c4782eb"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"ImportPath": "github.com/blang/semver",
|
"ImportPath": "github.com/blang/semver",
|
||||||
"Comment": "v3.0.1",
|
"Comment": "v3.0.1",
|
||||||
"Rev": "31b736133b98f26d5e078ec9eb591666edfd091f"
|
"Rev": "31b736133b98f26d5e078ec9eb591666edfd091f"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/boltdb/bolt",
|
||||||
|
"Comment": "v1.3.0-58-ge9cf4fa",
|
||||||
|
"Rev": "e9cf4fae01b5a8ff89d0ec6b32f0d9c9f79aefdd"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"ImportPath": "github.com/containerd/containerd",
|
"ImportPath": "github.com/containerd/containerd",
|
||||||
"Comment": "v0.2.3-745-gbbeaab5",
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
@ -51,11 +66,101 @@
|
|||||||
"Comment": "v0.2.3-745-gbbeaab5",
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/containerd/containerd/archive",
|
||||||
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/containerd/containerd/archive/compression",
|
||||||
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/containerd/containerd/content",
|
||||||
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/containerd/containerd/fs",
|
||||||
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/containerd/containerd/images",
|
||||||
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/containerd/containerd/log",
|
||||||
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/containerd/containerd/plugin",
|
||||||
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/containerd/containerd/progress",
|
||||||
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/containerd/containerd/reference",
|
||||||
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/containerd/containerd/remotes",
|
||||||
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/containerd/containerd/remotes/docker",
|
||||||
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/containerd/containerd/rootfs",
|
||||||
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/containerd/containerd/services/content",
|
||||||
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/containerd/containerd/services/images",
|
||||||
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/containerd/containerd/services/rootfs",
|
||||||
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/containerd/containerd/snapshot",
|
||||||
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/containerd/containerd/sys",
|
||||||
|
"Comment": "v0.2.3-745-gbbeaab5",
|
||||||
|
"Rev": "bbeaab5ee38568daa84b8c233a8067b524588355"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"ImportPath": "github.com/davecgh/go-spew/spew",
|
"ImportPath": "github.com/davecgh/go-spew/spew",
|
||||||
"Comment": "v1.1.0",
|
"Comment": "v1.1.0",
|
||||||
"Rev": "346938d642f2ec3594ed81d874461961cd0faa76"
|
"Rev": "346938d642f2ec3594ed81d874461961cd0faa76"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/docker/go-units",
|
||||||
|
"Comment": "v0.3.1",
|
||||||
|
"Rev": "f2d77a61e3c169b43402a0a1e84f06daf29b8190"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"ImportPath": "github.com/gogo/protobuf/gogoproto",
|
"ImportPath": "github.com/gogo/protobuf/gogoproto",
|
||||||
"Comment": "v0.3-150-gd2e1ade2",
|
"Comment": "v0.3-150-gd2e1ade2",
|
||||||
@ -93,15 +198,34 @@
|
|||||||
"ImportPath": "github.com/golang/protobuf/ptypes/empty",
|
"ImportPath": "github.com/golang/protobuf/ptypes/empty",
|
||||||
"Rev": "8ee79997227bf9b34611aee7946ae64735e6fd93"
|
"Rev": "8ee79997227bf9b34611aee7946ae64735e6fd93"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/nightlyone/lockfile",
|
||||||
|
"Rev": "1d49c987357a327b5b03aa84cbddd582c328615d"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"ImportPath": "github.com/opencontainers/go-digest",
|
"ImportPath": "github.com/opencontainers/go-digest",
|
||||||
"Rev": "21dfd564fd89c944783d00d069f33e3e7123c448"
|
"Rev": "21dfd564fd89c944783d00d069f33e3e7123c448"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/opencontainers/image-spec/identity",
|
||||||
|
"Comment": "v1.0.0-rc4-51-ga431dbc",
|
||||||
|
"Rev": "a431dbcf6a74fca2e0e040b819a836dbe3fb23ca"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"ImportPath": "github.com/opencontainers/image-spec/specs-go",
|
"ImportPath": "github.com/opencontainers/image-spec/specs-go",
|
||||||
"Comment": "v1.0.0-rc4-51-ga431dbc",
|
"Comment": "v1.0.0-rc4-51-ga431dbc",
|
||||||
"Rev": "a431dbcf6a74fca2e0e040b819a836dbe3fb23ca"
|
"Rev": "a431dbcf6a74fca2e0e040b819a836dbe3fb23ca"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/opencontainers/image-spec/specs-go/v1",
|
||||||
|
"Comment": "v1.0.0-rc4-51-ga431dbc",
|
||||||
|
"Rev": "a431dbcf6a74fca2e0e040b819a836dbe3fb23ca"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/opencontainers/runc/libcontainer/system",
|
||||||
|
"Comment": "v1.0.0-rc3-21-g50401b5",
|
||||||
|
"Rev": "50401b5b4c2e01e4f1372b73a021742deeaf4e2d"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"ImportPath": "github.com/opencontainers/runtime-spec/specs-go",
|
"ImportPath": "github.com/opencontainers/runtime-spec/specs-go",
|
||||||
"Comment": "v1.0.0-rc5",
|
"Comment": "v1.0.0-rc5",
|
||||||
@ -121,15 +245,28 @@
|
|||||||
"ImportPath": "github.com/spf13/pflag",
|
"ImportPath": "github.com/spf13/pflag",
|
||||||
"Rev": "9ff6c6923cfffbcd502984b8e0c80539a94968b7"
|
"Rev": "9ff6c6923cfffbcd502984b8e0c80539a94968b7"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/stevvooe/continuity/sysx",
|
||||||
|
"Rev": "2abd81dfcc64c06e1eb16a081fd187798f4c2919"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"ImportPath": "github.com/stretchr/testify/assert",
|
"ImportPath": "github.com/stretchr/testify/assert",
|
||||||
"Comment": "v1.1.4-6-g18a02ba",
|
"Comment": "v1.1.4-6-g18a02ba",
|
||||||
"Rev": "18a02ba4a312f95da08ff4cfc0055750ce50ae9e"
|
"Rev": "18a02ba4a312f95da08ff4cfc0055750ce50ae9e"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "github.com/stretchr/testify/require",
|
||||||
|
"Comment": "v1.1.4-6-g18a02ba",
|
||||||
|
"Rev": "18a02ba4a312f95da08ff4cfc0055750ce50ae9e"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"ImportPath": "golang.org/x/net/context",
|
"ImportPath": "golang.org/x/net/context",
|
||||||
"Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0"
|
"Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "golang.org/x/net/context/ctxhttp",
|
||||||
|
"Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"ImportPath": "golang.org/x/net/http2",
|
"ImportPath": "golang.org/x/net/http2",
|
||||||
"Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0"
|
"Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0"
|
||||||
@ -154,6 +291,10 @@
|
|||||||
"ImportPath": "golang.org/x/net/trace",
|
"ImportPath": "golang.org/x/net/trace",
|
||||||
"Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0"
|
"Rev": "e90d6d0afc4c315a0d87a568ae68577cc15149a0"
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"ImportPath": "golang.org/x/sync/errgroup",
|
||||||
|
"Rev": "450f422ab23cf9881c94e2db30cac0eb1b7cf80c"
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"ImportPath": "golang.org/x/sys/unix",
|
"ImportPath": "golang.org/x/sys/unix",
|
||||||
"Rev": "f3918c30c5c2cb527c0b071a27c35120a6c0719a"
|
"Rev": "f3918c30c5c2cb527c0b071a27c35120a6c0719a"
|
||||||
|
2
Makefile
2
Makefile
@ -69,7 +69,7 @@ cri-containerd: check-gopath
|
|||||||
$(PROJECT)/cmd/cri-containerd
|
$(PROJECT)/cmd/cri-containerd
|
||||||
|
|
||||||
test:
|
test:
|
||||||
go test -timeout=1m -v -race ./pkg/... $(BUILD_TAGS)
|
go test -timeout=10m -v -race ./pkg/... $(BUILD_TAGS)
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm -f $(BUILD_DIR)/cri-containerd
|
rm -f $(BUILD_DIR)/cri-containerd
|
||||||
|
150
pkg/metadata/image_metadata.go
Normal file
150
pkg/metadata/image_metadata.go
Normal file
@ -0,0 +1,150 @@
|
|||||||
|
/*
|
||||||
|
Copyright 2017 The Kubernetes Authors.
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package metadata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"github.com/kubernetes-incubator/cri-containerd/pkg/metadata/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The code is very similar to sandbox.go, but there is no template support
|
||||||
|
// in golang, thus similar files for different types.
|
||||||
|
// TODO(random-liu): Figure out a way to simplify this.
|
||||||
|
// TODO(random-liu): Handle versioning
|
||||||
|
|
||||||
|
// imageMetadataVersion is current version of image metadata.
|
||||||
|
const imageMetadataVersion = "v1" // nolint
|
||||||
|
|
||||||
|
// versionedImageMetadata is the internal struct representing the versioned
|
||||||
|
// image metadata
|
||||||
|
// nolint
|
||||||
|
type versionedImageMetadata struct {
|
||||||
|
// Version indicates the version of the versioned image metadata.
|
||||||
|
Version string `json:"version,omitempty"`
|
||||||
|
ImageMetadata
|
||||||
|
}
|
||||||
|
|
||||||
|
// ImageMetadata is the unversioned image metadata.
|
||||||
|
type ImageMetadata struct {
|
||||||
|
// Id of the image. Normally the Digest
|
||||||
|
ID string `json:"id,omitempty"`
|
||||||
|
// Other names by which this image is known.
|
||||||
|
RepoTags []string `json:"repo_tags,omitempty"`
|
||||||
|
// Digests by which this image is known.
|
||||||
|
RepoDigests []string `json:"repo_digests,omitempty"`
|
||||||
|
// Size of the image in bytes. Must be > 0.
|
||||||
|
Size uint64 `json:"size,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ImageMetadataUpdateFunc is the function used to update ImageMetadata.
|
||||||
|
type ImageMetadataUpdateFunc func(ImageMetadata) (ImageMetadata, error)
|
||||||
|
|
||||||
|
// imageMetadataToStoreUpdateFunc generates a metadata store UpdateFunc from ImageMetadataUpdateFunc.
|
||||||
|
func imageMetadataToStoreUpdateFunc(u ImageMetadataUpdateFunc) store.UpdateFunc {
|
||||||
|
return func(data []byte) ([]byte, error) {
|
||||||
|
meta := &ImageMetadata{}
|
||||||
|
if err := json.Unmarshal(data, meta); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
newMeta, err := u(*meta)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return json.Marshal(newMeta)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ImageMetadataStore is the store for metadata of all images.
|
||||||
|
type ImageMetadataStore interface {
|
||||||
|
// Create creates an image's metadata from ImageMetadata in the store.
|
||||||
|
Create(ImageMetadata) error
|
||||||
|
// Get gets the specified image metadata.
|
||||||
|
Get(string) (*ImageMetadata, error)
|
||||||
|
// Update updates a specified image metatdata.
|
||||||
|
Update(string, ImageMetadataUpdateFunc) error
|
||||||
|
// List lists all image metadatas.
|
||||||
|
List() ([]*ImageMetadata, error)
|
||||||
|
// Delete deletes the image's metatdata from the store.
|
||||||
|
Delete(string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// imageMetadataStore is an implmentation of ImageMetadataStore.
|
||||||
|
type imageMetadataStore struct {
|
||||||
|
store store.MetadataStore
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewImageMetadataStore creates an ImageMetadataStore from a basic MetadataStore.
|
||||||
|
func NewImageMetadataStore(store store.MetadataStore) ImageMetadataStore {
|
||||||
|
return &imageMetadataStore{store: store}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create creates a image's metadata from ImageMetadata in the store.
|
||||||
|
func (s *imageMetadataStore) Create(metadata ImageMetadata) error {
|
||||||
|
data, err := json.Marshal(&metadata)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return s.store.Create(metadata.ID, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get gets the specified image metadata.
|
||||||
|
func (s *imageMetadataStore) Get(digest string) (*ImageMetadata, error) {
|
||||||
|
data, err := s.store.Get(digest)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// Return nil without error if the corresponding metadata
|
||||||
|
// does not exist.
|
||||||
|
if data == nil {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
imageMetadata := &ImageMetadata{}
|
||||||
|
if err := json.Unmarshal(data, imageMetadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return imageMetadata, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update updates a specified image's metadata. The function is running in a
|
||||||
|
// transaction. Update will not be applied when the update function
|
||||||
|
// returns error.
|
||||||
|
func (s *imageMetadataStore) Update(digest string, u ImageMetadataUpdateFunc) error {
|
||||||
|
return s.store.Update(digest, imageMetadataToStoreUpdateFunc(u))
|
||||||
|
}
|
||||||
|
|
||||||
|
// List lists all image metadata.
|
||||||
|
func (s *imageMetadataStore) List() ([]*ImageMetadata, error) {
|
||||||
|
allData, err := s.store.List()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var imageMetadataA []*ImageMetadata
|
||||||
|
for _, data := range allData {
|
||||||
|
imageMetadata := &ImageMetadata{}
|
||||||
|
if err := json.Unmarshal(data, imageMetadata); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
imageMetadataA = append(imageMetadataA, imageMetadata)
|
||||||
|
}
|
||||||
|
return imageMetadataA, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete deletes the image metadata from the store.
|
||||||
|
func (s *imageMetadataStore) Delete(digest string) error {
|
||||||
|
return s.store.Delete(digest)
|
||||||
|
}
|
87
pkg/metadata/image_metadata_test.go
Normal file
87
pkg/metadata/image_metadata_test.go
Normal file
@ -0,0 +1,87 @@
|
|||||||
|
/*
|
||||||
|
Copyright 2017 The Kubernetes Authors.
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package metadata
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
assertlib "github.com/stretchr/testify/assert"
|
||||||
|
|
||||||
|
"github.com/kubernetes-incubator/cri-containerd/pkg/metadata/store"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestImageMetadataStore(t *testing.T) {
|
||||||
|
imageMetadataMap := map[string]*ImageMetadata{
|
||||||
|
"1": {
|
||||||
|
ID: "1", // TODO(mikebrow): fill
|
||||||
|
Size: 10,
|
||||||
|
},
|
||||||
|
"2": {
|
||||||
|
ID: "2",
|
||||||
|
Size: 20,
|
||||||
|
},
|
||||||
|
"3": {
|
||||||
|
ID: "3",
|
||||||
|
Size: 30,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
assert := assertlib.New(t)
|
||||||
|
|
||||||
|
s := NewImageMetadataStore(store.NewMetadataStore())
|
||||||
|
|
||||||
|
t.Logf("should be able to create image metadata")
|
||||||
|
for _, meta := range imageMetadataMap {
|
||||||
|
assert.NoError(s.Create(*meta))
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Logf("should be able to get image metadata")
|
||||||
|
for id, expectMeta := range imageMetadataMap {
|
||||||
|
meta, err := s.Get(id)
|
||||||
|
assert.NoError(err)
|
||||||
|
assert.Equal(expectMeta, meta)
|
||||||
|
}
|
||||||
|
|
||||||
|
t.Logf("should be able to list image metadata")
|
||||||
|
imgs, err := s.List()
|
||||||
|
assert.NoError(err)
|
||||||
|
assert.Len(imgs, 3)
|
||||||
|
|
||||||
|
t.Logf("should be able to update image metadata")
|
||||||
|
testID := "2"
|
||||||
|
newSize := uint64(200)
|
||||||
|
expectMeta := *imageMetadataMap[testID]
|
||||||
|
expectMeta.Size = newSize
|
||||||
|
err = s.Update(testID, func(o ImageMetadata) (ImageMetadata, error) {
|
||||||
|
o.Size = newSize
|
||||||
|
return o, nil
|
||||||
|
})
|
||||||
|
assert.NoError(err)
|
||||||
|
newMeta, err := s.Get(testID)
|
||||||
|
assert.NoError(err)
|
||||||
|
assert.Equal(&expectMeta, newMeta)
|
||||||
|
|
||||||
|
t.Logf("should be able to delete image metadata")
|
||||||
|
assert.NoError(s.Delete(testID))
|
||||||
|
imgs, err = s.List()
|
||||||
|
assert.NoError(err)
|
||||||
|
assert.Len(imgs, 2)
|
||||||
|
|
||||||
|
t.Logf("get should return nil without error after deletion")
|
||||||
|
meta, err := s.Get(testID)
|
||||||
|
assert.NoError(err)
|
||||||
|
assert.Nil(meta)
|
||||||
|
}
|
@ -17,14 +17,34 @@ limitations under the License.
|
|||||||
package server
|
package server
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"fmt"
|
||||||
|
|
||||||
"golang.org/x/net/context"
|
"golang.org/x/net/context"
|
||||||
|
|
||||||
"k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
|
"k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListImages lists existing images.
|
// ListImages lists existing images.
|
||||||
|
// TODO(mikebrow): add filters
|
||||||
|
// TODO(mikebrow): harden api
|
||||||
func (c *criContainerdService) ListImages(ctx context.Context, r *runtime.ListImagesRequest) (*runtime.ListImagesResponse, error) {
|
func (c *criContainerdService) ListImages(ctx context.Context, r *runtime.ListImagesRequest) (*runtime.ListImagesResponse, error) {
|
||||||
return nil, errors.New("not implemented")
|
imageMetadataA, err := c.imageMetadataStore.List()
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to list image metadata from store %v", err)
|
||||||
|
}
|
||||||
|
// TODO(mikebrow): Get the id->tags, and id->digest mapping from our checkpoint;
|
||||||
|
// Get other information from containerd image/content store
|
||||||
|
|
||||||
|
var images []*runtime.Image
|
||||||
|
for _, image := range imageMetadataA { // TODO(mikebrow): write a ImageMetadata to runtime.Image converter
|
||||||
|
ri := &runtime.Image{
|
||||||
|
Id: image.ID,
|
||||||
|
RepoTags: image.RepoTags,
|
||||||
|
RepoDigests: image.RepoDigests,
|
||||||
|
Size_: image.Size,
|
||||||
|
// TODO(mikebrow): Uid and Username?
|
||||||
|
}
|
||||||
|
images = append(images, ri)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &runtime.ListImagesResponse{Images: images}, nil
|
||||||
}
|
}
|
||||||
|
@ -17,14 +17,179 @@ limitations under the License.
|
|||||||
package server
|
package server
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/kubernetes-incubator/cri-containerd/pkg/metadata"
|
||||||
|
|
||||||
|
"github.com/containerd/containerd/content"
|
||||||
|
containerdimages "github.com/containerd/containerd/images"
|
||||||
|
"github.com/containerd/containerd/remotes"
|
||||||
|
"github.com/containerd/containerd/remotes/docker"
|
||||||
|
imagespec "github.com/opencontainers/image-spec/specs-go/v1"
|
||||||
"golang.org/x/net/context"
|
"golang.org/x/net/context"
|
||||||
|
|
||||||
"k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
|
"k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
|
||||||
)
|
)
|
||||||
|
|
||||||
// PullImage pulls an image with authentication config.
|
// PullImage pulls an image with authentication config.
|
||||||
|
// TODO(mikebrow): add authentication
|
||||||
|
// TODO(mikebrow): harden api (including figuring out at what layer we should be blocking on duplicate requests.)
|
||||||
func (c *criContainerdService) PullImage(ctx context.Context, r *runtime.PullImageRequest) (*runtime.PullImageResponse, error) {
|
func (c *criContainerdService) PullImage(ctx context.Context, r *runtime.PullImageRequest) (*runtime.PullImageResponse, error) {
|
||||||
return nil, errors.New("not implemented")
|
var (
|
||||||
|
err error
|
||||||
|
size int64
|
||||||
|
desc imagespec.Descriptor
|
||||||
|
)
|
||||||
|
|
||||||
|
image := r.GetImage().Image
|
||||||
|
|
||||||
|
if desc, size, err = c.pullImage(ctx, image); err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to pull image %q: %v", image, err)
|
||||||
|
}
|
||||||
|
digest := desc.Digest.String() // TODO(mikebrow): add truncIndex for image id
|
||||||
|
|
||||||
|
// TODO(mikebrow): pass a metadata struct to pullimage and fill in the tags/digests
|
||||||
|
// store the image metadata
|
||||||
|
// TODO(mikebrow): consider what to do if pullimage was called and metadata already exists (error? udpate?)
|
||||||
|
meta := &metadata.ImageMetadata{
|
||||||
|
ID: digest,
|
||||||
|
RepoTags: []string{image},
|
||||||
|
RepoDigests: []string{digest},
|
||||||
|
Size: uint64(size), // TODO(mikebrow): compressed or uncompressed size? using compressed
|
||||||
|
}
|
||||||
|
if err = c.imageMetadataStore.Create(*meta); err != nil {
|
||||||
|
return &runtime.PullImageResponse{ImageRef: digest},
|
||||||
|
fmt.Errorf("pulled image `%q` but failed to store metadata for digest: %s err: %v", image, digest, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return the image digest
|
||||||
|
return &runtime.PullImageResponse{ImageRef: digest}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// imageReferenceResolver attempts to resolve the image reference into a name
|
||||||
|
// and manifest via the containerd library call..
|
||||||
|
//
|
||||||
|
// The argument `ref` should be a scheme-less URI representing the remote.
|
||||||
|
// Structurally, it has a host and path. The "host" can be used to directly
|
||||||
|
// reference a specific host or be matched against a specific handler.
|
||||||
|
//
|
||||||
|
// The returned name should be used to identify the referenced entity.
|
||||||
|
// Dependending on the remote namespace, this may be immutable or mutable.
|
||||||
|
// While the name may differ from ref, it should itself be a valid ref.
|
||||||
|
//
|
||||||
|
// If the resolution fails, an error will be returned.
|
||||||
|
// TODO(mikebrow) add config.json based image.Config as an additional return value from this resolver fn()
|
||||||
|
func (c *criContainerdService) imageReferenceResolver(ctx context.Context, ref string) (resolvedImageName string, manifest imagespec.Manifest, compressedSize uint64, err error) {
|
||||||
|
var (
|
||||||
|
size int64
|
||||||
|
desc imagespec.Descriptor
|
||||||
|
fetcher remotes.Fetcher
|
||||||
|
)
|
||||||
|
|
||||||
|
// Resolve the image name; place that in the image store; then dispatch
|
||||||
|
// a handler to fetch the object for the manifest
|
||||||
|
resolver := docker.NewResolver()
|
||||||
|
resolvedImageName, desc, fetcher, err = resolver.Resolve(ctx, ref)
|
||||||
|
if err != nil {
|
||||||
|
return resolvedImageName, manifest, compressedSize, fmt.Errorf("failed to resolve ref %q: err: %v", ref, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = c.imageStore.Put(ctx, resolvedImageName, desc)
|
||||||
|
if err != nil {
|
||||||
|
return resolvedImageName, manifest, compressedSize, fmt.Errorf("failed to put %q: desc: %v err: %v", resolvedImageName, desc, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = containerdimages.Dispatch(
|
||||||
|
ctx,
|
||||||
|
remotes.FetchHandler(c.contentIngester, fetcher),
|
||||||
|
desc)
|
||||||
|
if err != nil {
|
||||||
|
return resolvedImageName, manifest, compressedSize, fmt.Errorf("failed to fetch %q: desc: %v err: %v", resolvedImageName, desc, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
image, err := c.imageStore.Get(ctx, resolvedImageName)
|
||||||
|
if err != nil {
|
||||||
|
return resolvedImageName, manifest, compressedSize,
|
||||||
|
fmt.Errorf("get failed for image:%q err: %v", resolvedImageName, err)
|
||||||
|
}
|
||||||
|
p, err := content.ReadBlob(ctx, c.contentProvider, image.Target.Digest)
|
||||||
|
if err != nil {
|
||||||
|
return resolvedImageName, manifest, compressedSize,
|
||||||
|
fmt.Errorf("readblob failed for digest:%q err: %v", image.Target.Digest, err)
|
||||||
|
}
|
||||||
|
err = json.Unmarshal(p, &manifest)
|
||||||
|
if err != nil {
|
||||||
|
return resolvedImageName, manifest, compressedSize,
|
||||||
|
fmt.Errorf("unmarshal blob to manifest failed for digest:%q err: %v", image.Target.Digest, err)
|
||||||
|
}
|
||||||
|
size, err = image.Size(ctx, c.contentProvider)
|
||||||
|
if err != nil {
|
||||||
|
return resolvedImageName, manifest, compressedSize,
|
||||||
|
fmt.Errorf("size failed for image:%q %v", image.Target.Digest, err)
|
||||||
|
}
|
||||||
|
compressedSize = uint64(size)
|
||||||
|
return resolvedImageName, manifest, compressedSize, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *criContainerdService) pullImage(ctx context.Context, ref string) (imagespec.Descriptor, int64, error) {
|
||||||
|
var (
|
||||||
|
err error
|
||||||
|
size int64
|
||||||
|
desc imagespec.Descriptor
|
||||||
|
resolvedImageName string
|
||||||
|
fetcher remotes.Fetcher
|
||||||
|
)
|
||||||
|
|
||||||
|
// Resolve the image name; place that in the image store; then dispatch
|
||||||
|
// a handler for a sequence of handlers which: 1) fetch the object using a
|
||||||
|
// FetchHandler; and 3) recurse through any sub-layers via a ChildrenHandler
|
||||||
|
resolver := docker.NewResolver()
|
||||||
|
|
||||||
|
resolvedImageName, desc, fetcher, err = resolver.Resolve(ctx, ref)
|
||||||
|
if err != nil {
|
||||||
|
return desc, size, fmt.Errorf("failed to resolve ref %q: err: %v", ref, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = c.imageStore.Put(ctx, resolvedImageName, desc)
|
||||||
|
if err != nil {
|
||||||
|
return desc, size, fmt.Errorf("failed to put %q: desc: %v err: %v", resolvedImageName, desc, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
err = containerdimages.Dispatch(
|
||||||
|
ctx,
|
||||||
|
containerdimages.Handlers(
|
||||||
|
remotes.FetchHandler(c.contentIngester, fetcher),
|
||||||
|
containerdimages.ChildrenHandler(c.contentProvider)),
|
||||||
|
desc)
|
||||||
|
if err != nil {
|
||||||
|
return desc, size, fmt.Errorf("failed to fetch %q: desc: %v err: %v", resolvedImageName, desc, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
image, err := c.imageStore.Get(ctx, resolvedImageName)
|
||||||
|
if err != nil {
|
||||||
|
return desc, size,
|
||||||
|
fmt.Errorf("get failed for image:%q err: %v", resolvedImageName, err)
|
||||||
|
}
|
||||||
|
p, err := content.ReadBlob(ctx, c.contentProvider, image.Target.Digest)
|
||||||
|
if err != nil {
|
||||||
|
return desc, size,
|
||||||
|
fmt.Errorf("readblob failed for digest:%q err: %v", image.Target.Digest, err)
|
||||||
|
}
|
||||||
|
var manifest imagespec.Manifest
|
||||||
|
err = json.Unmarshal(p, &manifest)
|
||||||
|
if err != nil {
|
||||||
|
return desc, size,
|
||||||
|
fmt.Errorf("unmarshal blob to manifest failed for digest:%q %v", image.Target.Digest, err)
|
||||||
|
}
|
||||||
|
_, err = c.rootfsUnpacker.Unpack(ctx, manifest.Layers) // ignoring returned chainID for now
|
||||||
|
if err != nil {
|
||||||
|
return desc, size,
|
||||||
|
fmt.Errorf("unpack failed for manifest layers:%v %v", manifest.Layers, err)
|
||||||
|
}
|
||||||
|
size, err = image.Size(ctx, c.contentProvider)
|
||||||
|
if err != nil {
|
||||||
|
return desc, size,
|
||||||
|
fmt.Errorf("size failed for image:%q %v", image.Target.Digest, err)
|
||||||
|
}
|
||||||
|
return desc, size, nil
|
||||||
}
|
}
|
||||||
|
@ -17,14 +17,17 @@ limitations under the License.
|
|||||||
package server
|
package server
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
|
|
||||||
"golang.org/x/net/context"
|
"golang.org/x/net/context"
|
||||||
|
|
||||||
"k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
|
"k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
|
||||||
)
|
)
|
||||||
|
|
||||||
// RemoveImage removes the image.
|
// RemoveImage removes the image.
|
||||||
|
// TODO(mikebrow): harden api
|
||||||
func (c *criContainerdService) RemoveImage(ctx context.Context, r *runtime.RemoveImageRequest) (*runtime.RemoveImageResponse, error) {
|
func (c *criContainerdService) RemoveImage(ctx context.Context, r *runtime.RemoveImageRequest) (*runtime.RemoveImageResponse, error) {
|
||||||
return nil, errors.New("not implemented")
|
// Only remove image from the internal metadata store for now.
|
||||||
|
// Note that the image must be digest here in current implementation.
|
||||||
|
// TODO(mikebrow): remove the image via containerd
|
||||||
|
err := c.imageMetadataStore.Delete(r.GetImage().GetImage())
|
||||||
|
return &runtime.RemoveImageResponse{}, err
|
||||||
}
|
}
|
||||||
|
@ -17,14 +17,48 @@ limitations under the License.
|
|||||||
package server
|
package server
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
|
|
||||||
"golang.org/x/net/context"
|
"golang.org/x/net/context"
|
||||||
|
|
||||||
"k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
|
"k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ImageStatus returns the status of the image, returns nil if the image doesn't present.
|
// ImageStatus returns the status of the image, returns nil if the image isn't present.
|
||||||
func (c *criContainerdService) ImageStatus(ctx context.Context, r *runtime.ImageStatusRequest) (*runtime.ImageStatusResponse, error) {
|
func (c *criContainerdService) ImageStatus(ctx context.Context, r *runtime.ImageStatusRequest) (*runtime.ImageStatusResponse, error) {
|
||||||
return nil, errors.New("not implemented")
|
ref := r.GetImage().GetImage()
|
||||||
|
// TODO(mikebrow): Get the id->tags, and id->digest mapping from our checkpoint;
|
||||||
|
// Get other information from containerd image/content store
|
||||||
|
|
||||||
|
// if the passed ref is a digest.. and is stored the following get should work
|
||||||
|
// note: get returns nil with no err
|
||||||
|
meta, _ := c.imageMetadataStore.Get(ref)
|
||||||
|
if meta != nil {
|
||||||
|
return &runtime.ImageStatusResponse{Image: &runtime.Image{ // TODO(mikebrow): write a ImageMetadata to runtim.Image converter
|
||||||
|
Id: meta.ID,
|
||||||
|
RepoTags: meta.RepoTags,
|
||||||
|
RepoDigests: meta.RepoDigests,
|
||||||
|
Size_: meta.Size,
|
||||||
|
// TODO(mikebrow): Uid and Username?
|
||||||
|
}}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Search for image by ref in repo tags if found the ID matching ref
|
||||||
|
// is our digest.
|
||||||
|
imageMetadataA, err := c.imageMetadataStore.List()
|
||||||
|
if err == nil {
|
||||||
|
for _, meta := range imageMetadataA {
|
||||||
|
for _, tag := range meta.RepoTags {
|
||||||
|
if ref == tag {
|
||||||
|
return &runtime.ImageStatusResponse{Image: &runtime.Image{ // TODO(mikebrow): write a ImageMetadata to runtim.Image converter
|
||||||
|
Id: meta.ID,
|
||||||
|
RepoTags: meta.RepoTags,
|
||||||
|
RepoDigests: meta.RepoDigests,
|
||||||
|
Size_: meta.Size,
|
||||||
|
// TODO(mikebrow): Uid and Username?
|
||||||
|
}}, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
@ -19,15 +19,23 @@ package server
|
|||||||
import (
|
import (
|
||||||
"google.golang.org/grpc"
|
"google.golang.org/grpc"
|
||||||
|
|
||||||
|
contentapi "github.com/containerd/containerd/api/services/content"
|
||||||
|
"github.com/containerd/containerd/api/services/execution"
|
||||||
|
imagesapi "github.com/containerd/containerd/api/services/images"
|
||||||
|
rootfsapi "github.com/containerd/containerd/api/services/rootfs"
|
||||||
|
"github.com/containerd/containerd/content"
|
||||||
|
"github.com/containerd/containerd/images"
|
||||||
|
"github.com/containerd/containerd/rootfs"
|
||||||
|
contentservice "github.com/containerd/containerd/services/content"
|
||||||
|
imagesservice "github.com/containerd/containerd/services/images"
|
||||||
|
rootfsservice "github.com/containerd/containerd/services/rootfs"
|
||||||
|
"github.com/kubernetes-incubator/cri-containerd/pkg/metadata"
|
||||||
|
"github.com/kubernetes-incubator/cri-containerd/pkg/metadata/store"
|
||||||
"k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
|
"k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
|
||||||
|
|
||||||
// TODO remove the underscores from the following imports as the services are
|
// TODO remove the underscores from the following imports as the services are
|
||||||
// implemented. "_" is being used to hold the reference to keep autocomplete
|
// implemented. "_" is being used to hold the reference to keep autocomplete
|
||||||
// from deleting them until referenced below.
|
// from deleting them until referenced below.
|
||||||
_ "github.com/containerd/containerd/api/services/content"
|
|
||||||
_ "github.com/containerd/containerd/api/services/execution"
|
|
||||||
_ "github.com/containerd/containerd/api/services/images"
|
|
||||||
_ "github.com/containerd/containerd/api/services/rootfs"
|
|
||||||
_ "github.com/containerd/containerd/api/types/container"
|
_ "github.com/containerd/containerd/api/types/container"
|
||||||
_ "github.com/containerd/containerd/api/types/descriptor"
|
_ "github.com/containerd/containerd/api/types/descriptor"
|
||||||
_ "github.com/containerd/containerd/api/types/mount"
|
_ "github.com/containerd/containerd/api/types/mount"
|
||||||
@ -42,10 +50,24 @@ type CRIContainerdService interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// criContainerdService implements CRIContainerdService.
|
// criContainerdService implements CRIContainerdService.
|
||||||
type criContainerdService struct{}
|
type criContainerdService struct {
|
||||||
|
containerService execution.ContainerServiceClient
|
||||||
|
imageStore images.Store
|
||||||
|
contentIngester content.Ingester
|
||||||
|
contentProvider content.Provider
|
||||||
|
rootfsUnpacker rootfs.Unpacker
|
||||||
|
imageMetadataStore metadata.ImageMetadataStore
|
||||||
|
}
|
||||||
|
|
||||||
// NewCRIContainerdService returns a new instance of CRIContainerdService
|
// NewCRIContainerdService returns a new instance of CRIContainerdService
|
||||||
func NewCRIContainerdService(conn *grpc.ClientConn) CRIContainerdService {
|
func NewCRIContainerdService(conn *grpc.ClientConn) CRIContainerdService {
|
||||||
// TODO: Initialize different containerd clients.
|
// TODO: Initialize different containerd clients.
|
||||||
return &criContainerdService{}
|
return &criContainerdService{
|
||||||
|
containerService: execution.NewContainerServiceClient(conn),
|
||||||
|
imageStore: imagesservice.NewStoreFromClient(imagesapi.NewImagesClient(conn)),
|
||||||
|
contentIngester: contentservice.NewIngesterFromClient(contentapi.NewContentClient(conn)),
|
||||||
|
contentProvider: contentservice.NewProviderFromClient(contentapi.NewContentClient(conn)),
|
||||||
|
rootfsUnpacker: rootfsservice.NewUnpackerFromClient(rootfsapi.NewRootFSClient(conn)),
|
||||||
|
imageMetadataStore: metadata.NewImageMetadataStore(store.NewMetadataStore()),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
1
vendor/github.com/Microsoft/go-winio/.gitignore
generated
vendored
Normal file
1
vendor/github.com/Microsoft/go-winio/.gitignore
generated
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
*.exe
|
22
vendor/github.com/Microsoft/go-winio/LICENSE
generated
vendored
Normal file
22
vendor/github.com/Microsoft/go-winio/LICENSE
generated
vendored
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (c) 2015 Microsoft
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
|
|
22
vendor/github.com/Microsoft/go-winio/README.md
generated
vendored
Normal file
22
vendor/github.com/Microsoft/go-winio/README.md
generated
vendored
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
# go-winio
|
||||||
|
|
||||||
|
This repository contains utilities for efficiently performing Win32 IO operations in
|
||||||
|
Go. Currently, this is focused on accessing named pipes and other file handles, and
|
||||||
|
for using named pipes as a net transport.
|
||||||
|
|
||||||
|
This code relies on IO completion ports to avoid blocking IO on system threads, allowing Go
|
||||||
|
to reuse the thread to schedule another goroutine. This limits support to Windows Vista and
|
||||||
|
newer operating systems. This is similar to the implementation of network sockets in Go's net
|
||||||
|
package.
|
||||||
|
|
||||||
|
Please see the LICENSE file for licensing information.
|
||||||
|
|
||||||
|
This project has adopted the [Microsoft Open Source Code of
|
||||||
|
Conduct](https://opensource.microsoft.com/codeofconduct/). For more information
|
||||||
|
see the [Code of Conduct
|
||||||
|
FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact
|
||||||
|
[opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional
|
||||||
|
questions or comments.
|
||||||
|
|
||||||
|
Thanks to natefinch for the inspiration for this library. See https://github.com/natefinch/npipe
|
||||||
|
for another named pipe implementation.
|
268
vendor/github.com/Microsoft/go-winio/backup.go
generated
vendored
Normal file
268
vendor/github.com/Microsoft/go-winio/backup.go
generated
vendored
Normal file
@ -0,0 +1,268 @@
|
|||||||
|
// +build windows
|
||||||
|
|
||||||
|
package winio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/ioutil"
|
||||||
|
"os"
|
||||||
|
"runtime"
|
||||||
|
"syscall"
|
||||||
|
"unicode/utf16"
|
||||||
|
)
|
||||||
|
|
||||||
|
//sys backupRead(h syscall.Handle, b []byte, bytesRead *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupRead
|
||||||
|
//sys backupWrite(h syscall.Handle, b []byte, bytesWritten *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupWrite
|
||||||
|
|
||||||
|
const (
|
||||||
|
BackupData = uint32(iota + 1)
|
||||||
|
BackupEaData
|
||||||
|
BackupSecurity
|
||||||
|
BackupAlternateData
|
||||||
|
BackupLink
|
||||||
|
BackupPropertyData
|
||||||
|
BackupObjectId
|
||||||
|
BackupReparseData
|
||||||
|
BackupSparseBlock
|
||||||
|
BackupTxfsData
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
StreamSparseAttributes = uint32(8)
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
WRITE_DAC = 0x40000
|
||||||
|
WRITE_OWNER = 0x80000
|
||||||
|
ACCESS_SYSTEM_SECURITY = 0x1000000
|
||||||
|
)
|
||||||
|
|
||||||
|
// BackupHeader represents a backup stream of a file.
|
||||||
|
type BackupHeader struct {
|
||||||
|
Id uint32 // The backup stream ID
|
||||||
|
Attributes uint32 // Stream attributes
|
||||||
|
Size int64 // The size of the stream in bytes
|
||||||
|
Name string // The name of the stream (for BackupAlternateData only).
|
||||||
|
Offset int64 // The offset of the stream in the file (for BackupSparseBlock only).
|
||||||
|
}
|
||||||
|
|
||||||
|
type win32StreamId struct {
|
||||||
|
StreamId uint32
|
||||||
|
Attributes uint32
|
||||||
|
Size uint64
|
||||||
|
NameSize uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
// BackupStreamReader reads from a stream produced by the BackupRead Win32 API and produces a series
|
||||||
|
// of BackupHeader values.
|
||||||
|
type BackupStreamReader struct {
|
||||||
|
r io.Reader
|
||||||
|
bytesLeft int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewBackupStreamReader produces a BackupStreamReader from any io.Reader.
|
||||||
|
func NewBackupStreamReader(r io.Reader) *BackupStreamReader {
|
||||||
|
return &BackupStreamReader{r, 0}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Next returns the next backup stream and prepares for calls to Write(). It skips the remainder of the current stream if
|
||||||
|
// it was not completely read.
|
||||||
|
func (r *BackupStreamReader) Next() (*BackupHeader, error) {
|
||||||
|
if r.bytesLeft > 0 {
|
||||||
|
if _, err := io.Copy(ioutil.Discard, r); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var wsi win32StreamId
|
||||||
|
if err := binary.Read(r.r, binary.LittleEndian, &wsi); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
hdr := &BackupHeader{
|
||||||
|
Id: wsi.StreamId,
|
||||||
|
Attributes: wsi.Attributes,
|
||||||
|
Size: int64(wsi.Size),
|
||||||
|
}
|
||||||
|
if wsi.NameSize != 0 {
|
||||||
|
name := make([]uint16, int(wsi.NameSize/2))
|
||||||
|
if err := binary.Read(r.r, binary.LittleEndian, name); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
hdr.Name = syscall.UTF16ToString(name)
|
||||||
|
}
|
||||||
|
if wsi.StreamId == BackupSparseBlock {
|
||||||
|
if err := binary.Read(r.r, binary.LittleEndian, &hdr.Offset); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
hdr.Size -= 8
|
||||||
|
}
|
||||||
|
r.bytesLeft = hdr.Size
|
||||||
|
return hdr, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read reads from the current backup stream.
|
||||||
|
func (r *BackupStreamReader) Read(b []byte) (int, error) {
|
||||||
|
if r.bytesLeft == 0 {
|
||||||
|
return 0, io.EOF
|
||||||
|
}
|
||||||
|
if int64(len(b)) > r.bytesLeft {
|
||||||
|
b = b[:r.bytesLeft]
|
||||||
|
}
|
||||||
|
n, err := r.r.Read(b)
|
||||||
|
r.bytesLeft -= int64(n)
|
||||||
|
if err == io.EOF {
|
||||||
|
err = io.ErrUnexpectedEOF
|
||||||
|
} else if r.bytesLeft == 0 && err == nil {
|
||||||
|
err = io.EOF
|
||||||
|
}
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// BackupStreamWriter writes a stream compatible with the BackupWrite Win32 API.
|
||||||
|
type BackupStreamWriter struct {
|
||||||
|
w io.Writer
|
||||||
|
bytesLeft int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewBackupStreamWriter produces a BackupStreamWriter on top of an io.Writer.
|
||||||
|
func NewBackupStreamWriter(w io.Writer) *BackupStreamWriter {
|
||||||
|
return &BackupStreamWriter{w, 0}
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteHeader writes the next backup stream header and prepares for calls to Write().
|
||||||
|
func (w *BackupStreamWriter) WriteHeader(hdr *BackupHeader) error {
|
||||||
|
if w.bytesLeft != 0 {
|
||||||
|
return fmt.Errorf("missing %d bytes", w.bytesLeft)
|
||||||
|
}
|
||||||
|
name := utf16.Encode([]rune(hdr.Name))
|
||||||
|
wsi := win32StreamId{
|
||||||
|
StreamId: hdr.Id,
|
||||||
|
Attributes: hdr.Attributes,
|
||||||
|
Size: uint64(hdr.Size),
|
||||||
|
NameSize: uint32(len(name) * 2),
|
||||||
|
}
|
||||||
|
if hdr.Id == BackupSparseBlock {
|
||||||
|
// Include space for the int64 block offset
|
||||||
|
wsi.Size += 8
|
||||||
|
}
|
||||||
|
if err := binary.Write(w.w, binary.LittleEndian, &wsi); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(name) != 0 {
|
||||||
|
if err := binary.Write(w.w, binary.LittleEndian, name); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if hdr.Id == BackupSparseBlock {
|
||||||
|
if err := binary.Write(w.w, binary.LittleEndian, hdr.Offset); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w.bytesLeft = hdr.Size
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write writes to the current backup stream.
|
||||||
|
func (w *BackupStreamWriter) Write(b []byte) (int, error) {
|
||||||
|
if w.bytesLeft < int64(len(b)) {
|
||||||
|
return 0, fmt.Errorf("too many bytes by %d", int64(len(b))-w.bytesLeft)
|
||||||
|
}
|
||||||
|
n, err := w.w.Write(b)
|
||||||
|
w.bytesLeft -= int64(n)
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// BackupFileReader provides an io.ReadCloser interface on top of the BackupRead Win32 API.
|
||||||
|
type BackupFileReader struct {
|
||||||
|
f *os.File
|
||||||
|
includeSecurity bool
|
||||||
|
ctx uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewBackupFileReader returns a new BackupFileReader from a file handle. If includeSecurity is true,
|
||||||
|
// Read will attempt to read the security descriptor of the file.
|
||||||
|
func NewBackupFileReader(f *os.File, includeSecurity bool) *BackupFileReader {
|
||||||
|
r := &BackupFileReader{f, includeSecurity, 0}
|
||||||
|
runtime.SetFinalizer(r, func(r *BackupFileReader) { r.Close() })
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read reads a backup stream from the file by calling the Win32 API BackupRead().
|
||||||
|
func (r *BackupFileReader) Read(b []byte) (int, error) {
|
||||||
|
var bytesRead uint32
|
||||||
|
err := backupRead(syscall.Handle(r.f.Fd()), b, &bytesRead, false, r.includeSecurity, &r.ctx)
|
||||||
|
if err != nil {
|
||||||
|
return 0, &os.PathError{"BackupRead", r.f.Name(), err}
|
||||||
|
}
|
||||||
|
if bytesRead == 0 {
|
||||||
|
return 0, io.EOF
|
||||||
|
}
|
||||||
|
return int(bytesRead), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close frees Win32 resources associated with the BackupFileReader. It does not close
|
||||||
|
// the underlying file.
|
||||||
|
func (r *BackupFileReader) Close() error {
|
||||||
|
if r.ctx != 0 {
|
||||||
|
backupRead(syscall.Handle(r.f.Fd()), nil, nil, true, false, &r.ctx)
|
||||||
|
r.ctx = 0
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// BackupFileWriter provides an io.WriteCloser interface on top of the BackupWrite Win32 API.
|
||||||
|
type BackupFileWriter struct {
|
||||||
|
f *os.File
|
||||||
|
includeSecurity bool
|
||||||
|
ctx uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewBackupFileWrtier returns a new BackupFileWriter from a file handle. If includeSecurity is true,
|
||||||
|
// Write() will attempt to restore the security descriptor from the stream.
|
||||||
|
func NewBackupFileWriter(f *os.File, includeSecurity bool) *BackupFileWriter {
|
||||||
|
w := &BackupFileWriter{f, includeSecurity, 0}
|
||||||
|
runtime.SetFinalizer(w, func(w *BackupFileWriter) { w.Close() })
|
||||||
|
return w
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write restores a portion of the file using the provided backup stream.
|
||||||
|
func (w *BackupFileWriter) Write(b []byte) (int, error) {
|
||||||
|
var bytesWritten uint32
|
||||||
|
err := backupWrite(syscall.Handle(w.f.Fd()), b, &bytesWritten, false, w.includeSecurity, &w.ctx)
|
||||||
|
if err != nil {
|
||||||
|
return 0, &os.PathError{"BackupWrite", w.f.Name(), err}
|
||||||
|
}
|
||||||
|
if int(bytesWritten) != len(b) {
|
||||||
|
return int(bytesWritten), errors.New("not all bytes could be written")
|
||||||
|
}
|
||||||
|
return len(b), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close frees Win32 resources associated with the BackupFileWriter. It does not
|
||||||
|
// close the underlying file.
|
||||||
|
func (w *BackupFileWriter) Close() error {
|
||||||
|
if w.ctx != 0 {
|
||||||
|
backupWrite(syscall.Handle(w.f.Fd()), nil, nil, true, false, &w.ctx)
|
||||||
|
w.ctx = 0
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// OpenForBackup opens a file or directory, potentially skipping access checks if the backup
|
||||||
|
// or restore privileges have been acquired.
|
||||||
|
//
|
||||||
|
// If the file opened was a directory, it cannot be used with Readdir().
|
||||||
|
func OpenForBackup(path string, access uint32, share uint32, createmode uint32) (*os.File, error) {
|
||||||
|
winPath, err := syscall.UTF16FromString(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
h, err := syscall.CreateFile(&winPath[0], access, share, nil, createmode, syscall.FILE_FLAG_BACKUP_SEMANTICS|syscall.FILE_FLAG_OPEN_REPARSE_POINT, 0)
|
||||||
|
if err != nil {
|
||||||
|
err = &os.PathError{Op: "open", Path: path, Err: err}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return os.NewFile(uintptr(h), path), nil
|
||||||
|
}
|
221
vendor/github.com/Microsoft/go-winio/file.go
generated
vendored
Normal file
221
vendor/github.com/Microsoft/go-winio/file.go
generated
vendored
Normal file
@ -0,0 +1,221 @@
|
|||||||
|
// +build windows
|
||||||
|
|
||||||
|
package winio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"runtime"
|
||||||
|
"sync"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
//sys cancelIoEx(file syscall.Handle, o *syscall.Overlapped) (err error) = CancelIoEx
|
||||||
|
//sys createIoCompletionPort(file syscall.Handle, port syscall.Handle, key uintptr, threadCount uint32) (newport syscall.Handle, err error) = CreateIoCompletionPort
|
||||||
|
//sys getQueuedCompletionStatus(port syscall.Handle, bytes *uint32, key *uintptr, o **ioOperation, timeout uint32) (err error) = GetQueuedCompletionStatus
|
||||||
|
//sys setFileCompletionNotificationModes(h syscall.Handle, flags uint8) (err error) = SetFileCompletionNotificationModes
|
||||||
|
//sys timeBeginPeriod(period uint32) (n int32) = winmm.timeBeginPeriod
|
||||||
|
|
||||||
|
const (
|
||||||
|
cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS = 1
|
||||||
|
cFILE_SKIP_SET_EVENT_ON_HANDLE = 2
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
ErrFileClosed = errors.New("file has already been closed")
|
||||||
|
ErrTimeout = &timeoutError{}
|
||||||
|
)
|
||||||
|
|
||||||
|
type timeoutError struct{}
|
||||||
|
|
||||||
|
func (e *timeoutError) Error() string { return "i/o timeout" }
|
||||||
|
func (e *timeoutError) Timeout() bool { return true }
|
||||||
|
func (e *timeoutError) Temporary() bool { return true }
|
||||||
|
|
||||||
|
var ioInitOnce sync.Once
|
||||||
|
var ioCompletionPort syscall.Handle
|
||||||
|
|
||||||
|
// ioResult contains the result of an asynchronous IO operation
|
||||||
|
type ioResult struct {
|
||||||
|
bytes uint32
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
// ioOperation represents an outstanding asynchronous Win32 IO
|
||||||
|
type ioOperation struct {
|
||||||
|
o syscall.Overlapped
|
||||||
|
ch chan ioResult
|
||||||
|
}
|
||||||
|
|
||||||
|
func initIo() {
|
||||||
|
h, err := createIoCompletionPort(syscall.InvalidHandle, 0, 0, 0xffffffff)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
ioCompletionPort = h
|
||||||
|
go ioCompletionProcessor(h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// win32File implements Reader, Writer, and Closer on a Win32 handle without blocking in a syscall.
|
||||||
|
// It takes ownership of this handle and will close it if it is garbage collected.
|
||||||
|
type win32File struct {
|
||||||
|
handle syscall.Handle
|
||||||
|
wg sync.WaitGroup
|
||||||
|
closing bool
|
||||||
|
readDeadline time.Time
|
||||||
|
writeDeadline time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
// makeWin32File makes a new win32File from an existing file handle
|
||||||
|
func makeWin32File(h syscall.Handle) (*win32File, error) {
|
||||||
|
f := &win32File{handle: h}
|
||||||
|
ioInitOnce.Do(initIo)
|
||||||
|
_, err := createIoCompletionPort(h, ioCompletionPort, 0, 0xffffffff)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
err = setFileCompletionNotificationModes(h, cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS|cFILE_SKIP_SET_EVENT_ON_HANDLE)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
runtime.SetFinalizer(f, (*win32File).closeHandle)
|
||||||
|
return f, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func MakeOpenFile(h syscall.Handle) (io.ReadWriteCloser, error) {
|
||||||
|
return makeWin32File(h)
|
||||||
|
}
|
||||||
|
|
||||||
|
// closeHandle closes the resources associated with a Win32 handle
|
||||||
|
func (f *win32File) closeHandle() {
|
||||||
|
if !f.closing {
|
||||||
|
// cancel all IO and wait for it to complete
|
||||||
|
f.closing = true
|
||||||
|
cancelIoEx(f.handle, nil)
|
||||||
|
f.wg.Wait()
|
||||||
|
// at this point, no new IO can start
|
||||||
|
syscall.Close(f.handle)
|
||||||
|
f.handle = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close closes a win32File.
|
||||||
|
func (f *win32File) Close() error {
|
||||||
|
f.closeHandle()
|
||||||
|
runtime.SetFinalizer(f, nil)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// prepareIo prepares for a new IO operation
|
||||||
|
func (f *win32File) prepareIo() (*ioOperation, error) {
|
||||||
|
f.wg.Add(1)
|
||||||
|
if f.closing {
|
||||||
|
return nil, ErrFileClosed
|
||||||
|
}
|
||||||
|
c := &ioOperation{}
|
||||||
|
c.ch = make(chan ioResult)
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ioCompletionProcessor processes completed async IOs forever
|
||||||
|
func ioCompletionProcessor(h syscall.Handle) {
|
||||||
|
// Set the timer resolution to 1. This fixes a performance regression in golang 1.6.
|
||||||
|
timeBeginPeriod(1)
|
||||||
|
for {
|
||||||
|
var bytes uint32
|
||||||
|
var key uintptr
|
||||||
|
var op *ioOperation
|
||||||
|
err := getQueuedCompletionStatus(h, &bytes, &key, &op, syscall.INFINITE)
|
||||||
|
if op == nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
op.ch <- ioResult{bytes, err}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// asyncIo processes the return value from ReadFile or WriteFile, blocking until
|
||||||
|
// the operation has actually completed.
|
||||||
|
func (f *win32File) asyncIo(c *ioOperation, deadline time.Time, bytes uint32, err error) (int, error) {
|
||||||
|
if err != syscall.ERROR_IO_PENDING {
|
||||||
|
f.wg.Done()
|
||||||
|
return int(bytes), err
|
||||||
|
} else {
|
||||||
|
var r ioResult
|
||||||
|
wait := true
|
||||||
|
timedout := false
|
||||||
|
if f.closing {
|
||||||
|
cancelIoEx(f.handle, &c.o)
|
||||||
|
} else if !deadline.IsZero() {
|
||||||
|
now := time.Now()
|
||||||
|
if !deadline.After(now) {
|
||||||
|
timedout = true
|
||||||
|
} else {
|
||||||
|
timeout := time.After(deadline.Sub(now))
|
||||||
|
select {
|
||||||
|
case r = <-c.ch:
|
||||||
|
wait = false
|
||||||
|
case <-timeout:
|
||||||
|
timedout = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if timedout {
|
||||||
|
cancelIoEx(f.handle, &c.o)
|
||||||
|
}
|
||||||
|
if wait {
|
||||||
|
r = <-c.ch
|
||||||
|
}
|
||||||
|
err = r.err
|
||||||
|
if err == syscall.ERROR_OPERATION_ABORTED {
|
||||||
|
if f.closing {
|
||||||
|
err = ErrFileClosed
|
||||||
|
} else if timedout {
|
||||||
|
err = ErrTimeout
|
||||||
|
}
|
||||||
|
}
|
||||||
|
f.wg.Done()
|
||||||
|
return int(r.bytes), err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read reads from a file handle.
|
||||||
|
func (f *win32File) Read(b []byte) (int, error) {
|
||||||
|
c, err := f.prepareIo()
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
var bytes uint32
|
||||||
|
err = syscall.ReadFile(f.handle, b, &bytes, &c.o)
|
||||||
|
n, err := f.asyncIo(c, f.readDeadline, bytes, err)
|
||||||
|
|
||||||
|
// Handle EOF conditions.
|
||||||
|
if err == nil && n == 0 && len(b) != 0 {
|
||||||
|
return 0, io.EOF
|
||||||
|
} else if err == syscall.ERROR_BROKEN_PIPE {
|
||||||
|
return 0, io.EOF
|
||||||
|
} else {
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write writes to a file handle.
|
||||||
|
func (f *win32File) Write(b []byte) (int, error) {
|
||||||
|
c, err := f.prepareIo()
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
var bytes uint32
|
||||||
|
err = syscall.WriteFile(f.handle, b, &bytes, &c.o)
|
||||||
|
return f.asyncIo(c, f.writeDeadline, bytes, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *win32File) SetReadDeadline(t time.Time) error {
|
||||||
|
f.readDeadline = t
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *win32File) SetWriteDeadline(t time.Time) error {
|
||||||
|
f.writeDeadline = t
|
||||||
|
return nil
|
||||||
|
}
|
56
vendor/github.com/Microsoft/go-winio/fileinfo.go
generated
vendored
Normal file
56
vendor/github.com/Microsoft/go-winio/fileinfo.go
generated
vendored
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
// +build windows
|
||||||
|
|
||||||
|
package winio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
//sys getFileInformationByHandleEx(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) = GetFileInformationByHandleEx
|
||||||
|
//sys setFileInformationByHandle(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) = SetFileInformationByHandle
|
||||||
|
|
||||||
|
const (
|
||||||
|
fileBasicInfo = 0
|
||||||
|
fileIDInfo = 0x12
|
||||||
|
)
|
||||||
|
|
||||||
|
// FileBasicInfo contains file access time and file attributes information.
|
||||||
|
type FileBasicInfo struct {
|
||||||
|
CreationTime, LastAccessTime, LastWriteTime, ChangeTime syscall.Filetime
|
||||||
|
FileAttributes uintptr // includes padding
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFileBasicInfo retrieves times and attributes for a file.
|
||||||
|
func GetFileBasicInfo(f *os.File) (*FileBasicInfo, error) {
|
||||||
|
bi := &FileBasicInfo{}
|
||||||
|
if err := getFileInformationByHandleEx(syscall.Handle(f.Fd()), fileBasicInfo, (*byte)(unsafe.Pointer(bi)), uint32(unsafe.Sizeof(*bi))); err != nil {
|
||||||
|
return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err}
|
||||||
|
}
|
||||||
|
return bi, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetFileBasicInfo sets times and attributes for a file.
|
||||||
|
func SetFileBasicInfo(f *os.File, bi *FileBasicInfo) error {
|
||||||
|
if err := setFileInformationByHandle(syscall.Handle(f.Fd()), fileBasicInfo, (*byte)(unsafe.Pointer(bi)), uint32(unsafe.Sizeof(*bi))); err != nil {
|
||||||
|
return &os.PathError{Op: "SetFileInformationByHandle", Path: f.Name(), Err: err}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileIDInfo contains the volume serial number and file ID for a file. This pair should be
|
||||||
|
// unique on a system.
|
||||||
|
type FileIDInfo struct {
|
||||||
|
VolumeSerialNumber uint64
|
||||||
|
FileID [16]byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFileID retrieves the unique (volume, file ID) pair for a file.
|
||||||
|
func GetFileID(f *os.File) (*FileIDInfo, error) {
|
||||||
|
fileID := &FileIDInfo{}
|
||||||
|
if err := getFileInformationByHandleEx(syscall.Handle(f.Fd()), fileIDInfo, (*byte)(unsafe.Pointer(fileID)), uint32(unsafe.Sizeof(*fileID))); err != nil {
|
||||||
|
return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err}
|
||||||
|
}
|
||||||
|
return fileID, nil
|
||||||
|
}
|
400
vendor/github.com/Microsoft/go-winio/pipe.go
generated
vendored
Normal file
400
vendor/github.com/Microsoft/go-winio/pipe.go
generated
vendored
Normal file
@ -0,0 +1,400 @@
|
|||||||
|
// +build windows
|
||||||
|
|
||||||
|
package winio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
//sys connectNamedPipe(pipe syscall.Handle, o *syscall.Overlapped) (err error) = ConnectNamedPipe
|
||||||
|
//sys createNamedPipe(name string, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *securityAttributes) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateNamedPipeW
|
||||||
|
//sys createFile(name string, access uint32, mode uint32, sa *securityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateFileW
|
||||||
|
//sys waitNamedPipe(name string, timeout uint32) (err error) = WaitNamedPipeW
|
||||||
|
//sys getNamedPipeInfo(pipe syscall.Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) = GetNamedPipeInfo
|
||||||
|
//sys getNamedPipeHandleState(pipe syscall.Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW
|
||||||
|
|
||||||
|
type securityAttributes struct {
|
||||||
|
Length uint32
|
||||||
|
SecurityDescriptor *byte
|
||||||
|
InheritHandle uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
cERROR_PIPE_BUSY = syscall.Errno(231)
|
||||||
|
cERROR_PIPE_CONNECTED = syscall.Errno(535)
|
||||||
|
cERROR_SEM_TIMEOUT = syscall.Errno(121)
|
||||||
|
|
||||||
|
cPIPE_ACCESS_DUPLEX = 0x3
|
||||||
|
cFILE_FLAG_FIRST_PIPE_INSTANCE = 0x80000
|
||||||
|
cSECURITY_SQOS_PRESENT = 0x100000
|
||||||
|
cSECURITY_ANONYMOUS = 0
|
||||||
|
|
||||||
|
cPIPE_REJECT_REMOTE_CLIENTS = 0x8
|
||||||
|
|
||||||
|
cPIPE_UNLIMITED_INSTANCES = 255
|
||||||
|
|
||||||
|
cNMPWAIT_USE_DEFAULT_WAIT = 0
|
||||||
|
cNMPWAIT_NOWAIT = 1
|
||||||
|
|
||||||
|
cPIPE_TYPE_MESSAGE = 4
|
||||||
|
|
||||||
|
cPIPE_READMODE_MESSAGE = 2
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ErrPipeListenerClosed is returned for pipe operations on listeners that have been closed.
|
||||||
|
// This error should match net.errClosing since docker takes a dependency on its text.
|
||||||
|
ErrPipeListenerClosed = errors.New("use of closed network connection")
|
||||||
|
|
||||||
|
errPipeWriteClosed = errors.New("pipe has been closed for write")
|
||||||
|
)
|
||||||
|
|
||||||
|
type win32Pipe struct {
|
||||||
|
*win32File
|
||||||
|
path string
|
||||||
|
}
|
||||||
|
|
||||||
|
type win32MessageBytePipe struct {
|
||||||
|
win32Pipe
|
||||||
|
writeClosed bool
|
||||||
|
readEOF bool
|
||||||
|
}
|
||||||
|
|
||||||
|
type pipeAddress string
|
||||||
|
|
||||||
|
func (f *win32Pipe) LocalAddr() net.Addr {
|
||||||
|
return pipeAddress(f.path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *win32Pipe) RemoteAddr() net.Addr {
|
||||||
|
return pipeAddress(f.path)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *win32Pipe) SetDeadline(t time.Time) error {
|
||||||
|
f.SetReadDeadline(t)
|
||||||
|
f.SetWriteDeadline(t)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CloseWrite closes the write side of a message pipe in byte mode.
|
||||||
|
func (f *win32MessageBytePipe) CloseWrite() error {
|
||||||
|
if f.writeClosed {
|
||||||
|
return errPipeWriteClosed
|
||||||
|
}
|
||||||
|
_, err := f.win32File.Write(nil)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
f.writeClosed = true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write writes bytes to a message pipe in byte mode. Zero-byte writes are ignored, since
|
||||||
|
// they are used to implement CloseWrite().
|
||||||
|
func (f *win32MessageBytePipe) Write(b []byte) (int, error) {
|
||||||
|
if f.writeClosed {
|
||||||
|
return 0, errPipeWriteClosed
|
||||||
|
}
|
||||||
|
if len(b) == 0 {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
return f.win32File.Write(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read reads bytes from a message pipe in byte mode. A read of a zero-byte message on a message
|
||||||
|
// mode pipe will return io.EOF, as will all subsequent reads.
|
||||||
|
func (f *win32MessageBytePipe) Read(b []byte) (int, error) {
|
||||||
|
if f.readEOF {
|
||||||
|
return 0, io.EOF
|
||||||
|
}
|
||||||
|
n, err := f.win32File.Read(b)
|
||||||
|
if err == io.EOF {
|
||||||
|
// If this was the result of a zero-byte read, then
|
||||||
|
// it is possible that the read was due to a zero-size
|
||||||
|
// message. Since we are simulating CloseWrite with a
|
||||||
|
// zero-byte message, ensure that all future Read() calls
|
||||||
|
// also return EOF.
|
||||||
|
f.readEOF = true
|
||||||
|
}
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s pipeAddress) Network() string {
|
||||||
|
return "pipe"
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s pipeAddress) String() string {
|
||||||
|
return string(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DialPipe connects to a named pipe by path, timing out if the connection
|
||||||
|
// takes longer than the specified duration. If timeout is nil, then the timeout
|
||||||
|
// is the default timeout established by the pipe server.
|
||||||
|
func DialPipe(path string, timeout *time.Duration) (net.Conn, error) {
|
||||||
|
var absTimeout time.Time
|
||||||
|
if timeout != nil {
|
||||||
|
absTimeout = time.Now().Add(*timeout)
|
||||||
|
}
|
||||||
|
var err error
|
||||||
|
var h syscall.Handle
|
||||||
|
for {
|
||||||
|
h, err = createFile(path, syscall.GENERIC_READ|syscall.GENERIC_WRITE, 0, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_OVERLAPPED|cSECURITY_SQOS_PRESENT|cSECURITY_ANONYMOUS, 0)
|
||||||
|
if err != cERROR_PIPE_BUSY {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
now := time.Now()
|
||||||
|
var ms uint32
|
||||||
|
if absTimeout.IsZero() {
|
||||||
|
ms = cNMPWAIT_USE_DEFAULT_WAIT
|
||||||
|
} else if now.After(absTimeout) {
|
||||||
|
ms = cNMPWAIT_NOWAIT
|
||||||
|
} else {
|
||||||
|
ms = uint32(absTimeout.Sub(now).Nanoseconds() / 1000 / 1000)
|
||||||
|
}
|
||||||
|
err = waitNamedPipe(path, ms)
|
||||||
|
if err != nil {
|
||||||
|
if err == cERROR_SEM_TIMEOUT {
|
||||||
|
return nil, ErrTimeout
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, &os.PathError{Op: "open", Path: path, Err: err}
|
||||||
|
}
|
||||||
|
|
||||||
|
var flags uint32
|
||||||
|
err = getNamedPipeInfo(h, &flags, nil, nil, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var state uint32
|
||||||
|
err = getNamedPipeHandleState(h, &state, nil, nil, nil, nil, 0)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if state&cPIPE_READMODE_MESSAGE != 0 {
|
||||||
|
return nil, &os.PathError{Op: "open", Path: path, Err: errors.New("message readmode pipes not supported")}
|
||||||
|
}
|
||||||
|
|
||||||
|
f, err := makeWin32File(h)
|
||||||
|
if err != nil {
|
||||||
|
syscall.Close(h)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the pipe is in message mode, return a message byte pipe, which
|
||||||
|
// supports CloseWrite().
|
||||||
|
if flags&cPIPE_TYPE_MESSAGE != 0 {
|
||||||
|
return &win32MessageBytePipe{
|
||||||
|
win32Pipe: win32Pipe{win32File: f, path: path},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return &win32Pipe{win32File: f, path: path}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type acceptResponse struct {
|
||||||
|
f *win32File
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
type win32PipeListener struct {
|
||||||
|
firstHandle syscall.Handle
|
||||||
|
path string
|
||||||
|
securityDescriptor []byte
|
||||||
|
config PipeConfig
|
||||||
|
acceptCh chan (chan acceptResponse)
|
||||||
|
closeCh chan int
|
||||||
|
doneCh chan int
|
||||||
|
}
|
||||||
|
|
||||||
|
func makeServerPipeHandle(path string, securityDescriptor []byte, c *PipeConfig, first bool) (syscall.Handle, error) {
|
||||||
|
var flags uint32 = cPIPE_ACCESS_DUPLEX | syscall.FILE_FLAG_OVERLAPPED
|
||||||
|
if first {
|
||||||
|
flags |= cFILE_FLAG_FIRST_PIPE_INSTANCE
|
||||||
|
}
|
||||||
|
|
||||||
|
var mode uint32 = cPIPE_REJECT_REMOTE_CLIENTS
|
||||||
|
if c.MessageMode {
|
||||||
|
mode |= cPIPE_TYPE_MESSAGE
|
||||||
|
}
|
||||||
|
|
||||||
|
var sa securityAttributes
|
||||||
|
sa.Length = uint32(unsafe.Sizeof(sa))
|
||||||
|
if securityDescriptor != nil {
|
||||||
|
sa.SecurityDescriptor = &securityDescriptor[0]
|
||||||
|
}
|
||||||
|
h, err := createNamedPipe(path, flags, mode, cPIPE_UNLIMITED_INSTANCES, uint32(c.OutputBufferSize), uint32(c.InputBufferSize), 0, &sa)
|
||||||
|
if err != nil {
|
||||||
|
return 0, &os.PathError{Op: "open", Path: path, Err: err}
|
||||||
|
}
|
||||||
|
return h, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *win32PipeListener) makeServerPipe() (*win32File, error) {
|
||||||
|
h, err := makeServerPipeHandle(l.path, l.securityDescriptor, &l.config, false)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
f, err := makeWin32File(h)
|
||||||
|
if err != nil {
|
||||||
|
syscall.Close(h)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return f, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *win32PipeListener) listenerRoutine() {
|
||||||
|
closed := false
|
||||||
|
for !closed {
|
||||||
|
select {
|
||||||
|
case <-l.closeCh:
|
||||||
|
closed = true
|
||||||
|
case responseCh := <-l.acceptCh:
|
||||||
|
p, err := l.makeServerPipe()
|
||||||
|
if err == nil {
|
||||||
|
// Wait for the client to connect.
|
||||||
|
ch := make(chan error)
|
||||||
|
go func() {
|
||||||
|
ch <- connectPipe(p)
|
||||||
|
}()
|
||||||
|
select {
|
||||||
|
case err = <-ch:
|
||||||
|
if err != nil {
|
||||||
|
p.Close()
|
||||||
|
p = nil
|
||||||
|
}
|
||||||
|
case <-l.closeCh:
|
||||||
|
// Abort the connect request by closing the handle.
|
||||||
|
p.Close()
|
||||||
|
p = nil
|
||||||
|
err = <-ch
|
||||||
|
if err == nil || err == ErrFileClosed {
|
||||||
|
err = ErrPipeListenerClosed
|
||||||
|
}
|
||||||
|
closed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
responseCh <- acceptResponse{p, err}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
syscall.Close(l.firstHandle)
|
||||||
|
l.firstHandle = 0
|
||||||
|
// Notify Close() and Accept() callers that the handle has been closed.
|
||||||
|
close(l.doneCh)
|
||||||
|
}
|
||||||
|
|
||||||
|
// PipeConfig contain configuration for the pipe listener.
|
||||||
|
type PipeConfig struct {
|
||||||
|
// SecurityDescriptor contains a Windows security descriptor in SDDL format.
|
||||||
|
SecurityDescriptor string
|
||||||
|
|
||||||
|
// MessageMode determines whether the pipe is in byte or message mode. In either
|
||||||
|
// case the pipe is read in byte mode by default. The only practical difference in
|
||||||
|
// this implementation is that CloseWrite() is only supported for message mode pipes;
|
||||||
|
// CloseWrite() is implemented as a zero-byte write, but zero-byte writes are only
|
||||||
|
// transferred to the reader (and returned as io.EOF in this implementation)
|
||||||
|
// when the pipe is in message mode.
|
||||||
|
MessageMode bool
|
||||||
|
|
||||||
|
// InputBufferSize specifies the size the input buffer, in bytes.
|
||||||
|
InputBufferSize int32
|
||||||
|
|
||||||
|
// OutputBufferSize specifies the size the input buffer, in bytes.
|
||||||
|
OutputBufferSize int32
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListenPipe creates a listener on a Windows named pipe path, e.g. \\.\pipe\mypipe.
|
||||||
|
// The pipe must not already exist.
|
||||||
|
func ListenPipe(path string, c *PipeConfig) (net.Listener, error) {
|
||||||
|
var (
|
||||||
|
sd []byte
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
if c == nil {
|
||||||
|
c = &PipeConfig{}
|
||||||
|
}
|
||||||
|
if c.SecurityDescriptor != "" {
|
||||||
|
sd, err = SddlToSecurityDescriptor(c.SecurityDescriptor)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
h, err := makeServerPipeHandle(path, sd, c, true)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// Immediately open and then close a client handle so that the named pipe is
|
||||||
|
// created but not currently accepting connections.
|
||||||
|
h2, err := createFile(path, 0, 0, nil, syscall.OPEN_EXISTING, cSECURITY_SQOS_PRESENT|cSECURITY_ANONYMOUS, 0)
|
||||||
|
if err != nil {
|
||||||
|
syscall.Close(h)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
syscall.Close(h2)
|
||||||
|
l := &win32PipeListener{
|
||||||
|
firstHandle: h,
|
||||||
|
path: path,
|
||||||
|
securityDescriptor: sd,
|
||||||
|
config: *c,
|
||||||
|
acceptCh: make(chan (chan acceptResponse)),
|
||||||
|
closeCh: make(chan int),
|
||||||
|
doneCh: make(chan int),
|
||||||
|
}
|
||||||
|
go l.listenerRoutine()
|
||||||
|
return l, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func connectPipe(p *win32File) error {
|
||||||
|
c, err := p.prepareIo()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
err = connectNamedPipe(p.handle, &c.o)
|
||||||
|
_, err = p.asyncIo(c, time.Time{}, 0, err)
|
||||||
|
if err != nil && err != cERROR_PIPE_CONNECTED {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *win32PipeListener) Accept() (net.Conn, error) {
|
||||||
|
ch := make(chan acceptResponse)
|
||||||
|
select {
|
||||||
|
case l.acceptCh <- ch:
|
||||||
|
response := <-ch
|
||||||
|
err := response.err
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if l.config.MessageMode {
|
||||||
|
return &win32MessageBytePipe{
|
||||||
|
win32Pipe: win32Pipe{win32File: response.f, path: l.path},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return &win32Pipe{win32File: response.f, path: l.path}, nil
|
||||||
|
case <-l.doneCh:
|
||||||
|
return nil, ErrPipeListenerClosed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *win32PipeListener) Close() error {
|
||||||
|
select {
|
||||||
|
case l.closeCh <- 1:
|
||||||
|
<-l.doneCh
|
||||||
|
case <-l.doneCh:
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (l *win32PipeListener) Addr() net.Addr {
|
||||||
|
return pipeAddress(l.path)
|
||||||
|
}
|
202
vendor/github.com/Microsoft/go-winio/privilege.go
generated
vendored
Normal file
202
vendor/github.com/Microsoft/go-winio/privilege.go
generated
vendored
Normal file
@ -0,0 +1,202 @@
|
|||||||
|
// +build windows
|
||||||
|
|
||||||
|
package winio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/binary"
|
||||||
|
"fmt"
|
||||||
|
"runtime"
|
||||||
|
"sync"
|
||||||
|
"syscall"
|
||||||
|
"unicode/utf16"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
//sys adjustTokenPrivileges(token windows.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) [true] = advapi32.AdjustTokenPrivileges
|
||||||
|
//sys impersonateSelf(level uint32) (err error) = advapi32.ImpersonateSelf
|
||||||
|
//sys revertToSelf() (err error) = advapi32.RevertToSelf
|
||||||
|
//sys openThreadToken(thread syscall.Handle, accessMask uint32, openAsSelf bool, token *windows.Token) (err error) = advapi32.OpenThreadToken
|
||||||
|
//sys getCurrentThread() (h syscall.Handle) = GetCurrentThread
|
||||||
|
//sys lookupPrivilegeValue(systemName string, name string, luid *uint64) (err error) = advapi32.LookupPrivilegeValueW
|
||||||
|
//sys lookupPrivilegeName(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) = advapi32.LookupPrivilegeNameW
|
||||||
|
//sys lookupPrivilegeDisplayName(systemName string, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) = advapi32.LookupPrivilegeDisplayNameW
|
||||||
|
|
||||||
|
const (
|
||||||
|
SE_PRIVILEGE_ENABLED = 2
|
||||||
|
|
||||||
|
ERROR_NOT_ALL_ASSIGNED syscall.Errno = 1300
|
||||||
|
|
||||||
|
SeBackupPrivilege = "SeBackupPrivilege"
|
||||||
|
SeRestorePrivilege = "SeRestorePrivilege"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
securityAnonymous = iota
|
||||||
|
securityIdentification
|
||||||
|
securityImpersonation
|
||||||
|
securityDelegation
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
privNames = make(map[string]uint64)
|
||||||
|
privNameMutex sync.Mutex
|
||||||
|
)
|
||||||
|
|
||||||
|
// PrivilegeError represents an error enabling privileges.
|
||||||
|
type PrivilegeError struct {
|
||||||
|
privileges []uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *PrivilegeError) Error() string {
|
||||||
|
s := ""
|
||||||
|
if len(e.privileges) > 1 {
|
||||||
|
s = "Could not enable privileges "
|
||||||
|
} else {
|
||||||
|
s = "Could not enable privilege "
|
||||||
|
}
|
||||||
|
for i, p := range e.privileges {
|
||||||
|
if i != 0 {
|
||||||
|
s += ", "
|
||||||
|
}
|
||||||
|
s += `"`
|
||||||
|
s += getPrivilegeName(p)
|
||||||
|
s += `"`
|
||||||
|
}
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// RunWithPrivilege enables a single privilege for a function call.
|
||||||
|
func RunWithPrivilege(name string, fn func() error) error {
|
||||||
|
return RunWithPrivileges([]string{name}, fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RunWithPrivileges enables privileges for a function call.
|
||||||
|
func RunWithPrivileges(names []string, fn func() error) error {
|
||||||
|
privileges, err := mapPrivileges(names)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
runtime.LockOSThread()
|
||||||
|
defer runtime.UnlockOSThread()
|
||||||
|
token, err := newThreadToken()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer releaseThreadToken(token)
|
||||||
|
err = adjustPrivileges(token, privileges, SE_PRIVILEGE_ENABLED)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return fn()
|
||||||
|
}
|
||||||
|
|
||||||
|
func mapPrivileges(names []string) ([]uint64, error) {
|
||||||
|
var privileges []uint64
|
||||||
|
privNameMutex.Lock()
|
||||||
|
defer privNameMutex.Unlock()
|
||||||
|
for _, name := range names {
|
||||||
|
p, ok := privNames[name]
|
||||||
|
if !ok {
|
||||||
|
err := lookupPrivilegeValue("", name, &p)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
privNames[name] = p
|
||||||
|
}
|
||||||
|
privileges = append(privileges, p)
|
||||||
|
}
|
||||||
|
return privileges, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// EnableProcessPrivileges enables privileges globally for the process.
|
||||||
|
func EnableProcessPrivileges(names []string) error {
|
||||||
|
return enableDisableProcessPrivilege(names, SE_PRIVILEGE_ENABLED)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DisableProcessPrivileges disables privileges globally for the process.
|
||||||
|
func DisableProcessPrivileges(names []string) error {
|
||||||
|
return enableDisableProcessPrivilege(names, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func enableDisableProcessPrivilege(names []string, action uint32) error {
|
||||||
|
privileges, err := mapPrivileges(names)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
p, _ := windows.GetCurrentProcess()
|
||||||
|
var token windows.Token
|
||||||
|
err = windows.OpenProcessToken(p, windows.TOKEN_ADJUST_PRIVILEGES|windows.TOKEN_QUERY, &token)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
defer token.Close()
|
||||||
|
return adjustPrivileges(token, privileges, action)
|
||||||
|
}
|
||||||
|
|
||||||
|
func adjustPrivileges(token windows.Token, privileges []uint64, action uint32) error {
|
||||||
|
var b bytes.Buffer
|
||||||
|
binary.Write(&b, binary.LittleEndian, uint32(len(privileges)))
|
||||||
|
for _, p := range privileges {
|
||||||
|
binary.Write(&b, binary.LittleEndian, p)
|
||||||
|
binary.Write(&b, binary.LittleEndian, action)
|
||||||
|
}
|
||||||
|
prevState := make([]byte, b.Len())
|
||||||
|
reqSize := uint32(0)
|
||||||
|
success, err := adjustTokenPrivileges(token, false, &b.Bytes()[0], uint32(len(prevState)), &prevState[0], &reqSize)
|
||||||
|
if !success {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err == ERROR_NOT_ALL_ASSIGNED {
|
||||||
|
return &PrivilegeError{privileges}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getPrivilegeName(luid uint64) string {
|
||||||
|
var nameBuffer [256]uint16
|
||||||
|
bufSize := uint32(len(nameBuffer))
|
||||||
|
err := lookupPrivilegeName("", &luid, &nameBuffer[0], &bufSize)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Sprintf("<unknown privilege %d>", luid)
|
||||||
|
}
|
||||||
|
|
||||||
|
var displayNameBuffer [256]uint16
|
||||||
|
displayBufSize := uint32(len(displayNameBuffer))
|
||||||
|
var langID uint32
|
||||||
|
err = lookupPrivilegeDisplayName("", &nameBuffer[0], &displayNameBuffer[0], &displayBufSize, &langID)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Sprintf("<unknown privilege %s>", string(utf16.Decode(nameBuffer[:bufSize])))
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(utf16.Decode(displayNameBuffer[:displayBufSize]))
|
||||||
|
}
|
||||||
|
|
||||||
|
func newThreadToken() (windows.Token, error) {
|
||||||
|
err := impersonateSelf(securityImpersonation)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var token windows.Token
|
||||||
|
err = openThreadToken(getCurrentThread(), syscall.TOKEN_ADJUST_PRIVILEGES|syscall.TOKEN_QUERY, false, &token)
|
||||||
|
if err != nil {
|
||||||
|
rerr := revertToSelf()
|
||||||
|
if rerr != nil {
|
||||||
|
panic(rerr)
|
||||||
|
}
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func releaseThreadToken(h windows.Token) {
|
||||||
|
err := revertToSelf()
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
h.Close()
|
||||||
|
}
|
128
vendor/github.com/Microsoft/go-winio/reparse.go
generated
vendored
Normal file
128
vendor/github.com/Microsoft/go-winio/reparse.go
generated
vendored
Normal file
@ -0,0 +1,128 @@
|
|||||||
|
package winio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/binary"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf16"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
reparseTagMountPoint = 0xA0000003
|
||||||
|
reparseTagSymlink = 0xA000000C
|
||||||
|
)
|
||||||
|
|
||||||
|
type reparseDataBuffer struct {
|
||||||
|
ReparseTag uint32
|
||||||
|
ReparseDataLength uint16
|
||||||
|
Reserved uint16
|
||||||
|
SubstituteNameOffset uint16
|
||||||
|
SubstituteNameLength uint16
|
||||||
|
PrintNameOffset uint16
|
||||||
|
PrintNameLength uint16
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReparsePoint describes a Win32 symlink or mount point.
|
||||||
|
type ReparsePoint struct {
|
||||||
|
Target string
|
||||||
|
IsMountPoint bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// UnsupportedReparsePointError is returned when trying to decode a non-symlink or
|
||||||
|
// mount point reparse point.
|
||||||
|
type UnsupportedReparsePointError struct {
|
||||||
|
Tag uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *UnsupportedReparsePointError) Error() string {
|
||||||
|
return fmt.Sprintf("unsupported reparse point %x", e.Tag)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecodeReparsePoint decodes a Win32 REPARSE_DATA_BUFFER structure containing either a symlink
|
||||||
|
// or a mount point.
|
||||||
|
func DecodeReparsePoint(b []byte) (*ReparsePoint, error) {
|
||||||
|
tag := binary.LittleEndian.Uint32(b[0:4])
|
||||||
|
return DecodeReparsePointData(tag, b[8:])
|
||||||
|
}
|
||||||
|
|
||||||
|
func DecodeReparsePointData(tag uint32, b []byte) (*ReparsePoint, error) {
|
||||||
|
isMountPoint := false
|
||||||
|
switch tag {
|
||||||
|
case reparseTagMountPoint:
|
||||||
|
isMountPoint = true
|
||||||
|
case reparseTagSymlink:
|
||||||
|
default:
|
||||||
|
return nil, &UnsupportedReparsePointError{tag}
|
||||||
|
}
|
||||||
|
nameOffset := 8 + binary.LittleEndian.Uint16(b[4:6])
|
||||||
|
if !isMountPoint {
|
||||||
|
nameOffset += 4
|
||||||
|
}
|
||||||
|
nameLength := binary.LittleEndian.Uint16(b[6:8])
|
||||||
|
name := make([]uint16, nameLength/2)
|
||||||
|
err := binary.Read(bytes.NewReader(b[nameOffset:nameOffset+nameLength]), binary.LittleEndian, &name)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &ReparsePoint{string(utf16.Decode(name)), isMountPoint}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func isDriveLetter(c byte) bool {
|
||||||
|
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|
||||||
|
}
|
||||||
|
|
||||||
|
// EncodeReparsePoint encodes a Win32 REPARSE_DATA_BUFFER structure describing a symlink or
|
||||||
|
// mount point.
|
||||||
|
func EncodeReparsePoint(rp *ReparsePoint) []byte {
|
||||||
|
// Generate an NT path and determine if this is a relative path.
|
||||||
|
var ntTarget string
|
||||||
|
relative := false
|
||||||
|
if strings.HasPrefix(rp.Target, `\\?\`) {
|
||||||
|
ntTarget = `\??\` + rp.Target[4:]
|
||||||
|
} else if strings.HasPrefix(rp.Target, `\\`) {
|
||||||
|
ntTarget = `\??\UNC\` + rp.Target[2:]
|
||||||
|
} else if len(rp.Target) >= 2 && isDriveLetter(rp.Target[0]) && rp.Target[1] == ':' {
|
||||||
|
ntTarget = `\??\` + rp.Target
|
||||||
|
} else {
|
||||||
|
ntTarget = rp.Target
|
||||||
|
relative = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// The paths must be NUL-terminated even though they are counted strings.
|
||||||
|
target16 := utf16.Encode([]rune(rp.Target + "\x00"))
|
||||||
|
ntTarget16 := utf16.Encode([]rune(ntTarget + "\x00"))
|
||||||
|
|
||||||
|
size := int(unsafe.Sizeof(reparseDataBuffer{})) - 8
|
||||||
|
size += len(ntTarget16)*2 + len(target16)*2
|
||||||
|
|
||||||
|
tag := uint32(reparseTagMountPoint)
|
||||||
|
if !rp.IsMountPoint {
|
||||||
|
tag = reparseTagSymlink
|
||||||
|
size += 4 // Add room for symlink flags
|
||||||
|
}
|
||||||
|
|
||||||
|
data := reparseDataBuffer{
|
||||||
|
ReparseTag: tag,
|
||||||
|
ReparseDataLength: uint16(size),
|
||||||
|
SubstituteNameOffset: 0,
|
||||||
|
SubstituteNameLength: uint16((len(ntTarget16) - 1) * 2),
|
||||||
|
PrintNameOffset: uint16(len(ntTarget16) * 2),
|
||||||
|
PrintNameLength: uint16((len(target16) - 1) * 2),
|
||||||
|
}
|
||||||
|
|
||||||
|
var b bytes.Buffer
|
||||||
|
binary.Write(&b, binary.LittleEndian, &data)
|
||||||
|
if !rp.IsMountPoint {
|
||||||
|
flags := uint32(0)
|
||||||
|
if relative {
|
||||||
|
flags |= 1
|
||||||
|
}
|
||||||
|
binary.Write(&b, binary.LittleEndian, flags)
|
||||||
|
}
|
||||||
|
|
||||||
|
binary.Write(&b, binary.LittleEndian, ntTarget16)
|
||||||
|
binary.Write(&b, binary.LittleEndian, target16)
|
||||||
|
return b.Bytes()
|
||||||
|
}
|
98
vendor/github.com/Microsoft/go-winio/sd.go
generated
vendored
Normal file
98
vendor/github.com/Microsoft/go-winio/sd.go
generated
vendored
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
// +build windows
|
||||||
|
|
||||||
|
package winio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
//sys lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) = advapi32.LookupAccountNameW
|
||||||
|
//sys convertSidToStringSid(sid *byte, str **uint16) (err error) = advapi32.ConvertSidToStringSidW
|
||||||
|
//sys convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd *uintptr, size *uint32) (err error) = advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW
|
||||||
|
//sys convertSecurityDescriptorToStringSecurityDescriptor(sd *byte, revision uint32, secInfo uint32, sddl **uint16, sddlSize *uint32) (err error) = advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW
|
||||||
|
//sys localFree(mem uintptr) = LocalFree
|
||||||
|
//sys getSecurityDescriptorLength(sd uintptr) (len uint32) = advapi32.GetSecurityDescriptorLength
|
||||||
|
|
||||||
|
const (
|
||||||
|
cERROR_NONE_MAPPED = syscall.Errno(1332)
|
||||||
|
)
|
||||||
|
|
||||||
|
type AccountLookupError struct {
|
||||||
|
Name string
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *AccountLookupError) Error() string {
|
||||||
|
if e.Name == "" {
|
||||||
|
return "lookup account: empty account name specified"
|
||||||
|
}
|
||||||
|
var s string
|
||||||
|
switch e.Err {
|
||||||
|
case cERROR_NONE_MAPPED:
|
||||||
|
s = "not found"
|
||||||
|
default:
|
||||||
|
s = e.Err.Error()
|
||||||
|
}
|
||||||
|
return "lookup account " + e.Name + ": " + s
|
||||||
|
}
|
||||||
|
|
||||||
|
type SddlConversionError struct {
|
||||||
|
Sddl string
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *SddlConversionError) Error() string {
|
||||||
|
return "convert " + e.Sddl + ": " + e.Err.Error()
|
||||||
|
}
|
||||||
|
|
||||||
|
// LookupSidByName looks up the SID of an account by name
|
||||||
|
func LookupSidByName(name string) (sid string, err error) {
|
||||||
|
if name == "" {
|
||||||
|
return "", &AccountLookupError{name, cERROR_NONE_MAPPED}
|
||||||
|
}
|
||||||
|
|
||||||
|
var sidSize, sidNameUse, refDomainSize uint32
|
||||||
|
err = lookupAccountName(nil, name, nil, &sidSize, nil, &refDomainSize, &sidNameUse)
|
||||||
|
if err != nil && err != syscall.ERROR_INSUFFICIENT_BUFFER {
|
||||||
|
return "", &AccountLookupError{name, err}
|
||||||
|
}
|
||||||
|
sidBuffer := make([]byte, sidSize)
|
||||||
|
refDomainBuffer := make([]uint16, refDomainSize)
|
||||||
|
err = lookupAccountName(nil, name, &sidBuffer[0], &sidSize, &refDomainBuffer[0], &refDomainSize, &sidNameUse)
|
||||||
|
if err != nil {
|
||||||
|
return "", &AccountLookupError{name, err}
|
||||||
|
}
|
||||||
|
var strBuffer *uint16
|
||||||
|
err = convertSidToStringSid(&sidBuffer[0], &strBuffer)
|
||||||
|
if err != nil {
|
||||||
|
return "", &AccountLookupError{name, err}
|
||||||
|
}
|
||||||
|
sid = syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(strBuffer))[:])
|
||||||
|
localFree(uintptr(unsafe.Pointer(strBuffer)))
|
||||||
|
return sid, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func SddlToSecurityDescriptor(sddl string) ([]byte, error) {
|
||||||
|
var sdBuffer uintptr
|
||||||
|
err := convertStringSecurityDescriptorToSecurityDescriptor(sddl, 1, &sdBuffer, nil)
|
||||||
|
if err != nil {
|
||||||
|
return nil, &SddlConversionError{sddl, err}
|
||||||
|
}
|
||||||
|
defer localFree(sdBuffer)
|
||||||
|
sd := make([]byte, getSecurityDescriptorLength(sdBuffer))
|
||||||
|
copy(sd, (*[0xffff]byte)(unsafe.Pointer(sdBuffer))[:len(sd)])
|
||||||
|
return sd, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func SecurityDescriptorToSddl(sd []byte) (string, error) {
|
||||||
|
var sddl *uint16
|
||||||
|
// The returned string length seems to including an aribtrary number of terminating NULs.
|
||||||
|
// Don't use it.
|
||||||
|
err := convertSecurityDescriptorToStringSecurityDescriptor(&sd[0], 1, 0xff, &sddl, nil)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
defer localFree(uintptr(unsafe.Pointer(sddl)))
|
||||||
|
return syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(sddl))[:]), nil
|
||||||
|
}
|
3
vendor/github.com/Microsoft/go-winio/syscall.go
generated
vendored
Normal file
3
vendor/github.com/Microsoft/go-winio/syscall.go
generated
vendored
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
package winio
|
||||||
|
|
||||||
|
//go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go file.go pipe.go sd.go fileinfo.go privilege.go backup.go
|
496
vendor/github.com/Microsoft/go-winio/zsyscall_windows.go
generated
vendored
Normal file
496
vendor/github.com/Microsoft/go-winio/zsyscall_windows.go
generated
vendored
Normal file
@ -0,0 +1,496 @@
|
|||||||
|
// MACHINE GENERATED BY 'go generate' COMMAND; DO NOT EDIT
|
||||||
|
|
||||||
|
package winio
|
||||||
|
|
||||||
|
import (
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ unsafe.Pointer
|
||||||
|
|
||||||
|
var (
|
||||||
|
modkernel32 = windows.NewLazySystemDLL("kernel32.dll")
|
||||||
|
modwinmm = windows.NewLazySystemDLL("winmm.dll")
|
||||||
|
modadvapi32 = windows.NewLazySystemDLL("advapi32.dll")
|
||||||
|
|
||||||
|
procCancelIoEx = modkernel32.NewProc("CancelIoEx")
|
||||||
|
procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort")
|
||||||
|
procGetQueuedCompletionStatus = modkernel32.NewProc("GetQueuedCompletionStatus")
|
||||||
|
procSetFileCompletionNotificationModes = modkernel32.NewProc("SetFileCompletionNotificationModes")
|
||||||
|
proctimeBeginPeriod = modwinmm.NewProc("timeBeginPeriod")
|
||||||
|
procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe")
|
||||||
|
procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW")
|
||||||
|
procCreateFileW = modkernel32.NewProc("CreateFileW")
|
||||||
|
procWaitNamedPipeW = modkernel32.NewProc("WaitNamedPipeW")
|
||||||
|
procGetNamedPipeInfo = modkernel32.NewProc("GetNamedPipeInfo")
|
||||||
|
procGetNamedPipeHandleStateW = modkernel32.NewProc("GetNamedPipeHandleStateW")
|
||||||
|
procLookupAccountNameW = modadvapi32.NewProc("LookupAccountNameW")
|
||||||
|
procConvertSidToStringSidW = modadvapi32.NewProc("ConvertSidToStringSidW")
|
||||||
|
procConvertStringSecurityDescriptorToSecurityDescriptorW = modadvapi32.NewProc("ConvertStringSecurityDescriptorToSecurityDescriptorW")
|
||||||
|
procConvertSecurityDescriptorToStringSecurityDescriptorW = modadvapi32.NewProc("ConvertSecurityDescriptorToStringSecurityDescriptorW")
|
||||||
|
procLocalFree = modkernel32.NewProc("LocalFree")
|
||||||
|
procGetSecurityDescriptorLength = modadvapi32.NewProc("GetSecurityDescriptorLength")
|
||||||
|
procGetFileInformationByHandleEx = modkernel32.NewProc("GetFileInformationByHandleEx")
|
||||||
|
procSetFileInformationByHandle = modkernel32.NewProc("SetFileInformationByHandle")
|
||||||
|
procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges")
|
||||||
|
procImpersonateSelf = modadvapi32.NewProc("ImpersonateSelf")
|
||||||
|
procRevertToSelf = modadvapi32.NewProc("RevertToSelf")
|
||||||
|
procOpenThreadToken = modadvapi32.NewProc("OpenThreadToken")
|
||||||
|
procGetCurrentThread = modkernel32.NewProc("GetCurrentThread")
|
||||||
|
procLookupPrivilegeValueW = modadvapi32.NewProc("LookupPrivilegeValueW")
|
||||||
|
procLookupPrivilegeNameW = modadvapi32.NewProc("LookupPrivilegeNameW")
|
||||||
|
procLookupPrivilegeDisplayNameW = modadvapi32.NewProc("LookupPrivilegeDisplayNameW")
|
||||||
|
procBackupRead = modkernel32.NewProc("BackupRead")
|
||||||
|
procBackupWrite = modkernel32.NewProc("BackupWrite")
|
||||||
|
)
|
||||||
|
|
||||||
|
func cancelIoEx(file syscall.Handle, o *syscall.Overlapped) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(file), uintptr(unsafe.Pointer(o)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func createIoCompletionPort(file syscall.Handle, port syscall.Handle, key uintptr, threadCount uint32) (newport syscall.Handle, err error) {
|
||||||
|
r0, _, e1 := syscall.Syscall6(procCreateIoCompletionPort.Addr(), 4, uintptr(file), uintptr(port), uintptr(key), uintptr(threadCount), 0, 0)
|
||||||
|
newport = syscall.Handle(r0)
|
||||||
|
if newport == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func getQueuedCompletionStatus(port syscall.Handle, bytes *uint32, key *uintptr, o **ioOperation, timeout uint32) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall6(procGetQueuedCompletionStatus.Addr(), 5, uintptr(port), uintptr(unsafe.Pointer(bytes)), uintptr(unsafe.Pointer(key)), uintptr(unsafe.Pointer(o)), uintptr(timeout), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func setFileCompletionNotificationModes(h syscall.Handle, flags uint8) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall(procSetFileCompletionNotificationModes.Addr(), 2, uintptr(h), uintptr(flags), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func timeBeginPeriod(period uint32) (n int32) {
|
||||||
|
r0, _, _ := syscall.Syscall(proctimeBeginPeriod.Addr(), 1, uintptr(period), 0, 0)
|
||||||
|
n = int32(r0)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func connectNamedPipe(pipe syscall.Handle, o *syscall.Overlapped) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall(procConnectNamedPipe.Addr(), 2, uintptr(pipe), uintptr(unsafe.Pointer(o)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func createNamedPipe(name string, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *securityAttributes) (handle syscall.Handle, err error) {
|
||||||
|
var _p0 *uint16
|
||||||
|
_p0, err = syscall.UTF16PtrFromString(name)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return _createNamedPipe(_p0, flags, pipeMode, maxInstances, outSize, inSize, defaultTimeout, sa)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _createNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *securityAttributes) (handle syscall.Handle, err error) {
|
||||||
|
r0, _, e1 := syscall.Syscall9(procCreateNamedPipeW.Addr(), 8, uintptr(unsafe.Pointer(name)), uintptr(flags), uintptr(pipeMode), uintptr(maxInstances), uintptr(outSize), uintptr(inSize), uintptr(defaultTimeout), uintptr(unsafe.Pointer(sa)), 0)
|
||||||
|
handle = syscall.Handle(r0)
|
||||||
|
if handle == syscall.InvalidHandle {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func createFile(name string, access uint32, mode uint32, sa *securityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) {
|
||||||
|
var _p0 *uint16
|
||||||
|
_p0, err = syscall.UTF16PtrFromString(name)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return _createFile(_p0, access, mode, sa, createmode, attrs, templatefile)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _createFile(name *uint16, access uint32, mode uint32, sa *securityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) {
|
||||||
|
r0, _, e1 := syscall.Syscall9(procCreateFileW.Addr(), 7, uintptr(unsafe.Pointer(name)), uintptr(access), uintptr(mode), uintptr(unsafe.Pointer(sa)), uintptr(createmode), uintptr(attrs), uintptr(templatefile), 0, 0)
|
||||||
|
handle = syscall.Handle(r0)
|
||||||
|
if handle == syscall.InvalidHandle {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func waitNamedPipe(name string, timeout uint32) (err error) {
|
||||||
|
var _p0 *uint16
|
||||||
|
_p0, err = syscall.UTF16PtrFromString(name)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return _waitNamedPipe(_p0, timeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _waitNamedPipe(name *uint16, timeout uint32) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall(procWaitNamedPipeW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(timeout), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func getNamedPipeInfo(pipe syscall.Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall6(procGetNamedPipeInfo.Addr(), 5, uintptr(pipe), uintptr(unsafe.Pointer(flags)), uintptr(unsafe.Pointer(outSize)), uintptr(unsafe.Pointer(inSize)), uintptr(unsafe.Pointer(maxInstances)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func getNamedPipeHandleState(pipe syscall.Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall9(procGetNamedPipeHandleStateW.Addr(), 7, uintptr(pipe), uintptr(unsafe.Pointer(state)), uintptr(unsafe.Pointer(curInstances)), uintptr(unsafe.Pointer(maxCollectionCount)), uintptr(unsafe.Pointer(collectDataTimeout)), uintptr(unsafe.Pointer(userName)), uintptr(maxUserNameSize), 0, 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) {
|
||||||
|
var _p0 *uint16
|
||||||
|
_p0, err = syscall.UTF16PtrFromString(accountName)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return _lookupAccountName(systemName, _p0, sid, sidSize, refDomain, refDomainSize, sidNameUse)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _lookupAccountName(systemName *uint16, accountName *uint16, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall9(procLookupAccountNameW.Addr(), 7, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(accountName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(sidSize)), uintptr(unsafe.Pointer(refDomain)), uintptr(unsafe.Pointer(refDomainSize)), uintptr(unsafe.Pointer(sidNameUse)), 0, 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func convertSidToStringSid(sid *byte, str **uint16) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall(procConvertSidToStringSidW.Addr(), 2, uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(str)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd *uintptr, size *uint32) (err error) {
|
||||||
|
var _p0 *uint16
|
||||||
|
_p0, err = syscall.UTF16PtrFromString(str)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return _convertStringSecurityDescriptorToSecurityDescriptor(_p0, revision, sd, size)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _convertStringSecurityDescriptorToSecurityDescriptor(str *uint16, revision uint32, sd *uintptr, size *uint32) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall6(procConvertStringSecurityDescriptorToSecurityDescriptorW.Addr(), 4, uintptr(unsafe.Pointer(str)), uintptr(revision), uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(size)), 0, 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func convertSecurityDescriptorToStringSecurityDescriptor(sd *byte, revision uint32, secInfo uint32, sddl **uint16, sddlSize *uint32) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall6(procConvertSecurityDescriptorToStringSecurityDescriptorW.Addr(), 5, uintptr(unsafe.Pointer(sd)), uintptr(revision), uintptr(secInfo), uintptr(unsafe.Pointer(sddl)), uintptr(unsafe.Pointer(sddlSize)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func localFree(mem uintptr) {
|
||||||
|
syscall.Syscall(procLocalFree.Addr(), 1, uintptr(mem), 0, 0)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func getSecurityDescriptorLength(sd uintptr) (len uint32) {
|
||||||
|
r0, _, _ := syscall.Syscall(procGetSecurityDescriptorLength.Addr(), 1, uintptr(sd), 0, 0)
|
||||||
|
len = uint32(r0)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func getFileInformationByHandleEx(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(), 4, uintptr(h), uintptr(class), uintptr(unsafe.Pointer(buffer)), uintptr(size), 0, 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func setFileInformationByHandle(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall6(procSetFileInformationByHandle.Addr(), 4, uintptr(h), uintptr(class), uintptr(unsafe.Pointer(buffer)), uintptr(size), 0, 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func adjustTokenPrivileges(token windows.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) {
|
||||||
|
var _p0 uint32
|
||||||
|
if releaseAll {
|
||||||
|
_p0 = 1
|
||||||
|
} else {
|
||||||
|
_p0 = 0
|
||||||
|
}
|
||||||
|
r0, _, e1 := syscall.Syscall6(procAdjustTokenPrivileges.Addr(), 6, uintptr(token), uintptr(_p0), uintptr(unsafe.Pointer(input)), uintptr(outputSize), uintptr(unsafe.Pointer(output)), uintptr(unsafe.Pointer(requiredSize)))
|
||||||
|
success = r0 != 0
|
||||||
|
if true {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func impersonateSelf(level uint32) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall(procImpersonateSelf.Addr(), 1, uintptr(level), 0, 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func revertToSelf() (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall(procRevertToSelf.Addr(), 0, 0, 0, 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func openThreadToken(thread syscall.Handle, accessMask uint32, openAsSelf bool, token *windows.Token) (err error) {
|
||||||
|
var _p0 uint32
|
||||||
|
if openAsSelf {
|
||||||
|
_p0 = 1
|
||||||
|
} else {
|
||||||
|
_p0 = 0
|
||||||
|
}
|
||||||
|
r1, _, e1 := syscall.Syscall6(procOpenThreadToken.Addr(), 4, uintptr(thread), uintptr(accessMask), uintptr(_p0), uintptr(unsafe.Pointer(token)), 0, 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func getCurrentThread() (h syscall.Handle) {
|
||||||
|
r0, _, _ := syscall.Syscall(procGetCurrentThread.Addr(), 0, 0, 0, 0)
|
||||||
|
h = syscall.Handle(r0)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func lookupPrivilegeValue(systemName string, name string, luid *uint64) (err error) {
|
||||||
|
var _p0 *uint16
|
||||||
|
_p0, err = syscall.UTF16PtrFromString(systemName)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var _p1 *uint16
|
||||||
|
_p1, err = syscall.UTF16PtrFromString(name)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return _lookupPrivilegeValue(_p0, _p1, luid)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _lookupPrivilegeValue(systemName *uint16, name *uint16, luid *uint64) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall(procLookupPrivilegeValueW.Addr(), 3, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(luid)))
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func lookupPrivilegeName(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) {
|
||||||
|
var _p0 *uint16
|
||||||
|
_p0, err = syscall.UTF16PtrFromString(systemName)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return _lookupPrivilegeName(_p0, luid, buffer, size)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _lookupPrivilegeName(systemName *uint16, luid *uint64, buffer *uint16, size *uint32) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall6(procLookupPrivilegeNameW.Addr(), 4, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(luid)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), 0, 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func lookupPrivilegeDisplayName(systemName string, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) {
|
||||||
|
var _p0 *uint16
|
||||||
|
_p0, err = syscall.UTF16PtrFromString(systemName)
|
||||||
|
if err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
return _lookupPrivilegeDisplayName(_p0, name, buffer, size, languageId)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _lookupPrivilegeDisplayName(systemName *uint16, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) {
|
||||||
|
r1, _, e1 := syscall.Syscall6(procLookupPrivilegeDisplayNameW.Addr(), 5, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), uintptr(unsafe.Pointer(languageId)), 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func backupRead(h syscall.Handle, b []byte, bytesRead *uint32, abort bool, processSecurity bool, context *uintptr) (err error) {
|
||||||
|
var _p0 *byte
|
||||||
|
if len(b) > 0 {
|
||||||
|
_p0 = &b[0]
|
||||||
|
}
|
||||||
|
var _p1 uint32
|
||||||
|
if abort {
|
||||||
|
_p1 = 1
|
||||||
|
} else {
|
||||||
|
_p1 = 0
|
||||||
|
}
|
||||||
|
var _p2 uint32
|
||||||
|
if processSecurity {
|
||||||
|
_p2 = 1
|
||||||
|
} else {
|
||||||
|
_p2 = 0
|
||||||
|
}
|
||||||
|
r1, _, e1 := syscall.Syscall9(procBackupRead.Addr(), 7, uintptr(h), uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(unsafe.Pointer(bytesRead)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(context)), 0, 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func backupWrite(h syscall.Handle, b []byte, bytesWritten *uint32, abort bool, processSecurity bool, context *uintptr) (err error) {
|
||||||
|
var _p0 *byte
|
||||||
|
if len(b) > 0 {
|
||||||
|
_p0 = &b[0]
|
||||||
|
}
|
||||||
|
var _p1 uint32
|
||||||
|
if abort {
|
||||||
|
_p1 = 1
|
||||||
|
} else {
|
||||||
|
_p1 = 0
|
||||||
|
}
|
||||||
|
var _p2 uint32
|
||||||
|
if processSecurity {
|
||||||
|
_p2 = 1
|
||||||
|
} else {
|
||||||
|
_p2 = 0
|
||||||
|
}
|
||||||
|
r1, _, e1 := syscall.Syscall9(procBackupWrite.Addr(), 7, uintptr(h), uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(unsafe.Pointer(bytesWritten)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(context)), 0, 0)
|
||||||
|
if r1 == 0 {
|
||||||
|
if e1 != 0 {
|
||||||
|
err = error(e1)
|
||||||
|
} else {
|
||||||
|
err = syscall.EINVAL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
1
vendor/github.com/Sirupsen/logrus/.gitignore
generated
vendored
Normal file
1
vendor/github.com/Sirupsen/logrus/.gitignore
generated
vendored
Normal file
@ -0,0 +1 @@
|
|||||||
|
logrus
|
10
vendor/github.com/Sirupsen/logrus/.travis.yml
generated
vendored
Normal file
10
vendor/github.com/Sirupsen/logrus/.travis.yml
generated
vendored
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
language: go
|
||||||
|
go:
|
||||||
|
- 1.3
|
||||||
|
- 1.4
|
||||||
|
- 1.5
|
||||||
|
- 1.6
|
||||||
|
- tip
|
||||||
|
install:
|
||||||
|
- go get -t ./...
|
||||||
|
script: GOMAXPROCS=4 GORACE="halt_on_error=1" go test -race -v ./...
|
66
vendor/github.com/Sirupsen/logrus/CHANGELOG.md
generated
vendored
Normal file
66
vendor/github.com/Sirupsen/logrus/CHANGELOG.md
generated
vendored
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
# 0.10.0
|
||||||
|
|
||||||
|
* feature: Add a test hook (#180)
|
||||||
|
* feature: `ParseLevel` is now case-insensitive (#326)
|
||||||
|
* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308)
|
||||||
|
* performance: avoid re-allocations on `WithFields` (#335)
|
||||||
|
|
||||||
|
# 0.9.0
|
||||||
|
|
||||||
|
* logrus/text_formatter: don't emit empty msg
|
||||||
|
* logrus/hooks/airbrake: move out of main repository
|
||||||
|
* logrus/hooks/sentry: move out of main repository
|
||||||
|
* logrus/hooks/papertrail: move out of main repository
|
||||||
|
* logrus/hooks/bugsnag: move out of main repository
|
||||||
|
* logrus/core: run tests with `-race`
|
||||||
|
* logrus/core: detect TTY based on `stderr`
|
||||||
|
* logrus/core: support `WithError` on logger
|
||||||
|
* logrus/core: Solaris support
|
||||||
|
|
||||||
|
# 0.8.7
|
||||||
|
|
||||||
|
* logrus/core: fix possible race (#216)
|
||||||
|
* logrus/doc: small typo fixes and doc improvements
|
||||||
|
|
||||||
|
|
||||||
|
# 0.8.6
|
||||||
|
|
||||||
|
* hooks/raven: allow passing an initialized client
|
||||||
|
|
||||||
|
# 0.8.5
|
||||||
|
|
||||||
|
* logrus/core: revert #208
|
||||||
|
|
||||||
|
# 0.8.4
|
||||||
|
|
||||||
|
* formatter/text: fix data race (#218)
|
||||||
|
|
||||||
|
# 0.8.3
|
||||||
|
|
||||||
|
* logrus/core: fix entry log level (#208)
|
||||||
|
* logrus/core: improve performance of text formatter by 40%
|
||||||
|
* logrus/core: expose `LevelHooks` type
|
||||||
|
* logrus/core: add support for DragonflyBSD and NetBSD
|
||||||
|
* formatter/text: print structs more verbosely
|
||||||
|
|
||||||
|
# 0.8.2
|
||||||
|
|
||||||
|
* logrus: fix more Fatal family functions
|
||||||
|
|
||||||
|
# 0.8.1
|
||||||
|
|
||||||
|
* logrus: fix not exiting on `Fatalf` and `Fatalln`
|
||||||
|
|
||||||
|
# 0.8.0
|
||||||
|
|
||||||
|
* logrus: defaults to stderr instead of stdout
|
||||||
|
* hooks/sentry: add special field for `*http.Request`
|
||||||
|
* formatter/text: ignore Windows for colors
|
||||||
|
|
||||||
|
# 0.7.3
|
||||||
|
|
||||||
|
* formatter/\*: allow configuration of timestamp layout
|
||||||
|
|
||||||
|
# 0.7.2
|
||||||
|
|
||||||
|
* formatter/text: Add configuration option for time format (#158)
|
21
vendor/github.com/Sirupsen/logrus/LICENSE
generated
vendored
Normal file
21
vendor/github.com/Sirupsen/logrus/LICENSE
generated
vendored
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (c) 2014 Simon Eskildsen
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||||
|
THE SOFTWARE.
|
425
vendor/github.com/Sirupsen/logrus/README.md
generated
vendored
Normal file
425
vendor/github.com/Sirupsen/logrus/README.md
generated
vendored
Normal file
@ -0,0 +1,425 @@
|
|||||||
|
# Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/> [](https://travis-ci.org/Sirupsen/logrus) [](https://godoc.org/github.com/Sirupsen/logrus)
|
||||||
|
|
||||||
|
Logrus is a structured logger for Go (golang), completely API compatible with
|
||||||
|
the standard library logger. [Godoc][godoc]. **Please note the Logrus API is not
|
||||||
|
yet stable (pre 1.0). Logrus itself is completely stable and has been used in
|
||||||
|
many large deployments. The core API is unlikely to change much but please
|
||||||
|
version control your Logrus to make sure you aren't fetching latest `master` on
|
||||||
|
every build.**
|
||||||
|
|
||||||
|
Nicely color-coded in development (when a TTY is attached, otherwise just
|
||||||
|
plain text):
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash
|
||||||
|
or Splunk:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the
|
||||||
|
ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"}
|
||||||
|
|
||||||
|
{"level":"warning","msg":"The group's number increased tremendously!",
|
||||||
|
"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"}
|
||||||
|
|
||||||
|
{"animal":"walrus","level":"info","msg":"A giant walrus appears!",
|
||||||
|
"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"}
|
||||||
|
|
||||||
|
{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.",
|
||||||
|
"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"}
|
||||||
|
|
||||||
|
{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,
|
||||||
|
"time":"2014-03-10 19:57:38.562543128 -0400 EDT"}
|
||||||
|
```
|
||||||
|
|
||||||
|
With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not
|
||||||
|
attached, the output is compatible with the
|
||||||
|
[logfmt](http://godoc.org/github.com/kr/logfmt) format:
|
||||||
|
|
||||||
|
```text
|
||||||
|
time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8
|
||||||
|
time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
|
||||||
|
time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true
|
||||||
|
time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4
|
||||||
|
time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009
|
||||||
|
time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true
|
||||||
|
exit status 1
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Example
|
||||||
|
|
||||||
|
The simplest way to use Logrus is simply the package-level exported logger:
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
log "github.com/Sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
log.WithFields(log.Fields{
|
||||||
|
"animal": "walrus",
|
||||||
|
}).Info("A walrus appears")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that it's completely api-compatible with the stdlib logger, so you can
|
||||||
|
replace your `log` imports everywhere with `log "github.com/Sirupsen/logrus"`
|
||||||
|
and you'll now have the flexibility of Logrus. You can customize it all you
|
||||||
|
want:
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
log "github.com/Sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
// Log as JSON instead of the default ASCII formatter.
|
||||||
|
log.SetFormatter(&log.JSONFormatter{})
|
||||||
|
|
||||||
|
// Output to stderr instead of stdout, could also be a file.
|
||||||
|
log.SetOutput(os.Stderr)
|
||||||
|
|
||||||
|
// Only log the warning severity or above.
|
||||||
|
log.SetLevel(log.WarnLevel)
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
log.WithFields(log.Fields{
|
||||||
|
"animal": "walrus",
|
||||||
|
"size": 10,
|
||||||
|
}).Info("A group of walrus emerges from the ocean")
|
||||||
|
|
||||||
|
log.WithFields(log.Fields{
|
||||||
|
"omg": true,
|
||||||
|
"number": 122,
|
||||||
|
}).Warn("The group's number increased tremendously!")
|
||||||
|
|
||||||
|
log.WithFields(log.Fields{
|
||||||
|
"omg": true,
|
||||||
|
"number": 100,
|
||||||
|
}).Fatal("The ice breaks!")
|
||||||
|
|
||||||
|
// A common pattern is to re-use fields between logging statements by re-using
|
||||||
|
// the logrus.Entry returned from WithFields()
|
||||||
|
contextLogger := log.WithFields(log.Fields{
|
||||||
|
"common": "this is a common field",
|
||||||
|
"other": "I also should be logged always",
|
||||||
|
})
|
||||||
|
|
||||||
|
contextLogger.Info("I'll be logged with common and other field")
|
||||||
|
contextLogger.Info("Me too")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
For more advanced usage such as logging to multiple locations from the same
|
||||||
|
application, you can also create an instance of the `logrus` Logger:
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/Sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Create a new instance of the logger. You can have any number of instances.
|
||||||
|
var log = logrus.New()
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// The API for setting attributes is a little different than the package level
|
||||||
|
// exported logger. See Godoc.
|
||||||
|
log.Out = os.Stderr
|
||||||
|
|
||||||
|
log.WithFields(logrus.Fields{
|
||||||
|
"animal": "walrus",
|
||||||
|
"size": 10,
|
||||||
|
}).Info("A group of walrus emerges from the ocean")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Fields
|
||||||
|
|
||||||
|
Logrus encourages careful, structured logging though logging fields instead of
|
||||||
|
long, unparseable error messages. For example, instead of: `log.Fatalf("Failed
|
||||||
|
to send event %s to topic %s with key %d")`, you should log the much more
|
||||||
|
discoverable:
|
||||||
|
|
||||||
|
```go
|
||||||
|
log.WithFields(log.Fields{
|
||||||
|
"event": event,
|
||||||
|
"topic": topic,
|
||||||
|
"key": key,
|
||||||
|
}).Fatal("Failed to send event")
|
||||||
|
```
|
||||||
|
|
||||||
|
We've found this API forces you to think about logging in a way that produces
|
||||||
|
much more useful logging messages. We've been in countless situations where just
|
||||||
|
a single added field to a log statement that was already there would've saved us
|
||||||
|
hours. The `WithFields` call is optional.
|
||||||
|
|
||||||
|
In general, with Logrus using any of the `printf`-family functions should be
|
||||||
|
seen as a hint you should add a field, however, you can still use the
|
||||||
|
`printf`-family functions with Logrus.
|
||||||
|
|
||||||
|
#### Hooks
|
||||||
|
|
||||||
|
You can add hooks for logging levels. For example to send errors to an exception
|
||||||
|
tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to
|
||||||
|
multiple places simultaneously, e.g. syslog.
|
||||||
|
|
||||||
|
Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in
|
||||||
|
`init`:
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
log "github.com/Sirupsen/logrus"
|
||||||
|
"gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "aibrake"
|
||||||
|
logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog"
|
||||||
|
"log/syslog"
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
|
||||||
|
// Use the Airbrake hook to report errors that have Error severity or above to
|
||||||
|
// an exception tracker. You can create custom hooks, see the Hooks section.
|
||||||
|
log.AddHook(airbrake.NewHook(123, "xyz", "production"))
|
||||||
|
|
||||||
|
hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
|
||||||
|
if err != nil {
|
||||||
|
log.Error("Unable to connect to local syslog daemon")
|
||||||
|
} else {
|
||||||
|
log.AddHook(hook)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md).
|
||||||
|
|
||||||
|
| Hook | Description |
|
||||||
|
| ----- | ----------- |
|
||||||
|
| [Airbrake](https://github.com/gemnasium/logrus-airbrake-hook) | Send errors to the Airbrake API V3. Uses the official [`gobrake`](https://github.com/airbrake/gobrake) behind the scenes. |
|
||||||
|
| [Airbrake "legacy"](https://github.com/gemnasium/logrus-airbrake-legacy-hook) | Send errors to an exception tracking service compatible with the Airbrake API V2. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. |
|
||||||
|
| [Papertrail](https://github.com/polds/logrus-papertrail-hook) | Send errors to the [Papertrail](https://papertrailapp.com) hosted logging service via UDP. |
|
||||||
|
| [Syslog](https://github.com/Sirupsen/logrus/blob/master/hooks/syslog/syslog.go) | Send errors to remote syslog server. Uses standard library `log/syslog` behind the scenes. |
|
||||||
|
| [Bugsnag](https://github.com/Shopify/logrus-bugsnag/blob/master/bugsnag.go) | Send errors to the Bugsnag exception tracking service. |
|
||||||
|
| [Sentry](https://github.com/evalphobia/logrus_sentry) | Send errors to the Sentry error logging and aggregation service. |
|
||||||
|
| [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. |
|
||||||
|
| [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) |
|
||||||
|
| [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. |
|
||||||
|
| [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` |
|
||||||
|
| [Graylog](https://github.com/gemnasium/logrus-graylog-hook) | Hook for logging to [Graylog](http://graylog2.org/) |
|
||||||
|
| [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) |
|
||||||
|
| [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem |
|
||||||
|
| [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger |
|
||||||
|
| [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail |
|
||||||
|
| [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar |
|
||||||
|
| [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd |
|
||||||
|
| [Mongodb](https://github.com/weekface/mgorus) | Hook for logging to mongodb |
|
||||||
|
| [Influxus] (http://github.com/vlad-doru/influxus) | Hook for concurrently logging to [InfluxDB] (http://influxdata.com/) |
|
||||||
|
| [InfluxDB](https://github.com/Abramovic/logrus_influxdb) | Hook for logging to influxdb |
|
||||||
|
| [Octokit](https://github.com/dorajistyle/logrus-octokit-hook) | Hook for logging to github via octokit |
|
||||||
|
| [DeferPanic](https://github.com/deferpanic/dp-logrus) | Hook for logging to DeferPanic |
|
||||||
|
| [Redis-Hook](https://github.com/rogierlommers/logrus-redis-hook) | Hook for logging to a ELK stack (through Redis) |
|
||||||
|
| [Amqp-Hook](https://github.com/vladoatanasov/logrus_amqp) | Hook for logging to Amqp broker (Like RabbitMQ) |
|
||||||
|
| [KafkaLogrus](https://github.com/goibibo/KafkaLogrus) | Hook for logging to kafka |
|
||||||
|
| [Typetalk](https://github.com/dragon3/logrus-typetalk-hook) | Hook for logging to [Typetalk](https://www.typetalk.in/) |
|
||||||
|
| [ElasticSearch](https://github.com/sohlich/elogrus) | Hook for logging to ElasticSearch|
|
||||||
|
| [Sumorus](https://github.com/doublefree/sumorus) | Hook for logging to [SumoLogic](https://www.sumologic.com/)|
|
||||||
|
| [Scribe](https://github.com/sagar8192/logrus-scribe-hook) | Hook for logging to [Scribe](https://github.com/facebookarchive/scribe)|
|
||||||
|
| [Logstash](https://github.com/bshuster-repo/logrus-logstash-hook) | Hook for logging to [Logstash](https://www.elastic.co/products/logstash) |
|
||||||
|
| [logz.io](https://github.com/ripcurld00d/logrus-logzio-hook) | Hook for logging to [logz.io](https://logz.io), a Log as a Service using Logstash |
|
||||||
|
| [Logmatic.io](https://github.com/logmatic/logmatic-go) | Hook for logging to [Logmatic.io](http://logmatic.io/) |
|
||||||
|
| [Pushover](https://github.com/toorop/logrus_pushover) | Send error via [Pushover](https://pushover.net) |
|
||||||
|
|
||||||
|
|
||||||
|
#### Level logging
|
||||||
|
|
||||||
|
Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic.
|
||||||
|
|
||||||
|
```go
|
||||||
|
log.Debug("Useful debugging information.")
|
||||||
|
log.Info("Something noteworthy happened!")
|
||||||
|
log.Warn("You should probably take a look at this.")
|
||||||
|
log.Error("Something failed but I'm not quitting.")
|
||||||
|
// Calls os.Exit(1) after logging
|
||||||
|
log.Fatal("Bye.")
|
||||||
|
// Calls panic() after logging
|
||||||
|
log.Panic("I'm bailing.")
|
||||||
|
```
|
||||||
|
|
||||||
|
You can set the logging level on a `Logger`, then it will only log entries with
|
||||||
|
that severity or anything above it:
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Will log anything that is info or above (warn, error, fatal, panic). Default.
|
||||||
|
log.SetLevel(log.InfoLevel)
|
||||||
|
```
|
||||||
|
|
||||||
|
It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose
|
||||||
|
environment if your application has that.
|
||||||
|
|
||||||
|
#### Entries
|
||||||
|
|
||||||
|
Besides the fields added with `WithField` or `WithFields` some fields are
|
||||||
|
automatically added to all logging events:
|
||||||
|
|
||||||
|
1. `time`. The timestamp when the entry was created.
|
||||||
|
2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after
|
||||||
|
the `AddFields` call. E.g. `Failed to send event.`
|
||||||
|
3. `level`. The logging level. E.g. `info`.
|
||||||
|
|
||||||
|
#### Environments
|
||||||
|
|
||||||
|
Logrus has no notion of environment.
|
||||||
|
|
||||||
|
If you wish for hooks and formatters to only be used in specific environments,
|
||||||
|
you should handle that yourself. For example, if your application has a global
|
||||||
|
variable `Environment`, which is a string representation of the environment you
|
||||||
|
could do:
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
log "github.com/Sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
init() {
|
||||||
|
// do something here to set environment depending on an environment variable
|
||||||
|
// or command-line flag
|
||||||
|
if Environment == "production" {
|
||||||
|
log.SetFormatter(&log.JSONFormatter{})
|
||||||
|
} else {
|
||||||
|
// The TextFormatter is default, you don't actually have to do this.
|
||||||
|
log.SetFormatter(&log.TextFormatter{})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This configuration is how `logrus` was intended to be used, but JSON in
|
||||||
|
production is mostly only useful if you do log aggregation with tools like
|
||||||
|
Splunk or Logstash.
|
||||||
|
|
||||||
|
#### Formatters
|
||||||
|
|
||||||
|
The built-in logging formatters are:
|
||||||
|
|
||||||
|
* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise
|
||||||
|
without colors.
|
||||||
|
* *Note:* to force colored output when there is no TTY, set the `ForceColors`
|
||||||
|
field to `true`. To force no colored output even if there is a TTY set the
|
||||||
|
`DisableColors` field to `true`
|
||||||
|
* `logrus.JSONFormatter`. Logs fields as JSON.
|
||||||
|
|
||||||
|
Third party logging formatters:
|
||||||
|
|
||||||
|
* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events.
|
||||||
|
* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout.
|
||||||
|
* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦.
|
||||||
|
|
||||||
|
You can define your formatter by implementing the `Formatter` interface,
|
||||||
|
requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a
|
||||||
|
`Fields` type (`map[string]interface{}`) with all your fields as well as the
|
||||||
|
default ones (see Entries section above):
|
||||||
|
|
||||||
|
```go
|
||||||
|
type MyJSONFormatter struct {
|
||||||
|
}
|
||||||
|
|
||||||
|
log.SetFormatter(new(MyJSONFormatter))
|
||||||
|
|
||||||
|
func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
|
||||||
|
// Note this doesn't include Time, Level and Message which are available on
|
||||||
|
// the Entry. Consult `godoc` on information about those fields or read the
|
||||||
|
// source of the official loggers.
|
||||||
|
serialized, err := json.Marshal(entry.Data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
|
||||||
|
}
|
||||||
|
return append(serialized, '\n'), nil
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Logger as an `io.Writer`
|
||||||
|
|
||||||
|
Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it.
|
||||||
|
|
||||||
|
```go
|
||||||
|
w := logger.Writer()
|
||||||
|
defer w.Close()
|
||||||
|
|
||||||
|
srv := http.Server{
|
||||||
|
// create a stdlib log.Logger that writes to
|
||||||
|
// logrus.Logger.
|
||||||
|
ErrorLog: log.New(w, "", 0),
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Each line written to that writer will be printed the usual way, using formatters
|
||||||
|
and hooks. The level for those entries is `info`.
|
||||||
|
|
||||||
|
#### Rotation
|
||||||
|
|
||||||
|
Log rotation is not provided with Logrus. Log rotation should be done by an
|
||||||
|
external program (like `logrotate(8)`) that can compress and delete old log
|
||||||
|
entries. It should not be a feature of the application-level logger.
|
||||||
|
|
||||||
|
#### Tools
|
||||||
|
|
||||||
|
| Tool | Description |
|
||||||
|
| ---- | ----------- |
|
||||||
|
|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will generated with different config at different environment.|
|
||||||
|
|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper arround Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) |
|
||||||
|
|
||||||
|
#### Testing
|
||||||
|
|
||||||
|
Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides:
|
||||||
|
|
||||||
|
* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just add the `test` hook
|
||||||
|
* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any):
|
||||||
|
|
||||||
|
```go
|
||||||
|
logger, hook := NewNullLogger()
|
||||||
|
logger.Error("Hello error")
|
||||||
|
|
||||||
|
assert.Equal(1, len(hook.Entries))
|
||||||
|
assert.Equal(logrus.ErrorLevel, hook.LastEntry().Level)
|
||||||
|
assert.Equal("Hello error", hook.LastEntry().Message)
|
||||||
|
|
||||||
|
hook.Reset()
|
||||||
|
assert.Nil(hook.LastEntry())
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Fatal handlers
|
||||||
|
|
||||||
|
Logrus can register one or more functions that will be called when any `fatal`
|
||||||
|
level message is logged. The registered handlers will be executed before
|
||||||
|
logrus performs a `os.Exit(1)`. This behavior may be helpful if callers need
|
||||||
|
to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted.
|
||||||
|
|
||||||
|
```
|
||||||
|
...
|
||||||
|
handler := func() {
|
||||||
|
// gracefully shutdown something...
|
||||||
|
}
|
||||||
|
logrus.RegisterExitHandler(handler)
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Thread safty
|
||||||
|
|
||||||
|
By default Logger is protected by mutex for concurrent writes, this mutex is invoked when calling hooks and writing logs.
|
||||||
|
If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking.
|
||||||
|
|
||||||
|
Situation when locking is not needed includes:
|
||||||
|
|
||||||
|
* You have no hooks registered, or hooks calling is already thread-safe.
|
||||||
|
|
||||||
|
* Writing to logger.Out is already thread-safe, for example:
|
||||||
|
|
||||||
|
1) logger.Out is protected by locks.
|
||||||
|
|
||||||
|
2) logger.Out is a os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allow multi-thread/multi-process writing)
|
||||||
|
|
||||||
|
(Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/)
|
64
vendor/github.com/Sirupsen/logrus/alt_exit.go
generated
vendored
Normal file
64
vendor/github.com/Sirupsen/logrus/alt_exit.go
generated
vendored
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
package logrus
|
||||||
|
|
||||||
|
// The following code was sourced and modified from the
|
||||||
|
// https://bitbucket.org/tebeka/atexit package governed by the following license:
|
||||||
|
//
|
||||||
|
// Copyright (c) 2012 Miki Tebeka <miki.tebeka@gmail.com>.
|
||||||
|
//
|
||||||
|
// Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||||
|
// this software and associated documentation files (the "Software"), to deal in
|
||||||
|
// the Software without restriction, including without limitation the rights to
|
||||||
|
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||||
|
// the Software, and to permit persons to whom the Software is furnished to do so,
|
||||||
|
// subject to the following conditions:
|
||||||
|
//
|
||||||
|
// The above copyright notice and this permission notice shall be included in all
|
||||||
|
// copies or substantial portions of the Software.
|
||||||
|
//
|
||||||
|
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||||
|
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||||
|
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||||
|
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||||
|
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
var handlers = []func(){}
|
||||||
|
|
||||||
|
func runHandler(handler func()) {
|
||||||
|
defer func() {
|
||||||
|
if err := recover(); err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
handler()
|
||||||
|
}
|
||||||
|
|
||||||
|
func runHandlers() {
|
||||||
|
for _, handler := range handlers {
|
||||||
|
runHandler(handler)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code)
|
||||||
|
func Exit(code int) {
|
||||||
|
runHandlers()
|
||||||
|
os.Exit(code)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RegisterExitHandler adds a Logrus Exit handler, call logrus.Exit to invoke
|
||||||
|
// all handlers. The handlers will also be invoked when any Fatal log entry is
|
||||||
|
// made.
|
||||||
|
//
|
||||||
|
// This method is useful when a caller wishes to use logrus to log a fatal
|
||||||
|
// message but also needs to gracefully shutdown. An example usecase could be
|
||||||
|
// closing database connections, or sending a alert that the application is
|
||||||
|
// closing.
|
||||||
|
func RegisterExitHandler(handler func()) {
|
||||||
|
handlers = append(handlers, handler)
|
||||||
|
}
|
26
vendor/github.com/Sirupsen/logrus/doc.go
generated
vendored
Normal file
26
vendor/github.com/Sirupsen/logrus/doc.go
generated
vendored
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
/*
|
||||||
|
Package logrus is a structured logger for Go, completely API compatible with the standard library logger.
|
||||||
|
|
||||||
|
|
||||||
|
The simplest way to use Logrus is simply the package-level exported logger:
|
||||||
|
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
log "github.com/Sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
log.WithFields(log.Fields{
|
||||||
|
"animal": "walrus",
|
||||||
|
"number": 1,
|
||||||
|
"size": 10,
|
||||||
|
}).Info("A walrus appears")
|
||||||
|
}
|
||||||
|
|
||||||
|
Output:
|
||||||
|
time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10
|
||||||
|
|
||||||
|
For a full guide visit https://github.com/Sirupsen/logrus
|
||||||
|
*/
|
||||||
|
package logrus
|
275
vendor/github.com/Sirupsen/logrus/entry.go
generated
vendored
Normal file
275
vendor/github.com/Sirupsen/logrus/entry.go
generated
vendored
Normal file
@ -0,0 +1,275 @@
|
|||||||
|
package logrus
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
var bufferPool *sync.Pool
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
bufferPool = &sync.Pool{
|
||||||
|
New: func() interface{} {
|
||||||
|
return new(bytes.Buffer)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Defines the key when adding errors using WithError.
|
||||||
|
var ErrorKey = "error"
|
||||||
|
|
||||||
|
// An entry is the final or intermediate Logrus logging entry. It contains all
|
||||||
|
// the fields passed with WithField{,s}. It's finally logged when Debug, Info,
|
||||||
|
// Warn, Error, Fatal or Panic is called on it. These objects can be reused and
|
||||||
|
// passed around as much as you wish to avoid field duplication.
|
||||||
|
type Entry struct {
|
||||||
|
Logger *Logger
|
||||||
|
|
||||||
|
// Contains all the fields set by the user.
|
||||||
|
Data Fields
|
||||||
|
|
||||||
|
// Time at which the log entry was created
|
||||||
|
Time time.Time
|
||||||
|
|
||||||
|
// Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic
|
||||||
|
Level Level
|
||||||
|
|
||||||
|
// Message passed to Debug, Info, Warn, Error, Fatal or Panic
|
||||||
|
Message string
|
||||||
|
|
||||||
|
// When formatter is called in entry.log(), an Buffer may be set to entry
|
||||||
|
Buffer *bytes.Buffer
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewEntry(logger *Logger) *Entry {
|
||||||
|
return &Entry{
|
||||||
|
Logger: logger,
|
||||||
|
// Default is three fields, give a little extra room
|
||||||
|
Data: make(Fields, 5),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns the string representation from the reader and ultimately the
|
||||||
|
// formatter.
|
||||||
|
func (entry *Entry) String() (string, error) {
|
||||||
|
serialized, err := entry.Logger.Formatter.Format(entry)
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
str := string(serialized)
|
||||||
|
return str, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add an error as single field (using the key defined in ErrorKey) to the Entry.
|
||||||
|
func (entry *Entry) WithError(err error) *Entry {
|
||||||
|
return entry.WithField(ErrorKey, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add a single field to the Entry.
|
||||||
|
func (entry *Entry) WithField(key string, value interface{}) *Entry {
|
||||||
|
return entry.WithFields(Fields{key: value})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add a map of fields to the Entry.
|
||||||
|
func (entry *Entry) WithFields(fields Fields) *Entry {
|
||||||
|
data := make(Fields, len(entry.Data)+len(fields))
|
||||||
|
for k, v := range entry.Data {
|
||||||
|
data[k] = v
|
||||||
|
}
|
||||||
|
for k, v := range fields {
|
||||||
|
data[k] = v
|
||||||
|
}
|
||||||
|
return &Entry{Logger: entry.Logger, Data: data}
|
||||||
|
}
|
||||||
|
|
||||||
|
// This function is not declared with a pointer value because otherwise
|
||||||
|
// race conditions will occur when using multiple goroutines
|
||||||
|
func (entry Entry) log(level Level, msg string) {
|
||||||
|
var buffer *bytes.Buffer
|
||||||
|
entry.Time = time.Now()
|
||||||
|
entry.Level = level
|
||||||
|
entry.Message = msg
|
||||||
|
|
||||||
|
if err := entry.Logger.Hooks.Fire(level, &entry); err != nil {
|
||||||
|
entry.Logger.mu.Lock()
|
||||||
|
fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
|
||||||
|
entry.Logger.mu.Unlock()
|
||||||
|
}
|
||||||
|
buffer = bufferPool.Get().(*bytes.Buffer)
|
||||||
|
buffer.Reset()
|
||||||
|
defer bufferPool.Put(buffer)
|
||||||
|
entry.Buffer = buffer
|
||||||
|
serialized, err := entry.Logger.Formatter.Format(&entry)
|
||||||
|
entry.Buffer = nil
|
||||||
|
if err != nil {
|
||||||
|
entry.Logger.mu.Lock()
|
||||||
|
fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
|
||||||
|
entry.Logger.mu.Unlock()
|
||||||
|
} else {
|
||||||
|
entry.Logger.mu.Lock()
|
||||||
|
_, err = entry.Logger.Out.Write(serialized)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
|
||||||
|
}
|
||||||
|
entry.Logger.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// To avoid Entry#log() returning a value that only would make sense for
|
||||||
|
// panic() to use in Entry#Panic(), we avoid the allocation by checking
|
||||||
|
// directly here.
|
||||||
|
if level <= PanicLevel {
|
||||||
|
panic(&entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Debug(args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= DebugLevel {
|
||||||
|
entry.log(DebugLevel, fmt.Sprint(args...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Print(args ...interface{}) {
|
||||||
|
entry.Info(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Info(args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= InfoLevel {
|
||||||
|
entry.log(InfoLevel, fmt.Sprint(args...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Warn(args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= WarnLevel {
|
||||||
|
entry.log(WarnLevel, fmt.Sprint(args...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Warning(args ...interface{}) {
|
||||||
|
entry.Warn(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Error(args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= ErrorLevel {
|
||||||
|
entry.log(ErrorLevel, fmt.Sprint(args...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Fatal(args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= FatalLevel {
|
||||||
|
entry.log(FatalLevel, fmt.Sprint(args...))
|
||||||
|
}
|
||||||
|
Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Panic(args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= PanicLevel {
|
||||||
|
entry.log(PanicLevel, fmt.Sprint(args...))
|
||||||
|
}
|
||||||
|
panic(fmt.Sprint(args...))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entry Printf family functions
|
||||||
|
|
||||||
|
func (entry *Entry) Debugf(format string, args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= DebugLevel {
|
||||||
|
entry.Debug(fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Infof(format string, args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= InfoLevel {
|
||||||
|
entry.Info(fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Printf(format string, args ...interface{}) {
|
||||||
|
entry.Infof(format, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Warnf(format string, args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= WarnLevel {
|
||||||
|
entry.Warn(fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Warningf(format string, args ...interface{}) {
|
||||||
|
entry.Warnf(format, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Errorf(format string, args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= ErrorLevel {
|
||||||
|
entry.Error(fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Fatalf(format string, args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= FatalLevel {
|
||||||
|
entry.Fatal(fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Panicf(format string, args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= PanicLevel {
|
||||||
|
entry.Panic(fmt.Sprintf(format, args...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entry Println family functions
|
||||||
|
|
||||||
|
func (entry *Entry) Debugln(args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= DebugLevel {
|
||||||
|
entry.Debug(entry.sprintlnn(args...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Infoln(args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= InfoLevel {
|
||||||
|
entry.Info(entry.sprintlnn(args...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Println(args ...interface{}) {
|
||||||
|
entry.Infoln(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Warnln(args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= WarnLevel {
|
||||||
|
entry.Warn(entry.sprintlnn(args...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Warningln(args ...interface{}) {
|
||||||
|
entry.Warnln(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Errorln(args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= ErrorLevel {
|
||||||
|
entry.Error(entry.sprintlnn(args...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Fatalln(args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= FatalLevel {
|
||||||
|
entry.Fatal(entry.sprintlnn(args...))
|
||||||
|
}
|
||||||
|
Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (entry *Entry) Panicln(args ...interface{}) {
|
||||||
|
if entry.Logger.Level >= PanicLevel {
|
||||||
|
entry.Panic(entry.sprintlnn(args...))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sprintlnn => Sprint no newline. This is to get the behavior of how
|
||||||
|
// fmt.Sprintln where spaces are always added between operands, regardless of
|
||||||
|
// their type. Instead of vendoring the Sprintln implementation to spare a
|
||||||
|
// string allocation, we do the simplest thing.
|
||||||
|
func (entry *Entry) sprintlnn(args ...interface{}) string {
|
||||||
|
msg := fmt.Sprintln(args...)
|
||||||
|
return msg[:len(msg)-1]
|
||||||
|
}
|
193
vendor/github.com/Sirupsen/logrus/exported.go
generated
vendored
Normal file
193
vendor/github.com/Sirupsen/logrus/exported.go
generated
vendored
Normal file
@ -0,0 +1,193 @@
|
|||||||
|
package logrus
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// std is the name of the standard logger in stdlib `log`
|
||||||
|
std = New()
|
||||||
|
)
|
||||||
|
|
||||||
|
func StandardLogger() *Logger {
|
||||||
|
return std
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetOutput sets the standard logger output.
|
||||||
|
func SetOutput(out io.Writer) {
|
||||||
|
std.mu.Lock()
|
||||||
|
defer std.mu.Unlock()
|
||||||
|
std.Out = out
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetFormatter sets the standard logger formatter.
|
||||||
|
func SetFormatter(formatter Formatter) {
|
||||||
|
std.mu.Lock()
|
||||||
|
defer std.mu.Unlock()
|
||||||
|
std.Formatter = formatter
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetLevel sets the standard logger level.
|
||||||
|
func SetLevel(level Level) {
|
||||||
|
std.mu.Lock()
|
||||||
|
defer std.mu.Unlock()
|
||||||
|
std.Level = level
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLevel returns the standard logger level.
|
||||||
|
func GetLevel() Level {
|
||||||
|
std.mu.Lock()
|
||||||
|
defer std.mu.Unlock()
|
||||||
|
return std.Level
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddHook adds a hook to the standard logger hooks.
|
||||||
|
func AddHook(hook Hook) {
|
||||||
|
std.mu.Lock()
|
||||||
|
defer std.mu.Unlock()
|
||||||
|
std.Hooks.Add(hook)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key.
|
||||||
|
func WithError(err error) *Entry {
|
||||||
|
return std.WithField(ErrorKey, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithField creates an entry from the standard logger and adds a field to
|
||||||
|
// it. If you want multiple fields, use `WithFields`.
|
||||||
|
//
|
||||||
|
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
|
||||||
|
// or Panic on the Entry it returns.
|
||||||
|
func WithField(key string, value interface{}) *Entry {
|
||||||
|
return std.WithField(key, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithFields creates an entry from the standard logger and adds multiple
|
||||||
|
// fields to it. This is simply a helper for `WithField`, invoking it
|
||||||
|
// once for each field.
|
||||||
|
//
|
||||||
|
// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
|
||||||
|
// or Panic on the Entry it returns.
|
||||||
|
func WithFields(fields Fields) *Entry {
|
||||||
|
return std.WithFields(fields)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debug logs a message at level Debug on the standard logger.
|
||||||
|
func Debug(args ...interface{}) {
|
||||||
|
std.Debug(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Print logs a message at level Info on the standard logger.
|
||||||
|
func Print(args ...interface{}) {
|
||||||
|
std.Print(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Info logs a message at level Info on the standard logger.
|
||||||
|
func Info(args ...interface{}) {
|
||||||
|
std.Info(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Warn logs a message at level Warn on the standard logger.
|
||||||
|
func Warn(args ...interface{}) {
|
||||||
|
std.Warn(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Warning logs a message at level Warn on the standard logger.
|
||||||
|
func Warning(args ...interface{}) {
|
||||||
|
std.Warning(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Error logs a message at level Error on the standard logger.
|
||||||
|
func Error(args ...interface{}) {
|
||||||
|
std.Error(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Panic logs a message at level Panic on the standard logger.
|
||||||
|
func Panic(args ...interface{}) {
|
||||||
|
std.Panic(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fatal logs a message at level Fatal on the standard logger.
|
||||||
|
func Fatal(args ...interface{}) {
|
||||||
|
std.Fatal(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debugf logs a message at level Debug on the standard logger.
|
||||||
|
func Debugf(format string, args ...interface{}) {
|
||||||
|
std.Debugf(format, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Printf logs a message at level Info on the standard logger.
|
||||||
|
func Printf(format string, args ...interface{}) {
|
||||||
|
std.Printf(format, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Infof logs a message at level Info on the standard logger.
|
||||||
|
func Infof(format string, args ...interface{}) {
|
||||||
|
std.Infof(format, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Warnf logs a message at level Warn on the standard logger.
|
||||||
|
func Warnf(format string, args ...interface{}) {
|
||||||
|
std.Warnf(format, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Warningf logs a message at level Warn on the standard logger.
|
||||||
|
func Warningf(format string, args ...interface{}) {
|
||||||
|
std.Warningf(format, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Errorf logs a message at level Error on the standard logger.
|
||||||
|
func Errorf(format string, args ...interface{}) {
|
||||||
|
std.Errorf(format, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Panicf logs a message at level Panic on the standard logger.
|
||||||
|
func Panicf(format string, args ...interface{}) {
|
||||||
|
std.Panicf(format, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fatalf logs a message at level Fatal on the standard logger.
|
||||||
|
func Fatalf(format string, args ...interface{}) {
|
||||||
|
std.Fatalf(format, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debugln logs a message at level Debug on the standard logger.
|
||||||
|
func Debugln(args ...interface{}) {
|
||||||
|
std.Debugln(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Println logs a message at level Info on the standard logger.
|
||||||
|
func Println(args ...interface{}) {
|
||||||
|
std.Println(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Infoln logs a message at level Info on the standard logger.
|
||||||
|
func Infoln(args ...interface{}) {
|
||||||
|
std.Infoln(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Warnln logs a message at level Warn on the standard logger.
|
||||||
|
func Warnln(args ...interface{}) {
|
||||||
|
std.Warnln(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Warningln logs a message at level Warn on the standard logger.
|
||||||
|
func Warningln(args ...interface{}) {
|
||||||
|
std.Warningln(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Errorln logs a message at level Error on the standard logger.
|
||||||
|
func Errorln(args ...interface{}) {
|
||||||
|
std.Errorln(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Panicln logs a message at level Panic on the standard logger.
|
||||||
|
func Panicln(args ...interface{}) {
|
||||||
|
std.Panicln(args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fatalln logs a message at level Fatal on the standard logger.
|
||||||
|
func Fatalln(args ...interface{}) {
|
||||||
|
std.Fatalln(args...)
|
||||||
|
}
|
45
vendor/github.com/Sirupsen/logrus/formatter.go
generated
vendored
Normal file
45
vendor/github.com/Sirupsen/logrus/formatter.go
generated
vendored
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
package logrus
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
const DefaultTimestampFormat = time.RFC3339
|
||||||
|
|
||||||
|
// The Formatter interface is used to implement a custom Formatter. It takes an
|
||||||
|
// `Entry`. It exposes all the fields, including the default ones:
|
||||||
|
//
|
||||||
|
// * `entry.Data["msg"]`. The message passed from Info, Warn, Error ..
|
||||||
|
// * `entry.Data["time"]`. The timestamp.
|
||||||
|
// * `entry.Data["level"]. The level the entry was logged at.
|
||||||
|
//
|
||||||
|
// Any additional fields added with `WithField` or `WithFields` are also in
|
||||||
|
// `entry.Data`. Format is expected to return an array of bytes which are then
|
||||||
|
// logged to `logger.Out`.
|
||||||
|
type Formatter interface {
|
||||||
|
Format(*Entry) ([]byte, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// This is to not silently overwrite `time`, `msg` and `level` fields when
|
||||||
|
// dumping it. If this code wasn't there doing:
|
||||||
|
//
|
||||||
|
// logrus.WithField("level", 1).Info("hello")
|
||||||
|
//
|
||||||
|
// Would just silently drop the user provided level. Instead with this code
|
||||||
|
// it'll logged as:
|
||||||
|
//
|
||||||
|
// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."}
|
||||||
|
//
|
||||||
|
// It's not exported because it's still using Data in an opinionated way. It's to
|
||||||
|
// avoid code duplication between the two default formatters.
|
||||||
|
func prefixFieldClashes(data Fields) {
|
||||||
|
if t, ok := data["time"]; ok {
|
||||||
|
data["fields.time"] = t
|
||||||
|
}
|
||||||
|
|
||||||
|
if m, ok := data["msg"]; ok {
|
||||||
|
data["fields.msg"] = m
|
||||||
|
}
|
||||||
|
|
||||||
|
if l, ok := data["level"]; ok {
|
||||||
|
data["fields.level"] = l
|
||||||
|
}
|
||||||
|
}
|
34
vendor/github.com/Sirupsen/logrus/hooks.go
generated
vendored
Normal file
34
vendor/github.com/Sirupsen/logrus/hooks.go
generated
vendored
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
package logrus
|
||||||
|
|
||||||
|
// A hook to be fired when logging on the logging levels returned from
|
||||||
|
// `Levels()` on your implementation of the interface. Note that this is not
|
||||||
|
// fired in a goroutine or a channel with workers, you should handle such
|
||||||
|
// functionality yourself if your call is non-blocking and you don't wish for
|
||||||
|
// the logging calls for levels returned from `Levels()` to block.
|
||||||
|
type Hook interface {
|
||||||
|
Levels() []Level
|
||||||
|
Fire(*Entry) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// Internal type for storing the hooks on a logger instance.
|
||||||
|
type LevelHooks map[Level][]Hook
|
||||||
|
|
||||||
|
// Add a hook to an instance of logger. This is called with
|
||||||
|
// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface.
|
||||||
|
func (hooks LevelHooks) Add(hook Hook) {
|
||||||
|
for _, level := range hook.Levels() {
|
||||||
|
hooks[level] = append(hooks[level], hook)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fire all the hooks for the passed level. Used by `entry.log` to fire
|
||||||
|
// appropriate hooks for a log entry.
|
||||||
|
func (hooks LevelHooks) Fire(level Level, entry *Entry) error {
|
||||||
|
for _, hook := range hooks[level] {
|
||||||
|
if err := hook.Fire(entry); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
41
vendor/github.com/Sirupsen/logrus/json_formatter.go
generated
vendored
Normal file
41
vendor/github.com/Sirupsen/logrus/json_formatter.go
generated
vendored
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
package logrus
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
type JSONFormatter struct {
|
||||||
|
// TimestampFormat sets the format used for marshaling timestamps.
|
||||||
|
TimestampFormat string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
|
||||||
|
data := make(Fields, len(entry.Data)+3)
|
||||||
|
for k, v := range entry.Data {
|
||||||
|
switch v := v.(type) {
|
||||||
|
case error:
|
||||||
|
// Otherwise errors are ignored by `encoding/json`
|
||||||
|
// https://github.com/Sirupsen/logrus/issues/137
|
||||||
|
data[k] = v.Error()
|
||||||
|
default:
|
||||||
|
data[k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
prefixFieldClashes(data)
|
||||||
|
|
||||||
|
timestampFormat := f.TimestampFormat
|
||||||
|
if timestampFormat == "" {
|
||||||
|
timestampFormat = DefaultTimestampFormat
|
||||||
|
}
|
||||||
|
|
||||||
|
data["time"] = entry.Time.Format(timestampFormat)
|
||||||
|
data["msg"] = entry.Message
|
||||||
|
data["level"] = entry.Level.String()
|
||||||
|
|
||||||
|
serialized, err := json.Marshal(data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
|
||||||
|
}
|
||||||
|
return append(serialized, '\n'), nil
|
||||||
|
}
|
308
vendor/github.com/Sirupsen/logrus/logger.go
generated
vendored
Normal file
308
vendor/github.com/Sirupsen/logrus/logger.go
generated
vendored
Normal file
@ -0,0 +1,308 @@
|
|||||||
|
package logrus
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Logger struct {
|
||||||
|
// The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
|
||||||
|
// file, or leave it default which is `os.Stderr`. You can also set this to
|
||||||
|
// something more adventorous, such as logging to Kafka.
|
||||||
|
Out io.Writer
|
||||||
|
// Hooks for the logger instance. These allow firing events based on logging
|
||||||
|
// levels and log entries. For example, to send errors to an error tracking
|
||||||
|
// service, log to StatsD or dump the core on fatal errors.
|
||||||
|
Hooks LevelHooks
|
||||||
|
// All log entries pass through the formatter before logged to Out. The
|
||||||
|
// included formatters are `TextFormatter` and `JSONFormatter` for which
|
||||||
|
// TextFormatter is the default. In development (when a TTY is attached) it
|
||||||
|
// logs with colors, but to a file it wouldn't. You can easily implement your
|
||||||
|
// own that implements the `Formatter` interface, see the `README` or included
|
||||||
|
// formatters for examples.
|
||||||
|
Formatter Formatter
|
||||||
|
// The logging level the logger should log at. This is typically (and defaults
|
||||||
|
// to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
|
||||||
|
// logged. `logrus.Debug` is useful in
|
||||||
|
Level Level
|
||||||
|
// Used to sync writing to the log. Locking is enabled by Default
|
||||||
|
mu MutexWrap
|
||||||
|
// Reusable empty entry
|
||||||
|
entryPool sync.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
type MutexWrap struct {
|
||||||
|
lock sync.Mutex
|
||||||
|
disabled bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (mw *MutexWrap) Lock() {
|
||||||
|
if !mw.disabled {
|
||||||
|
mw.lock.Lock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (mw *MutexWrap) Unlock() {
|
||||||
|
if !mw.disabled {
|
||||||
|
mw.lock.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (mw *MutexWrap) Disable() {
|
||||||
|
mw.disabled = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Creates a new logger. Configuration should be set by changing `Formatter`,
|
||||||
|
// `Out` and `Hooks` directly on the default logger instance. You can also just
|
||||||
|
// instantiate your own:
|
||||||
|
//
|
||||||
|
// var log = &Logger{
|
||||||
|
// Out: os.Stderr,
|
||||||
|
// Formatter: new(JSONFormatter),
|
||||||
|
// Hooks: make(LevelHooks),
|
||||||
|
// Level: logrus.DebugLevel,
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// It's recommended to make this a global instance called `log`.
|
||||||
|
func New() *Logger {
|
||||||
|
return &Logger{
|
||||||
|
Out: os.Stderr,
|
||||||
|
Formatter: new(TextFormatter),
|
||||||
|
Hooks: make(LevelHooks),
|
||||||
|
Level: InfoLevel,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) newEntry() *Entry {
|
||||||
|
entry, ok := logger.entryPool.Get().(*Entry)
|
||||||
|
if ok {
|
||||||
|
return entry
|
||||||
|
}
|
||||||
|
return NewEntry(logger)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) releaseEntry(entry *Entry) {
|
||||||
|
logger.entryPool.Put(entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adds a field to the log entry, note that it doesn't log until you call
|
||||||
|
// Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry.
|
||||||
|
// If you want multiple fields, use `WithFields`.
|
||||||
|
func (logger *Logger) WithField(key string, value interface{}) *Entry {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
defer logger.releaseEntry(entry)
|
||||||
|
return entry.WithField(key, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Adds a struct of fields to the log entry. All it does is call `WithField` for
|
||||||
|
// each `Field`.
|
||||||
|
func (logger *Logger) WithFields(fields Fields) *Entry {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
defer logger.releaseEntry(entry)
|
||||||
|
return entry.WithFields(fields)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add an error as single field to the log entry. All it does is call
|
||||||
|
// `WithError` for the given `error`.
|
||||||
|
func (logger *Logger) WithError(err error) *Entry {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
defer logger.releaseEntry(entry)
|
||||||
|
return entry.WithError(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Debugf(format string, args ...interface{}) {
|
||||||
|
if logger.Level >= DebugLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Debugf(format, args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Infof(format string, args ...interface{}) {
|
||||||
|
if logger.Level >= InfoLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Infof(format, args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Printf(format string, args ...interface{}) {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Printf(format, args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Warnf(format string, args ...interface{}) {
|
||||||
|
if logger.Level >= WarnLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Warnf(format, args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Warningf(format string, args ...interface{}) {
|
||||||
|
if logger.Level >= WarnLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Warnf(format, args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Errorf(format string, args ...interface{}) {
|
||||||
|
if logger.Level >= ErrorLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Errorf(format, args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Fatalf(format string, args ...interface{}) {
|
||||||
|
if logger.Level >= FatalLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Fatalf(format, args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Panicf(format string, args ...interface{}) {
|
||||||
|
if logger.Level >= PanicLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Panicf(format, args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Debug(args ...interface{}) {
|
||||||
|
if logger.Level >= DebugLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Debug(args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Info(args ...interface{}) {
|
||||||
|
if logger.Level >= InfoLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Info(args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Print(args ...interface{}) {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Info(args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Warn(args ...interface{}) {
|
||||||
|
if logger.Level >= WarnLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Warn(args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Warning(args ...interface{}) {
|
||||||
|
if logger.Level >= WarnLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Warn(args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Error(args ...interface{}) {
|
||||||
|
if logger.Level >= ErrorLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Error(args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Fatal(args ...interface{}) {
|
||||||
|
if logger.Level >= FatalLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Fatal(args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Panic(args ...interface{}) {
|
||||||
|
if logger.Level >= PanicLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Panic(args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Debugln(args ...interface{}) {
|
||||||
|
if logger.Level >= DebugLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Debugln(args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Infoln(args ...interface{}) {
|
||||||
|
if logger.Level >= InfoLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Infoln(args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Println(args ...interface{}) {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Println(args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Warnln(args ...interface{}) {
|
||||||
|
if logger.Level >= WarnLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Warnln(args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Warningln(args ...interface{}) {
|
||||||
|
if logger.Level >= WarnLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Warnln(args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Errorln(args ...interface{}) {
|
||||||
|
if logger.Level >= ErrorLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Errorln(args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Fatalln(args ...interface{}) {
|
||||||
|
if logger.Level >= FatalLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Fatalln(args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) Panicln(args ...interface{}) {
|
||||||
|
if logger.Level >= PanicLevel {
|
||||||
|
entry := logger.newEntry()
|
||||||
|
entry.Panicln(args...)
|
||||||
|
logger.releaseEntry(entry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
//When file is opened with appending mode, it's safe to
|
||||||
|
//write concurrently to a file (within 4k message on Linux).
|
||||||
|
//In these cases user can choose to disable the lock.
|
||||||
|
func (logger *Logger) SetNoLock() {
|
||||||
|
logger.mu.Disable()
|
||||||
|
}
|
143
vendor/github.com/Sirupsen/logrus/logrus.go
generated
vendored
Normal file
143
vendor/github.com/Sirupsen/logrus/logrus.go
generated
vendored
Normal file
@ -0,0 +1,143 @@
|
|||||||
|
package logrus
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Fields type, used to pass to `WithFields`.
|
||||||
|
type Fields map[string]interface{}
|
||||||
|
|
||||||
|
// Level type
|
||||||
|
type Level uint8
|
||||||
|
|
||||||
|
// Convert the Level to a string. E.g. PanicLevel becomes "panic".
|
||||||
|
func (level Level) String() string {
|
||||||
|
switch level {
|
||||||
|
case DebugLevel:
|
||||||
|
return "debug"
|
||||||
|
case InfoLevel:
|
||||||
|
return "info"
|
||||||
|
case WarnLevel:
|
||||||
|
return "warning"
|
||||||
|
case ErrorLevel:
|
||||||
|
return "error"
|
||||||
|
case FatalLevel:
|
||||||
|
return "fatal"
|
||||||
|
case PanicLevel:
|
||||||
|
return "panic"
|
||||||
|
}
|
||||||
|
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseLevel takes a string level and returns the Logrus log level constant.
|
||||||
|
func ParseLevel(lvl string) (Level, error) {
|
||||||
|
switch strings.ToLower(lvl) {
|
||||||
|
case "panic":
|
||||||
|
return PanicLevel, nil
|
||||||
|
case "fatal":
|
||||||
|
return FatalLevel, nil
|
||||||
|
case "error":
|
||||||
|
return ErrorLevel, nil
|
||||||
|
case "warn", "warning":
|
||||||
|
return WarnLevel, nil
|
||||||
|
case "info":
|
||||||
|
return InfoLevel, nil
|
||||||
|
case "debug":
|
||||||
|
return DebugLevel, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var l Level
|
||||||
|
return l, fmt.Errorf("not a valid logrus Level: %q", lvl)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A constant exposing all logging levels
|
||||||
|
var AllLevels = []Level{
|
||||||
|
PanicLevel,
|
||||||
|
FatalLevel,
|
||||||
|
ErrorLevel,
|
||||||
|
WarnLevel,
|
||||||
|
InfoLevel,
|
||||||
|
DebugLevel,
|
||||||
|
}
|
||||||
|
|
||||||
|
// These are the different logging levels. You can set the logging level to log
|
||||||
|
// on your instance of logger, obtained with `logrus.New()`.
|
||||||
|
const (
|
||||||
|
// PanicLevel level, highest level of severity. Logs and then calls panic with the
|
||||||
|
// message passed to Debug, Info, ...
|
||||||
|
PanicLevel Level = iota
|
||||||
|
// FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the
|
||||||
|
// logging level is set to Panic.
|
||||||
|
FatalLevel
|
||||||
|
// ErrorLevel level. Logs. Used for errors that should definitely be noted.
|
||||||
|
// Commonly used for hooks to send errors to an error tracking service.
|
||||||
|
ErrorLevel
|
||||||
|
// WarnLevel level. Non-critical entries that deserve eyes.
|
||||||
|
WarnLevel
|
||||||
|
// InfoLevel level. General operational entries about what's going on inside the
|
||||||
|
// application.
|
||||||
|
InfoLevel
|
||||||
|
// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
|
||||||
|
DebugLevel
|
||||||
|
)
|
||||||
|
|
||||||
|
// Won't compile if StdLogger can't be realized by a log.Logger
|
||||||
|
var (
|
||||||
|
_ StdLogger = &log.Logger{}
|
||||||
|
_ StdLogger = &Entry{}
|
||||||
|
_ StdLogger = &Logger{}
|
||||||
|
)
|
||||||
|
|
||||||
|
// StdLogger is what your logrus-enabled library should take, that way
|
||||||
|
// it'll accept a stdlib logger and a logrus logger. There's no standard
|
||||||
|
// interface, this is the closest we get, unfortunately.
|
||||||
|
type StdLogger interface {
|
||||||
|
Print(...interface{})
|
||||||
|
Printf(string, ...interface{})
|
||||||
|
Println(...interface{})
|
||||||
|
|
||||||
|
Fatal(...interface{})
|
||||||
|
Fatalf(string, ...interface{})
|
||||||
|
Fatalln(...interface{})
|
||||||
|
|
||||||
|
Panic(...interface{})
|
||||||
|
Panicf(string, ...interface{})
|
||||||
|
Panicln(...interface{})
|
||||||
|
}
|
||||||
|
|
||||||
|
// The FieldLogger interface generalizes the Entry and Logger types
|
||||||
|
type FieldLogger interface {
|
||||||
|
WithField(key string, value interface{}) *Entry
|
||||||
|
WithFields(fields Fields) *Entry
|
||||||
|
WithError(err error) *Entry
|
||||||
|
|
||||||
|
Debugf(format string, args ...interface{})
|
||||||
|
Infof(format string, args ...interface{})
|
||||||
|
Printf(format string, args ...interface{})
|
||||||
|
Warnf(format string, args ...interface{})
|
||||||
|
Warningf(format string, args ...interface{})
|
||||||
|
Errorf(format string, args ...interface{})
|
||||||
|
Fatalf(format string, args ...interface{})
|
||||||
|
Panicf(format string, args ...interface{})
|
||||||
|
|
||||||
|
Debug(args ...interface{})
|
||||||
|
Info(args ...interface{})
|
||||||
|
Print(args ...interface{})
|
||||||
|
Warn(args ...interface{})
|
||||||
|
Warning(args ...interface{})
|
||||||
|
Error(args ...interface{})
|
||||||
|
Fatal(args ...interface{})
|
||||||
|
Panic(args ...interface{})
|
||||||
|
|
||||||
|
Debugln(args ...interface{})
|
||||||
|
Infoln(args ...interface{})
|
||||||
|
Println(args ...interface{})
|
||||||
|
Warnln(args ...interface{})
|
||||||
|
Warningln(args ...interface{})
|
||||||
|
Errorln(args ...interface{})
|
||||||
|
Fatalln(args ...interface{})
|
||||||
|
Panicln(args ...interface{})
|
||||||
|
}
|
8
vendor/github.com/Sirupsen/logrus/terminal_appengine.go
generated
vendored
Normal file
8
vendor/github.com/Sirupsen/logrus/terminal_appengine.go
generated
vendored
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
// +build appengine
|
||||||
|
|
||||||
|
package logrus
|
||||||
|
|
||||||
|
// IsTerminal returns true if stderr's file descriptor is a terminal.
|
||||||
|
func IsTerminal() bool {
|
||||||
|
return true
|
||||||
|
}
|
10
vendor/github.com/Sirupsen/logrus/terminal_bsd.go
generated
vendored
Normal file
10
vendor/github.com/Sirupsen/logrus/terminal_bsd.go
generated
vendored
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
// +build darwin freebsd openbsd netbsd dragonfly
|
||||||
|
// +build !appengine
|
||||||
|
|
||||||
|
package logrus
|
||||||
|
|
||||||
|
import "syscall"
|
||||||
|
|
||||||
|
const ioctlReadTermios = syscall.TIOCGETA
|
||||||
|
|
||||||
|
type Termios syscall.Termios
|
14
vendor/github.com/Sirupsen/logrus/terminal_linux.go
generated
vendored
Normal file
14
vendor/github.com/Sirupsen/logrus/terminal_linux.go
generated
vendored
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
// Based on ssh/terminal:
|
||||||
|
// Copyright 2013 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build !appengine
|
||||||
|
|
||||||
|
package logrus
|
||||||
|
|
||||||
|
import "syscall"
|
||||||
|
|
||||||
|
const ioctlReadTermios = syscall.TCGETS
|
||||||
|
|
||||||
|
type Termios syscall.Termios
|
22
vendor/github.com/Sirupsen/logrus/terminal_notwindows.go
generated
vendored
Normal file
22
vendor/github.com/Sirupsen/logrus/terminal_notwindows.go
generated
vendored
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
// Based on ssh/terminal:
|
||||||
|
// Copyright 2011 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build linux darwin freebsd openbsd netbsd dragonfly
|
||||||
|
// +build !appengine
|
||||||
|
|
||||||
|
package logrus
|
||||||
|
|
||||||
|
import (
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IsTerminal returns true if stderr's file descriptor is a terminal.
|
||||||
|
func IsTerminal() bool {
|
||||||
|
fd := syscall.Stderr
|
||||||
|
var termios Termios
|
||||||
|
_, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
|
||||||
|
return err == 0
|
||||||
|
}
|
15
vendor/github.com/Sirupsen/logrus/terminal_solaris.go
generated
vendored
Normal file
15
vendor/github.com/Sirupsen/logrus/terminal_solaris.go
generated
vendored
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
// +build solaris,!appengine
|
||||||
|
|
||||||
|
package logrus
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
)
|
||||||
|
|
||||||
|
// IsTerminal returns true if the given file descriptor is a terminal.
|
||||||
|
func IsTerminal() bool {
|
||||||
|
_, err := unix.IoctlGetTermios(int(os.Stdout.Fd()), unix.TCGETA)
|
||||||
|
return err == nil
|
||||||
|
}
|
27
vendor/github.com/Sirupsen/logrus/terminal_windows.go
generated
vendored
Normal file
27
vendor/github.com/Sirupsen/logrus/terminal_windows.go
generated
vendored
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
// Based on ssh/terminal:
|
||||||
|
// Copyright 2011 The Go Authors. All rights reserved.
|
||||||
|
// Use of this source code is governed by a BSD-style
|
||||||
|
// license that can be found in the LICENSE file.
|
||||||
|
|
||||||
|
// +build windows,!appengine
|
||||||
|
|
||||||
|
package logrus
|
||||||
|
|
||||||
|
import (
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
var kernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||||
|
|
||||||
|
var (
|
||||||
|
procGetConsoleMode = kernel32.NewProc("GetConsoleMode")
|
||||||
|
)
|
||||||
|
|
||||||
|
// IsTerminal returns true if stderr's file descriptor is a terminal.
|
||||||
|
func IsTerminal() bool {
|
||||||
|
fd := syscall.Stderr
|
||||||
|
var st uint32
|
||||||
|
r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0)
|
||||||
|
return r != 0 && e == 0
|
||||||
|
}
|
168
vendor/github.com/Sirupsen/logrus/text_formatter.go
generated
vendored
Normal file
168
vendor/github.com/Sirupsen/logrus/text_formatter.go
generated
vendored
Normal file
@ -0,0 +1,168 @@
|
|||||||
|
package logrus
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"runtime"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
nocolor = 0
|
||||||
|
red = 31
|
||||||
|
green = 32
|
||||||
|
yellow = 33
|
||||||
|
blue = 34
|
||||||
|
gray = 37
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
baseTimestamp time.Time
|
||||||
|
isTerminal bool
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
baseTimestamp = time.Now()
|
||||||
|
isTerminal = IsTerminal()
|
||||||
|
}
|
||||||
|
|
||||||
|
func miniTS() int {
|
||||||
|
return int(time.Since(baseTimestamp) / time.Second)
|
||||||
|
}
|
||||||
|
|
||||||
|
type TextFormatter struct {
|
||||||
|
// Set to true to bypass checking for a TTY before outputting colors.
|
||||||
|
ForceColors bool
|
||||||
|
|
||||||
|
// Force disabling colors.
|
||||||
|
DisableColors bool
|
||||||
|
|
||||||
|
// Disable timestamp logging. useful when output is redirected to logging
|
||||||
|
// system that already adds timestamps.
|
||||||
|
DisableTimestamp bool
|
||||||
|
|
||||||
|
// Enable logging the full timestamp when a TTY is attached instead of just
|
||||||
|
// the time passed since beginning of execution.
|
||||||
|
FullTimestamp bool
|
||||||
|
|
||||||
|
// TimestampFormat to use for display when a full timestamp is printed
|
||||||
|
TimestampFormat string
|
||||||
|
|
||||||
|
// The fields are sorted by default for a consistent output. For applications
|
||||||
|
// that log extremely frequently and don't use the JSON formatter this may not
|
||||||
|
// be desired.
|
||||||
|
DisableSorting bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
|
||||||
|
var b *bytes.Buffer
|
||||||
|
var keys []string = make([]string, 0, len(entry.Data))
|
||||||
|
for k := range entry.Data {
|
||||||
|
keys = append(keys, k)
|
||||||
|
}
|
||||||
|
|
||||||
|
if !f.DisableSorting {
|
||||||
|
sort.Strings(keys)
|
||||||
|
}
|
||||||
|
if entry.Buffer != nil {
|
||||||
|
b = entry.Buffer
|
||||||
|
} else {
|
||||||
|
b = &bytes.Buffer{}
|
||||||
|
}
|
||||||
|
|
||||||
|
prefixFieldClashes(entry.Data)
|
||||||
|
|
||||||
|
isColorTerminal := isTerminal && (runtime.GOOS != "windows")
|
||||||
|
isColored := (f.ForceColors || isColorTerminal) && !f.DisableColors
|
||||||
|
|
||||||
|
timestampFormat := f.TimestampFormat
|
||||||
|
if timestampFormat == "" {
|
||||||
|
timestampFormat = DefaultTimestampFormat
|
||||||
|
}
|
||||||
|
if isColored {
|
||||||
|
f.printColored(b, entry, keys, timestampFormat)
|
||||||
|
} else {
|
||||||
|
if !f.DisableTimestamp {
|
||||||
|
f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat))
|
||||||
|
}
|
||||||
|
f.appendKeyValue(b, "level", entry.Level.String())
|
||||||
|
if entry.Message != "" {
|
||||||
|
f.appendKeyValue(b, "msg", entry.Message)
|
||||||
|
}
|
||||||
|
for _, key := range keys {
|
||||||
|
f.appendKeyValue(b, key, entry.Data[key])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
b.WriteByte('\n')
|
||||||
|
return b.Bytes(), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) {
|
||||||
|
var levelColor int
|
||||||
|
switch entry.Level {
|
||||||
|
case DebugLevel:
|
||||||
|
levelColor = gray
|
||||||
|
case WarnLevel:
|
||||||
|
levelColor = yellow
|
||||||
|
case ErrorLevel, FatalLevel, PanicLevel:
|
||||||
|
levelColor = red
|
||||||
|
default:
|
||||||
|
levelColor = blue
|
||||||
|
}
|
||||||
|
|
||||||
|
levelText := strings.ToUpper(entry.Level.String())[0:4]
|
||||||
|
|
||||||
|
if !f.FullTimestamp {
|
||||||
|
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, miniTS(), entry.Message)
|
||||||
|
} else {
|
||||||
|
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message)
|
||||||
|
}
|
||||||
|
for _, k := range keys {
|
||||||
|
v := entry.Data[k]
|
||||||
|
fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k)
|
||||||
|
f.appendValue(b, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func needsQuoting(text string) bool {
|
||||||
|
for _, ch := range text {
|
||||||
|
if !((ch >= 'a' && ch <= 'z') ||
|
||||||
|
(ch >= 'A' && ch <= 'Z') ||
|
||||||
|
(ch >= '0' && ch <= '9') ||
|
||||||
|
ch == '-' || ch == '.') {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
|
||||||
|
|
||||||
|
b.WriteString(key)
|
||||||
|
b.WriteByte('=')
|
||||||
|
f.appendValue(b, value)
|
||||||
|
b.WriteByte(' ')
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
|
||||||
|
switch value := value.(type) {
|
||||||
|
case string:
|
||||||
|
if !needsQuoting(value) {
|
||||||
|
b.WriteString(value)
|
||||||
|
} else {
|
||||||
|
fmt.Fprintf(b, "%q", value)
|
||||||
|
}
|
||||||
|
case error:
|
||||||
|
errmsg := value.Error()
|
||||||
|
if !needsQuoting(errmsg) {
|
||||||
|
b.WriteString(errmsg)
|
||||||
|
} else {
|
||||||
|
fmt.Fprintf(b, "%q", errmsg)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
fmt.Fprint(b, value)
|
||||||
|
}
|
||||||
|
}
|
53
vendor/github.com/Sirupsen/logrus/writer.go
generated
vendored
Normal file
53
vendor/github.com/Sirupsen/logrus/writer.go
generated
vendored
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
package logrus
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"io"
|
||||||
|
"runtime"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (logger *Logger) Writer() *io.PipeWriter {
|
||||||
|
return logger.WriterLevel(InfoLevel)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) WriterLevel(level Level) *io.PipeWriter {
|
||||||
|
reader, writer := io.Pipe()
|
||||||
|
|
||||||
|
var printFunc func(args ...interface{})
|
||||||
|
switch level {
|
||||||
|
case DebugLevel:
|
||||||
|
printFunc = logger.Debug
|
||||||
|
case InfoLevel:
|
||||||
|
printFunc = logger.Info
|
||||||
|
case WarnLevel:
|
||||||
|
printFunc = logger.Warn
|
||||||
|
case ErrorLevel:
|
||||||
|
printFunc = logger.Error
|
||||||
|
case FatalLevel:
|
||||||
|
printFunc = logger.Fatal
|
||||||
|
case PanicLevel:
|
||||||
|
printFunc = logger.Panic
|
||||||
|
default:
|
||||||
|
printFunc = logger.Print
|
||||||
|
}
|
||||||
|
|
||||||
|
go logger.writerScanner(reader, printFunc)
|
||||||
|
runtime.SetFinalizer(writer, writerFinalizer)
|
||||||
|
|
||||||
|
return writer
|
||||||
|
}
|
||||||
|
|
||||||
|
func (logger *Logger) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) {
|
||||||
|
scanner := bufio.NewScanner(reader)
|
||||||
|
for scanner.Scan() {
|
||||||
|
printFunc(scanner.Text())
|
||||||
|
}
|
||||||
|
if err := scanner.Err(); err != nil {
|
||||||
|
logger.Errorf("Error while reading from Writer: %s", err)
|
||||||
|
}
|
||||||
|
reader.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func writerFinalizer(writer *io.PipeWriter) {
|
||||||
|
writer.Close()
|
||||||
|
}
|
4
vendor/github.com/boltdb/bolt/.gitignore
generated
vendored
Normal file
4
vendor/github.com/boltdb/bolt/.gitignore
generated
vendored
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
*.prof
|
||||||
|
*.test
|
||||||
|
*.swp
|
||||||
|
/bin/
|
20
vendor/github.com/boltdb/bolt/LICENSE
generated
vendored
Normal file
20
vendor/github.com/boltdb/bolt/LICENSE
generated
vendored
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (c) 2013 Ben Johnson
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||||
|
this software and associated documentation files (the "Software"), to deal in
|
||||||
|
the Software without restriction, including without limitation the rights to
|
||||||
|
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
||||||
|
the Software, and to permit persons to whom the Software is furnished to do so,
|
||||||
|
subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||||
|
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||||
|
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
||||||
|
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
||||||
|
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
18
vendor/github.com/boltdb/bolt/Makefile
generated
vendored
Normal file
18
vendor/github.com/boltdb/bolt/Makefile
generated
vendored
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
BRANCH=`git rev-parse --abbrev-ref HEAD`
|
||||||
|
COMMIT=`git rev-parse --short HEAD`
|
||||||
|
GOLDFLAGS="-X main.branch $(BRANCH) -X main.commit $(COMMIT)"
|
||||||
|
|
||||||
|
default: build
|
||||||
|
|
||||||
|
race:
|
||||||
|
@go test -v -race -test.run="TestSimulate_(100op|1000op)"
|
||||||
|
|
||||||
|
# go get github.com/kisielk/errcheck
|
||||||
|
errcheck:
|
||||||
|
@errcheck -ignorepkg=bytes -ignore=os:Remove github.com/boltdb/bolt
|
||||||
|
|
||||||
|
test:
|
||||||
|
@go test -v -cover .
|
||||||
|
@go test -v ./cmd/bolt
|
||||||
|
|
||||||
|
.PHONY: fmt test
|
915
vendor/github.com/boltdb/bolt/README.md
generated
vendored
Normal file
915
vendor/github.com/boltdb/bolt/README.md
generated
vendored
Normal file
@ -0,0 +1,915 @@
|
|||||||
|
Bolt [](https://coveralls.io/r/boltdb/bolt?branch=master) [](https://godoc.org/github.com/boltdb/bolt) 
|
||||||
|
====
|
||||||
|
|
||||||
|
Bolt is a pure Go key/value store inspired by [Howard Chu's][hyc_symas]
|
||||||
|
[LMDB project][lmdb]. The goal of the project is to provide a simple,
|
||||||
|
fast, and reliable database for projects that don't require a full database
|
||||||
|
server such as Postgres or MySQL.
|
||||||
|
|
||||||
|
Since Bolt is meant to be used as such a low-level piece of functionality,
|
||||||
|
simplicity is key. The API will be small and only focus on getting values
|
||||||
|
and setting values. That's it.
|
||||||
|
|
||||||
|
[hyc_symas]: https://twitter.com/hyc_symas
|
||||||
|
[lmdb]: http://symas.com/mdb/
|
||||||
|
|
||||||
|
## Project Status
|
||||||
|
|
||||||
|
Bolt is stable, the API is fixed, and the file format is fixed. Full unit
|
||||||
|
test coverage and randomized black box testing are used to ensure database
|
||||||
|
consistency and thread safety. Bolt is currently used in high-load production
|
||||||
|
environments serving databases as large as 1TB. Many companies such as
|
||||||
|
Shopify and Heroku use Bolt-backed services every day.
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
- [Getting Started](#getting-started)
|
||||||
|
- [Installing](#installing)
|
||||||
|
- [Opening a database](#opening-a-database)
|
||||||
|
- [Transactions](#transactions)
|
||||||
|
- [Read-write transactions](#read-write-transactions)
|
||||||
|
- [Read-only transactions](#read-only-transactions)
|
||||||
|
- [Batch read-write transactions](#batch-read-write-transactions)
|
||||||
|
- [Managing transactions manually](#managing-transactions-manually)
|
||||||
|
- [Using buckets](#using-buckets)
|
||||||
|
- [Using key/value pairs](#using-keyvalue-pairs)
|
||||||
|
- [Autoincrementing integer for the bucket](#autoincrementing-integer-for-the-bucket)
|
||||||
|
- [Iterating over keys](#iterating-over-keys)
|
||||||
|
- [Prefix scans](#prefix-scans)
|
||||||
|
- [Range scans](#range-scans)
|
||||||
|
- [ForEach()](#foreach)
|
||||||
|
- [Nested buckets](#nested-buckets)
|
||||||
|
- [Database backups](#database-backups)
|
||||||
|
- [Statistics](#statistics)
|
||||||
|
- [Read-Only Mode](#read-only-mode)
|
||||||
|
- [Mobile Use (iOS/Android)](#mobile-use-iosandroid)
|
||||||
|
- [Resources](#resources)
|
||||||
|
- [Comparison with other databases](#comparison-with-other-databases)
|
||||||
|
- [Postgres, MySQL, & other relational databases](#postgres-mysql--other-relational-databases)
|
||||||
|
- [LevelDB, RocksDB](#leveldb-rocksdb)
|
||||||
|
- [LMDB](#lmdb)
|
||||||
|
- [Caveats & Limitations](#caveats--limitations)
|
||||||
|
- [Reading the Source](#reading-the-source)
|
||||||
|
- [Other Projects Using Bolt](#other-projects-using-bolt)
|
||||||
|
|
||||||
|
## Getting Started
|
||||||
|
|
||||||
|
### Installing
|
||||||
|
|
||||||
|
To start using Bolt, install Go and run `go get`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
$ go get github.com/boltdb/bolt/...
|
||||||
|
```
|
||||||
|
|
||||||
|
This will retrieve the library and install the `bolt` command line utility into
|
||||||
|
your `$GOBIN` path.
|
||||||
|
|
||||||
|
|
||||||
|
### Opening a database
|
||||||
|
|
||||||
|
The top-level object in Bolt is a `DB`. It is represented as a single file on
|
||||||
|
your disk and represents a consistent snapshot of your data.
|
||||||
|
|
||||||
|
To open your database, simply use the `bolt.Open()` function:
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"github.com/boltdb/bolt"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// Open the my.db data file in your current directory.
|
||||||
|
// It will be created if it doesn't exist.
|
||||||
|
db, err := bolt.Open("my.db", 0600, nil)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
defer db.Close()
|
||||||
|
|
||||||
|
...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Please note that Bolt obtains a file lock on the data file so multiple processes
|
||||||
|
cannot open the same database at the same time. Opening an already open Bolt
|
||||||
|
database will cause it to hang until the other process closes it. To prevent
|
||||||
|
an indefinite wait you can pass a timeout option to the `Open()` function:
|
||||||
|
|
||||||
|
```go
|
||||||
|
db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second})
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### Transactions
|
||||||
|
|
||||||
|
Bolt allows only one read-write transaction at a time but allows as many
|
||||||
|
read-only transactions as you want at a time. Each transaction has a consistent
|
||||||
|
view of the data as it existed when the transaction started.
|
||||||
|
|
||||||
|
Individual transactions and all objects created from them (e.g. buckets, keys)
|
||||||
|
are not thread safe. To work with data in multiple goroutines you must start
|
||||||
|
a transaction for each one or use locking to ensure only one goroutine accesses
|
||||||
|
a transaction at a time. Creating transaction from the `DB` is thread safe.
|
||||||
|
|
||||||
|
Read-only transactions and read-write transactions should not depend on one
|
||||||
|
another and generally shouldn't be opened simultaneously in the same goroutine.
|
||||||
|
This can cause a deadlock as the read-write transaction needs to periodically
|
||||||
|
re-map the data file but it cannot do so while a read-only transaction is open.
|
||||||
|
|
||||||
|
|
||||||
|
#### Read-write transactions
|
||||||
|
|
||||||
|
To start a read-write transaction, you can use the `DB.Update()` function:
|
||||||
|
|
||||||
|
```go
|
||||||
|
err := db.Update(func(tx *bolt.Tx) error {
|
||||||
|
...
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Inside the closure, you have a consistent view of the database. You commit the
|
||||||
|
transaction by returning `nil` at the end. You can also rollback the transaction
|
||||||
|
at any point by returning an error. All database operations are allowed inside
|
||||||
|
a read-write transaction.
|
||||||
|
|
||||||
|
Always check the return error as it will report any disk failures that can cause
|
||||||
|
your transaction to not complete. If you return an error within your closure
|
||||||
|
it will be passed through.
|
||||||
|
|
||||||
|
|
||||||
|
#### Read-only transactions
|
||||||
|
|
||||||
|
To start a read-only transaction, you can use the `DB.View()` function:
|
||||||
|
|
||||||
|
```go
|
||||||
|
err := db.View(func(tx *bolt.Tx) error {
|
||||||
|
...
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
You also get a consistent view of the database within this closure, however,
|
||||||
|
no mutating operations are allowed within a read-only transaction. You can only
|
||||||
|
retrieve buckets, retrieve values, and copy the database within a read-only
|
||||||
|
transaction.
|
||||||
|
|
||||||
|
|
||||||
|
#### Batch read-write transactions
|
||||||
|
|
||||||
|
Each `DB.Update()` waits for disk to commit the writes. This overhead
|
||||||
|
can be minimized by combining multiple updates with the `DB.Batch()`
|
||||||
|
function:
|
||||||
|
|
||||||
|
```go
|
||||||
|
err := db.Batch(func(tx *bolt.Tx) error {
|
||||||
|
...
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Concurrent Batch calls are opportunistically combined into larger
|
||||||
|
transactions. Batch is only useful when there are multiple goroutines
|
||||||
|
calling it.
|
||||||
|
|
||||||
|
The trade-off is that `Batch` can call the given
|
||||||
|
function multiple times, if parts of the transaction fail. The
|
||||||
|
function must be idempotent and side effects must take effect only
|
||||||
|
after a successful return from `DB.Batch()`.
|
||||||
|
|
||||||
|
For example: don't display messages from inside the function, instead
|
||||||
|
set variables in the enclosing scope:
|
||||||
|
|
||||||
|
```go
|
||||||
|
var id uint64
|
||||||
|
err := db.Batch(func(tx *bolt.Tx) error {
|
||||||
|
// Find last key in bucket, decode as bigendian uint64, increment
|
||||||
|
// by one, encode back to []byte, and add new key.
|
||||||
|
...
|
||||||
|
id = newValue
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return ...
|
||||||
|
}
|
||||||
|
fmt.Println("Allocated ID %d", id)
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
#### Managing transactions manually
|
||||||
|
|
||||||
|
The `DB.View()` and `DB.Update()` functions are wrappers around the `DB.Begin()`
|
||||||
|
function. These helper functions will start the transaction, execute a function,
|
||||||
|
and then safely close your transaction if an error is returned. This is the
|
||||||
|
recommended way to use Bolt transactions.
|
||||||
|
|
||||||
|
However, sometimes you may want to manually start and end your transactions.
|
||||||
|
You can use the `DB.Begin()` function directly but **please** be sure to close
|
||||||
|
the transaction.
|
||||||
|
|
||||||
|
```go
|
||||||
|
// Start a writable transaction.
|
||||||
|
tx, err := db.Begin(true)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
|
||||||
|
// Use the transaction...
|
||||||
|
_, err := tx.CreateBucket([]byte("MyBucket"))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Commit the transaction and check for error.
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The first argument to `DB.Begin()` is a boolean stating if the transaction
|
||||||
|
should be writable.
|
||||||
|
|
||||||
|
|
||||||
|
### Using buckets
|
||||||
|
|
||||||
|
Buckets are collections of key/value pairs within the database. All keys in a
|
||||||
|
bucket must be unique. You can create a bucket using the `DB.CreateBucket()`
|
||||||
|
function:
|
||||||
|
|
||||||
|
```go
|
||||||
|
db.Update(func(tx *bolt.Tx) error {
|
||||||
|
b, err := tx.CreateBucket([]byte("MyBucket"))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("create bucket: %s", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also create a bucket only if it doesn't exist by using the
|
||||||
|
`Tx.CreateBucketIfNotExists()` function. It's a common pattern to call this
|
||||||
|
function for all your top-level buckets after you open your database so you can
|
||||||
|
guarantee that they exist for future transactions.
|
||||||
|
|
||||||
|
To delete a bucket, simply call the `Tx.DeleteBucket()` function.
|
||||||
|
|
||||||
|
|
||||||
|
### Using key/value pairs
|
||||||
|
|
||||||
|
To save a key/value pair to a bucket, use the `Bucket.Put()` function:
|
||||||
|
|
||||||
|
```go
|
||||||
|
db.Update(func(tx *bolt.Tx) error {
|
||||||
|
b := tx.Bucket([]byte("MyBucket"))
|
||||||
|
err := b.Put([]byte("answer"), []byte("42"))
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
This will set the value of the `"answer"` key to `"42"` in the `MyBucket`
|
||||||
|
bucket. To retrieve this value, we can use the `Bucket.Get()` function:
|
||||||
|
|
||||||
|
```go
|
||||||
|
db.View(func(tx *bolt.Tx) error {
|
||||||
|
b := tx.Bucket([]byte("MyBucket"))
|
||||||
|
v := b.Get([]byte("answer"))
|
||||||
|
fmt.Printf("The answer is: %s\n", v)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
The `Get()` function does not return an error because its operation is
|
||||||
|
guaranteed to work (unless there is some kind of system failure). If the key
|
||||||
|
exists then it will return its byte slice value. If it doesn't exist then it
|
||||||
|
will return `nil`. It's important to note that you can have a zero-length value
|
||||||
|
set to a key which is different than the key not existing.
|
||||||
|
|
||||||
|
Use the `Bucket.Delete()` function to delete a key from the bucket.
|
||||||
|
|
||||||
|
Please note that values returned from `Get()` are only valid while the
|
||||||
|
transaction is open. If you need to use a value outside of the transaction
|
||||||
|
then you must use `copy()` to copy it to another byte slice.
|
||||||
|
|
||||||
|
|
||||||
|
### Autoincrementing integer for the bucket
|
||||||
|
By using the `NextSequence()` function, you can let Bolt determine a sequence
|
||||||
|
which can be used as the unique identifier for your key/value pairs. See the
|
||||||
|
example below.
|
||||||
|
|
||||||
|
```go
|
||||||
|
// CreateUser saves u to the store. The new user ID is set on u once the data is persisted.
|
||||||
|
func (s *Store) CreateUser(u *User) error {
|
||||||
|
return s.db.Update(func(tx *bolt.Tx) error {
|
||||||
|
// Retrieve the users bucket.
|
||||||
|
// This should be created when the DB is first opened.
|
||||||
|
b := tx.Bucket([]byte("users"))
|
||||||
|
|
||||||
|
// Generate ID for the user.
|
||||||
|
// This returns an error only if the Tx is closed or not writeable.
|
||||||
|
// That can't happen in an Update() call so I ignore the error check.
|
||||||
|
id, _ := b.NextSequence()
|
||||||
|
u.ID = int(id)
|
||||||
|
|
||||||
|
// Marshal user data into bytes.
|
||||||
|
buf, err := json.Marshal(u)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Persist bytes to users bucket.
|
||||||
|
return b.Put(itob(u.ID), buf)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// itob returns an 8-byte big endian representation of v.
|
||||||
|
func itob(v int) []byte {
|
||||||
|
b := make([]byte, 8)
|
||||||
|
binary.BigEndian.PutUint64(b, uint64(v))
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
ID int
|
||||||
|
...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Iterating over keys
|
||||||
|
|
||||||
|
Bolt stores its keys in byte-sorted order within a bucket. This makes sequential
|
||||||
|
iteration over these keys extremely fast. To iterate over keys we'll use a
|
||||||
|
`Cursor`:
|
||||||
|
|
||||||
|
```go
|
||||||
|
db.View(func(tx *bolt.Tx) error {
|
||||||
|
// Assume bucket exists and has keys
|
||||||
|
b := tx.Bucket([]byte("MyBucket"))
|
||||||
|
|
||||||
|
c := b.Cursor()
|
||||||
|
|
||||||
|
for k, v := c.First(); k != nil; k, v = c.Next() {
|
||||||
|
fmt.Printf("key=%s, value=%s\n", k, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
The cursor allows you to move to a specific point in the list of keys and move
|
||||||
|
forward or backward through the keys one at a time.
|
||||||
|
|
||||||
|
The following functions are available on the cursor:
|
||||||
|
|
||||||
|
```
|
||||||
|
First() Move to the first key.
|
||||||
|
Last() Move to the last key.
|
||||||
|
Seek() Move to a specific key.
|
||||||
|
Next() Move to the next key.
|
||||||
|
Prev() Move to the previous key.
|
||||||
|
```
|
||||||
|
|
||||||
|
Each of those functions has a return signature of `(key []byte, value []byte)`.
|
||||||
|
When you have iterated to the end of the cursor then `Next()` will return a
|
||||||
|
`nil` key. You must seek to a position using `First()`, `Last()`, or `Seek()`
|
||||||
|
before calling `Next()` or `Prev()`. If you do not seek to a position then
|
||||||
|
these functions will return a `nil` key.
|
||||||
|
|
||||||
|
During iteration, if the key is non-`nil` but the value is `nil`, that means
|
||||||
|
the key refers to a bucket rather than a value. Use `Bucket.Bucket()` to
|
||||||
|
access the sub-bucket.
|
||||||
|
|
||||||
|
|
||||||
|
#### Prefix scans
|
||||||
|
|
||||||
|
To iterate over a key prefix, you can combine `Seek()` and `bytes.HasPrefix()`:
|
||||||
|
|
||||||
|
```go
|
||||||
|
db.View(func(tx *bolt.Tx) error {
|
||||||
|
// Assume bucket exists and has keys
|
||||||
|
c := tx.Bucket([]byte("MyBucket")).Cursor()
|
||||||
|
|
||||||
|
prefix := []byte("1234")
|
||||||
|
for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() {
|
||||||
|
fmt.Printf("key=%s, value=%s\n", k, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Range scans
|
||||||
|
|
||||||
|
Another common use case is scanning over a range such as a time range. If you
|
||||||
|
use a sortable time encoding such as RFC3339 then you can query a specific
|
||||||
|
date range like this:
|
||||||
|
|
||||||
|
```go
|
||||||
|
db.View(func(tx *bolt.Tx) error {
|
||||||
|
// Assume our events bucket exists and has RFC3339 encoded time keys.
|
||||||
|
c := tx.Bucket([]byte("Events")).Cursor()
|
||||||
|
|
||||||
|
// Our time range spans the 90's decade.
|
||||||
|
min := []byte("1990-01-01T00:00:00Z")
|
||||||
|
max := []byte("2000-01-01T00:00:00Z")
|
||||||
|
|
||||||
|
// Iterate over the 90's.
|
||||||
|
for k, v := c.Seek(min); k != nil && bytes.Compare(k, max) <= 0; k, v = c.Next() {
|
||||||
|
fmt.Printf("%s: %s\n", k, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Note that, while RFC3339 is sortable, the Golang implementation of RFC3339Nano does not use a fixed number of digits after the decimal point and is therefore not sortable.
|
||||||
|
|
||||||
|
|
||||||
|
#### ForEach()
|
||||||
|
|
||||||
|
You can also use the function `ForEach()` if you know you'll be iterating over
|
||||||
|
all the keys in a bucket:
|
||||||
|
|
||||||
|
```go
|
||||||
|
db.View(func(tx *bolt.Tx) error {
|
||||||
|
// Assume bucket exists and has keys
|
||||||
|
b := tx.Bucket([]byte("MyBucket"))
|
||||||
|
|
||||||
|
b.ForEach(func(k, v []byte) error {
|
||||||
|
fmt.Printf("key=%s, value=%s\n", k, v)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Please note that keys and values in `ForEach()` are only valid while
|
||||||
|
the transaction is open. If you need to use a key or value outside of
|
||||||
|
the transaction, you must use `copy()` to copy it to another byte
|
||||||
|
slice.
|
||||||
|
|
||||||
|
### Nested buckets
|
||||||
|
|
||||||
|
You can also store a bucket in a key to create nested buckets. The API is the
|
||||||
|
same as the bucket management API on the `DB` object:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func (*Bucket) CreateBucket(key []byte) (*Bucket, error)
|
||||||
|
func (*Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error)
|
||||||
|
func (*Bucket) DeleteBucket(key []byte) error
|
||||||
|
```
|
||||||
|
|
||||||
|
Say you had a multi-tenant application where the root level bucket was the account bucket. Inside of this bucket was a sequence of accounts which themselves are buckets. And inside the sequence bucket you could have many buckets pertaining to the Account itself (Users, Notes, etc) isolating the information into logical groupings.
|
||||||
|
|
||||||
|
```go
|
||||||
|
|
||||||
|
// createUser creates a new user in the given account.
|
||||||
|
func createUser(accountID int, u *User) error {
|
||||||
|
// Start the transaction.
|
||||||
|
tx, err := db.Begin(true)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer tx.Rollback()
|
||||||
|
|
||||||
|
// Retrieve the root bucket for the account.
|
||||||
|
// Assume this has already been created when the account was set up.
|
||||||
|
root := tx.Bucket([]byte(strconv.FormatUint(accountID, 10)))
|
||||||
|
|
||||||
|
// Setup the users bucket.
|
||||||
|
bkt, err := root.CreateBucketIfNotExists([]byte("USERS"))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate an ID for the new user.
|
||||||
|
userID, err := bkt.NextSequence()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
u.ID = userID
|
||||||
|
|
||||||
|
// Marshal and save the encoded user.
|
||||||
|
if buf, err := json.Marshal(u); err != nil {
|
||||||
|
return err
|
||||||
|
} else if err := bkt.Put([]byte(strconv.FormatUint(u.ID, 10)), buf); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Commit the transaction.
|
||||||
|
if err := tx.Commit(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
### Database backups
|
||||||
|
|
||||||
|
Bolt is a single file so it's easy to backup. You can use the `Tx.WriteTo()`
|
||||||
|
function to write a consistent view of the database to a writer. If you call
|
||||||
|
this from a read-only transaction, it will perform a hot backup and not block
|
||||||
|
your other database reads and writes.
|
||||||
|
|
||||||
|
By default, it will use a regular file handle which will utilize the operating
|
||||||
|
system's page cache. See the [`Tx`](https://godoc.org/github.com/boltdb/bolt#Tx)
|
||||||
|
documentation for information about optimizing for larger-than-RAM datasets.
|
||||||
|
|
||||||
|
One common use case is to backup over HTTP so you can use tools like `cURL` to
|
||||||
|
do database backups:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func BackupHandleFunc(w http.ResponseWriter, req *http.Request) {
|
||||||
|
err := db.View(func(tx *bolt.Tx) error {
|
||||||
|
w.Header().Set("Content-Type", "application/octet-stream")
|
||||||
|
w.Header().Set("Content-Disposition", `attachment; filename="my.db"`)
|
||||||
|
w.Header().Set("Content-Length", strconv.Itoa(int(tx.Size())))
|
||||||
|
_, err := tx.WriteTo(w)
|
||||||
|
return err
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Then you can backup using this command:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
$ curl http://localhost/backup > my.db
|
||||||
|
```
|
||||||
|
|
||||||
|
Or you can open your browser to `http://localhost/backup` and it will download
|
||||||
|
automatically.
|
||||||
|
|
||||||
|
If you want to backup to another file you can use the `Tx.CopyFile()` helper
|
||||||
|
function.
|
||||||
|
|
||||||
|
|
||||||
|
### Statistics
|
||||||
|
|
||||||
|
The database keeps a running count of many of the internal operations it
|
||||||
|
performs so you can better understand what's going on. By grabbing a snapshot
|
||||||
|
of these stats at two points in time we can see what operations were performed
|
||||||
|
in that time range.
|
||||||
|
|
||||||
|
For example, we could start a goroutine to log stats every 10 seconds:
|
||||||
|
|
||||||
|
```go
|
||||||
|
go func() {
|
||||||
|
// Grab the initial stats.
|
||||||
|
prev := db.Stats()
|
||||||
|
|
||||||
|
for {
|
||||||
|
// Wait for 10s.
|
||||||
|
time.Sleep(10 * time.Second)
|
||||||
|
|
||||||
|
// Grab the current stats and diff them.
|
||||||
|
stats := db.Stats()
|
||||||
|
diff := stats.Sub(&prev)
|
||||||
|
|
||||||
|
// Encode stats to JSON and print to STDERR.
|
||||||
|
json.NewEncoder(os.Stderr).Encode(diff)
|
||||||
|
|
||||||
|
// Save stats for the next loop.
|
||||||
|
prev = stats
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
```
|
||||||
|
|
||||||
|
It's also useful to pipe these stats to a service such as statsd for monitoring
|
||||||
|
or to provide an HTTP endpoint that will perform a fixed-length sample.
|
||||||
|
|
||||||
|
|
||||||
|
### Read-Only Mode
|
||||||
|
|
||||||
|
Sometimes it is useful to create a shared, read-only Bolt database. To this,
|
||||||
|
set the `Options.ReadOnly` flag when opening your database. Read-only mode
|
||||||
|
uses a shared lock to allow multiple processes to read from the database but
|
||||||
|
it will block any processes from opening the database in read-write mode.
|
||||||
|
|
||||||
|
```go
|
||||||
|
db, err := bolt.Open("my.db", 0666, &bolt.Options{ReadOnly: true})
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Mobile Use (iOS/Android)
|
||||||
|
|
||||||
|
Bolt is able to run on mobile devices by leveraging the binding feature of the
|
||||||
|
[gomobile](https://github.com/golang/mobile) tool. Create a struct that will
|
||||||
|
contain your database logic and a reference to a `*bolt.DB` with a initializing
|
||||||
|
constructor that takes in a filepath where the database file will be stored.
|
||||||
|
Neither Android nor iOS require extra permissions or cleanup from using this method.
|
||||||
|
|
||||||
|
```go
|
||||||
|
func NewBoltDB(filepath string) *BoltDB {
|
||||||
|
db, err := bolt.Open(filepath+"/demo.db", 0600, nil)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &BoltDB{db}
|
||||||
|
}
|
||||||
|
|
||||||
|
type BoltDB struct {
|
||||||
|
db *bolt.DB
|
||||||
|
...
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BoltDB) Path() string {
|
||||||
|
return b.db.Path()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *BoltDB) Close() {
|
||||||
|
b.db.Close()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Database logic should be defined as methods on this wrapper struct.
|
||||||
|
|
||||||
|
To initialize this struct from the native language (both platforms now sync
|
||||||
|
their local storage to the cloud. These snippets disable that functionality for the
|
||||||
|
database file):
|
||||||
|
|
||||||
|
#### Android
|
||||||
|
|
||||||
|
```java
|
||||||
|
String path;
|
||||||
|
if (android.os.Build.VERSION.SDK_INT >=android.os.Build.VERSION_CODES.LOLLIPOP){
|
||||||
|
path = getNoBackupFilesDir().getAbsolutePath();
|
||||||
|
} else{
|
||||||
|
path = getFilesDir().getAbsolutePath();
|
||||||
|
}
|
||||||
|
Boltmobiledemo.BoltDB boltDB = Boltmobiledemo.NewBoltDB(path)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### iOS
|
||||||
|
|
||||||
|
```objc
|
||||||
|
- (void)demo {
|
||||||
|
NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
|
||||||
|
NSUserDomainMask,
|
||||||
|
YES) objectAtIndex:0];
|
||||||
|
GoBoltmobiledemoBoltDB * demo = GoBoltmobiledemoNewBoltDB(path);
|
||||||
|
[self addSkipBackupAttributeToItemAtPath:demo.path];
|
||||||
|
//Some DB Logic would go here
|
||||||
|
[demo close];
|
||||||
|
}
|
||||||
|
|
||||||
|
- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString
|
||||||
|
{
|
||||||
|
NSURL* URL= [NSURL fileURLWithPath: filePathString];
|
||||||
|
assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]);
|
||||||
|
|
||||||
|
NSError *error = nil;
|
||||||
|
BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES]
|
||||||
|
forKey: NSURLIsExcludedFromBackupKey error: &error];
|
||||||
|
if(!success){
|
||||||
|
NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error);
|
||||||
|
}
|
||||||
|
return success;
|
||||||
|
}
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
For more information on getting started with Bolt, check out the following articles:
|
||||||
|
|
||||||
|
* [Intro to BoltDB: Painless Performant Persistence](http://npf.io/2014/07/intro-to-boltdb-painless-performant-persistence/) by [Nate Finch](https://github.com/natefinch).
|
||||||
|
* [Bolt -- an embedded key/value database for Go](https://www.progville.com/go/bolt-embedded-db-golang/) by Progville
|
||||||
|
|
||||||
|
|
||||||
|
## Comparison with other databases
|
||||||
|
|
||||||
|
### Postgres, MySQL, & other relational databases
|
||||||
|
|
||||||
|
Relational databases structure data into rows and are only accessible through
|
||||||
|
the use of SQL. This approach provides flexibility in how you store and query
|
||||||
|
your data but also incurs overhead in parsing and planning SQL statements. Bolt
|
||||||
|
accesses all data by a byte slice key. This makes Bolt fast to read and write
|
||||||
|
data by key but provides no built-in support for joining values together.
|
||||||
|
|
||||||
|
Most relational databases (with the exception of SQLite) are standalone servers
|
||||||
|
that run separately from your application. This gives your systems
|
||||||
|
flexibility to connect multiple application servers to a single database
|
||||||
|
server but also adds overhead in serializing and transporting data over the
|
||||||
|
network. Bolt runs as a library included in your application so all data access
|
||||||
|
has to go through your application's process. This brings data closer to your
|
||||||
|
application but limits multi-process access to the data.
|
||||||
|
|
||||||
|
|
||||||
|
### LevelDB, RocksDB
|
||||||
|
|
||||||
|
LevelDB and its derivatives (RocksDB, HyperLevelDB) are similar to Bolt in that
|
||||||
|
they are libraries bundled into the application, however, their underlying
|
||||||
|
structure is a log-structured merge-tree (LSM tree). An LSM tree optimizes
|
||||||
|
random writes by using a write ahead log and multi-tiered, sorted files called
|
||||||
|
SSTables. Bolt uses a B+tree internally and only a single file. Both approaches
|
||||||
|
have trade-offs.
|
||||||
|
|
||||||
|
If you require a high random write throughput (>10,000 w/sec) or you need to use
|
||||||
|
spinning disks then LevelDB could be a good choice. If your application is
|
||||||
|
read-heavy or does a lot of range scans then Bolt could be a good choice.
|
||||||
|
|
||||||
|
One other important consideration is that LevelDB does not have transactions.
|
||||||
|
It supports batch writing of key/values pairs and it supports read snapshots
|
||||||
|
but it will not give you the ability to do a compare-and-swap operation safely.
|
||||||
|
Bolt supports fully serializable ACID transactions.
|
||||||
|
|
||||||
|
|
||||||
|
### LMDB
|
||||||
|
|
||||||
|
Bolt was originally a port of LMDB so it is architecturally similar. Both use
|
||||||
|
a B+tree, have ACID semantics with fully serializable transactions, and support
|
||||||
|
lock-free MVCC using a single writer and multiple readers.
|
||||||
|
|
||||||
|
The two projects have somewhat diverged. LMDB heavily focuses on raw performance
|
||||||
|
while Bolt has focused on simplicity and ease of use. For example, LMDB allows
|
||||||
|
several unsafe actions such as direct writes for the sake of performance. Bolt
|
||||||
|
opts to disallow actions which can leave the database in a corrupted state. The
|
||||||
|
only exception to this in Bolt is `DB.NoSync`.
|
||||||
|
|
||||||
|
There are also a few differences in API. LMDB requires a maximum mmap size when
|
||||||
|
opening an `mdb_env` whereas Bolt will handle incremental mmap resizing
|
||||||
|
automatically. LMDB overloads the getter and setter functions with multiple
|
||||||
|
flags whereas Bolt splits these specialized cases into their own functions.
|
||||||
|
|
||||||
|
|
||||||
|
## Caveats & Limitations
|
||||||
|
|
||||||
|
It's important to pick the right tool for the job and Bolt is no exception.
|
||||||
|
Here are a few things to note when evaluating and using Bolt:
|
||||||
|
|
||||||
|
* Bolt is good for read intensive workloads. Sequential write performance is
|
||||||
|
also fast but random writes can be slow. You can use `DB.Batch()` or add a
|
||||||
|
write-ahead log to help mitigate this issue.
|
||||||
|
|
||||||
|
* Bolt uses a B+tree internally so there can be a lot of random page access.
|
||||||
|
SSDs provide a significant performance boost over spinning disks.
|
||||||
|
|
||||||
|
* Try to avoid long running read transactions. Bolt uses copy-on-write so
|
||||||
|
old pages cannot be reclaimed while an old transaction is using them.
|
||||||
|
|
||||||
|
* Byte slices returned from Bolt are only valid during a transaction. Once the
|
||||||
|
transaction has been committed or rolled back then the memory they point to
|
||||||
|
can be reused by a new page or can be unmapped from virtual memory and you'll
|
||||||
|
see an `unexpected fault address` panic when accessing it.
|
||||||
|
|
||||||
|
* Bolt uses an exclusive write lock on the database file so it cannot be
|
||||||
|
shared by multiple processes.
|
||||||
|
|
||||||
|
* Be careful when using `Bucket.FillPercent`. Setting a high fill percent for
|
||||||
|
buckets that have random inserts will cause your database to have very poor
|
||||||
|
page utilization.
|
||||||
|
|
||||||
|
* Use larger buckets in general. Smaller buckets causes poor page utilization
|
||||||
|
once they become larger than the page size (typically 4KB).
|
||||||
|
|
||||||
|
* Bulk loading a lot of random writes into a new bucket can be slow as the
|
||||||
|
page will not split until the transaction is committed. Randomly inserting
|
||||||
|
more than 100,000 key/value pairs into a single new bucket in a single
|
||||||
|
transaction is not advised.
|
||||||
|
|
||||||
|
* Bolt uses a memory-mapped file so the underlying operating system handles the
|
||||||
|
caching of the data. Typically, the OS will cache as much of the file as it
|
||||||
|
can in memory and will release memory as needed to other processes. This means
|
||||||
|
that Bolt can show very high memory usage when working with large databases.
|
||||||
|
However, this is expected and the OS will release memory as needed. Bolt can
|
||||||
|
handle databases much larger than the available physical RAM, provided its
|
||||||
|
memory-map fits in the process virtual address space. It may be problematic
|
||||||
|
on 32-bits systems.
|
||||||
|
|
||||||
|
* The data structures in the Bolt database are memory mapped so the data file
|
||||||
|
will be endian specific. This means that you cannot copy a Bolt file from a
|
||||||
|
little endian machine to a big endian machine and have it work. For most
|
||||||
|
users this is not a concern since most modern CPUs are little endian.
|
||||||
|
|
||||||
|
* Because of the way pages are laid out on disk, Bolt cannot truncate data files
|
||||||
|
and return free pages back to the disk. Instead, Bolt maintains a free list
|
||||||
|
of unused pages within its data file. These free pages can be reused by later
|
||||||
|
transactions. This works well for many use cases as databases generally tend
|
||||||
|
to grow. However, it's important to note that deleting large chunks of data
|
||||||
|
will not allow you to reclaim that space on disk.
|
||||||
|
|
||||||
|
For more information on page allocation, [see this comment][page-allocation].
|
||||||
|
|
||||||
|
[page-allocation]: https://github.com/boltdb/bolt/issues/308#issuecomment-74811638
|
||||||
|
|
||||||
|
|
||||||
|
## Reading the Source
|
||||||
|
|
||||||
|
Bolt is a relatively small code base (<3KLOC) for an embedded, serializable,
|
||||||
|
transactional key/value database so it can be a good starting point for people
|
||||||
|
interested in how databases work.
|
||||||
|
|
||||||
|
The best places to start are the main entry points into Bolt:
|
||||||
|
|
||||||
|
- `Open()` - Initializes the reference to the database. It's responsible for
|
||||||
|
creating the database if it doesn't exist, obtaining an exclusive lock on the
|
||||||
|
file, reading the meta pages, & memory-mapping the file.
|
||||||
|
|
||||||
|
- `DB.Begin()` - Starts a read-only or read-write transaction depending on the
|
||||||
|
value of the `writable` argument. This requires briefly obtaining the "meta"
|
||||||
|
lock to keep track of open transactions. Only one read-write transaction can
|
||||||
|
exist at a time so the "rwlock" is acquired during the life of a read-write
|
||||||
|
transaction.
|
||||||
|
|
||||||
|
- `Bucket.Put()` - Writes a key/value pair into a bucket. After validating the
|
||||||
|
arguments, a cursor is used to traverse the B+tree to the page and position
|
||||||
|
where they key & value will be written. Once the position is found, the bucket
|
||||||
|
materializes the underlying page and the page's parent pages into memory as
|
||||||
|
"nodes". These nodes are where mutations occur during read-write transactions.
|
||||||
|
These changes get flushed to disk during commit.
|
||||||
|
|
||||||
|
- `Bucket.Get()` - Retrieves a key/value pair from a bucket. This uses a cursor
|
||||||
|
to move to the page & position of a key/value pair. During a read-only
|
||||||
|
transaction, the key and value data is returned as a direct reference to the
|
||||||
|
underlying mmap file so there's no allocation overhead. For read-write
|
||||||
|
transactions, this data may reference the mmap file or one of the in-memory
|
||||||
|
node values.
|
||||||
|
|
||||||
|
- `Cursor` - This object is simply for traversing the B+tree of on-disk pages
|
||||||
|
or in-memory nodes. It can seek to a specific key, move to the first or last
|
||||||
|
value, or it can move forward or backward. The cursor handles the movement up
|
||||||
|
and down the B+tree transparently to the end user.
|
||||||
|
|
||||||
|
- `Tx.Commit()` - Converts the in-memory dirty nodes and the list of free pages
|
||||||
|
into pages to be written to disk. Writing to disk then occurs in two phases.
|
||||||
|
First, the dirty pages are written to disk and an `fsync()` occurs. Second, a
|
||||||
|
new meta page with an incremented transaction ID is written and another
|
||||||
|
`fsync()` occurs. This two phase write ensures that partially written data
|
||||||
|
pages are ignored in the event of a crash since the meta page pointing to them
|
||||||
|
is never written. Partially written meta pages are invalidated because they
|
||||||
|
are written with a checksum.
|
||||||
|
|
||||||
|
If you have additional notes that could be helpful for others, please submit
|
||||||
|
them via pull request.
|
||||||
|
|
||||||
|
|
||||||
|
## Other Projects Using Bolt
|
||||||
|
|
||||||
|
Below is a list of public, open source projects that use Bolt:
|
||||||
|
|
||||||
|
* [BoltDbWeb](https://github.com/evnix/boltdbweb) - A web based GUI for BoltDB files.
|
||||||
|
* [Operation Go: A Routine Mission](http://gocode.io) - An online programming game for Golang using Bolt for user accounts and a leaderboard.
|
||||||
|
* [Bazil](https://bazil.org/) - A file system that lets your data reside where it is most convenient for it to reside.
|
||||||
|
* [DVID](https://github.com/janelia-flyem/dvid) - Added Bolt as optional storage engine and testing it against Basho-tuned leveldb.
|
||||||
|
* [Skybox Analytics](https://github.com/skybox/skybox) - A standalone funnel analysis tool for web analytics.
|
||||||
|
* [Scuttlebutt](https://github.com/benbjohnson/scuttlebutt) - Uses Bolt to store and process all Twitter mentions of GitHub projects.
|
||||||
|
* [Wiki](https://github.com/peterhellberg/wiki) - A tiny wiki using Goji, BoltDB and Blackfriday.
|
||||||
|
* [ChainStore](https://github.com/pressly/chainstore) - Simple key-value interface to a variety of storage engines organized as a chain of operations.
|
||||||
|
* [MetricBase](https://github.com/msiebuhr/MetricBase) - Single-binary version of Graphite.
|
||||||
|
* [Gitchain](https://github.com/gitchain/gitchain) - Decentralized, peer-to-peer Git repositories aka "Git meets Bitcoin".
|
||||||
|
* [event-shuttle](https://github.com/sclasen/event-shuttle) - A Unix system service to collect and reliably deliver messages to Kafka.
|
||||||
|
* [ipxed](https://github.com/kelseyhightower/ipxed) - Web interface and api for ipxed.
|
||||||
|
* [BoltStore](https://github.com/yosssi/boltstore) - Session store using Bolt.
|
||||||
|
* [photosite/session](https://godoc.org/bitbucket.org/kardianos/photosite/session) - Sessions for a photo viewing site.
|
||||||
|
* [LedisDB](https://github.com/siddontang/ledisdb) - A high performance NoSQL, using Bolt as optional storage.
|
||||||
|
* [ipLocator](https://github.com/AndreasBriese/ipLocator) - A fast ip-geo-location-server using bolt with bloom filters.
|
||||||
|
* [cayley](https://github.com/google/cayley) - Cayley is an open-source graph database using Bolt as optional backend.
|
||||||
|
* [bleve](http://www.blevesearch.com/) - A pure Go search engine similar to ElasticSearch that uses Bolt as the default storage backend.
|
||||||
|
* [tentacool](https://github.com/optiflows/tentacool) - REST api server to manage system stuff (IP, DNS, Gateway...) on a linux server.
|
||||||
|
* [Seaweed File System](https://github.com/chrislusf/seaweedfs) - Highly scalable distributed key~file system with O(1) disk read.
|
||||||
|
* [InfluxDB](https://influxdata.com) - Scalable datastore for metrics, events, and real-time analytics.
|
||||||
|
* [Freehold](http://tshannon.bitbucket.org/freehold/) - An open, secure, and lightweight platform for your files and data.
|
||||||
|
* [Prometheus Annotation Server](https://github.com/oliver006/prom_annotation_server) - Annotation server for PromDash & Prometheus service monitoring system.
|
||||||
|
* [Consul](https://github.com/hashicorp/consul) - Consul is service discovery and configuration made easy. Distributed, highly available, and datacenter-aware.
|
||||||
|
* [Kala](https://github.com/ajvb/kala) - Kala is a modern job scheduler optimized to run on a single node. It is persistent, JSON over HTTP API, ISO 8601 duration notation, and dependent jobs.
|
||||||
|
* [drive](https://github.com/odeke-em/drive) - drive is an unofficial Google Drive command line client for \*NIX operating systems.
|
||||||
|
* [stow](https://github.com/djherbis/stow) - a persistence manager for objects
|
||||||
|
backed by boltdb.
|
||||||
|
* [buckets](https://github.com/joyrexus/buckets) - a bolt wrapper streamlining
|
||||||
|
simple tx and key scans.
|
||||||
|
* [mbuckets](https://github.com/abhigupta912/mbuckets) - A Bolt wrapper that allows easy operations on multi level (nested) buckets.
|
||||||
|
* [Request Baskets](https://github.com/darklynx/request-baskets) - A web service to collect arbitrary HTTP requests and inspect them via REST API or simple web UI, similar to [RequestBin](http://requestb.in/) service
|
||||||
|
* [Go Report Card](https://goreportcard.com/) - Go code quality report cards as a (free and open source) service.
|
||||||
|
* [Boltdb Boilerplate](https://github.com/bobintornado/boltdb-boilerplate) - Boilerplate wrapper around bolt aiming to make simple calls one-liners.
|
||||||
|
* [lru](https://github.com/crowdriff/lru) - Easy to use Bolt-backed Least-Recently-Used (LRU) read-through cache with chainable remote stores.
|
||||||
|
* [Storm](https://github.com/asdine/storm) - Simple and powerful ORM for BoltDB.
|
||||||
|
* [GoWebApp](https://github.com/josephspurrier/gowebapp) - A basic MVC web application in Go using BoltDB.
|
||||||
|
* [SimpleBolt](https://github.com/xyproto/simplebolt) - A simple way to use BoltDB. Deals mainly with strings.
|
||||||
|
* [Algernon](https://github.com/xyproto/algernon) - A HTTP/2 web server with built-in support for Lua. Uses BoltDB as the default database backend.
|
||||||
|
* [MuLiFS](https://github.com/dankomiocevic/mulifs) - Music Library Filesystem creates a filesystem to organise your music files.
|
||||||
|
* [GoShort](https://github.com/pankajkhairnar/goShort) - GoShort is a URL shortener written in Golang and BoltDB for persistent key/value storage and for routing it's using high performent HTTPRouter.
|
||||||
|
* [torrent](https://github.com/anacrolix/torrent) - Full-featured BitTorrent client package and utilities in Go. BoltDB is a storage backend in development.
|
||||||
|
* [gopherpit](https://github.com/gopherpit/gopherpit) - A web service to manage Go remote import paths with custom domains
|
||||||
|
* [bolter](https://github.com/hasit/bolter) - Command-line app for viewing BoltDB file in your terminal.
|
||||||
|
* [btcwallet](https://github.com/btcsuite/btcwallet) - A bitcoin wallet.
|
||||||
|
* [dcrwallet](https://github.com/decred/dcrwallet) - A wallet for the Decred cryptocurrency.
|
||||||
|
* [Ironsmith](https://github.com/timshannon/ironsmith) - A simple, script-driven continuous integration (build - > test -> release) tool, with no external dependencies
|
||||||
|
* [BoltHold](https://github.com/timshannon/bolthold) - An embeddable NoSQL store for Go types built on BoltDB
|
||||||
|
|
||||||
|
If you are using Bolt in a project please send a pull request to add it to the list.
|
18
vendor/github.com/boltdb/bolt/appveyor.yml
generated
vendored
Normal file
18
vendor/github.com/boltdb/bolt/appveyor.yml
generated
vendored
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
version: "{build}"
|
||||||
|
|
||||||
|
os: Windows Server 2012 R2
|
||||||
|
|
||||||
|
clone_folder: c:\gopath\src\github.com\boltdb\bolt
|
||||||
|
|
||||||
|
environment:
|
||||||
|
GOPATH: c:\gopath
|
||||||
|
|
||||||
|
install:
|
||||||
|
- echo %PATH%
|
||||||
|
- echo %GOPATH%
|
||||||
|
- go version
|
||||||
|
- go env
|
||||||
|
- go get -v -t ./...
|
||||||
|
|
||||||
|
build_script:
|
||||||
|
- go test -v ./...
|
10
vendor/github.com/boltdb/bolt/bolt_386.go
generated
vendored
Normal file
10
vendor/github.com/boltdb/bolt/bolt_386.go
generated
vendored
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
package bolt
|
||||||
|
|
||||||
|
// maxMapSize represents the largest mmap size supported by Bolt.
|
||||||
|
const maxMapSize = 0x7FFFFFFF // 2GB
|
||||||
|
|
||||||
|
// maxAllocSize is the size used when creating array pointers.
|
||||||
|
const maxAllocSize = 0xFFFFFFF
|
||||||
|
|
||||||
|
// Are unaligned load/stores broken on this arch?
|
||||||
|
var brokenUnaligned = false
|
10
vendor/github.com/boltdb/bolt/bolt_amd64.go
generated
vendored
Normal file
10
vendor/github.com/boltdb/bolt/bolt_amd64.go
generated
vendored
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
package bolt
|
||||||
|
|
||||||
|
// maxMapSize represents the largest mmap size supported by Bolt.
|
||||||
|
const maxMapSize = 0xFFFFFFFFFFFF // 256TB
|
||||||
|
|
||||||
|
// maxAllocSize is the size used when creating array pointers.
|
||||||
|
const maxAllocSize = 0x7FFFFFFF
|
||||||
|
|
||||||
|
// Are unaligned load/stores broken on this arch?
|
||||||
|
var brokenUnaligned = false
|
28
vendor/github.com/boltdb/bolt/bolt_arm.go
generated
vendored
Normal file
28
vendor/github.com/boltdb/bolt/bolt_arm.go
generated
vendored
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
package bolt
|
||||||
|
|
||||||
|
import "unsafe"
|
||||||
|
|
||||||
|
// maxMapSize represents the largest mmap size supported by Bolt.
|
||||||
|
const maxMapSize = 0x7FFFFFFF // 2GB
|
||||||
|
|
||||||
|
// maxAllocSize is the size used when creating array pointers.
|
||||||
|
const maxAllocSize = 0xFFFFFFF
|
||||||
|
|
||||||
|
// Are unaligned load/stores broken on this arch?
|
||||||
|
var brokenUnaligned bool
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
// Simple check to see whether this arch handles unaligned load/stores
|
||||||
|
// correctly.
|
||||||
|
|
||||||
|
// ARM9 and older devices require load/stores to be from/to aligned
|
||||||
|
// addresses. If not, the lower 2 bits are cleared and that address is
|
||||||
|
// read in a jumbled up order.
|
||||||
|
|
||||||
|
// See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka15414.html
|
||||||
|
|
||||||
|
raw := [6]byte{0xfe, 0xef, 0x11, 0x22, 0x22, 0x11}
|
||||||
|
val := *(*uint32)(unsafe.Pointer(uintptr(unsafe.Pointer(&raw)) + 2))
|
||||||
|
|
||||||
|
brokenUnaligned = val != 0x11222211
|
||||||
|
}
|
12
vendor/github.com/boltdb/bolt/bolt_arm64.go
generated
vendored
Normal file
12
vendor/github.com/boltdb/bolt/bolt_arm64.go
generated
vendored
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
// +build arm64
|
||||||
|
|
||||||
|
package bolt
|
||||||
|
|
||||||
|
// maxMapSize represents the largest mmap size supported by Bolt.
|
||||||
|
const maxMapSize = 0xFFFFFFFFFFFF // 256TB
|
||||||
|
|
||||||
|
// maxAllocSize is the size used when creating array pointers.
|
||||||
|
const maxAllocSize = 0x7FFFFFFF
|
||||||
|
|
||||||
|
// Are unaligned load/stores broken on this arch?
|
||||||
|
var brokenUnaligned = false
|
10
vendor/github.com/boltdb/bolt/bolt_linux.go
generated
vendored
Normal file
10
vendor/github.com/boltdb/bolt/bolt_linux.go
generated
vendored
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
package bolt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fdatasync flushes written data to a file descriptor.
|
||||||
|
func fdatasync(db *DB) error {
|
||||||
|
return syscall.Fdatasync(int(db.file.Fd()))
|
||||||
|
}
|
27
vendor/github.com/boltdb/bolt/bolt_openbsd.go
generated
vendored
Normal file
27
vendor/github.com/boltdb/bolt/bolt_openbsd.go
generated
vendored
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
package bolt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"syscall"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
msAsync = 1 << iota // perform asynchronous writes
|
||||||
|
msSync // perform synchronous writes
|
||||||
|
msInvalidate // invalidate cached data
|
||||||
|
)
|
||||||
|
|
||||||
|
func msync(db *DB) error {
|
||||||
|
_, _, errno := syscall.Syscall(syscall.SYS_MSYNC, uintptr(unsafe.Pointer(db.data)), uintptr(db.datasz), msInvalidate)
|
||||||
|
if errno != 0 {
|
||||||
|
return errno
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func fdatasync(db *DB) error {
|
||||||
|
if db.data != nil {
|
||||||
|
return msync(db)
|
||||||
|
}
|
||||||
|
return db.file.Sync()
|
||||||
|
}
|
9
vendor/github.com/boltdb/bolt/bolt_ppc.go
generated
vendored
Normal file
9
vendor/github.com/boltdb/bolt/bolt_ppc.go
generated
vendored
Normal file
@ -0,0 +1,9 @@
|
|||||||
|
// +build ppc
|
||||||
|
|
||||||
|
package bolt
|
||||||
|
|
||||||
|
// maxMapSize represents the largest mmap size supported by Bolt.
|
||||||
|
const maxMapSize = 0x7FFFFFFF // 2GB
|
||||||
|
|
||||||
|
// maxAllocSize is the size used when creating array pointers.
|
||||||
|
const maxAllocSize = 0xFFFFFFF
|
12
vendor/github.com/boltdb/bolt/bolt_ppc64.go
generated
vendored
Normal file
12
vendor/github.com/boltdb/bolt/bolt_ppc64.go
generated
vendored
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
// +build ppc64
|
||||||
|
|
||||||
|
package bolt
|
||||||
|
|
||||||
|
// maxMapSize represents the largest mmap size supported by Bolt.
|
||||||
|
const maxMapSize = 0xFFFFFFFFFFFF // 256TB
|
||||||
|
|
||||||
|
// maxAllocSize is the size used when creating array pointers.
|
||||||
|
const maxAllocSize = 0x7FFFFFFF
|
||||||
|
|
||||||
|
// Are unaligned load/stores broken on this arch?
|
||||||
|
var brokenUnaligned = false
|
12
vendor/github.com/boltdb/bolt/bolt_ppc64le.go
generated
vendored
Normal file
12
vendor/github.com/boltdb/bolt/bolt_ppc64le.go
generated
vendored
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
// +build ppc64le
|
||||||
|
|
||||||
|
package bolt
|
||||||
|
|
||||||
|
// maxMapSize represents the largest mmap size supported by Bolt.
|
||||||
|
const maxMapSize = 0xFFFFFFFFFFFF // 256TB
|
||||||
|
|
||||||
|
// maxAllocSize is the size used when creating array pointers.
|
||||||
|
const maxAllocSize = 0x7FFFFFFF
|
||||||
|
|
||||||
|
// Are unaligned load/stores broken on this arch?
|
||||||
|
var brokenUnaligned = false
|
12
vendor/github.com/boltdb/bolt/bolt_s390x.go
generated
vendored
Normal file
12
vendor/github.com/boltdb/bolt/bolt_s390x.go
generated
vendored
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
// +build s390x
|
||||||
|
|
||||||
|
package bolt
|
||||||
|
|
||||||
|
// maxMapSize represents the largest mmap size supported by Bolt.
|
||||||
|
const maxMapSize = 0xFFFFFFFFFFFF // 256TB
|
||||||
|
|
||||||
|
// maxAllocSize is the size used when creating array pointers.
|
||||||
|
const maxAllocSize = 0x7FFFFFFF
|
||||||
|
|
||||||
|
// Are unaligned load/stores broken on this arch?
|
||||||
|
var brokenUnaligned = false
|
89
vendor/github.com/boltdb/bolt/bolt_unix.go
generated
vendored
Normal file
89
vendor/github.com/boltdb/bolt/bolt_unix.go
generated
vendored
Normal file
@ -0,0 +1,89 @@
|
|||||||
|
// +build !windows,!plan9,!solaris
|
||||||
|
|
||||||
|
package bolt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
// flock acquires an advisory lock on a file descriptor.
|
||||||
|
func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error {
|
||||||
|
var t time.Time
|
||||||
|
for {
|
||||||
|
// If we're beyond our timeout then return an error.
|
||||||
|
// This can only occur after we've attempted a flock once.
|
||||||
|
if t.IsZero() {
|
||||||
|
t = time.Now()
|
||||||
|
} else if timeout > 0 && time.Since(t) > timeout {
|
||||||
|
return ErrTimeout
|
||||||
|
}
|
||||||
|
flag := syscall.LOCK_SH
|
||||||
|
if exclusive {
|
||||||
|
flag = syscall.LOCK_EX
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise attempt to obtain an exclusive lock.
|
||||||
|
err := syscall.Flock(int(db.file.Fd()), flag|syscall.LOCK_NB)
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
} else if err != syscall.EWOULDBLOCK {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for a bit and try again.
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// funlock releases an advisory lock on a file descriptor.
|
||||||
|
func funlock(db *DB) error {
|
||||||
|
return syscall.Flock(int(db.file.Fd()), syscall.LOCK_UN)
|
||||||
|
}
|
||||||
|
|
||||||
|
// mmap memory maps a DB's data file.
|
||||||
|
func mmap(db *DB, sz int) error {
|
||||||
|
// Map the data file to memory.
|
||||||
|
b, err := syscall.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Advise the kernel that the mmap is accessed randomly.
|
||||||
|
if err := madvise(b, syscall.MADV_RANDOM); err != nil {
|
||||||
|
return fmt.Errorf("madvise: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save the original byte slice and convert to a byte array pointer.
|
||||||
|
db.dataref = b
|
||||||
|
db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0]))
|
||||||
|
db.datasz = sz
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// munmap unmaps a DB's data file from memory.
|
||||||
|
func munmap(db *DB) error {
|
||||||
|
// Ignore the unmap if we have no mapped data.
|
||||||
|
if db.dataref == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unmap using the original byte slice.
|
||||||
|
err := syscall.Munmap(db.dataref)
|
||||||
|
db.dataref = nil
|
||||||
|
db.data = nil
|
||||||
|
db.datasz = 0
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// NOTE: This function is copied from stdlib because it is not available on darwin.
|
||||||
|
func madvise(b []byte, advice int) (err error) {
|
||||||
|
_, _, e1 := syscall.Syscall(syscall.SYS_MADVISE, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), uintptr(advice))
|
||||||
|
if e1 != 0 {
|
||||||
|
err = e1
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
90
vendor/github.com/boltdb/bolt/bolt_unix_solaris.go
generated
vendored
Normal file
90
vendor/github.com/boltdb/bolt/bolt_unix_solaris.go
generated
vendored
Normal file
@ -0,0 +1,90 @@
|
|||||||
|
package bolt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
)
|
||||||
|
|
||||||
|
// flock acquires an advisory lock on a file descriptor.
|
||||||
|
func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error {
|
||||||
|
var t time.Time
|
||||||
|
for {
|
||||||
|
// If we're beyond our timeout then return an error.
|
||||||
|
// This can only occur after we've attempted a flock once.
|
||||||
|
if t.IsZero() {
|
||||||
|
t = time.Now()
|
||||||
|
} else if timeout > 0 && time.Since(t) > timeout {
|
||||||
|
return ErrTimeout
|
||||||
|
}
|
||||||
|
var lock syscall.Flock_t
|
||||||
|
lock.Start = 0
|
||||||
|
lock.Len = 0
|
||||||
|
lock.Pid = 0
|
||||||
|
lock.Whence = 0
|
||||||
|
lock.Pid = 0
|
||||||
|
if exclusive {
|
||||||
|
lock.Type = syscall.F_WRLCK
|
||||||
|
} else {
|
||||||
|
lock.Type = syscall.F_RDLCK
|
||||||
|
}
|
||||||
|
err := syscall.FcntlFlock(db.file.Fd(), syscall.F_SETLK, &lock)
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
} else if err != syscall.EAGAIN {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for a bit and try again.
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// funlock releases an advisory lock on a file descriptor.
|
||||||
|
func funlock(db *DB) error {
|
||||||
|
var lock syscall.Flock_t
|
||||||
|
lock.Start = 0
|
||||||
|
lock.Len = 0
|
||||||
|
lock.Type = syscall.F_UNLCK
|
||||||
|
lock.Whence = 0
|
||||||
|
return syscall.FcntlFlock(uintptr(db.file.Fd()), syscall.F_SETLK, &lock)
|
||||||
|
}
|
||||||
|
|
||||||
|
// mmap memory maps a DB's data file.
|
||||||
|
func mmap(db *DB, sz int) error {
|
||||||
|
// Map the data file to memory.
|
||||||
|
b, err := unix.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Advise the kernel that the mmap is accessed randomly.
|
||||||
|
if err := unix.Madvise(b, syscall.MADV_RANDOM); err != nil {
|
||||||
|
return fmt.Errorf("madvise: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save the original byte slice and convert to a byte array pointer.
|
||||||
|
db.dataref = b
|
||||||
|
db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0]))
|
||||||
|
db.datasz = sz
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// munmap unmaps a DB's data file from memory.
|
||||||
|
func munmap(db *DB) error {
|
||||||
|
// Ignore the unmap if we have no mapped data.
|
||||||
|
if db.dataref == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unmap using the original byte slice.
|
||||||
|
err := unix.Munmap(db.dataref)
|
||||||
|
db.dataref = nil
|
||||||
|
db.data = nil
|
||||||
|
db.datasz = 0
|
||||||
|
return err
|
||||||
|
}
|
144
vendor/github.com/boltdb/bolt/bolt_windows.go
generated
vendored
Normal file
144
vendor/github.com/boltdb/bolt/bolt_windows.go
generated
vendored
Normal file
@ -0,0 +1,144 @@
|
|||||||
|
package bolt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
// LockFileEx code derived from golang build filemutex_windows.go @ v1.5.1
|
||||||
|
var (
|
||||||
|
modkernel32 = syscall.NewLazyDLL("kernel32.dll")
|
||||||
|
procLockFileEx = modkernel32.NewProc("LockFileEx")
|
||||||
|
procUnlockFileEx = modkernel32.NewProc("UnlockFileEx")
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
lockExt = ".lock"
|
||||||
|
|
||||||
|
// see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203(v=vs.85).aspx
|
||||||
|
flagLockExclusive = 2
|
||||||
|
flagLockFailImmediately = 1
|
||||||
|
|
||||||
|
// see https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx
|
||||||
|
errLockViolation syscall.Errno = 0x21
|
||||||
|
)
|
||||||
|
|
||||||
|
func lockFileEx(h syscall.Handle, flags, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) {
|
||||||
|
r, _, err := procLockFileEx.Call(uintptr(h), uintptr(flags), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol)))
|
||||||
|
if r == 0 {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func unlockFileEx(h syscall.Handle, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) {
|
||||||
|
r, _, err := procUnlockFileEx.Call(uintptr(h), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol)), 0)
|
||||||
|
if r == 0 {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// fdatasync flushes written data to a file descriptor.
|
||||||
|
func fdatasync(db *DB) error {
|
||||||
|
return db.file.Sync()
|
||||||
|
}
|
||||||
|
|
||||||
|
// flock acquires an advisory lock on a file descriptor.
|
||||||
|
func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error {
|
||||||
|
// Create a separate lock file on windows because a process
|
||||||
|
// cannot share an exclusive lock on the same file. This is
|
||||||
|
// needed during Tx.WriteTo().
|
||||||
|
f, err := os.OpenFile(db.path+lockExt, os.O_CREATE, mode)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
db.lockfile = f
|
||||||
|
|
||||||
|
var t time.Time
|
||||||
|
for {
|
||||||
|
// If we're beyond our timeout then return an error.
|
||||||
|
// This can only occur after we've attempted a flock once.
|
||||||
|
if t.IsZero() {
|
||||||
|
t = time.Now()
|
||||||
|
} else if timeout > 0 && time.Since(t) > timeout {
|
||||||
|
return ErrTimeout
|
||||||
|
}
|
||||||
|
|
||||||
|
var flag uint32 = flagLockFailImmediately
|
||||||
|
if exclusive {
|
||||||
|
flag |= flagLockExclusive
|
||||||
|
}
|
||||||
|
|
||||||
|
err := lockFileEx(syscall.Handle(db.lockfile.Fd()), flag, 0, 1, 0, &syscall.Overlapped{})
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
} else if err != errLockViolation {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for a bit and try again.
|
||||||
|
time.Sleep(50 * time.Millisecond)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// funlock releases an advisory lock on a file descriptor.
|
||||||
|
func funlock(db *DB) error {
|
||||||
|
err := unlockFileEx(syscall.Handle(db.lockfile.Fd()), 0, 1, 0, &syscall.Overlapped{})
|
||||||
|
db.lockfile.Close()
|
||||||
|
os.Remove(db.path + lockExt)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// mmap memory maps a DB's data file.
|
||||||
|
// Based on: https://github.com/edsrzf/mmap-go
|
||||||
|
func mmap(db *DB, sz int) error {
|
||||||
|
if !db.readOnly {
|
||||||
|
// Truncate the database to the size of the mmap.
|
||||||
|
if err := db.file.Truncate(int64(sz)); err != nil {
|
||||||
|
return fmt.Errorf("truncate: %s", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open a file mapping handle.
|
||||||
|
sizelo := uint32(sz >> 32)
|
||||||
|
sizehi := uint32(sz) & 0xffffffff
|
||||||
|
h, errno := syscall.CreateFileMapping(syscall.Handle(db.file.Fd()), nil, syscall.PAGE_READONLY, sizelo, sizehi, nil)
|
||||||
|
if h == 0 {
|
||||||
|
return os.NewSyscallError("CreateFileMapping", errno)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create the memory map.
|
||||||
|
addr, errno := syscall.MapViewOfFile(h, syscall.FILE_MAP_READ, 0, 0, uintptr(sz))
|
||||||
|
if addr == 0 {
|
||||||
|
return os.NewSyscallError("MapViewOfFile", errno)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close mapping handle.
|
||||||
|
if err := syscall.CloseHandle(syscall.Handle(h)); err != nil {
|
||||||
|
return os.NewSyscallError("CloseHandle", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert to a byte array.
|
||||||
|
db.data = ((*[maxMapSize]byte)(unsafe.Pointer(addr)))
|
||||||
|
db.datasz = sz
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// munmap unmaps a pointer from a file.
|
||||||
|
// Based on: https://github.com/edsrzf/mmap-go
|
||||||
|
func munmap(db *DB) error {
|
||||||
|
if db.data == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := (uintptr)(unsafe.Pointer(&db.data[0]))
|
||||||
|
if err := syscall.UnmapViewOfFile(addr); err != nil {
|
||||||
|
return os.NewSyscallError("UnmapViewOfFile", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
8
vendor/github.com/boltdb/bolt/boltsync_unix.go
generated
vendored
Normal file
8
vendor/github.com/boltdb/bolt/boltsync_unix.go
generated
vendored
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
// +build !windows,!plan9,!linux,!openbsd
|
||||||
|
|
||||||
|
package bolt
|
||||||
|
|
||||||
|
// fdatasync flushes written data to a file descriptor.
|
||||||
|
func fdatasync(db *DB) error {
|
||||||
|
return db.file.Sync()
|
||||||
|
}
|
777
vendor/github.com/boltdb/bolt/bucket.go
generated
vendored
Normal file
777
vendor/github.com/boltdb/bolt/bucket.go
generated
vendored
Normal file
@ -0,0 +1,777 @@
|
|||||||
|
package bolt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// MaxKeySize is the maximum length of a key, in bytes.
|
||||||
|
MaxKeySize = 32768
|
||||||
|
|
||||||
|
// MaxValueSize is the maximum length of a value, in bytes.
|
||||||
|
MaxValueSize = (1 << 31) - 2
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
maxUint = ^uint(0)
|
||||||
|
minUint = 0
|
||||||
|
maxInt = int(^uint(0) >> 1)
|
||||||
|
minInt = -maxInt - 1
|
||||||
|
)
|
||||||
|
|
||||||
|
const bucketHeaderSize = int(unsafe.Sizeof(bucket{}))
|
||||||
|
|
||||||
|
const (
|
||||||
|
minFillPercent = 0.1
|
||||||
|
maxFillPercent = 1.0
|
||||||
|
)
|
||||||
|
|
||||||
|
// DefaultFillPercent is the percentage that split pages are filled.
|
||||||
|
// This value can be changed by setting Bucket.FillPercent.
|
||||||
|
const DefaultFillPercent = 0.5
|
||||||
|
|
||||||
|
// Bucket represents a collection of key/value pairs inside the database.
|
||||||
|
type Bucket struct {
|
||||||
|
*bucket
|
||||||
|
tx *Tx // the associated transaction
|
||||||
|
buckets map[string]*Bucket // subbucket cache
|
||||||
|
page *page // inline page reference
|
||||||
|
rootNode *node // materialized node for the root page.
|
||||||
|
nodes map[pgid]*node // node cache
|
||||||
|
|
||||||
|
// Sets the threshold for filling nodes when they split. By default,
|
||||||
|
// the bucket will fill to 50% but it can be useful to increase this
|
||||||
|
// amount if you know that your write workloads are mostly append-only.
|
||||||
|
//
|
||||||
|
// This is non-persisted across transactions so it must be set in every Tx.
|
||||||
|
FillPercent float64
|
||||||
|
}
|
||||||
|
|
||||||
|
// bucket represents the on-file representation of a bucket.
|
||||||
|
// This is stored as the "value" of a bucket key. If the bucket is small enough,
|
||||||
|
// then its root page can be stored inline in the "value", after the bucket
|
||||||
|
// header. In the case of inline buckets, the "root" will be 0.
|
||||||
|
type bucket struct {
|
||||||
|
root pgid // page id of the bucket's root-level page
|
||||||
|
sequence uint64 // monotonically incrementing, used by NextSequence()
|
||||||
|
}
|
||||||
|
|
||||||
|
// newBucket returns a new bucket associated with a transaction.
|
||||||
|
func newBucket(tx *Tx) Bucket {
|
||||||
|
var b = Bucket{tx: tx, FillPercent: DefaultFillPercent}
|
||||||
|
if tx.writable {
|
||||||
|
b.buckets = make(map[string]*Bucket)
|
||||||
|
b.nodes = make(map[pgid]*node)
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tx returns the tx of the bucket.
|
||||||
|
func (b *Bucket) Tx() *Tx {
|
||||||
|
return b.tx
|
||||||
|
}
|
||||||
|
|
||||||
|
// Root returns the root of the bucket.
|
||||||
|
func (b *Bucket) Root() pgid {
|
||||||
|
return b.root
|
||||||
|
}
|
||||||
|
|
||||||
|
// Writable returns whether the bucket is writable.
|
||||||
|
func (b *Bucket) Writable() bool {
|
||||||
|
return b.tx.writable
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cursor creates a cursor associated with the bucket.
|
||||||
|
// The cursor is only valid as long as the transaction is open.
|
||||||
|
// Do not use a cursor after the transaction is closed.
|
||||||
|
func (b *Bucket) Cursor() *Cursor {
|
||||||
|
// Update transaction statistics.
|
||||||
|
b.tx.stats.CursorCount++
|
||||||
|
|
||||||
|
// Allocate and return a cursor.
|
||||||
|
return &Cursor{
|
||||||
|
bucket: b,
|
||||||
|
stack: make([]elemRef, 0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bucket retrieves a nested bucket by name.
|
||||||
|
// Returns nil if the bucket does not exist.
|
||||||
|
// The bucket instance is only valid for the lifetime of the transaction.
|
||||||
|
func (b *Bucket) Bucket(name []byte) *Bucket {
|
||||||
|
if b.buckets != nil {
|
||||||
|
if child := b.buckets[string(name)]; child != nil {
|
||||||
|
return child
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move cursor to key.
|
||||||
|
c := b.Cursor()
|
||||||
|
k, v, flags := c.seek(name)
|
||||||
|
|
||||||
|
// Return nil if the key doesn't exist or it is not a bucket.
|
||||||
|
if !bytes.Equal(name, k) || (flags&bucketLeafFlag) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise create a bucket and cache it.
|
||||||
|
var child = b.openBucket(v)
|
||||||
|
if b.buckets != nil {
|
||||||
|
b.buckets[string(name)] = child
|
||||||
|
}
|
||||||
|
|
||||||
|
return child
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper method that re-interprets a sub-bucket value
|
||||||
|
// from a parent into a Bucket
|
||||||
|
func (b *Bucket) openBucket(value []byte) *Bucket {
|
||||||
|
var child = newBucket(b.tx)
|
||||||
|
|
||||||
|
// If unaligned load/stores are broken on this arch and value is
|
||||||
|
// unaligned simply clone to an aligned byte array.
|
||||||
|
unaligned := brokenUnaligned && uintptr(unsafe.Pointer(&value[0]))&3 != 0
|
||||||
|
|
||||||
|
if unaligned {
|
||||||
|
value = cloneBytes(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// If this is a writable transaction then we need to copy the bucket entry.
|
||||||
|
// Read-only transactions can point directly at the mmap entry.
|
||||||
|
if b.tx.writable && !unaligned {
|
||||||
|
child.bucket = &bucket{}
|
||||||
|
*child.bucket = *(*bucket)(unsafe.Pointer(&value[0]))
|
||||||
|
} else {
|
||||||
|
child.bucket = (*bucket)(unsafe.Pointer(&value[0]))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save a reference to the inline page if the bucket is inline.
|
||||||
|
if child.root == 0 {
|
||||||
|
child.page = (*page)(unsafe.Pointer(&value[bucketHeaderSize]))
|
||||||
|
}
|
||||||
|
|
||||||
|
return &child
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateBucket creates a new bucket at the given key and returns the new bucket.
|
||||||
|
// Returns an error if the key already exists, if the bucket name is blank, or if the bucket name is too long.
|
||||||
|
// The bucket instance is only valid for the lifetime of the transaction.
|
||||||
|
func (b *Bucket) CreateBucket(key []byte) (*Bucket, error) {
|
||||||
|
if b.tx.db == nil {
|
||||||
|
return nil, ErrTxClosed
|
||||||
|
} else if !b.tx.writable {
|
||||||
|
return nil, ErrTxNotWritable
|
||||||
|
} else if len(key) == 0 {
|
||||||
|
return nil, ErrBucketNameRequired
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move cursor to correct position.
|
||||||
|
c := b.Cursor()
|
||||||
|
k, _, flags := c.seek(key)
|
||||||
|
|
||||||
|
// Return an error if there is an existing key.
|
||||||
|
if bytes.Equal(key, k) {
|
||||||
|
if (flags & bucketLeafFlag) != 0 {
|
||||||
|
return nil, ErrBucketExists
|
||||||
|
}
|
||||||
|
return nil, ErrIncompatibleValue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create empty, inline bucket.
|
||||||
|
var bucket = Bucket{
|
||||||
|
bucket: &bucket{},
|
||||||
|
rootNode: &node{isLeaf: true},
|
||||||
|
FillPercent: DefaultFillPercent,
|
||||||
|
}
|
||||||
|
var value = bucket.write()
|
||||||
|
|
||||||
|
// Insert into node.
|
||||||
|
key = cloneBytes(key)
|
||||||
|
c.node().put(key, key, value, 0, bucketLeafFlag)
|
||||||
|
|
||||||
|
// Since subbuckets are not allowed on inline buckets, we need to
|
||||||
|
// dereference the inline page, if it exists. This will cause the bucket
|
||||||
|
// to be treated as a regular, non-inline bucket for the rest of the tx.
|
||||||
|
b.page = nil
|
||||||
|
|
||||||
|
return b.Bucket(key), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateBucketIfNotExists creates a new bucket if it doesn't already exist and returns a reference to it.
|
||||||
|
// Returns an error if the bucket name is blank, or if the bucket name is too long.
|
||||||
|
// The bucket instance is only valid for the lifetime of the transaction.
|
||||||
|
func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) {
|
||||||
|
child, err := b.CreateBucket(key)
|
||||||
|
if err == ErrBucketExists {
|
||||||
|
return b.Bucket(key), nil
|
||||||
|
} else if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return child, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteBucket deletes a bucket at the given key.
|
||||||
|
// Returns an error if the bucket does not exists, or if the key represents a non-bucket value.
|
||||||
|
func (b *Bucket) DeleteBucket(key []byte) error {
|
||||||
|
if b.tx.db == nil {
|
||||||
|
return ErrTxClosed
|
||||||
|
} else if !b.Writable() {
|
||||||
|
return ErrTxNotWritable
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move cursor to correct position.
|
||||||
|
c := b.Cursor()
|
||||||
|
k, _, flags := c.seek(key)
|
||||||
|
|
||||||
|
// Return an error if bucket doesn't exist or is not a bucket.
|
||||||
|
if !bytes.Equal(key, k) {
|
||||||
|
return ErrBucketNotFound
|
||||||
|
} else if (flags & bucketLeafFlag) == 0 {
|
||||||
|
return ErrIncompatibleValue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recursively delete all child buckets.
|
||||||
|
child := b.Bucket(key)
|
||||||
|
err := child.ForEach(func(k, v []byte) error {
|
||||||
|
if v == nil {
|
||||||
|
if err := child.DeleteBucket(k); err != nil {
|
||||||
|
return fmt.Errorf("delete bucket: %s", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove cached copy.
|
||||||
|
delete(b.buckets, string(key))
|
||||||
|
|
||||||
|
// Release all bucket pages to freelist.
|
||||||
|
child.nodes = nil
|
||||||
|
child.rootNode = nil
|
||||||
|
child.free()
|
||||||
|
|
||||||
|
// Delete the node if we have a matching key.
|
||||||
|
c.node().del(key)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get retrieves the value for a key in the bucket.
|
||||||
|
// Returns a nil value if the key does not exist or if the key is a nested bucket.
|
||||||
|
// The returned value is only valid for the life of the transaction.
|
||||||
|
func (b *Bucket) Get(key []byte) []byte {
|
||||||
|
k, v, flags := b.Cursor().seek(key)
|
||||||
|
|
||||||
|
// Return nil if this is a bucket.
|
||||||
|
if (flags & bucketLeafFlag) != 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// If our target node isn't the same key as what's passed in then return nil.
|
||||||
|
if !bytes.Equal(key, k) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
// Put sets the value for a key in the bucket.
|
||||||
|
// If the key exist then its previous value will be overwritten.
|
||||||
|
// Supplied value must remain valid for the life of the transaction.
|
||||||
|
// Returns an error if the bucket was created from a read-only transaction, if the key is blank, if the key is too large, or if the value is too large.
|
||||||
|
func (b *Bucket) Put(key []byte, value []byte) error {
|
||||||
|
if b.tx.db == nil {
|
||||||
|
return ErrTxClosed
|
||||||
|
} else if !b.Writable() {
|
||||||
|
return ErrTxNotWritable
|
||||||
|
} else if len(key) == 0 {
|
||||||
|
return ErrKeyRequired
|
||||||
|
} else if len(key) > MaxKeySize {
|
||||||
|
return ErrKeyTooLarge
|
||||||
|
} else if int64(len(value)) > MaxValueSize {
|
||||||
|
return ErrValueTooLarge
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move cursor to correct position.
|
||||||
|
c := b.Cursor()
|
||||||
|
k, _, flags := c.seek(key)
|
||||||
|
|
||||||
|
// Return an error if there is an existing key with a bucket value.
|
||||||
|
if bytes.Equal(key, k) && (flags&bucketLeafFlag) != 0 {
|
||||||
|
return ErrIncompatibleValue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Insert into node.
|
||||||
|
key = cloneBytes(key)
|
||||||
|
c.node().put(key, key, value, 0, 0)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete removes a key from the bucket.
|
||||||
|
// If the key does not exist then nothing is done and a nil error is returned.
|
||||||
|
// Returns an error if the bucket was created from a read-only transaction.
|
||||||
|
func (b *Bucket) Delete(key []byte) error {
|
||||||
|
if b.tx.db == nil {
|
||||||
|
return ErrTxClosed
|
||||||
|
} else if !b.Writable() {
|
||||||
|
return ErrTxNotWritable
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move cursor to correct position.
|
||||||
|
c := b.Cursor()
|
||||||
|
_, _, flags := c.seek(key)
|
||||||
|
|
||||||
|
// Return an error if there is already existing bucket value.
|
||||||
|
if (flags & bucketLeafFlag) != 0 {
|
||||||
|
return ErrIncompatibleValue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete the node if we have a matching key.
|
||||||
|
c.node().del(key)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sequence returns the current integer for the bucket without incrementing it.
|
||||||
|
func (b *Bucket) Sequence() uint64 { return b.bucket.sequence }
|
||||||
|
|
||||||
|
// SetSequence updates the sequence number for the bucket.
|
||||||
|
func (b *Bucket) SetSequence(v uint64) error {
|
||||||
|
if b.tx.db == nil {
|
||||||
|
return ErrTxClosed
|
||||||
|
} else if !b.Writable() {
|
||||||
|
return ErrTxNotWritable
|
||||||
|
}
|
||||||
|
|
||||||
|
// Materialize the root node if it hasn't been already so that the
|
||||||
|
// bucket will be saved during commit.
|
||||||
|
if b.rootNode == nil {
|
||||||
|
_ = b.node(b.root, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Increment and return the sequence.
|
||||||
|
b.bucket.sequence = v
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// NextSequence returns an autoincrementing integer for the bucket.
|
||||||
|
func (b *Bucket) NextSequence() (uint64, error) {
|
||||||
|
if b.tx.db == nil {
|
||||||
|
return 0, ErrTxClosed
|
||||||
|
} else if !b.Writable() {
|
||||||
|
return 0, ErrTxNotWritable
|
||||||
|
}
|
||||||
|
|
||||||
|
// Materialize the root node if it hasn't been already so that the
|
||||||
|
// bucket will be saved during commit.
|
||||||
|
if b.rootNode == nil {
|
||||||
|
_ = b.node(b.root, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Increment and return the sequence.
|
||||||
|
b.bucket.sequence++
|
||||||
|
return b.bucket.sequence, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ForEach executes a function for each key/value pair in a bucket.
|
||||||
|
// If the provided function returns an error then the iteration is stopped and
|
||||||
|
// the error is returned to the caller. The provided function must not modify
|
||||||
|
// the bucket; this will result in undefined behavior.
|
||||||
|
func (b *Bucket) ForEach(fn func(k, v []byte) error) error {
|
||||||
|
if b.tx.db == nil {
|
||||||
|
return ErrTxClosed
|
||||||
|
}
|
||||||
|
c := b.Cursor()
|
||||||
|
for k, v := c.First(); k != nil; k, v = c.Next() {
|
||||||
|
if err := fn(k, v); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stat returns stats on a bucket.
|
||||||
|
func (b *Bucket) Stats() BucketStats {
|
||||||
|
var s, subStats BucketStats
|
||||||
|
pageSize := b.tx.db.pageSize
|
||||||
|
s.BucketN += 1
|
||||||
|
if b.root == 0 {
|
||||||
|
s.InlineBucketN += 1
|
||||||
|
}
|
||||||
|
b.forEachPage(func(p *page, depth int) {
|
||||||
|
if (p.flags & leafPageFlag) != 0 {
|
||||||
|
s.KeyN += int(p.count)
|
||||||
|
|
||||||
|
// used totals the used bytes for the page
|
||||||
|
used := pageHeaderSize
|
||||||
|
|
||||||
|
if p.count != 0 {
|
||||||
|
// If page has any elements, add all element headers.
|
||||||
|
used += leafPageElementSize * int(p.count-1)
|
||||||
|
|
||||||
|
// Add all element key, value sizes.
|
||||||
|
// The computation takes advantage of the fact that the position
|
||||||
|
// of the last element's key/value equals to the total of the sizes
|
||||||
|
// of all previous elements' keys and values.
|
||||||
|
// It also includes the last element's header.
|
||||||
|
lastElement := p.leafPageElement(p.count - 1)
|
||||||
|
used += int(lastElement.pos + lastElement.ksize + lastElement.vsize)
|
||||||
|
}
|
||||||
|
|
||||||
|
if b.root == 0 {
|
||||||
|
// For inlined bucket just update the inline stats
|
||||||
|
s.InlineBucketInuse += used
|
||||||
|
} else {
|
||||||
|
// For non-inlined bucket update all the leaf stats
|
||||||
|
s.LeafPageN++
|
||||||
|
s.LeafInuse += used
|
||||||
|
s.LeafOverflowN += int(p.overflow)
|
||||||
|
|
||||||
|
// Collect stats from sub-buckets.
|
||||||
|
// Do that by iterating over all element headers
|
||||||
|
// looking for the ones with the bucketLeafFlag.
|
||||||
|
for i := uint16(0); i < p.count; i++ {
|
||||||
|
e := p.leafPageElement(i)
|
||||||
|
if (e.flags & bucketLeafFlag) != 0 {
|
||||||
|
// For any bucket element, open the element value
|
||||||
|
// and recursively call Stats on the contained bucket.
|
||||||
|
subStats.Add(b.openBucket(e.value()).Stats())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (p.flags & branchPageFlag) != 0 {
|
||||||
|
s.BranchPageN++
|
||||||
|
lastElement := p.branchPageElement(p.count - 1)
|
||||||
|
|
||||||
|
// used totals the used bytes for the page
|
||||||
|
// Add header and all element headers.
|
||||||
|
used := pageHeaderSize + (branchPageElementSize * int(p.count-1))
|
||||||
|
|
||||||
|
// Add size of all keys and values.
|
||||||
|
// Again, use the fact that last element's position equals to
|
||||||
|
// the total of key, value sizes of all previous elements.
|
||||||
|
used += int(lastElement.pos + lastElement.ksize)
|
||||||
|
s.BranchInuse += used
|
||||||
|
s.BranchOverflowN += int(p.overflow)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep track of maximum page depth.
|
||||||
|
if depth+1 > s.Depth {
|
||||||
|
s.Depth = (depth + 1)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// Alloc stats can be computed from page counts and pageSize.
|
||||||
|
s.BranchAlloc = (s.BranchPageN + s.BranchOverflowN) * pageSize
|
||||||
|
s.LeafAlloc = (s.LeafPageN + s.LeafOverflowN) * pageSize
|
||||||
|
|
||||||
|
// Add the max depth of sub-buckets to get total nested depth.
|
||||||
|
s.Depth += subStats.Depth
|
||||||
|
// Add the stats for all sub-buckets
|
||||||
|
s.Add(subStats)
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// forEachPage iterates over every page in a bucket, including inline pages.
|
||||||
|
func (b *Bucket) forEachPage(fn func(*page, int)) {
|
||||||
|
// If we have an inline page then just use that.
|
||||||
|
if b.page != nil {
|
||||||
|
fn(b.page, 0)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise traverse the page hierarchy.
|
||||||
|
b.tx.forEachPage(b.root, 0, fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// forEachPageNode iterates over every page (or node) in a bucket.
|
||||||
|
// This also includes inline pages.
|
||||||
|
func (b *Bucket) forEachPageNode(fn func(*page, *node, int)) {
|
||||||
|
// If we have an inline page or root node then just use that.
|
||||||
|
if b.page != nil {
|
||||||
|
fn(b.page, nil, 0)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
b._forEachPageNode(b.root, 0, fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (b *Bucket) _forEachPageNode(pgid pgid, depth int, fn func(*page, *node, int)) {
|
||||||
|
var p, n = b.pageNode(pgid)
|
||||||
|
|
||||||
|
// Execute function.
|
||||||
|
fn(p, n, depth)
|
||||||
|
|
||||||
|
// Recursively loop over children.
|
||||||
|
if p != nil {
|
||||||
|
if (p.flags & branchPageFlag) != 0 {
|
||||||
|
for i := 0; i < int(p.count); i++ {
|
||||||
|
elem := p.branchPageElement(uint16(i))
|
||||||
|
b._forEachPageNode(elem.pgid, depth+1, fn)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if !n.isLeaf {
|
||||||
|
for _, inode := range n.inodes {
|
||||||
|
b._forEachPageNode(inode.pgid, depth+1, fn)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// spill writes all the nodes for this bucket to dirty pages.
|
||||||
|
func (b *Bucket) spill() error {
|
||||||
|
// Spill all child buckets first.
|
||||||
|
for name, child := range b.buckets {
|
||||||
|
// If the child bucket is small enough and it has no child buckets then
|
||||||
|
// write it inline into the parent bucket's page. Otherwise spill it
|
||||||
|
// like a normal bucket and make the parent value a pointer to the page.
|
||||||
|
var value []byte
|
||||||
|
if child.inlineable() {
|
||||||
|
child.free()
|
||||||
|
value = child.write()
|
||||||
|
} else {
|
||||||
|
if err := child.spill(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the child bucket header in this bucket.
|
||||||
|
value = make([]byte, unsafe.Sizeof(bucket{}))
|
||||||
|
var bucket = (*bucket)(unsafe.Pointer(&value[0]))
|
||||||
|
*bucket = *child.bucket
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip writing the bucket if there are no materialized nodes.
|
||||||
|
if child.rootNode == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update parent node.
|
||||||
|
var c = b.Cursor()
|
||||||
|
k, _, flags := c.seek([]byte(name))
|
||||||
|
if !bytes.Equal([]byte(name), k) {
|
||||||
|
panic(fmt.Sprintf("misplaced bucket header: %x -> %x", []byte(name), k))
|
||||||
|
}
|
||||||
|
if flags&bucketLeafFlag == 0 {
|
||||||
|
panic(fmt.Sprintf("unexpected bucket header flag: %x", flags))
|
||||||
|
}
|
||||||
|
c.node().put([]byte(name), []byte(name), value, 0, bucketLeafFlag)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ignore if there's not a materialized root node.
|
||||||
|
if b.rootNode == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Spill nodes.
|
||||||
|
if err := b.rootNode.spill(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
b.rootNode = b.rootNode.root()
|
||||||
|
|
||||||
|
// Update the root node for this bucket.
|
||||||
|
if b.rootNode.pgid >= b.tx.meta.pgid {
|
||||||
|
panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", b.rootNode.pgid, b.tx.meta.pgid))
|
||||||
|
}
|
||||||
|
b.root = b.rootNode.pgid
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// inlineable returns true if a bucket is small enough to be written inline
|
||||||
|
// and if it contains no subbuckets. Otherwise returns false.
|
||||||
|
func (b *Bucket) inlineable() bool {
|
||||||
|
var n = b.rootNode
|
||||||
|
|
||||||
|
// Bucket must only contain a single leaf node.
|
||||||
|
if n == nil || !n.isLeaf {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bucket is not inlineable if it contains subbuckets or if it goes beyond
|
||||||
|
// our threshold for inline bucket size.
|
||||||
|
var size = pageHeaderSize
|
||||||
|
for _, inode := range n.inodes {
|
||||||
|
size += leafPageElementSize + len(inode.key) + len(inode.value)
|
||||||
|
|
||||||
|
if inode.flags&bucketLeafFlag != 0 {
|
||||||
|
return false
|
||||||
|
} else if size > b.maxInlineBucketSize() {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Returns the maximum total size of a bucket to make it a candidate for inlining.
|
||||||
|
func (b *Bucket) maxInlineBucketSize() int {
|
||||||
|
return b.tx.db.pageSize / 4
|
||||||
|
}
|
||||||
|
|
||||||
|
// write allocates and writes a bucket to a byte slice.
|
||||||
|
func (b *Bucket) write() []byte {
|
||||||
|
// Allocate the appropriate size.
|
||||||
|
var n = b.rootNode
|
||||||
|
var value = make([]byte, bucketHeaderSize+n.size())
|
||||||
|
|
||||||
|
// Write a bucket header.
|
||||||
|
var bucket = (*bucket)(unsafe.Pointer(&value[0]))
|
||||||
|
*bucket = *b.bucket
|
||||||
|
|
||||||
|
// Convert byte slice to a fake page and write the root node.
|
||||||
|
var p = (*page)(unsafe.Pointer(&value[bucketHeaderSize]))
|
||||||
|
n.write(p)
|
||||||
|
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
// rebalance attempts to balance all nodes.
|
||||||
|
func (b *Bucket) rebalance() {
|
||||||
|
for _, n := range b.nodes {
|
||||||
|
n.rebalance()
|
||||||
|
}
|
||||||
|
for _, child := range b.buckets {
|
||||||
|
child.rebalance()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// node creates a node from a page and associates it with a given parent.
|
||||||
|
func (b *Bucket) node(pgid pgid, parent *node) *node {
|
||||||
|
_assert(b.nodes != nil, "nodes map expected")
|
||||||
|
|
||||||
|
// Retrieve node if it's already been created.
|
||||||
|
if n := b.nodes[pgid]; n != nil {
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise create a node and cache it.
|
||||||
|
n := &node{bucket: b, parent: parent}
|
||||||
|
if parent == nil {
|
||||||
|
b.rootNode = n
|
||||||
|
} else {
|
||||||
|
parent.children = append(parent.children, n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use the inline page if this is an inline bucket.
|
||||||
|
var p = b.page
|
||||||
|
if p == nil {
|
||||||
|
p = b.tx.page(pgid)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read the page into the node and cache it.
|
||||||
|
n.read(p)
|
||||||
|
b.nodes[pgid] = n
|
||||||
|
|
||||||
|
// Update statistics.
|
||||||
|
b.tx.stats.NodeCount++
|
||||||
|
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// free recursively frees all pages in the bucket.
|
||||||
|
func (b *Bucket) free() {
|
||||||
|
if b.root == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var tx = b.tx
|
||||||
|
b.forEachPageNode(func(p *page, n *node, _ int) {
|
||||||
|
if p != nil {
|
||||||
|
tx.db.freelist.free(tx.meta.txid, p)
|
||||||
|
} else {
|
||||||
|
n.free()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
b.root = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// dereference removes all references to the old mmap.
|
||||||
|
func (b *Bucket) dereference() {
|
||||||
|
if b.rootNode != nil {
|
||||||
|
b.rootNode.root().dereference()
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, child := range b.buckets {
|
||||||
|
child.dereference()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// pageNode returns the in-memory node, if it exists.
|
||||||
|
// Otherwise returns the underlying page.
|
||||||
|
func (b *Bucket) pageNode(id pgid) (*page, *node) {
|
||||||
|
// Inline buckets have a fake page embedded in their value so treat them
|
||||||
|
// differently. We'll return the rootNode (if available) or the fake page.
|
||||||
|
if b.root == 0 {
|
||||||
|
if id != 0 {
|
||||||
|
panic(fmt.Sprintf("inline bucket non-zero page access(2): %d != 0", id))
|
||||||
|
}
|
||||||
|
if b.rootNode != nil {
|
||||||
|
return nil, b.rootNode
|
||||||
|
}
|
||||||
|
return b.page, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check the node cache for non-inline buckets.
|
||||||
|
if b.nodes != nil {
|
||||||
|
if n := b.nodes[id]; n != nil {
|
||||||
|
return nil, n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Finally lookup the page from the transaction if no node is materialized.
|
||||||
|
return b.tx.page(id), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// BucketStats records statistics about resources used by a bucket.
|
||||||
|
type BucketStats struct {
|
||||||
|
// Page count statistics.
|
||||||
|
BranchPageN int // number of logical branch pages
|
||||||
|
BranchOverflowN int // number of physical branch overflow pages
|
||||||
|
LeafPageN int // number of logical leaf pages
|
||||||
|
LeafOverflowN int // number of physical leaf overflow pages
|
||||||
|
|
||||||
|
// Tree statistics.
|
||||||
|
KeyN int // number of keys/value pairs
|
||||||
|
Depth int // number of levels in B+tree
|
||||||
|
|
||||||
|
// Page size utilization.
|
||||||
|
BranchAlloc int // bytes allocated for physical branch pages
|
||||||
|
BranchInuse int // bytes actually used for branch data
|
||||||
|
LeafAlloc int // bytes allocated for physical leaf pages
|
||||||
|
LeafInuse int // bytes actually used for leaf data
|
||||||
|
|
||||||
|
// Bucket statistics
|
||||||
|
BucketN int // total number of buckets including the top bucket
|
||||||
|
InlineBucketN int // total number on inlined buckets
|
||||||
|
InlineBucketInuse int // bytes used for inlined buckets (also accounted for in LeafInuse)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *BucketStats) Add(other BucketStats) {
|
||||||
|
s.BranchPageN += other.BranchPageN
|
||||||
|
s.BranchOverflowN += other.BranchOverflowN
|
||||||
|
s.LeafPageN += other.LeafPageN
|
||||||
|
s.LeafOverflowN += other.LeafOverflowN
|
||||||
|
s.KeyN += other.KeyN
|
||||||
|
if s.Depth < other.Depth {
|
||||||
|
s.Depth = other.Depth
|
||||||
|
}
|
||||||
|
s.BranchAlloc += other.BranchAlloc
|
||||||
|
s.BranchInuse += other.BranchInuse
|
||||||
|
s.LeafAlloc += other.LeafAlloc
|
||||||
|
s.LeafInuse += other.LeafInuse
|
||||||
|
|
||||||
|
s.BucketN += other.BucketN
|
||||||
|
s.InlineBucketN += other.InlineBucketN
|
||||||
|
s.InlineBucketInuse += other.InlineBucketInuse
|
||||||
|
}
|
||||||
|
|
||||||
|
// cloneBytes returns a copy of a given slice.
|
||||||
|
func cloneBytes(v []byte) []byte {
|
||||||
|
var clone = make([]byte, len(v))
|
||||||
|
copy(clone, v)
|
||||||
|
return clone
|
||||||
|
}
|
400
vendor/github.com/boltdb/bolt/cursor.go
generated
vendored
Normal file
400
vendor/github.com/boltdb/bolt/cursor.go
generated
vendored
Normal file
@ -0,0 +1,400 @@
|
|||||||
|
package bolt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Cursor represents an iterator that can traverse over all key/value pairs in a bucket in sorted order.
|
||||||
|
// Cursors see nested buckets with value == nil.
|
||||||
|
// Cursors can be obtained from a transaction and are valid as long as the transaction is open.
|
||||||
|
//
|
||||||
|
// Keys and values returned from the cursor are only valid for the life of the transaction.
|
||||||
|
//
|
||||||
|
// Changing data while traversing with a cursor may cause it to be invalidated
|
||||||
|
// and return unexpected keys and/or values. You must reposition your cursor
|
||||||
|
// after mutating data.
|
||||||
|
type Cursor struct {
|
||||||
|
bucket *Bucket
|
||||||
|
stack []elemRef
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bucket returns the bucket that this cursor was created from.
|
||||||
|
func (c *Cursor) Bucket() *Bucket {
|
||||||
|
return c.bucket
|
||||||
|
}
|
||||||
|
|
||||||
|
// First moves the cursor to the first item in the bucket and returns its key and value.
|
||||||
|
// If the bucket is empty then a nil key and value are returned.
|
||||||
|
// The returned key and value are only valid for the life of the transaction.
|
||||||
|
func (c *Cursor) First() (key []byte, value []byte) {
|
||||||
|
_assert(c.bucket.tx.db != nil, "tx closed")
|
||||||
|
c.stack = c.stack[:0]
|
||||||
|
p, n := c.bucket.pageNode(c.bucket.root)
|
||||||
|
c.stack = append(c.stack, elemRef{page: p, node: n, index: 0})
|
||||||
|
c.first()
|
||||||
|
|
||||||
|
// If we land on an empty page then move to the next value.
|
||||||
|
// https://github.com/boltdb/bolt/issues/450
|
||||||
|
if c.stack[len(c.stack)-1].count() == 0 {
|
||||||
|
c.next()
|
||||||
|
}
|
||||||
|
|
||||||
|
k, v, flags := c.keyValue()
|
||||||
|
if (flags & uint32(bucketLeafFlag)) != 0 {
|
||||||
|
return k, nil
|
||||||
|
}
|
||||||
|
return k, v
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// Last moves the cursor to the last item in the bucket and returns its key and value.
|
||||||
|
// If the bucket is empty then a nil key and value are returned.
|
||||||
|
// The returned key and value are only valid for the life of the transaction.
|
||||||
|
func (c *Cursor) Last() (key []byte, value []byte) {
|
||||||
|
_assert(c.bucket.tx.db != nil, "tx closed")
|
||||||
|
c.stack = c.stack[:0]
|
||||||
|
p, n := c.bucket.pageNode(c.bucket.root)
|
||||||
|
ref := elemRef{page: p, node: n}
|
||||||
|
ref.index = ref.count() - 1
|
||||||
|
c.stack = append(c.stack, ref)
|
||||||
|
c.last()
|
||||||
|
k, v, flags := c.keyValue()
|
||||||
|
if (flags & uint32(bucketLeafFlag)) != 0 {
|
||||||
|
return k, nil
|
||||||
|
}
|
||||||
|
return k, v
|
||||||
|
}
|
||||||
|
|
||||||
|
// Next moves the cursor to the next item in the bucket and returns its key and value.
|
||||||
|
// If the cursor is at the end of the bucket then a nil key and value are returned.
|
||||||
|
// The returned key and value are only valid for the life of the transaction.
|
||||||
|
func (c *Cursor) Next() (key []byte, value []byte) {
|
||||||
|
_assert(c.bucket.tx.db != nil, "tx closed")
|
||||||
|
k, v, flags := c.next()
|
||||||
|
if (flags & uint32(bucketLeafFlag)) != 0 {
|
||||||
|
return k, nil
|
||||||
|
}
|
||||||
|
return k, v
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prev moves the cursor to the previous item in the bucket and returns its key and value.
|
||||||
|
// If the cursor is at the beginning of the bucket then a nil key and value are returned.
|
||||||
|
// The returned key and value are only valid for the life of the transaction.
|
||||||
|
func (c *Cursor) Prev() (key []byte, value []byte) {
|
||||||
|
_assert(c.bucket.tx.db != nil, "tx closed")
|
||||||
|
|
||||||
|
// Attempt to move back one element until we're successful.
|
||||||
|
// Move up the stack as we hit the beginning of each page in our stack.
|
||||||
|
for i := len(c.stack) - 1; i >= 0; i-- {
|
||||||
|
elem := &c.stack[i]
|
||||||
|
if elem.index > 0 {
|
||||||
|
elem.index--
|
||||||
|
break
|
||||||
|
}
|
||||||
|
c.stack = c.stack[:i]
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we've hit the end then return nil.
|
||||||
|
if len(c.stack) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move down the stack to find the last element of the last leaf under this branch.
|
||||||
|
c.last()
|
||||||
|
k, v, flags := c.keyValue()
|
||||||
|
if (flags & uint32(bucketLeafFlag)) != 0 {
|
||||||
|
return k, nil
|
||||||
|
}
|
||||||
|
return k, v
|
||||||
|
}
|
||||||
|
|
||||||
|
// Seek moves the cursor to a given key and returns it.
|
||||||
|
// If the key does not exist then the next key is used. If no keys
|
||||||
|
// follow, a nil key is returned.
|
||||||
|
// The returned key and value are only valid for the life of the transaction.
|
||||||
|
func (c *Cursor) Seek(seek []byte) (key []byte, value []byte) {
|
||||||
|
k, v, flags := c.seek(seek)
|
||||||
|
|
||||||
|
// If we ended up after the last element of a page then move to the next one.
|
||||||
|
if ref := &c.stack[len(c.stack)-1]; ref.index >= ref.count() {
|
||||||
|
k, v, flags = c.next()
|
||||||
|
}
|
||||||
|
|
||||||
|
if k == nil {
|
||||||
|
return nil, nil
|
||||||
|
} else if (flags & uint32(bucketLeafFlag)) != 0 {
|
||||||
|
return k, nil
|
||||||
|
}
|
||||||
|
return k, v
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete removes the current key/value under the cursor from the bucket.
|
||||||
|
// Delete fails if current key/value is a bucket or if the transaction is not writable.
|
||||||
|
func (c *Cursor) Delete() error {
|
||||||
|
if c.bucket.tx.db == nil {
|
||||||
|
return ErrTxClosed
|
||||||
|
} else if !c.bucket.Writable() {
|
||||||
|
return ErrTxNotWritable
|
||||||
|
}
|
||||||
|
|
||||||
|
key, _, flags := c.keyValue()
|
||||||
|
// Return an error if current value is a bucket.
|
||||||
|
if (flags & bucketLeafFlag) != 0 {
|
||||||
|
return ErrIncompatibleValue
|
||||||
|
}
|
||||||
|
c.node().del(key)
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// seek moves the cursor to a given key and returns it.
|
||||||
|
// If the key does not exist then the next key is used.
|
||||||
|
func (c *Cursor) seek(seek []byte) (key []byte, value []byte, flags uint32) {
|
||||||
|
_assert(c.bucket.tx.db != nil, "tx closed")
|
||||||
|
|
||||||
|
// Start from root page/node and traverse to correct page.
|
||||||
|
c.stack = c.stack[:0]
|
||||||
|
c.search(seek, c.bucket.root)
|
||||||
|
ref := &c.stack[len(c.stack)-1]
|
||||||
|
|
||||||
|
// If the cursor is pointing to the end of page/node then return nil.
|
||||||
|
if ref.index >= ref.count() {
|
||||||
|
return nil, nil, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// If this is a bucket then return a nil value.
|
||||||
|
return c.keyValue()
|
||||||
|
}
|
||||||
|
|
||||||
|
// first moves the cursor to the first leaf element under the last page in the stack.
|
||||||
|
func (c *Cursor) first() {
|
||||||
|
for {
|
||||||
|
// Exit when we hit a leaf page.
|
||||||
|
var ref = &c.stack[len(c.stack)-1]
|
||||||
|
if ref.isLeaf() {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep adding pages pointing to the first element to the stack.
|
||||||
|
var pgid pgid
|
||||||
|
if ref.node != nil {
|
||||||
|
pgid = ref.node.inodes[ref.index].pgid
|
||||||
|
} else {
|
||||||
|
pgid = ref.page.branchPageElement(uint16(ref.index)).pgid
|
||||||
|
}
|
||||||
|
p, n := c.bucket.pageNode(pgid)
|
||||||
|
c.stack = append(c.stack, elemRef{page: p, node: n, index: 0})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// last moves the cursor to the last leaf element under the last page in the stack.
|
||||||
|
func (c *Cursor) last() {
|
||||||
|
for {
|
||||||
|
// Exit when we hit a leaf page.
|
||||||
|
ref := &c.stack[len(c.stack)-1]
|
||||||
|
if ref.isLeaf() {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
// Keep adding pages pointing to the last element in the stack.
|
||||||
|
var pgid pgid
|
||||||
|
if ref.node != nil {
|
||||||
|
pgid = ref.node.inodes[ref.index].pgid
|
||||||
|
} else {
|
||||||
|
pgid = ref.page.branchPageElement(uint16(ref.index)).pgid
|
||||||
|
}
|
||||||
|
p, n := c.bucket.pageNode(pgid)
|
||||||
|
|
||||||
|
var nextRef = elemRef{page: p, node: n}
|
||||||
|
nextRef.index = nextRef.count() - 1
|
||||||
|
c.stack = append(c.stack, nextRef)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// next moves to the next leaf element and returns the key and value.
|
||||||
|
// If the cursor is at the last leaf element then it stays there and returns nil.
|
||||||
|
func (c *Cursor) next() (key []byte, value []byte, flags uint32) {
|
||||||
|
for {
|
||||||
|
// Attempt to move over one element until we're successful.
|
||||||
|
// Move up the stack as we hit the end of each page in our stack.
|
||||||
|
var i int
|
||||||
|
for i = len(c.stack) - 1; i >= 0; i-- {
|
||||||
|
elem := &c.stack[i]
|
||||||
|
if elem.index < elem.count()-1 {
|
||||||
|
elem.index++
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we've hit the root page then stop and return. This will leave the
|
||||||
|
// cursor on the last element of the last page.
|
||||||
|
if i == -1 {
|
||||||
|
return nil, nil, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise start from where we left off in the stack and find the
|
||||||
|
// first element of the first leaf page.
|
||||||
|
c.stack = c.stack[:i+1]
|
||||||
|
c.first()
|
||||||
|
|
||||||
|
// If this is an empty page then restart and move back up the stack.
|
||||||
|
// https://github.com/boltdb/bolt/issues/450
|
||||||
|
if c.stack[len(c.stack)-1].count() == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.keyValue()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// search recursively performs a binary search against a given page/node until it finds a given key.
|
||||||
|
func (c *Cursor) search(key []byte, pgid pgid) {
|
||||||
|
p, n := c.bucket.pageNode(pgid)
|
||||||
|
if p != nil && (p.flags&(branchPageFlag|leafPageFlag)) == 0 {
|
||||||
|
panic(fmt.Sprintf("invalid page type: %d: %x", p.id, p.flags))
|
||||||
|
}
|
||||||
|
e := elemRef{page: p, node: n}
|
||||||
|
c.stack = append(c.stack, e)
|
||||||
|
|
||||||
|
// If we're on a leaf page/node then find the specific node.
|
||||||
|
if e.isLeaf() {
|
||||||
|
c.nsearch(key)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if n != nil {
|
||||||
|
c.searchNode(key, n)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.searchPage(key, p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Cursor) searchNode(key []byte, n *node) {
|
||||||
|
var exact bool
|
||||||
|
index := sort.Search(len(n.inodes), func(i int) bool {
|
||||||
|
// TODO(benbjohnson): Optimize this range search. It's a bit hacky right now.
|
||||||
|
// sort.Search() finds the lowest index where f() != -1 but we need the highest index.
|
||||||
|
ret := bytes.Compare(n.inodes[i].key, key)
|
||||||
|
if ret == 0 {
|
||||||
|
exact = true
|
||||||
|
}
|
||||||
|
return ret != -1
|
||||||
|
})
|
||||||
|
if !exact && index > 0 {
|
||||||
|
index--
|
||||||
|
}
|
||||||
|
c.stack[len(c.stack)-1].index = index
|
||||||
|
|
||||||
|
// Recursively search to the next page.
|
||||||
|
c.search(key, n.inodes[index].pgid)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Cursor) searchPage(key []byte, p *page) {
|
||||||
|
// Binary search for the correct range.
|
||||||
|
inodes := p.branchPageElements()
|
||||||
|
|
||||||
|
var exact bool
|
||||||
|
index := sort.Search(int(p.count), func(i int) bool {
|
||||||
|
// TODO(benbjohnson): Optimize this range search. It's a bit hacky right now.
|
||||||
|
// sort.Search() finds the lowest index where f() != -1 but we need the highest index.
|
||||||
|
ret := bytes.Compare(inodes[i].key(), key)
|
||||||
|
if ret == 0 {
|
||||||
|
exact = true
|
||||||
|
}
|
||||||
|
return ret != -1
|
||||||
|
})
|
||||||
|
if !exact && index > 0 {
|
||||||
|
index--
|
||||||
|
}
|
||||||
|
c.stack[len(c.stack)-1].index = index
|
||||||
|
|
||||||
|
// Recursively search to the next page.
|
||||||
|
c.search(key, inodes[index].pgid)
|
||||||
|
}
|
||||||
|
|
||||||
|
// nsearch searches the leaf node on the top of the stack for a key.
|
||||||
|
func (c *Cursor) nsearch(key []byte) {
|
||||||
|
e := &c.stack[len(c.stack)-1]
|
||||||
|
p, n := e.page, e.node
|
||||||
|
|
||||||
|
// If we have a node then search its inodes.
|
||||||
|
if n != nil {
|
||||||
|
index := sort.Search(len(n.inodes), func(i int) bool {
|
||||||
|
return bytes.Compare(n.inodes[i].key, key) != -1
|
||||||
|
})
|
||||||
|
e.index = index
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we have a page then search its leaf elements.
|
||||||
|
inodes := p.leafPageElements()
|
||||||
|
index := sort.Search(int(p.count), func(i int) bool {
|
||||||
|
return bytes.Compare(inodes[i].key(), key) != -1
|
||||||
|
})
|
||||||
|
e.index = index
|
||||||
|
}
|
||||||
|
|
||||||
|
// keyValue returns the key and value of the current leaf element.
|
||||||
|
func (c *Cursor) keyValue() ([]byte, []byte, uint32) {
|
||||||
|
ref := &c.stack[len(c.stack)-1]
|
||||||
|
if ref.count() == 0 || ref.index >= ref.count() {
|
||||||
|
return nil, nil, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Retrieve value from node.
|
||||||
|
if ref.node != nil {
|
||||||
|
inode := &ref.node.inodes[ref.index]
|
||||||
|
return inode.key, inode.value, inode.flags
|
||||||
|
}
|
||||||
|
|
||||||
|
// Or retrieve value from page.
|
||||||
|
elem := ref.page.leafPageElement(uint16(ref.index))
|
||||||
|
return elem.key(), elem.value(), elem.flags
|
||||||
|
}
|
||||||
|
|
||||||
|
// node returns the node that the cursor is currently positioned on.
|
||||||
|
func (c *Cursor) node() *node {
|
||||||
|
_assert(len(c.stack) > 0, "accessing a node with a zero-length cursor stack")
|
||||||
|
|
||||||
|
// If the top of the stack is a leaf node then just return it.
|
||||||
|
if ref := &c.stack[len(c.stack)-1]; ref.node != nil && ref.isLeaf() {
|
||||||
|
return ref.node
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start from root and traverse down the hierarchy.
|
||||||
|
var n = c.stack[0].node
|
||||||
|
if n == nil {
|
||||||
|
n = c.bucket.node(c.stack[0].page.id, nil)
|
||||||
|
}
|
||||||
|
for _, ref := range c.stack[:len(c.stack)-1] {
|
||||||
|
_assert(!n.isLeaf, "expected branch node")
|
||||||
|
n = n.childAt(int(ref.index))
|
||||||
|
}
|
||||||
|
_assert(n.isLeaf, "expected leaf node")
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// elemRef represents a reference to an element on a given page/node.
|
||||||
|
type elemRef struct {
|
||||||
|
page *page
|
||||||
|
node *node
|
||||||
|
index int
|
||||||
|
}
|
||||||
|
|
||||||
|
// isLeaf returns whether the ref is pointing at a leaf page/node.
|
||||||
|
func (r *elemRef) isLeaf() bool {
|
||||||
|
if r.node != nil {
|
||||||
|
return r.node.isLeaf
|
||||||
|
}
|
||||||
|
return (r.page.flags & leafPageFlag) != 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// count returns the number of inodes or page elements.
|
||||||
|
func (r *elemRef) count() int {
|
||||||
|
if r.node != nil {
|
||||||
|
return len(r.node.inodes)
|
||||||
|
}
|
||||||
|
return int(r.page.count)
|
||||||
|
}
|
1039
vendor/github.com/boltdb/bolt/db.go
generated
vendored
Normal file
1039
vendor/github.com/boltdb/bolt/db.go
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
44
vendor/github.com/boltdb/bolt/doc.go
generated
vendored
Normal file
44
vendor/github.com/boltdb/bolt/doc.go
generated
vendored
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
/*
|
||||||
|
Package bolt implements a low-level key/value store in pure Go. It supports
|
||||||
|
fully serializable transactions, ACID semantics, and lock-free MVCC with
|
||||||
|
multiple readers and a single writer. Bolt can be used for projects that
|
||||||
|
want a simple data store without the need to add large dependencies such as
|
||||||
|
Postgres or MySQL.
|
||||||
|
|
||||||
|
Bolt is a single-level, zero-copy, B+tree data store. This means that Bolt is
|
||||||
|
optimized for fast read access and does not require recovery in the event of a
|
||||||
|
system crash. Transactions which have not finished committing will simply be
|
||||||
|
rolled back in the event of a crash.
|
||||||
|
|
||||||
|
The design of Bolt is based on Howard Chu's LMDB database project.
|
||||||
|
|
||||||
|
Bolt currently works on Windows, Mac OS X, and Linux.
|
||||||
|
|
||||||
|
|
||||||
|
Basics
|
||||||
|
|
||||||
|
There are only a few types in Bolt: DB, Bucket, Tx, and Cursor. The DB is
|
||||||
|
a collection of buckets and is represented by a single file on disk. A bucket is
|
||||||
|
a collection of unique keys that are associated with values.
|
||||||
|
|
||||||
|
Transactions provide either read-only or read-write access to the database.
|
||||||
|
Read-only transactions can retrieve key/value pairs and can use Cursors to
|
||||||
|
iterate over the dataset sequentially. Read-write transactions can create and
|
||||||
|
delete buckets and can insert and remove keys. Only one read-write transaction
|
||||||
|
is allowed at a time.
|
||||||
|
|
||||||
|
|
||||||
|
Caveats
|
||||||
|
|
||||||
|
The database uses a read-only, memory-mapped data file to ensure that
|
||||||
|
applications cannot corrupt the database, however, this means that keys and
|
||||||
|
values returned from Bolt cannot be changed. Writing to a read-only byte slice
|
||||||
|
will cause Go to panic.
|
||||||
|
|
||||||
|
Keys and values retrieved from the database are only valid for the life of
|
||||||
|
the transaction. When used outside the transaction, these byte slices can
|
||||||
|
point to different data or can point to invalid memory which will cause a panic.
|
||||||
|
|
||||||
|
|
||||||
|
*/
|
||||||
|
package bolt
|
71
vendor/github.com/boltdb/bolt/errors.go
generated
vendored
Normal file
71
vendor/github.com/boltdb/bolt/errors.go
generated
vendored
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
package bolt
|
||||||
|
|
||||||
|
import "errors"
|
||||||
|
|
||||||
|
// These errors can be returned when opening or calling methods on a DB.
|
||||||
|
var (
|
||||||
|
// ErrDatabaseNotOpen is returned when a DB instance is accessed before it
|
||||||
|
// is opened or after it is closed.
|
||||||
|
ErrDatabaseNotOpen = errors.New("database not open")
|
||||||
|
|
||||||
|
// ErrDatabaseOpen is returned when opening a database that is
|
||||||
|
// already open.
|
||||||
|
ErrDatabaseOpen = errors.New("database already open")
|
||||||
|
|
||||||
|
// ErrInvalid is returned when both meta pages on a database are invalid.
|
||||||
|
// This typically occurs when a file is not a bolt database.
|
||||||
|
ErrInvalid = errors.New("invalid database")
|
||||||
|
|
||||||
|
// ErrVersionMismatch is returned when the data file was created with a
|
||||||
|
// different version of Bolt.
|
||||||
|
ErrVersionMismatch = errors.New("version mismatch")
|
||||||
|
|
||||||
|
// ErrChecksum is returned when either meta page checksum does not match.
|
||||||
|
ErrChecksum = errors.New("checksum error")
|
||||||
|
|
||||||
|
// ErrTimeout is returned when a database cannot obtain an exclusive lock
|
||||||
|
// on the data file after the timeout passed to Open().
|
||||||
|
ErrTimeout = errors.New("timeout")
|
||||||
|
)
|
||||||
|
|
||||||
|
// These errors can occur when beginning or committing a Tx.
|
||||||
|
var (
|
||||||
|
// ErrTxNotWritable is returned when performing a write operation on a
|
||||||
|
// read-only transaction.
|
||||||
|
ErrTxNotWritable = errors.New("tx not writable")
|
||||||
|
|
||||||
|
// ErrTxClosed is returned when committing or rolling back a transaction
|
||||||
|
// that has already been committed or rolled back.
|
||||||
|
ErrTxClosed = errors.New("tx closed")
|
||||||
|
|
||||||
|
// ErrDatabaseReadOnly is returned when a mutating transaction is started on a
|
||||||
|
// read-only database.
|
||||||
|
ErrDatabaseReadOnly = errors.New("database is in read-only mode")
|
||||||
|
)
|
||||||
|
|
||||||
|
// These errors can occur when putting or deleting a value or a bucket.
|
||||||
|
var (
|
||||||
|
// ErrBucketNotFound is returned when trying to access a bucket that has
|
||||||
|
// not been created yet.
|
||||||
|
ErrBucketNotFound = errors.New("bucket not found")
|
||||||
|
|
||||||
|
// ErrBucketExists is returned when creating a bucket that already exists.
|
||||||
|
ErrBucketExists = errors.New("bucket already exists")
|
||||||
|
|
||||||
|
// ErrBucketNameRequired is returned when creating a bucket with a blank name.
|
||||||
|
ErrBucketNameRequired = errors.New("bucket name required")
|
||||||
|
|
||||||
|
// ErrKeyRequired is returned when inserting a zero-length key.
|
||||||
|
ErrKeyRequired = errors.New("key required")
|
||||||
|
|
||||||
|
// ErrKeyTooLarge is returned when inserting a key that is larger than MaxKeySize.
|
||||||
|
ErrKeyTooLarge = errors.New("key too large")
|
||||||
|
|
||||||
|
// ErrValueTooLarge is returned when inserting a value that is larger than MaxValueSize.
|
||||||
|
ErrValueTooLarge = errors.New("value too large")
|
||||||
|
|
||||||
|
// ErrIncompatibleValue is returned when trying create or delete a bucket
|
||||||
|
// on an existing non-bucket key or when trying to create or delete a
|
||||||
|
// non-bucket key on an existing bucket key.
|
||||||
|
ErrIncompatibleValue = errors.New("incompatible value")
|
||||||
|
)
|
252
vendor/github.com/boltdb/bolt/freelist.go
generated
vendored
Normal file
252
vendor/github.com/boltdb/bolt/freelist.go
generated
vendored
Normal file
@ -0,0 +1,252 @@
|
|||||||
|
package bolt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
// freelist represents a list of all pages that are available for allocation.
|
||||||
|
// It also tracks pages that have been freed but are still in use by open transactions.
|
||||||
|
type freelist struct {
|
||||||
|
ids []pgid // all free and available free page ids.
|
||||||
|
pending map[txid][]pgid // mapping of soon-to-be free page ids by tx.
|
||||||
|
cache map[pgid]bool // fast lookup of all free and pending page ids.
|
||||||
|
}
|
||||||
|
|
||||||
|
// newFreelist returns an empty, initialized freelist.
|
||||||
|
func newFreelist() *freelist {
|
||||||
|
return &freelist{
|
||||||
|
pending: make(map[txid][]pgid),
|
||||||
|
cache: make(map[pgid]bool),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// size returns the size of the page after serialization.
|
||||||
|
func (f *freelist) size() int {
|
||||||
|
n := f.count()
|
||||||
|
if n >= 0xFFFF {
|
||||||
|
// The first element will be used to store the count. See freelist.write.
|
||||||
|
n++
|
||||||
|
}
|
||||||
|
return pageHeaderSize + (int(unsafe.Sizeof(pgid(0))) * n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// count returns count of pages on the freelist
|
||||||
|
func (f *freelist) count() int {
|
||||||
|
return f.free_count() + f.pending_count()
|
||||||
|
}
|
||||||
|
|
||||||
|
// free_count returns count of free pages
|
||||||
|
func (f *freelist) free_count() int {
|
||||||
|
return len(f.ids)
|
||||||
|
}
|
||||||
|
|
||||||
|
// pending_count returns count of pending pages
|
||||||
|
func (f *freelist) pending_count() int {
|
||||||
|
var count int
|
||||||
|
for _, list := range f.pending {
|
||||||
|
count += len(list)
|
||||||
|
}
|
||||||
|
return count
|
||||||
|
}
|
||||||
|
|
||||||
|
// copyall copies into dst a list of all free ids and all pending ids in one sorted list.
|
||||||
|
// f.count returns the minimum length required for dst.
|
||||||
|
func (f *freelist) copyall(dst []pgid) {
|
||||||
|
m := make(pgids, 0, f.pending_count())
|
||||||
|
for _, list := range f.pending {
|
||||||
|
m = append(m, list...)
|
||||||
|
}
|
||||||
|
sort.Sort(m)
|
||||||
|
mergepgids(dst, f.ids, m)
|
||||||
|
}
|
||||||
|
|
||||||
|
// allocate returns the starting page id of a contiguous list of pages of a given size.
|
||||||
|
// If a contiguous block cannot be found then 0 is returned.
|
||||||
|
func (f *freelist) allocate(n int) pgid {
|
||||||
|
if len(f.ids) == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
var initial, previd pgid
|
||||||
|
for i, id := range f.ids {
|
||||||
|
if id <= 1 {
|
||||||
|
panic(fmt.Sprintf("invalid page allocation: %d", id))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Reset initial page if this is not contiguous.
|
||||||
|
if previd == 0 || id-previd != 1 {
|
||||||
|
initial = id
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we found a contiguous block then remove it and return it.
|
||||||
|
if (id-initial)+1 == pgid(n) {
|
||||||
|
// If we're allocating off the beginning then take the fast path
|
||||||
|
// and just adjust the existing slice. This will use extra memory
|
||||||
|
// temporarily but the append() in free() will realloc the slice
|
||||||
|
// as is necessary.
|
||||||
|
if (i + 1) == n {
|
||||||
|
f.ids = f.ids[i+1:]
|
||||||
|
} else {
|
||||||
|
copy(f.ids[i-n+1:], f.ids[i+1:])
|
||||||
|
f.ids = f.ids[:len(f.ids)-n]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove from the free cache.
|
||||||
|
for i := pgid(0); i < pgid(n); i++ {
|
||||||
|
delete(f.cache, initial+i)
|
||||||
|
}
|
||||||
|
|
||||||
|
return initial
|
||||||
|
}
|
||||||
|
|
||||||
|
previd = id
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// free releases a page and its overflow for a given transaction id.
|
||||||
|
// If the page is already free then a panic will occur.
|
||||||
|
func (f *freelist) free(txid txid, p *page) {
|
||||||
|
if p.id <= 1 {
|
||||||
|
panic(fmt.Sprintf("cannot free page 0 or 1: %d", p.id))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Free page and all its overflow pages.
|
||||||
|
var ids = f.pending[txid]
|
||||||
|
for id := p.id; id <= p.id+pgid(p.overflow); id++ {
|
||||||
|
// Verify that page is not already free.
|
||||||
|
if f.cache[id] {
|
||||||
|
panic(fmt.Sprintf("page %d already freed", id))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add to the freelist and cache.
|
||||||
|
ids = append(ids, id)
|
||||||
|
f.cache[id] = true
|
||||||
|
}
|
||||||
|
f.pending[txid] = ids
|
||||||
|
}
|
||||||
|
|
||||||
|
// release moves all page ids for a transaction id (or older) to the freelist.
|
||||||
|
func (f *freelist) release(txid txid) {
|
||||||
|
m := make(pgids, 0)
|
||||||
|
for tid, ids := range f.pending {
|
||||||
|
if tid <= txid {
|
||||||
|
// Move transaction's pending pages to the available freelist.
|
||||||
|
// Don't remove from the cache since the page is still free.
|
||||||
|
m = append(m, ids...)
|
||||||
|
delete(f.pending, tid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sort.Sort(m)
|
||||||
|
f.ids = pgids(f.ids).merge(m)
|
||||||
|
}
|
||||||
|
|
||||||
|
// rollback removes the pages from a given pending tx.
|
||||||
|
func (f *freelist) rollback(txid txid) {
|
||||||
|
// Remove page ids from cache.
|
||||||
|
for _, id := range f.pending[txid] {
|
||||||
|
delete(f.cache, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove pages from pending list.
|
||||||
|
delete(f.pending, txid)
|
||||||
|
}
|
||||||
|
|
||||||
|
// freed returns whether a given page is in the free list.
|
||||||
|
func (f *freelist) freed(pgid pgid) bool {
|
||||||
|
return f.cache[pgid]
|
||||||
|
}
|
||||||
|
|
||||||
|
// read initializes the freelist from a freelist page.
|
||||||
|
func (f *freelist) read(p *page) {
|
||||||
|
// If the page.count is at the max uint16 value (64k) then it's considered
|
||||||
|
// an overflow and the size of the freelist is stored as the first element.
|
||||||
|
idx, count := 0, int(p.count)
|
||||||
|
if count == 0xFFFF {
|
||||||
|
idx = 1
|
||||||
|
count = int(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copy the list of page ids from the freelist.
|
||||||
|
if count == 0 {
|
||||||
|
f.ids = nil
|
||||||
|
} else {
|
||||||
|
ids := ((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[idx:count]
|
||||||
|
f.ids = make([]pgid, len(ids))
|
||||||
|
copy(f.ids, ids)
|
||||||
|
|
||||||
|
// Make sure they're sorted.
|
||||||
|
sort.Sort(pgids(f.ids))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rebuild the page cache.
|
||||||
|
f.reindex()
|
||||||
|
}
|
||||||
|
|
||||||
|
// write writes the page ids onto a freelist page. All free and pending ids are
|
||||||
|
// saved to disk since in the event of a program crash, all pending ids will
|
||||||
|
// become free.
|
||||||
|
func (f *freelist) write(p *page) error {
|
||||||
|
// Combine the old free pgids and pgids waiting on an open transaction.
|
||||||
|
|
||||||
|
// Update the header flag.
|
||||||
|
p.flags |= freelistPageFlag
|
||||||
|
|
||||||
|
// The page.count can only hold up to 64k elements so if we overflow that
|
||||||
|
// number then we handle it by putting the size in the first element.
|
||||||
|
lenids := f.count()
|
||||||
|
if lenids == 0 {
|
||||||
|
p.count = uint16(lenids)
|
||||||
|
} else if lenids < 0xFFFF {
|
||||||
|
p.count = uint16(lenids)
|
||||||
|
f.copyall(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[:])
|
||||||
|
} else {
|
||||||
|
p.count = 0xFFFF
|
||||||
|
((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0] = pgid(lenids)
|
||||||
|
f.copyall(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[1:])
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// reload reads the freelist from a page and filters out pending items.
|
||||||
|
func (f *freelist) reload(p *page) {
|
||||||
|
f.read(p)
|
||||||
|
|
||||||
|
// Build a cache of only pending pages.
|
||||||
|
pcache := make(map[pgid]bool)
|
||||||
|
for _, pendingIDs := range f.pending {
|
||||||
|
for _, pendingID := range pendingIDs {
|
||||||
|
pcache[pendingID] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check each page in the freelist and build a new available freelist
|
||||||
|
// with any pages not in the pending lists.
|
||||||
|
var a []pgid
|
||||||
|
for _, id := range f.ids {
|
||||||
|
if !pcache[id] {
|
||||||
|
a = append(a, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
f.ids = a
|
||||||
|
|
||||||
|
// Once the available list is rebuilt then rebuild the free cache so that
|
||||||
|
// it includes the available and pending free pages.
|
||||||
|
f.reindex()
|
||||||
|
}
|
||||||
|
|
||||||
|
// reindex rebuilds the free cache based on available and pending free lists.
|
||||||
|
func (f *freelist) reindex() {
|
||||||
|
f.cache = make(map[pgid]bool, len(f.ids))
|
||||||
|
for _, id := range f.ids {
|
||||||
|
f.cache[id] = true
|
||||||
|
}
|
||||||
|
for _, pendingIDs := range f.pending {
|
||||||
|
for _, pendingID := range pendingIDs {
|
||||||
|
f.cache[pendingID] = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
604
vendor/github.com/boltdb/bolt/node.go
generated
vendored
Normal file
604
vendor/github.com/boltdb/bolt/node.go
generated
vendored
Normal file
@ -0,0 +1,604 @@
|
|||||||
|
package bolt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
// node represents an in-memory, deserialized page.
|
||||||
|
type node struct {
|
||||||
|
bucket *Bucket
|
||||||
|
isLeaf bool
|
||||||
|
unbalanced bool
|
||||||
|
spilled bool
|
||||||
|
key []byte
|
||||||
|
pgid pgid
|
||||||
|
parent *node
|
||||||
|
children nodes
|
||||||
|
inodes inodes
|
||||||
|
}
|
||||||
|
|
||||||
|
// root returns the top-level node this node is attached to.
|
||||||
|
func (n *node) root() *node {
|
||||||
|
if n.parent == nil {
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
return n.parent.root()
|
||||||
|
}
|
||||||
|
|
||||||
|
// minKeys returns the minimum number of inodes this node should have.
|
||||||
|
func (n *node) minKeys() int {
|
||||||
|
if n.isLeaf {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
// size returns the size of the node after serialization.
|
||||||
|
func (n *node) size() int {
|
||||||
|
sz, elsz := pageHeaderSize, n.pageElementSize()
|
||||||
|
for i := 0; i < len(n.inodes); i++ {
|
||||||
|
item := &n.inodes[i]
|
||||||
|
sz += elsz + len(item.key) + len(item.value)
|
||||||
|
}
|
||||||
|
return sz
|
||||||
|
}
|
||||||
|
|
||||||
|
// sizeLessThan returns true if the node is less than a given size.
|
||||||
|
// This is an optimization to avoid calculating a large node when we only need
|
||||||
|
// to know if it fits inside a certain page size.
|
||||||
|
func (n *node) sizeLessThan(v int) bool {
|
||||||
|
sz, elsz := pageHeaderSize, n.pageElementSize()
|
||||||
|
for i := 0; i < len(n.inodes); i++ {
|
||||||
|
item := &n.inodes[i]
|
||||||
|
sz += elsz + len(item.key) + len(item.value)
|
||||||
|
if sz >= v {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// pageElementSize returns the size of each page element based on the type of node.
|
||||||
|
func (n *node) pageElementSize() int {
|
||||||
|
if n.isLeaf {
|
||||||
|
return leafPageElementSize
|
||||||
|
}
|
||||||
|
return branchPageElementSize
|
||||||
|
}
|
||||||
|
|
||||||
|
// childAt returns the child node at a given index.
|
||||||
|
func (n *node) childAt(index int) *node {
|
||||||
|
if n.isLeaf {
|
||||||
|
panic(fmt.Sprintf("invalid childAt(%d) on a leaf node", index))
|
||||||
|
}
|
||||||
|
return n.bucket.node(n.inodes[index].pgid, n)
|
||||||
|
}
|
||||||
|
|
||||||
|
// childIndex returns the index of a given child node.
|
||||||
|
func (n *node) childIndex(child *node) int {
|
||||||
|
index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, child.key) != -1 })
|
||||||
|
return index
|
||||||
|
}
|
||||||
|
|
||||||
|
// numChildren returns the number of children.
|
||||||
|
func (n *node) numChildren() int {
|
||||||
|
return len(n.inodes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// nextSibling returns the next node with the same parent.
|
||||||
|
func (n *node) nextSibling() *node {
|
||||||
|
if n.parent == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
index := n.parent.childIndex(n)
|
||||||
|
if index >= n.parent.numChildren()-1 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return n.parent.childAt(index + 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// prevSibling returns the previous node with the same parent.
|
||||||
|
func (n *node) prevSibling() *node {
|
||||||
|
if n.parent == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
index := n.parent.childIndex(n)
|
||||||
|
if index == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return n.parent.childAt(index - 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// put inserts a key/value.
|
||||||
|
func (n *node) put(oldKey, newKey, value []byte, pgid pgid, flags uint32) {
|
||||||
|
if pgid >= n.bucket.tx.meta.pgid {
|
||||||
|
panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", pgid, n.bucket.tx.meta.pgid))
|
||||||
|
} else if len(oldKey) <= 0 {
|
||||||
|
panic("put: zero-length old key")
|
||||||
|
} else if len(newKey) <= 0 {
|
||||||
|
panic("put: zero-length new key")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find insertion index.
|
||||||
|
index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, oldKey) != -1 })
|
||||||
|
|
||||||
|
// Add capacity and shift nodes if we don't have an exact match and need to insert.
|
||||||
|
exact := (len(n.inodes) > 0 && index < len(n.inodes) && bytes.Equal(n.inodes[index].key, oldKey))
|
||||||
|
if !exact {
|
||||||
|
n.inodes = append(n.inodes, inode{})
|
||||||
|
copy(n.inodes[index+1:], n.inodes[index:])
|
||||||
|
}
|
||||||
|
|
||||||
|
inode := &n.inodes[index]
|
||||||
|
inode.flags = flags
|
||||||
|
inode.key = newKey
|
||||||
|
inode.value = value
|
||||||
|
inode.pgid = pgid
|
||||||
|
_assert(len(inode.key) > 0, "put: zero-length inode key")
|
||||||
|
}
|
||||||
|
|
||||||
|
// del removes a key from the node.
|
||||||
|
func (n *node) del(key []byte) {
|
||||||
|
// Find index of key.
|
||||||
|
index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, key) != -1 })
|
||||||
|
|
||||||
|
// Exit if the key isn't found.
|
||||||
|
if index >= len(n.inodes) || !bytes.Equal(n.inodes[index].key, key) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete inode from the node.
|
||||||
|
n.inodes = append(n.inodes[:index], n.inodes[index+1:]...)
|
||||||
|
|
||||||
|
// Mark the node as needing rebalancing.
|
||||||
|
n.unbalanced = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// read initializes the node from a page.
|
||||||
|
func (n *node) read(p *page) {
|
||||||
|
n.pgid = p.id
|
||||||
|
n.isLeaf = ((p.flags & leafPageFlag) != 0)
|
||||||
|
n.inodes = make(inodes, int(p.count))
|
||||||
|
|
||||||
|
for i := 0; i < int(p.count); i++ {
|
||||||
|
inode := &n.inodes[i]
|
||||||
|
if n.isLeaf {
|
||||||
|
elem := p.leafPageElement(uint16(i))
|
||||||
|
inode.flags = elem.flags
|
||||||
|
inode.key = elem.key()
|
||||||
|
inode.value = elem.value()
|
||||||
|
} else {
|
||||||
|
elem := p.branchPageElement(uint16(i))
|
||||||
|
inode.pgid = elem.pgid
|
||||||
|
inode.key = elem.key()
|
||||||
|
}
|
||||||
|
_assert(len(inode.key) > 0, "read: zero-length inode key")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save first key so we can find the node in the parent when we spill.
|
||||||
|
if len(n.inodes) > 0 {
|
||||||
|
n.key = n.inodes[0].key
|
||||||
|
_assert(len(n.key) > 0, "read: zero-length node key")
|
||||||
|
} else {
|
||||||
|
n.key = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// write writes the items onto one or more pages.
|
||||||
|
func (n *node) write(p *page) {
|
||||||
|
// Initialize page.
|
||||||
|
if n.isLeaf {
|
||||||
|
p.flags |= leafPageFlag
|
||||||
|
} else {
|
||||||
|
p.flags |= branchPageFlag
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(n.inodes) >= 0xFFFF {
|
||||||
|
panic(fmt.Sprintf("inode overflow: %d (pgid=%d)", len(n.inodes), p.id))
|
||||||
|
}
|
||||||
|
p.count = uint16(len(n.inodes))
|
||||||
|
|
||||||
|
// Stop here if there are no items to write.
|
||||||
|
if p.count == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Loop over each item and write it to the page.
|
||||||
|
b := (*[maxAllocSize]byte)(unsafe.Pointer(&p.ptr))[n.pageElementSize()*len(n.inodes):]
|
||||||
|
for i, item := range n.inodes {
|
||||||
|
_assert(len(item.key) > 0, "write: zero-length inode key")
|
||||||
|
|
||||||
|
// Write the page element.
|
||||||
|
if n.isLeaf {
|
||||||
|
elem := p.leafPageElement(uint16(i))
|
||||||
|
elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem)))
|
||||||
|
elem.flags = item.flags
|
||||||
|
elem.ksize = uint32(len(item.key))
|
||||||
|
elem.vsize = uint32(len(item.value))
|
||||||
|
} else {
|
||||||
|
elem := p.branchPageElement(uint16(i))
|
||||||
|
elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem)))
|
||||||
|
elem.ksize = uint32(len(item.key))
|
||||||
|
elem.pgid = item.pgid
|
||||||
|
_assert(elem.pgid != p.id, "write: circular dependency occurred")
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the length of key+value is larger than the max allocation size
|
||||||
|
// then we need to reallocate the byte array pointer.
|
||||||
|
//
|
||||||
|
// See: https://github.com/boltdb/bolt/pull/335
|
||||||
|
klen, vlen := len(item.key), len(item.value)
|
||||||
|
if len(b) < klen+vlen {
|
||||||
|
b = (*[maxAllocSize]byte)(unsafe.Pointer(&b[0]))[:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write data for the element to the end of the page.
|
||||||
|
copy(b[0:], item.key)
|
||||||
|
b = b[klen:]
|
||||||
|
copy(b[0:], item.value)
|
||||||
|
b = b[vlen:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// DEBUG ONLY: n.dump()
|
||||||
|
}
|
||||||
|
|
||||||
|
// split breaks up a node into multiple smaller nodes, if appropriate.
|
||||||
|
// This should only be called from the spill() function.
|
||||||
|
func (n *node) split(pageSize int) []*node {
|
||||||
|
var nodes []*node
|
||||||
|
|
||||||
|
node := n
|
||||||
|
for {
|
||||||
|
// Split node into two.
|
||||||
|
a, b := node.splitTwo(pageSize)
|
||||||
|
nodes = append(nodes, a)
|
||||||
|
|
||||||
|
// If we can't split then exit the loop.
|
||||||
|
if b == nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set node to b so it gets split on the next iteration.
|
||||||
|
node = b
|
||||||
|
}
|
||||||
|
|
||||||
|
return nodes
|
||||||
|
}
|
||||||
|
|
||||||
|
// splitTwo breaks up a node into two smaller nodes, if appropriate.
|
||||||
|
// This should only be called from the split() function.
|
||||||
|
func (n *node) splitTwo(pageSize int) (*node, *node) {
|
||||||
|
// Ignore the split if the page doesn't have at least enough nodes for
|
||||||
|
// two pages or if the nodes can fit in a single page.
|
||||||
|
if len(n.inodes) <= (minKeysPerPage*2) || n.sizeLessThan(pageSize) {
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine the threshold before starting a new node.
|
||||||
|
var fillPercent = n.bucket.FillPercent
|
||||||
|
if fillPercent < minFillPercent {
|
||||||
|
fillPercent = minFillPercent
|
||||||
|
} else if fillPercent > maxFillPercent {
|
||||||
|
fillPercent = maxFillPercent
|
||||||
|
}
|
||||||
|
threshold := int(float64(pageSize) * fillPercent)
|
||||||
|
|
||||||
|
// Determine split position and sizes of the two pages.
|
||||||
|
splitIndex, _ := n.splitIndex(threshold)
|
||||||
|
|
||||||
|
// Split node into two separate nodes.
|
||||||
|
// If there's no parent then we'll need to create one.
|
||||||
|
if n.parent == nil {
|
||||||
|
n.parent = &node{bucket: n.bucket, children: []*node{n}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create a new node and add it to the parent.
|
||||||
|
next := &node{bucket: n.bucket, isLeaf: n.isLeaf, parent: n.parent}
|
||||||
|
n.parent.children = append(n.parent.children, next)
|
||||||
|
|
||||||
|
// Split inodes across two nodes.
|
||||||
|
next.inodes = n.inodes[splitIndex:]
|
||||||
|
n.inodes = n.inodes[:splitIndex]
|
||||||
|
|
||||||
|
// Update the statistics.
|
||||||
|
n.bucket.tx.stats.Split++
|
||||||
|
|
||||||
|
return n, next
|
||||||
|
}
|
||||||
|
|
||||||
|
// splitIndex finds the position where a page will fill a given threshold.
|
||||||
|
// It returns the index as well as the size of the first page.
|
||||||
|
// This is only be called from split().
|
||||||
|
func (n *node) splitIndex(threshold int) (index, sz int) {
|
||||||
|
sz = pageHeaderSize
|
||||||
|
|
||||||
|
// Loop until we only have the minimum number of keys required for the second page.
|
||||||
|
for i := 0; i < len(n.inodes)-minKeysPerPage; i++ {
|
||||||
|
index = i
|
||||||
|
inode := n.inodes[i]
|
||||||
|
elsize := n.pageElementSize() + len(inode.key) + len(inode.value)
|
||||||
|
|
||||||
|
// If we have at least the minimum number of keys and adding another
|
||||||
|
// node would put us over the threshold then exit and return.
|
||||||
|
if i >= minKeysPerPage && sz+elsize > threshold {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add the element size to the total size.
|
||||||
|
sz += elsize
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// spill writes the nodes to dirty pages and splits nodes as it goes.
|
||||||
|
// Returns an error if dirty pages cannot be allocated.
|
||||||
|
func (n *node) spill() error {
|
||||||
|
var tx = n.bucket.tx
|
||||||
|
if n.spilled {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Spill child nodes first. Child nodes can materialize sibling nodes in
|
||||||
|
// the case of split-merge so we cannot use a range loop. We have to check
|
||||||
|
// the children size on every loop iteration.
|
||||||
|
sort.Sort(n.children)
|
||||||
|
for i := 0; i < len(n.children); i++ {
|
||||||
|
if err := n.children[i].spill(); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// We no longer need the child list because it's only used for spill tracking.
|
||||||
|
n.children = nil
|
||||||
|
|
||||||
|
// Split nodes into appropriate sizes. The first node will always be n.
|
||||||
|
var nodes = n.split(tx.db.pageSize)
|
||||||
|
for _, node := range nodes {
|
||||||
|
// Add node's page to the freelist if it's not new.
|
||||||
|
if node.pgid > 0 {
|
||||||
|
tx.db.freelist.free(tx.meta.txid, tx.page(node.pgid))
|
||||||
|
node.pgid = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allocate contiguous space for the node.
|
||||||
|
p, err := tx.allocate((node.size() / tx.db.pageSize) + 1)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write the node.
|
||||||
|
if p.id >= tx.meta.pgid {
|
||||||
|
panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", p.id, tx.meta.pgid))
|
||||||
|
}
|
||||||
|
node.pgid = p.id
|
||||||
|
node.write(p)
|
||||||
|
node.spilled = true
|
||||||
|
|
||||||
|
// Insert into parent inodes.
|
||||||
|
if node.parent != nil {
|
||||||
|
var key = node.key
|
||||||
|
if key == nil {
|
||||||
|
key = node.inodes[0].key
|
||||||
|
}
|
||||||
|
|
||||||
|
node.parent.put(key, node.inodes[0].key, nil, node.pgid, 0)
|
||||||
|
node.key = node.inodes[0].key
|
||||||
|
_assert(len(node.key) > 0, "spill: zero-length node key")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update the statistics.
|
||||||
|
tx.stats.Spill++
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the root node split and created a new root then we need to spill that
|
||||||
|
// as well. We'll clear out the children to make sure it doesn't try to respill.
|
||||||
|
if n.parent != nil && n.parent.pgid == 0 {
|
||||||
|
n.children = nil
|
||||||
|
return n.parent.spill()
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// rebalance attempts to combine the node with sibling nodes if the node fill
|
||||||
|
// size is below a threshold or if there are not enough keys.
|
||||||
|
func (n *node) rebalance() {
|
||||||
|
if !n.unbalanced {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
n.unbalanced = false
|
||||||
|
|
||||||
|
// Update statistics.
|
||||||
|
n.bucket.tx.stats.Rebalance++
|
||||||
|
|
||||||
|
// Ignore if node is above threshold (25%) and has enough keys.
|
||||||
|
var threshold = n.bucket.tx.db.pageSize / 4
|
||||||
|
if n.size() > threshold && len(n.inodes) > n.minKeys() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Root node has special handling.
|
||||||
|
if n.parent == nil {
|
||||||
|
// If root node is a branch and only has one node then collapse it.
|
||||||
|
if !n.isLeaf && len(n.inodes) == 1 {
|
||||||
|
// Move root's child up.
|
||||||
|
child := n.bucket.node(n.inodes[0].pgid, n)
|
||||||
|
n.isLeaf = child.isLeaf
|
||||||
|
n.inodes = child.inodes[:]
|
||||||
|
n.children = child.children
|
||||||
|
|
||||||
|
// Reparent all child nodes being moved.
|
||||||
|
for _, inode := range n.inodes {
|
||||||
|
if child, ok := n.bucket.nodes[inode.pgid]; ok {
|
||||||
|
child.parent = n
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove old child.
|
||||||
|
child.parent = nil
|
||||||
|
delete(n.bucket.nodes, child.pgid)
|
||||||
|
child.free()
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// If node has no keys then just remove it.
|
||||||
|
if n.numChildren() == 0 {
|
||||||
|
n.parent.del(n.key)
|
||||||
|
n.parent.removeChild(n)
|
||||||
|
delete(n.bucket.nodes, n.pgid)
|
||||||
|
n.free()
|
||||||
|
n.parent.rebalance()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_assert(n.parent.numChildren() > 1, "parent must have at least 2 children")
|
||||||
|
|
||||||
|
// Destination node is right sibling if idx == 0, otherwise left sibling.
|
||||||
|
var target *node
|
||||||
|
var useNextSibling = (n.parent.childIndex(n) == 0)
|
||||||
|
if useNextSibling {
|
||||||
|
target = n.nextSibling()
|
||||||
|
} else {
|
||||||
|
target = n.prevSibling()
|
||||||
|
}
|
||||||
|
|
||||||
|
// If both this node and the target node are too small then merge them.
|
||||||
|
if useNextSibling {
|
||||||
|
// Reparent all child nodes being moved.
|
||||||
|
for _, inode := range target.inodes {
|
||||||
|
if child, ok := n.bucket.nodes[inode.pgid]; ok {
|
||||||
|
child.parent.removeChild(child)
|
||||||
|
child.parent = n
|
||||||
|
child.parent.children = append(child.parent.children, child)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copy over inodes from target and remove target.
|
||||||
|
n.inodes = append(n.inodes, target.inodes...)
|
||||||
|
n.parent.del(target.key)
|
||||||
|
n.parent.removeChild(target)
|
||||||
|
delete(n.bucket.nodes, target.pgid)
|
||||||
|
target.free()
|
||||||
|
} else {
|
||||||
|
// Reparent all child nodes being moved.
|
||||||
|
for _, inode := range n.inodes {
|
||||||
|
if child, ok := n.bucket.nodes[inode.pgid]; ok {
|
||||||
|
child.parent.removeChild(child)
|
||||||
|
child.parent = target
|
||||||
|
child.parent.children = append(child.parent.children, child)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copy over inodes to target and remove node.
|
||||||
|
target.inodes = append(target.inodes, n.inodes...)
|
||||||
|
n.parent.del(n.key)
|
||||||
|
n.parent.removeChild(n)
|
||||||
|
delete(n.bucket.nodes, n.pgid)
|
||||||
|
n.free()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Either this node or the target node was deleted from the parent so rebalance it.
|
||||||
|
n.parent.rebalance()
|
||||||
|
}
|
||||||
|
|
||||||
|
// removes a node from the list of in-memory children.
|
||||||
|
// This does not affect the inodes.
|
||||||
|
func (n *node) removeChild(target *node) {
|
||||||
|
for i, child := range n.children {
|
||||||
|
if child == target {
|
||||||
|
n.children = append(n.children[:i], n.children[i+1:]...)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// dereference causes the node to copy all its inode key/value references to heap memory.
|
||||||
|
// This is required when the mmap is reallocated so inodes are not pointing to stale data.
|
||||||
|
func (n *node) dereference() {
|
||||||
|
if n.key != nil {
|
||||||
|
key := make([]byte, len(n.key))
|
||||||
|
copy(key, n.key)
|
||||||
|
n.key = key
|
||||||
|
_assert(n.pgid == 0 || len(n.key) > 0, "dereference: zero-length node key on existing node")
|
||||||
|
}
|
||||||
|
|
||||||
|
for i := range n.inodes {
|
||||||
|
inode := &n.inodes[i]
|
||||||
|
|
||||||
|
key := make([]byte, len(inode.key))
|
||||||
|
copy(key, inode.key)
|
||||||
|
inode.key = key
|
||||||
|
_assert(len(inode.key) > 0, "dereference: zero-length inode key")
|
||||||
|
|
||||||
|
value := make([]byte, len(inode.value))
|
||||||
|
copy(value, inode.value)
|
||||||
|
inode.value = value
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recursively dereference children.
|
||||||
|
for _, child := range n.children {
|
||||||
|
child.dereference()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update statistics.
|
||||||
|
n.bucket.tx.stats.NodeDeref++
|
||||||
|
}
|
||||||
|
|
||||||
|
// free adds the node's underlying page to the freelist.
|
||||||
|
func (n *node) free() {
|
||||||
|
if n.pgid != 0 {
|
||||||
|
n.bucket.tx.db.freelist.free(n.bucket.tx.meta.txid, n.bucket.tx.page(n.pgid))
|
||||||
|
n.pgid = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// dump writes the contents of the node to STDERR for debugging purposes.
|
||||||
|
/*
|
||||||
|
func (n *node) dump() {
|
||||||
|
// Write node header.
|
||||||
|
var typ = "branch"
|
||||||
|
if n.isLeaf {
|
||||||
|
typ = "leaf"
|
||||||
|
}
|
||||||
|
warnf("[NODE %d {type=%s count=%d}]", n.pgid, typ, len(n.inodes))
|
||||||
|
|
||||||
|
// Write out abbreviated version of each item.
|
||||||
|
for _, item := range n.inodes {
|
||||||
|
if n.isLeaf {
|
||||||
|
if item.flags&bucketLeafFlag != 0 {
|
||||||
|
bucket := (*bucket)(unsafe.Pointer(&item.value[0]))
|
||||||
|
warnf("+L %08x -> (bucket root=%d)", trunc(item.key, 4), bucket.root)
|
||||||
|
} else {
|
||||||
|
warnf("+L %08x -> %08x", trunc(item.key, 4), trunc(item.value, 4))
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
warnf("+B %08x -> pgid=%d", trunc(item.key, 4), item.pgid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
warn("")
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
type nodes []*node
|
||||||
|
|
||||||
|
func (s nodes) Len() int { return len(s) }
|
||||||
|
func (s nodes) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||||
|
func (s nodes) Less(i, j int) bool { return bytes.Compare(s[i].inodes[0].key, s[j].inodes[0].key) == -1 }
|
||||||
|
|
||||||
|
// inode represents an internal node inside of a node.
|
||||||
|
// It can be used to point to elements in a page or point
|
||||||
|
// to an element which hasn't been added to a page yet.
|
||||||
|
type inode struct {
|
||||||
|
flags uint32
|
||||||
|
pgid pgid
|
||||||
|
key []byte
|
||||||
|
value []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
type inodes []inode
|
197
vendor/github.com/boltdb/bolt/page.go
generated
vendored
Normal file
197
vendor/github.com/boltdb/bolt/page.go
generated
vendored
Normal file
@ -0,0 +1,197 @@
|
|||||||
|
package bolt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"sort"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
const pageHeaderSize = int(unsafe.Offsetof(((*page)(nil)).ptr))
|
||||||
|
|
||||||
|
const minKeysPerPage = 2
|
||||||
|
|
||||||
|
const branchPageElementSize = int(unsafe.Sizeof(branchPageElement{}))
|
||||||
|
const leafPageElementSize = int(unsafe.Sizeof(leafPageElement{}))
|
||||||
|
|
||||||
|
const (
|
||||||
|
branchPageFlag = 0x01
|
||||||
|
leafPageFlag = 0x02
|
||||||
|
metaPageFlag = 0x04
|
||||||
|
freelistPageFlag = 0x10
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
bucketLeafFlag = 0x01
|
||||||
|
)
|
||||||
|
|
||||||
|
type pgid uint64
|
||||||
|
|
||||||
|
type page struct {
|
||||||
|
id pgid
|
||||||
|
flags uint16
|
||||||
|
count uint16
|
||||||
|
overflow uint32
|
||||||
|
ptr uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
// typ returns a human readable page type string used for debugging.
|
||||||
|
func (p *page) typ() string {
|
||||||
|
if (p.flags & branchPageFlag) != 0 {
|
||||||
|
return "branch"
|
||||||
|
} else if (p.flags & leafPageFlag) != 0 {
|
||||||
|
return "leaf"
|
||||||
|
} else if (p.flags & metaPageFlag) != 0 {
|
||||||
|
return "meta"
|
||||||
|
} else if (p.flags & freelistPageFlag) != 0 {
|
||||||
|
return "freelist"
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("unknown<%02x>", p.flags)
|
||||||
|
}
|
||||||
|
|
||||||
|
// meta returns a pointer to the metadata section of the page.
|
||||||
|
func (p *page) meta() *meta {
|
||||||
|
return (*meta)(unsafe.Pointer(&p.ptr))
|
||||||
|
}
|
||||||
|
|
||||||
|
// leafPageElement retrieves the leaf node by index
|
||||||
|
func (p *page) leafPageElement(index uint16) *leafPageElement {
|
||||||
|
n := &((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[index]
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
// leafPageElements retrieves a list of leaf nodes.
|
||||||
|
func (p *page) leafPageElements() []leafPageElement {
|
||||||
|
if p.count == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return ((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// branchPageElement retrieves the branch node by index
|
||||||
|
func (p *page) branchPageElement(index uint16) *branchPageElement {
|
||||||
|
return &((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[index]
|
||||||
|
}
|
||||||
|
|
||||||
|
// branchPageElements retrieves a list of branch nodes.
|
||||||
|
func (p *page) branchPageElements() []branchPageElement {
|
||||||
|
if p.count == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return ((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// dump writes n bytes of the page to STDERR as hex output.
|
||||||
|
func (p *page) hexdump(n int) {
|
||||||
|
buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:n]
|
||||||
|
fmt.Fprintf(os.Stderr, "%x\n", buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
type pages []*page
|
||||||
|
|
||||||
|
func (s pages) Len() int { return len(s) }
|
||||||
|
func (s pages) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||||
|
func (s pages) Less(i, j int) bool { return s[i].id < s[j].id }
|
||||||
|
|
||||||
|
// branchPageElement represents a node on a branch page.
|
||||||
|
type branchPageElement struct {
|
||||||
|
pos uint32
|
||||||
|
ksize uint32
|
||||||
|
pgid pgid
|
||||||
|
}
|
||||||
|
|
||||||
|
// key returns a byte slice of the node key.
|
||||||
|
func (n *branchPageElement) key() []byte {
|
||||||
|
buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
|
||||||
|
return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos]))[:n.ksize]
|
||||||
|
}
|
||||||
|
|
||||||
|
// leafPageElement represents a node on a leaf page.
|
||||||
|
type leafPageElement struct {
|
||||||
|
flags uint32
|
||||||
|
pos uint32
|
||||||
|
ksize uint32
|
||||||
|
vsize uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
// key returns a byte slice of the node key.
|
||||||
|
func (n *leafPageElement) key() []byte {
|
||||||
|
buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
|
||||||
|
return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos]))[:n.ksize:n.ksize]
|
||||||
|
}
|
||||||
|
|
||||||
|
// value returns a byte slice of the node value.
|
||||||
|
func (n *leafPageElement) value() []byte {
|
||||||
|
buf := (*[maxAllocSize]byte)(unsafe.Pointer(n))
|
||||||
|
return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos+n.ksize]))[:n.vsize:n.vsize]
|
||||||
|
}
|
||||||
|
|
||||||
|
// PageInfo represents human readable information about a page.
|
||||||
|
type PageInfo struct {
|
||||||
|
ID int
|
||||||
|
Type string
|
||||||
|
Count int
|
||||||
|
OverflowCount int
|
||||||
|
}
|
||||||
|
|
||||||
|
type pgids []pgid
|
||||||
|
|
||||||
|
func (s pgids) Len() int { return len(s) }
|
||||||
|
func (s pgids) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||||
|
func (s pgids) Less(i, j int) bool { return s[i] < s[j] }
|
||||||
|
|
||||||
|
// merge returns the sorted union of a and b.
|
||||||
|
func (a pgids) merge(b pgids) pgids {
|
||||||
|
// Return the opposite slice if one is nil.
|
||||||
|
if len(a) == 0 {
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
if len(b) == 0 {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
merged := make(pgids, len(a)+len(b))
|
||||||
|
mergepgids(merged, a, b)
|
||||||
|
return merged
|
||||||
|
}
|
||||||
|
|
||||||
|
// mergepgids copies the sorted union of a and b into dst.
|
||||||
|
// If dst is too small, it panics.
|
||||||
|
func mergepgids(dst, a, b pgids) {
|
||||||
|
if len(dst) < len(a)+len(b) {
|
||||||
|
panic(fmt.Errorf("mergepgids bad len %d < %d + %d", len(dst), len(a), len(b)))
|
||||||
|
}
|
||||||
|
// Copy in the opposite slice if one is nil.
|
||||||
|
if len(a) == 0 {
|
||||||
|
copy(dst, b)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if len(b) == 0 {
|
||||||
|
copy(dst, a)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merged will hold all elements from both lists.
|
||||||
|
merged := dst[:0]
|
||||||
|
|
||||||
|
// Assign lead to the slice with a lower starting value, follow to the higher value.
|
||||||
|
lead, follow := a, b
|
||||||
|
if b[0] < a[0] {
|
||||||
|
lead, follow = b, a
|
||||||
|
}
|
||||||
|
|
||||||
|
// Continue while there are elements in the lead.
|
||||||
|
for len(lead) > 0 {
|
||||||
|
// Merge largest prefix of lead that is ahead of follow[0].
|
||||||
|
n := sort.Search(len(lead), func(i int) bool { return lead[i] > follow[0] })
|
||||||
|
merged = append(merged, lead[:n]...)
|
||||||
|
if n >= len(lead) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
// Swap lead and follow.
|
||||||
|
lead, follow = follow, lead[n:]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Append what's left in follow.
|
||||||
|
_ = append(merged, follow...)
|
||||||
|
}
|
684
vendor/github.com/boltdb/bolt/tx.go
generated
vendored
Normal file
684
vendor/github.com/boltdb/bolt/tx.go
generated
vendored
Normal file
@ -0,0 +1,684 @@
|
|||||||
|
package bolt
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
// txid represents the internal transaction identifier.
|
||||||
|
type txid uint64
|
||||||
|
|
||||||
|
// Tx represents a read-only or read/write transaction on the database.
|
||||||
|
// Read-only transactions can be used for retrieving values for keys and creating cursors.
|
||||||
|
// Read/write transactions can create and remove buckets and create and remove keys.
|
||||||
|
//
|
||||||
|
// IMPORTANT: You must commit or rollback transactions when you are done with
|
||||||
|
// them. Pages can not be reclaimed by the writer until no more transactions
|
||||||
|
// are using them. A long running read transaction can cause the database to
|
||||||
|
// quickly grow.
|
||||||
|
type Tx struct {
|
||||||
|
writable bool
|
||||||
|
managed bool
|
||||||
|
db *DB
|
||||||
|
meta *meta
|
||||||
|
root Bucket
|
||||||
|
pages map[pgid]*page
|
||||||
|
stats TxStats
|
||||||
|
commitHandlers []func()
|
||||||
|
|
||||||
|
// WriteFlag specifies the flag for write-related methods like WriteTo().
|
||||||
|
// Tx opens the database file with the specified flag to copy the data.
|
||||||
|
//
|
||||||
|
// By default, the flag is unset, which works well for mostly in-memory
|
||||||
|
// workloads. For databases that are much larger than available RAM,
|
||||||
|
// set the flag to syscall.O_DIRECT to avoid trashing the page cache.
|
||||||
|
WriteFlag int
|
||||||
|
}
|
||||||
|
|
||||||
|
// init initializes the transaction.
|
||||||
|
func (tx *Tx) init(db *DB) {
|
||||||
|
tx.db = db
|
||||||
|
tx.pages = nil
|
||||||
|
|
||||||
|
// Copy the meta page since it can be changed by the writer.
|
||||||
|
tx.meta = &meta{}
|
||||||
|
db.meta().copy(tx.meta)
|
||||||
|
|
||||||
|
// Copy over the root bucket.
|
||||||
|
tx.root = newBucket(tx)
|
||||||
|
tx.root.bucket = &bucket{}
|
||||||
|
*tx.root.bucket = tx.meta.root
|
||||||
|
|
||||||
|
// Increment the transaction id and add a page cache for writable transactions.
|
||||||
|
if tx.writable {
|
||||||
|
tx.pages = make(map[pgid]*page)
|
||||||
|
tx.meta.txid += txid(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ID returns the transaction id.
|
||||||
|
func (tx *Tx) ID() int {
|
||||||
|
return int(tx.meta.txid)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DB returns a reference to the database that created the transaction.
|
||||||
|
func (tx *Tx) DB() *DB {
|
||||||
|
return tx.db
|
||||||
|
}
|
||||||
|
|
||||||
|
// Size returns current database size in bytes as seen by this transaction.
|
||||||
|
func (tx *Tx) Size() int64 {
|
||||||
|
return int64(tx.meta.pgid) * int64(tx.db.pageSize)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Writable returns whether the transaction can perform write operations.
|
||||||
|
func (tx *Tx) Writable() bool {
|
||||||
|
return tx.writable
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cursor creates a cursor associated with the root bucket.
|
||||||
|
// All items in the cursor will return a nil value because all root bucket keys point to buckets.
|
||||||
|
// The cursor is only valid as long as the transaction is open.
|
||||||
|
// Do not use a cursor after the transaction is closed.
|
||||||
|
func (tx *Tx) Cursor() *Cursor {
|
||||||
|
return tx.root.Cursor()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stats retrieves a copy of the current transaction statistics.
|
||||||
|
func (tx *Tx) Stats() TxStats {
|
||||||
|
return tx.stats
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bucket retrieves a bucket by name.
|
||||||
|
// Returns nil if the bucket does not exist.
|
||||||
|
// The bucket instance is only valid for the lifetime of the transaction.
|
||||||
|
func (tx *Tx) Bucket(name []byte) *Bucket {
|
||||||
|
return tx.root.Bucket(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateBucket creates a new bucket.
|
||||||
|
// Returns an error if the bucket already exists, if the bucket name is blank, or if the bucket name is too long.
|
||||||
|
// The bucket instance is only valid for the lifetime of the transaction.
|
||||||
|
func (tx *Tx) CreateBucket(name []byte) (*Bucket, error) {
|
||||||
|
return tx.root.CreateBucket(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateBucketIfNotExists creates a new bucket if it doesn't already exist.
|
||||||
|
// Returns an error if the bucket name is blank, or if the bucket name is too long.
|
||||||
|
// The bucket instance is only valid for the lifetime of the transaction.
|
||||||
|
func (tx *Tx) CreateBucketIfNotExists(name []byte) (*Bucket, error) {
|
||||||
|
return tx.root.CreateBucketIfNotExists(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteBucket deletes a bucket.
|
||||||
|
// Returns an error if the bucket cannot be found or if the key represents a non-bucket value.
|
||||||
|
func (tx *Tx) DeleteBucket(name []byte) error {
|
||||||
|
return tx.root.DeleteBucket(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ForEach executes a function for each bucket in the root.
|
||||||
|
// If the provided function returns an error then the iteration is stopped and
|
||||||
|
// the error is returned to the caller.
|
||||||
|
func (tx *Tx) ForEach(fn func(name []byte, b *Bucket) error) error {
|
||||||
|
return tx.root.ForEach(func(k, v []byte) error {
|
||||||
|
if err := fn(k, tx.root.Bucket(k)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// OnCommit adds a handler function to be executed after the transaction successfully commits.
|
||||||
|
func (tx *Tx) OnCommit(fn func()) {
|
||||||
|
tx.commitHandlers = append(tx.commitHandlers, fn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Commit writes all changes to disk and updates the meta page.
|
||||||
|
// Returns an error if a disk write error occurs, or if Commit is
|
||||||
|
// called on a read-only transaction.
|
||||||
|
func (tx *Tx) Commit() error {
|
||||||
|
_assert(!tx.managed, "managed tx commit not allowed")
|
||||||
|
if tx.db == nil {
|
||||||
|
return ErrTxClosed
|
||||||
|
} else if !tx.writable {
|
||||||
|
return ErrTxNotWritable
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO(benbjohnson): Use vectorized I/O to write out dirty pages.
|
||||||
|
|
||||||
|
// Rebalance nodes which have had deletions.
|
||||||
|
var startTime = time.Now()
|
||||||
|
tx.root.rebalance()
|
||||||
|
if tx.stats.Rebalance > 0 {
|
||||||
|
tx.stats.RebalanceTime += time.Since(startTime)
|
||||||
|
}
|
||||||
|
|
||||||
|
// spill data onto dirty pages.
|
||||||
|
startTime = time.Now()
|
||||||
|
if err := tx.root.spill(); err != nil {
|
||||||
|
tx.rollback()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tx.stats.SpillTime += time.Since(startTime)
|
||||||
|
|
||||||
|
// Free the old root bucket.
|
||||||
|
tx.meta.root.root = tx.root.root
|
||||||
|
|
||||||
|
opgid := tx.meta.pgid
|
||||||
|
|
||||||
|
// Free the freelist and allocate new pages for it. This will overestimate
|
||||||
|
// the size of the freelist but not underestimate the size (which would be bad).
|
||||||
|
tx.db.freelist.free(tx.meta.txid, tx.db.page(tx.meta.freelist))
|
||||||
|
p, err := tx.allocate((tx.db.freelist.size() / tx.db.pageSize) + 1)
|
||||||
|
if err != nil {
|
||||||
|
tx.rollback()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.db.freelist.write(p); err != nil {
|
||||||
|
tx.rollback()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tx.meta.freelist = p.id
|
||||||
|
|
||||||
|
// If the high water mark has moved up then attempt to grow the database.
|
||||||
|
if tx.meta.pgid > opgid {
|
||||||
|
if err := tx.db.grow(int(tx.meta.pgid+1) * tx.db.pageSize); err != nil {
|
||||||
|
tx.rollback()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write dirty pages to disk.
|
||||||
|
startTime = time.Now()
|
||||||
|
if err := tx.write(); err != nil {
|
||||||
|
tx.rollback()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// If strict mode is enabled then perform a consistency check.
|
||||||
|
// Only the first consistency error is reported in the panic.
|
||||||
|
if tx.db.StrictMode {
|
||||||
|
ch := tx.Check()
|
||||||
|
var errs []string
|
||||||
|
for {
|
||||||
|
err, ok := <-ch
|
||||||
|
if !ok {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
errs = append(errs, err.Error())
|
||||||
|
}
|
||||||
|
if len(errs) > 0 {
|
||||||
|
panic("check fail: " + strings.Join(errs, "\n"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write meta to disk.
|
||||||
|
if err := tx.writeMeta(); err != nil {
|
||||||
|
tx.rollback()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
tx.stats.WriteTime += time.Since(startTime)
|
||||||
|
|
||||||
|
// Finalize the transaction.
|
||||||
|
tx.close()
|
||||||
|
|
||||||
|
// Execute commit handlers now that the locks have been removed.
|
||||||
|
for _, fn := range tx.commitHandlers {
|
||||||
|
fn()
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rollback closes the transaction and ignores all previous updates. Read-only
|
||||||
|
// transactions must be rolled back and not committed.
|
||||||
|
func (tx *Tx) Rollback() error {
|
||||||
|
_assert(!tx.managed, "managed tx rollback not allowed")
|
||||||
|
if tx.db == nil {
|
||||||
|
return ErrTxClosed
|
||||||
|
}
|
||||||
|
tx.rollback()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tx *Tx) rollback() {
|
||||||
|
if tx.db == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if tx.writable {
|
||||||
|
tx.db.freelist.rollback(tx.meta.txid)
|
||||||
|
tx.db.freelist.reload(tx.db.page(tx.db.meta().freelist))
|
||||||
|
}
|
||||||
|
tx.close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tx *Tx) close() {
|
||||||
|
if tx.db == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if tx.writable {
|
||||||
|
// Grab freelist stats.
|
||||||
|
var freelistFreeN = tx.db.freelist.free_count()
|
||||||
|
var freelistPendingN = tx.db.freelist.pending_count()
|
||||||
|
var freelistAlloc = tx.db.freelist.size()
|
||||||
|
|
||||||
|
// Remove transaction ref & writer lock.
|
||||||
|
tx.db.rwtx = nil
|
||||||
|
tx.db.rwlock.Unlock()
|
||||||
|
|
||||||
|
// Merge statistics.
|
||||||
|
tx.db.statlock.Lock()
|
||||||
|
tx.db.stats.FreePageN = freelistFreeN
|
||||||
|
tx.db.stats.PendingPageN = freelistPendingN
|
||||||
|
tx.db.stats.FreeAlloc = (freelistFreeN + freelistPendingN) * tx.db.pageSize
|
||||||
|
tx.db.stats.FreelistInuse = freelistAlloc
|
||||||
|
tx.db.stats.TxStats.add(&tx.stats)
|
||||||
|
tx.db.statlock.Unlock()
|
||||||
|
} else {
|
||||||
|
tx.db.removeTx(tx)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear all references.
|
||||||
|
tx.db = nil
|
||||||
|
tx.meta = nil
|
||||||
|
tx.root = Bucket{tx: tx}
|
||||||
|
tx.pages = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copy writes the entire database to a writer.
|
||||||
|
// This function exists for backwards compatibility. Use WriteTo() instead.
|
||||||
|
func (tx *Tx) Copy(w io.Writer) error {
|
||||||
|
_, err := tx.WriteTo(w)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteTo writes the entire database to a writer.
|
||||||
|
// If err == nil then exactly tx.Size() bytes will be written into the writer.
|
||||||
|
func (tx *Tx) WriteTo(w io.Writer) (n int64, err error) {
|
||||||
|
// Attempt to open reader with WriteFlag
|
||||||
|
f, err := os.OpenFile(tx.db.path, os.O_RDONLY|tx.WriteFlag, 0)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer func() { _ = f.Close() }()
|
||||||
|
|
||||||
|
// Generate a meta page. We use the same page data for both meta pages.
|
||||||
|
buf := make([]byte, tx.db.pageSize)
|
||||||
|
page := (*page)(unsafe.Pointer(&buf[0]))
|
||||||
|
page.flags = metaPageFlag
|
||||||
|
*page.meta() = *tx.meta
|
||||||
|
|
||||||
|
// Write meta 0.
|
||||||
|
page.id = 0
|
||||||
|
page.meta().checksum = page.meta().sum64()
|
||||||
|
nn, err := w.Write(buf)
|
||||||
|
n += int64(nn)
|
||||||
|
if err != nil {
|
||||||
|
return n, fmt.Errorf("meta 0 copy: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write meta 1 with a lower transaction id.
|
||||||
|
page.id = 1
|
||||||
|
page.meta().txid -= 1
|
||||||
|
page.meta().checksum = page.meta().sum64()
|
||||||
|
nn, err = w.Write(buf)
|
||||||
|
n += int64(nn)
|
||||||
|
if err != nil {
|
||||||
|
return n, fmt.Errorf("meta 1 copy: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move past the meta pages in the file.
|
||||||
|
if _, err := f.Seek(int64(tx.db.pageSize*2), os.SEEK_SET); err != nil {
|
||||||
|
return n, fmt.Errorf("seek: %s", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Copy data pages.
|
||||||
|
wn, err := io.CopyN(w, f, tx.Size()-int64(tx.db.pageSize*2))
|
||||||
|
n += wn
|
||||||
|
if err != nil {
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return n, f.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// CopyFile copies the entire database to file at the given path.
|
||||||
|
// A reader transaction is maintained during the copy so it is safe to continue
|
||||||
|
// using the database while a copy is in progress.
|
||||||
|
func (tx *Tx) CopyFile(path string, mode os.FileMode) error {
|
||||||
|
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
err = tx.Copy(f)
|
||||||
|
if err != nil {
|
||||||
|
_ = f.Close()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return f.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check performs several consistency checks on the database for this transaction.
|
||||||
|
// An error is returned if any inconsistency is found.
|
||||||
|
//
|
||||||
|
// It can be safely run concurrently on a writable transaction. However, this
|
||||||
|
// incurs a high cost for large databases and databases with a lot of subbuckets
|
||||||
|
// because of caching. This overhead can be removed if running on a read-only
|
||||||
|
// transaction, however, it is not safe to execute other writer transactions at
|
||||||
|
// the same time.
|
||||||
|
func (tx *Tx) Check() <-chan error {
|
||||||
|
ch := make(chan error)
|
||||||
|
go tx.check(ch)
|
||||||
|
return ch
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tx *Tx) check(ch chan error) {
|
||||||
|
// Check if any pages are double freed.
|
||||||
|
freed := make(map[pgid]bool)
|
||||||
|
all := make([]pgid, tx.db.freelist.count())
|
||||||
|
tx.db.freelist.copyall(all)
|
||||||
|
for _, id := range all {
|
||||||
|
if freed[id] {
|
||||||
|
ch <- fmt.Errorf("page %d: already freed", id)
|
||||||
|
}
|
||||||
|
freed[id] = true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Track every reachable page.
|
||||||
|
reachable := make(map[pgid]*page)
|
||||||
|
reachable[0] = tx.page(0) // meta0
|
||||||
|
reachable[1] = tx.page(1) // meta1
|
||||||
|
for i := uint32(0); i <= tx.page(tx.meta.freelist).overflow; i++ {
|
||||||
|
reachable[tx.meta.freelist+pgid(i)] = tx.page(tx.meta.freelist)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recursively check buckets.
|
||||||
|
tx.checkBucket(&tx.root, reachable, freed, ch)
|
||||||
|
|
||||||
|
// Ensure all pages below high water mark are either reachable or freed.
|
||||||
|
for i := pgid(0); i < tx.meta.pgid; i++ {
|
||||||
|
_, isReachable := reachable[i]
|
||||||
|
if !isReachable && !freed[i] {
|
||||||
|
ch <- fmt.Errorf("page %d: unreachable unfreed", int(i))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close the channel to signal completion.
|
||||||
|
close(ch)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (tx *Tx) checkBucket(b *Bucket, reachable map[pgid]*page, freed map[pgid]bool, ch chan error) {
|
||||||
|
// Ignore inline buckets.
|
||||||
|
if b.root == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check every page used by this bucket.
|
||||||
|
b.tx.forEachPage(b.root, 0, func(p *page, _ int) {
|
||||||
|
if p.id > tx.meta.pgid {
|
||||||
|
ch <- fmt.Errorf("page %d: out of bounds: %d", int(p.id), int(b.tx.meta.pgid))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure each page is only referenced once.
|
||||||
|
for i := pgid(0); i <= pgid(p.overflow); i++ {
|
||||||
|
var id = p.id + i
|
||||||
|
if _, ok := reachable[id]; ok {
|
||||||
|
ch <- fmt.Errorf("page %d: multiple references", int(id))
|
||||||
|
}
|
||||||
|
reachable[id] = p
|
||||||
|
}
|
||||||
|
|
||||||
|
// We should only encounter un-freed leaf and branch pages.
|
||||||
|
if freed[p.id] {
|
||||||
|
ch <- fmt.Errorf("page %d: reachable freed", int(p.id))
|
||||||
|
} else if (p.flags&branchPageFlag) == 0 && (p.flags&leafPageFlag) == 0 {
|
||||||
|
ch <- fmt.Errorf("page %d: invalid type: %s", int(p.id), p.typ())
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// Check each bucket within this bucket.
|
||||||
|
_ = b.ForEach(func(k, v []byte) error {
|
||||||
|
if child := b.Bucket(k); child != nil {
|
||||||
|
tx.checkBucket(child, reachable, freed, ch)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// allocate returns a contiguous block of memory starting at a given page.
|
||||||
|
func (tx *Tx) allocate(count int) (*page, error) {
|
||||||
|
p, err := tx.db.allocate(count)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Save to our page cache.
|
||||||
|
tx.pages[p.id] = p
|
||||||
|
|
||||||
|
// Update statistics.
|
||||||
|
tx.stats.PageCount++
|
||||||
|
tx.stats.PageAlloc += count * tx.db.pageSize
|
||||||
|
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// write writes any dirty pages to disk.
|
||||||
|
func (tx *Tx) write() error {
|
||||||
|
// Sort pages by id.
|
||||||
|
pages := make(pages, 0, len(tx.pages))
|
||||||
|
for _, p := range tx.pages {
|
||||||
|
pages = append(pages, p)
|
||||||
|
}
|
||||||
|
// Clear out page cache early.
|
||||||
|
tx.pages = make(map[pgid]*page)
|
||||||
|
sort.Sort(pages)
|
||||||
|
|
||||||
|
// Write pages to disk in order.
|
||||||
|
for _, p := range pages {
|
||||||
|
size := (int(p.overflow) + 1) * tx.db.pageSize
|
||||||
|
offset := int64(p.id) * int64(tx.db.pageSize)
|
||||||
|
|
||||||
|
// Write out page in "max allocation" sized chunks.
|
||||||
|
ptr := (*[maxAllocSize]byte)(unsafe.Pointer(p))
|
||||||
|
for {
|
||||||
|
// Limit our write to our max allocation size.
|
||||||
|
sz := size
|
||||||
|
if sz > maxAllocSize-1 {
|
||||||
|
sz = maxAllocSize - 1
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write chunk to disk.
|
||||||
|
buf := ptr[:sz]
|
||||||
|
if _, err := tx.db.ops.writeAt(buf, offset); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update statistics.
|
||||||
|
tx.stats.Write++
|
||||||
|
|
||||||
|
// Exit inner for loop if we've written all the chunks.
|
||||||
|
size -= sz
|
||||||
|
if size == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise move offset forward and move pointer to next chunk.
|
||||||
|
offset += int64(sz)
|
||||||
|
ptr = (*[maxAllocSize]byte)(unsafe.Pointer(&ptr[sz]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ignore file sync if flag is set on DB.
|
||||||
|
if !tx.db.NoSync || IgnoreNoSync {
|
||||||
|
if err := fdatasync(tx.db); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Put small pages back to page pool.
|
||||||
|
for _, p := range pages {
|
||||||
|
// Ignore page sizes over 1 page.
|
||||||
|
// These are allocated using make() instead of the page pool.
|
||||||
|
if int(p.overflow) != 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:tx.db.pageSize]
|
||||||
|
|
||||||
|
// See https://go.googlesource.com/go/+/f03c9202c43e0abb130669852082117ca50aa9b1
|
||||||
|
for i := range buf {
|
||||||
|
buf[i] = 0
|
||||||
|
}
|
||||||
|
tx.db.pagePool.Put(buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeMeta writes the meta to the disk.
|
||||||
|
func (tx *Tx) writeMeta() error {
|
||||||
|
// Create a temporary buffer for the meta page.
|
||||||
|
buf := make([]byte, tx.db.pageSize)
|
||||||
|
p := tx.db.pageInBuffer(buf, 0)
|
||||||
|
tx.meta.write(p)
|
||||||
|
|
||||||
|
// Write the meta page to file.
|
||||||
|
if _, err := tx.db.ops.writeAt(buf, int64(p.id)*int64(tx.db.pageSize)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !tx.db.NoSync || IgnoreNoSync {
|
||||||
|
if err := fdatasync(tx.db); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Update statistics.
|
||||||
|
tx.stats.Write++
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// page returns a reference to the page with a given id.
|
||||||
|
// If page has been written to then a temporary buffered page is returned.
|
||||||
|
func (tx *Tx) page(id pgid) *page {
|
||||||
|
// Check the dirty pages first.
|
||||||
|
if tx.pages != nil {
|
||||||
|
if p, ok := tx.pages[id]; ok {
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Otherwise return directly from the mmap.
|
||||||
|
return tx.db.page(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// forEachPage iterates over every page within a given page and executes a function.
|
||||||
|
func (tx *Tx) forEachPage(pgid pgid, depth int, fn func(*page, int)) {
|
||||||
|
p := tx.page(pgid)
|
||||||
|
|
||||||
|
// Execute function.
|
||||||
|
fn(p, depth)
|
||||||
|
|
||||||
|
// Recursively loop over children.
|
||||||
|
if (p.flags & branchPageFlag) != 0 {
|
||||||
|
for i := 0; i < int(p.count); i++ {
|
||||||
|
elem := p.branchPageElement(uint16(i))
|
||||||
|
tx.forEachPage(elem.pgid, depth+1, fn)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Page returns page information for a given page number.
|
||||||
|
// This is only safe for concurrent use when used by a writable transaction.
|
||||||
|
func (tx *Tx) Page(id int) (*PageInfo, error) {
|
||||||
|
if tx.db == nil {
|
||||||
|
return nil, ErrTxClosed
|
||||||
|
} else if pgid(id) >= tx.meta.pgid {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build the page info.
|
||||||
|
p := tx.db.page(pgid(id))
|
||||||
|
info := &PageInfo{
|
||||||
|
ID: id,
|
||||||
|
Count: int(p.count),
|
||||||
|
OverflowCount: int(p.overflow),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine the type (or if it's free).
|
||||||
|
if tx.db.freelist.freed(pgid(id)) {
|
||||||
|
info.Type = "free"
|
||||||
|
} else {
|
||||||
|
info.Type = p.typ()
|
||||||
|
}
|
||||||
|
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TxStats represents statistics about the actions performed by the transaction.
|
||||||
|
type TxStats struct {
|
||||||
|
// Page statistics.
|
||||||
|
PageCount int // number of page allocations
|
||||||
|
PageAlloc int // total bytes allocated
|
||||||
|
|
||||||
|
// Cursor statistics.
|
||||||
|
CursorCount int // number of cursors created
|
||||||
|
|
||||||
|
// Node statistics
|
||||||
|
NodeCount int // number of node allocations
|
||||||
|
NodeDeref int // number of node dereferences
|
||||||
|
|
||||||
|
// Rebalance statistics.
|
||||||
|
Rebalance int // number of node rebalances
|
||||||
|
RebalanceTime time.Duration // total time spent rebalancing
|
||||||
|
|
||||||
|
// Split/Spill statistics.
|
||||||
|
Split int // number of nodes split
|
||||||
|
Spill int // number of nodes spilled
|
||||||
|
SpillTime time.Duration // total time spent spilling
|
||||||
|
|
||||||
|
// Write statistics.
|
||||||
|
Write int // number of writes performed
|
||||||
|
WriteTime time.Duration // total time spent writing to disk
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *TxStats) add(other *TxStats) {
|
||||||
|
s.PageCount += other.PageCount
|
||||||
|
s.PageAlloc += other.PageAlloc
|
||||||
|
s.CursorCount += other.CursorCount
|
||||||
|
s.NodeCount += other.NodeCount
|
||||||
|
s.NodeDeref += other.NodeDeref
|
||||||
|
s.Rebalance += other.Rebalance
|
||||||
|
s.RebalanceTime += other.RebalanceTime
|
||||||
|
s.Split += other.Split
|
||||||
|
s.Spill += other.Spill
|
||||||
|
s.SpillTime += other.SpillTime
|
||||||
|
s.Write += other.Write
|
||||||
|
s.WriteTime += other.WriteTime
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sub calculates and returns the difference between two sets of transaction stats.
|
||||||
|
// This is useful when obtaining stats at two different points and time and
|
||||||
|
// you need the performance counters that occurred within that time span.
|
||||||
|
func (s *TxStats) Sub(other *TxStats) TxStats {
|
||||||
|
var diff TxStats
|
||||||
|
diff.PageCount = s.PageCount - other.PageCount
|
||||||
|
diff.PageAlloc = s.PageAlloc - other.PageAlloc
|
||||||
|
diff.CursorCount = s.CursorCount - other.CursorCount
|
||||||
|
diff.NodeCount = s.NodeCount - other.NodeCount
|
||||||
|
diff.NodeDeref = s.NodeDeref - other.NodeDeref
|
||||||
|
diff.Rebalance = s.Rebalance - other.Rebalance
|
||||||
|
diff.RebalanceTime = s.RebalanceTime - other.RebalanceTime
|
||||||
|
diff.Split = s.Split - other.Split
|
||||||
|
diff.Spill = s.Spill - other.Spill
|
||||||
|
diff.SpillTime = s.SpillTime - other.SpillTime
|
||||||
|
diff.Write = s.Write - other.Write
|
||||||
|
diff.WriteTime = s.WriteTime - other.WriteTime
|
||||||
|
return diff
|
||||||
|
}
|
125
vendor/github.com/containerd/containerd/archive/compression/compression.go
generated
vendored
Normal file
125
vendor/github.com/containerd/containerd/archive/compression/compression.go
generated
vendored
Normal file
@ -0,0 +1,125 @@
|
|||||||
|
package compression
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"bytes"
|
||||||
|
"compress/gzip"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
type (
|
||||||
|
// Compression is the state represents if compressed or not.
|
||||||
|
Compression int
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
// Uncompressed represents the uncompressed.
|
||||||
|
Uncompressed Compression = iota
|
||||||
|
// Gzip is gzip compression algorithm.
|
||||||
|
Gzip
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
bufioReader32KPool = &sync.Pool{
|
||||||
|
New: func() interface{} { return bufio.NewReaderSize(nil, 32*1024) },
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
type readCloserWrapper struct {
|
||||||
|
io.Reader
|
||||||
|
closer func() error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *readCloserWrapper) Close() error {
|
||||||
|
if r.closer != nil {
|
||||||
|
return r.closer()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type writeCloserWrapper struct {
|
||||||
|
io.Writer
|
||||||
|
closer func() error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *writeCloserWrapper) Close() error {
|
||||||
|
if w.closer != nil {
|
||||||
|
w.closer()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// DetectCompression detects the compression algorithm of the source.
|
||||||
|
func DetectCompression(source []byte) Compression {
|
||||||
|
for compression, m := range map[Compression][]byte{
|
||||||
|
Gzip: {0x1F, 0x8B, 0x08},
|
||||||
|
} {
|
||||||
|
if len(source) < len(m) {
|
||||||
|
// Len too short
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if bytes.Equal(m, source[:len(m)]) {
|
||||||
|
return compression
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Uncompressed
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecompressStream decompresses the archive and returns a ReaderCloser with the decompressed archive.
|
||||||
|
func DecompressStream(archive io.Reader) (io.ReadCloser, error) {
|
||||||
|
buf := bufioReader32KPool.Get().(*bufio.Reader)
|
||||||
|
buf.Reset(archive)
|
||||||
|
bs, err := buf.Peek(10)
|
||||||
|
if err != nil && err != io.EOF {
|
||||||
|
// Note: we'll ignore any io.EOF error because there are some odd
|
||||||
|
// cases where the layer.tar file will be empty (zero bytes) and
|
||||||
|
// that results in an io.EOF from the Peek() call. So, in those
|
||||||
|
// cases we'll just treat it as a non-compressed stream and
|
||||||
|
// that means just create an empty layer.
|
||||||
|
// See Issue docker/docker#18170
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
closer := func() error {
|
||||||
|
buf.Reset(nil)
|
||||||
|
bufioReader32KPool.Put(buf)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
switch compression := DetectCompression(bs); compression {
|
||||||
|
case Uncompressed:
|
||||||
|
readBufWrapper := &readCloserWrapper{buf, closer}
|
||||||
|
return readBufWrapper, nil
|
||||||
|
case Gzip:
|
||||||
|
gzReader, err := gzip.NewReader(buf)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
readBufWrapper := &readCloserWrapper{gzReader, closer}
|
||||||
|
return readBufWrapper, nil
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupported compression format %s", (&compression).Extension())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// CompressStream compresseses the dest with specified compression algorithm.
|
||||||
|
func CompressStream(dest io.Writer, compression Compression) (io.WriteCloser, error) {
|
||||||
|
switch compression {
|
||||||
|
case Uncompressed:
|
||||||
|
return &writeCloserWrapper{dest, nil}, nil
|
||||||
|
case Gzip:
|
||||||
|
return gzip.NewWriter(dest), nil
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupported compression format %s", (&compression).Extension())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extension returns the extension of a file that uses the specified compression algorithm.
|
||||||
|
func (compression *Compression) Extension() string {
|
||||||
|
switch *compression {
|
||||||
|
case Gzip:
|
||||||
|
return "gz"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
490
vendor/github.com/containerd/containerd/archive/tar.go
generated
vendored
Normal file
490
vendor/github.com/containerd/containerd/archive/tar.go
generated
vendored
Normal file
@ -0,0 +1,490 @@
|
|||||||
|
package archive
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/tar"
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/ioutil"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/containerd/containerd/fs"
|
||||||
|
"github.com/containerd/containerd/log"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
bufferPool = &sync.Pool{
|
||||||
|
New: func() interface{} {
|
||||||
|
return make([]byte, 32*1024)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
breakoutError = errors.New("file name outside of root")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Diff returns a tar stream of the computed filesystem
|
||||||
|
// difference between the provided directories.
|
||||||
|
//
|
||||||
|
// Produces a tar using OCI style file markers for deletions. Deleted
|
||||||
|
// files will be prepended with the prefix ".wh.". This style is
|
||||||
|
// based off AUFS whiteouts.
|
||||||
|
// See https://github.com/opencontainers/image-spec/blob/master/layer.md
|
||||||
|
func Diff(ctx context.Context, a, b string) io.ReadCloser {
|
||||||
|
r, w := io.Pipe()
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
var err error
|
||||||
|
cw := newChangeWriter(w, b)
|
||||||
|
if err = fs.Changes(ctx, a, b, cw.HandleChange); err != nil {
|
||||||
|
err = errors.Wrap(err, "failed to create diff tar stream")
|
||||||
|
} else {
|
||||||
|
err = cw.Close()
|
||||||
|
}
|
||||||
|
if err = w.CloseWithError(err); err != nil {
|
||||||
|
log.G(ctx).WithError(err).Debugf("closing tar pipe failed")
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
const (
|
||||||
|
// whiteoutPrefix prefix means file is a whiteout. If this is followed by a
|
||||||
|
// filename this means that file has been removed from the base layer.
|
||||||
|
// See https://github.com/opencontainers/image-spec/blob/master/layer.md#whiteouts
|
||||||
|
whiteoutPrefix = ".wh."
|
||||||
|
|
||||||
|
// whiteoutMetaPrefix prefix means whiteout has a special meaning and is not
|
||||||
|
// for removing an actual file. Normally these files are excluded from exported
|
||||||
|
// archives.
|
||||||
|
whiteoutMetaPrefix = whiteoutPrefix + whiteoutPrefix
|
||||||
|
|
||||||
|
// whiteoutLinkDir is a directory AUFS uses for storing hardlink links to other
|
||||||
|
// layers. Normally these should not go into exported archives and all changed
|
||||||
|
// hardlinks should be copied to the top layer.
|
||||||
|
whiteoutLinkDir = whiteoutMetaPrefix + "plnk"
|
||||||
|
|
||||||
|
// whiteoutOpaqueDir file means directory has been made opaque - meaning
|
||||||
|
// readdir calls to this directory do not follow to lower layers.
|
||||||
|
whiteoutOpaqueDir = whiteoutMetaPrefix + ".opq"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Apply applies a tar stream of an OCI style diff tar.
|
||||||
|
// See https://github.com/opencontainers/image-spec/blob/master/layer.md#applying-changesets
|
||||||
|
func Apply(ctx context.Context, root string, r io.Reader) (int64, error) {
|
||||||
|
root = filepath.Clean(root)
|
||||||
|
fn := prepareApply()
|
||||||
|
defer fn()
|
||||||
|
|
||||||
|
var (
|
||||||
|
tr = tar.NewReader(r)
|
||||||
|
size int64
|
||||||
|
dirs []*tar.Header
|
||||||
|
|
||||||
|
// Used for handling opaque directory markers which
|
||||||
|
// may occur out of order
|
||||||
|
unpackedPaths = make(map[string]struct{})
|
||||||
|
|
||||||
|
// Used for aufs plink directory
|
||||||
|
aufsTempdir = ""
|
||||||
|
aufsHardlinks = make(map[string]*tar.Header)
|
||||||
|
)
|
||||||
|
|
||||||
|
// Iterate through the files in the archive.
|
||||||
|
for {
|
||||||
|
hdr, err := tr.Next()
|
||||||
|
if err == io.EOF {
|
||||||
|
// end of tar archive
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
size += hdr.Size
|
||||||
|
|
||||||
|
// Normalize name, for safety and for a simple is-root check
|
||||||
|
hdr.Name = filepath.Clean(hdr.Name)
|
||||||
|
|
||||||
|
if skipFile(hdr) {
|
||||||
|
log.G(ctx).Warnf("file %q ignored: archive may not be supported on system", hdr.Name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Note as these operations are platform specific, so must the slash be.
|
||||||
|
if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) {
|
||||||
|
// Not the root directory, ensure that the parent directory exists.
|
||||||
|
// This happened in some tests where an image had a tarfile without any
|
||||||
|
// parent directories.
|
||||||
|
parent := filepath.Dir(hdr.Name)
|
||||||
|
parentPath := filepath.Join(root, parent)
|
||||||
|
|
||||||
|
if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) {
|
||||||
|
err = mkdirAll(parentPath, 0600)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip AUFS metadata dirs
|
||||||
|
if strings.HasPrefix(hdr.Name, whiteoutMetaPrefix) {
|
||||||
|
// Regular files inside /.wh..wh.plnk can be used as hardlink targets
|
||||||
|
// We don't want this directory, but we need the files in them so that
|
||||||
|
// such hardlinks can be resolved.
|
||||||
|
if strings.HasPrefix(hdr.Name, whiteoutLinkDir) && hdr.Typeflag == tar.TypeReg {
|
||||||
|
basename := filepath.Base(hdr.Name)
|
||||||
|
aufsHardlinks[basename] = hdr
|
||||||
|
if aufsTempdir == "" {
|
||||||
|
if aufsTempdir, err = ioutil.TempDir("", "dockerplnk"); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer os.RemoveAll(aufsTempdir)
|
||||||
|
}
|
||||||
|
if err := createTarFile(ctx, filepath.Join(aufsTempdir, basename), root, hdr, tr); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if hdr.Name != whiteoutOpaqueDir {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
path := filepath.Join(root, hdr.Name)
|
||||||
|
rel, err := filepath.Rel(root, path)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Note as these operations are platform specific, so must the slash be.
|
||||||
|
if strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
|
||||||
|
return 0, errors.Wrapf(breakoutError, "%q is outside of %q", hdr.Name, root)
|
||||||
|
}
|
||||||
|
base := filepath.Base(path)
|
||||||
|
|
||||||
|
if strings.HasPrefix(base, whiteoutPrefix) {
|
||||||
|
dir := filepath.Dir(path)
|
||||||
|
if base == whiteoutOpaqueDir {
|
||||||
|
_, err := os.Lstat(dir)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
err = nil // parent was deleted
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if path == dir {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if _, exists := unpackedPaths[path]; !exists {
|
||||||
|
err := os.RemoveAll(path)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
originalBase := base[len(whiteoutPrefix):]
|
||||||
|
originalPath := filepath.Join(dir, originalBase)
|
||||||
|
if err := os.RemoveAll(originalPath); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// If path exits we almost always just want to remove and replace it.
|
||||||
|
// The only exception is when it is a directory *and* the file from
|
||||||
|
// the layer is also a directory. Then we want to merge them (i.e.
|
||||||
|
// just apply the metadata from the layer).
|
||||||
|
if fi, err := os.Lstat(path); err == nil {
|
||||||
|
if !(fi.IsDir() && hdr.Typeflag == tar.TypeDir) {
|
||||||
|
if err := os.RemoveAll(path); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
srcData := io.Reader(tr)
|
||||||
|
srcHdr := hdr
|
||||||
|
|
||||||
|
// Hard links into /.wh..wh.plnk don't work, as we don't extract that directory, so
|
||||||
|
// we manually retarget these into the temporary files we extracted them into
|
||||||
|
if hdr.Typeflag == tar.TypeLink && strings.HasPrefix(filepath.Clean(hdr.Linkname), whiteoutLinkDir) {
|
||||||
|
linkBasename := filepath.Base(hdr.Linkname)
|
||||||
|
srcHdr = aufsHardlinks[linkBasename]
|
||||||
|
if srcHdr == nil {
|
||||||
|
return 0, fmt.Errorf("Invalid aufs hardlink")
|
||||||
|
}
|
||||||
|
tmpFile, err := os.Open(filepath.Join(aufsTempdir, linkBasename))
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer tmpFile.Close()
|
||||||
|
srcData = tmpFile
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := createTarFile(ctx, path, root, srcHdr, srcData); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Directory mtimes must be handled at the end to avoid further
|
||||||
|
// file creation in them to modify the directory mtime
|
||||||
|
if hdr.Typeflag == tar.TypeDir {
|
||||||
|
dirs = append(dirs, hdr)
|
||||||
|
}
|
||||||
|
unpackedPaths[path] = struct{}{}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, hdr := range dirs {
|
||||||
|
path := filepath.Join(root, hdr.Name)
|
||||||
|
if err := chtimes(path, boundTime(latestTime(hdr.AccessTime, hdr.ModTime)), boundTime(hdr.ModTime)); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return size, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type changeWriter struct {
|
||||||
|
tw *tar.Writer
|
||||||
|
source string
|
||||||
|
whiteoutT time.Time
|
||||||
|
inodeCache map[uint64]string
|
||||||
|
}
|
||||||
|
|
||||||
|
func newChangeWriter(w io.Writer, source string) *changeWriter {
|
||||||
|
return &changeWriter{
|
||||||
|
tw: tar.NewWriter(w),
|
||||||
|
source: source,
|
||||||
|
whiteoutT: time.Now(),
|
||||||
|
inodeCache: map[uint64]string{},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cw *changeWriter) HandleChange(k fs.ChangeKind, p string, f os.FileInfo, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if k == fs.ChangeKindDelete {
|
||||||
|
whiteOutDir := filepath.Dir(p)
|
||||||
|
whiteOutBase := filepath.Base(p)
|
||||||
|
whiteOut := filepath.Join(whiteOutDir, whiteoutPrefix+whiteOutBase)
|
||||||
|
hdr := &tar.Header{
|
||||||
|
Name: whiteOut[1:],
|
||||||
|
Size: 0,
|
||||||
|
ModTime: cw.whiteoutT,
|
||||||
|
AccessTime: cw.whiteoutT,
|
||||||
|
ChangeTime: cw.whiteoutT,
|
||||||
|
}
|
||||||
|
if err := cw.tw.WriteHeader(hdr); err != nil {
|
||||||
|
errors.Wrap(err, "failed to write whiteout header")
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
var (
|
||||||
|
link string
|
||||||
|
err error
|
||||||
|
source = filepath.Join(cw.source, p)
|
||||||
|
)
|
||||||
|
|
||||||
|
if f.Mode()&os.ModeSymlink != 0 {
|
||||||
|
if link, err = os.Readlink(source); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
hdr, err := tar.FileInfoHeader(f, link)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
hdr.Mode = int64(chmodTarEntry(os.FileMode(hdr.Mode)))
|
||||||
|
|
||||||
|
name := p
|
||||||
|
if strings.HasPrefix(name, string(filepath.Separator)) {
|
||||||
|
name, err = filepath.Rel(string(filepath.Separator), name)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "failed to make path relative")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
name, err = tarName(name)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "cannot canonicalize path")
|
||||||
|
}
|
||||||
|
// suffix with '/' for directories
|
||||||
|
if f.IsDir() && !strings.HasSuffix(name, "/") {
|
||||||
|
name += "/"
|
||||||
|
}
|
||||||
|
hdr.Name = name
|
||||||
|
|
||||||
|
if err := setHeaderForSpecialDevice(hdr, name, f); err != nil {
|
||||||
|
return errors.Wrap(err, "failed to set device headers")
|
||||||
|
}
|
||||||
|
|
||||||
|
linkname, err := fs.GetLinkSource(name, f, cw.inodeCache)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "failed to get hardlink")
|
||||||
|
}
|
||||||
|
|
||||||
|
if linkname != "" {
|
||||||
|
hdr.Typeflag = tar.TypeLink
|
||||||
|
hdr.Linkname = linkname
|
||||||
|
hdr.Size = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
if capability, err := getxattr(source, "security.capability"); err != nil {
|
||||||
|
return errors.Wrap(err, "failed to get capabilities xattr")
|
||||||
|
} else if capability != nil {
|
||||||
|
hdr.Xattrs = map[string]string{
|
||||||
|
"security.capability": string(capability),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := cw.tw.WriteHeader(hdr); err != nil {
|
||||||
|
return errors.Wrap(err, "failed to write file header")
|
||||||
|
}
|
||||||
|
|
||||||
|
if hdr.Typeflag == tar.TypeReg && hdr.Size > 0 {
|
||||||
|
file, err := open(source)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to open path: %v", source)
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
buf := bufferPool.Get().([]byte)
|
||||||
|
n, err := io.CopyBuffer(cw.tw, file, buf)
|
||||||
|
bufferPool.Put(buf)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "failed to copy")
|
||||||
|
}
|
||||||
|
if n != hdr.Size {
|
||||||
|
return errors.New("short write copying file")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cw *changeWriter) Close() error {
|
||||||
|
if err := cw.tw.Close(); err != nil {
|
||||||
|
return errors.Wrap(err, "failed to close tar writer")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func createTarFile(ctx context.Context, path, extractDir string, hdr *tar.Header, reader io.Reader) error {
|
||||||
|
// hdr.Mode is in linux format, which we can use for syscalls,
|
||||||
|
// but for os.Foo() calls we need the mode converted to os.FileMode,
|
||||||
|
// so use hdrInfo.Mode() (they differ for e.g. setuid bits)
|
||||||
|
hdrInfo := hdr.FileInfo()
|
||||||
|
|
||||||
|
switch hdr.Typeflag {
|
||||||
|
case tar.TypeDir:
|
||||||
|
// Create directory unless it exists as a directory already.
|
||||||
|
// In that case we just want to merge the two
|
||||||
|
if fi, err := os.Lstat(path); !(err == nil && fi.IsDir()) {
|
||||||
|
if err := os.Mkdir(path, hdrInfo.Mode()); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case tar.TypeReg, tar.TypeRegA:
|
||||||
|
file, err := openFile(path, os.O_CREATE|os.O_WRONLY, hdrInfo.Mode())
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
buf := bufferPool.Get().([]byte)
|
||||||
|
_, err = io.CopyBuffer(file, reader, buf)
|
||||||
|
if err1 := file.Close(); err == nil {
|
||||||
|
err = err1
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
case tar.TypeBlock, tar.TypeChar:
|
||||||
|
// Handle this is an OS-specific way
|
||||||
|
if err := handleTarTypeBlockCharFifo(hdr, path); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
case tar.TypeFifo:
|
||||||
|
// Handle this is an OS-specific way
|
||||||
|
if err := handleTarTypeBlockCharFifo(hdr, path); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
case tar.TypeLink:
|
||||||
|
targetPath := filepath.Join(extractDir, hdr.Linkname)
|
||||||
|
// check for hardlink breakout
|
||||||
|
if !strings.HasPrefix(targetPath, extractDir) {
|
||||||
|
return errors.Wrapf(breakoutError, "invalid hardlink %q -> %q", targetPath, hdr.Linkname)
|
||||||
|
}
|
||||||
|
if err := os.Link(targetPath, path); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
case tar.TypeSymlink:
|
||||||
|
// path -> hdr.Linkname = targetPath
|
||||||
|
// e.g. /extractDir/path/to/symlink -> ../2/file = /extractDir/path/2/file
|
||||||
|
targetPath := filepath.Join(filepath.Dir(path), hdr.Linkname)
|
||||||
|
|
||||||
|
// the reason we don't need to check symlinks in the path (with FollowSymlinkInScope) is because
|
||||||
|
// that symlink would first have to be created, which would be caught earlier, at this very check:
|
||||||
|
if !strings.HasPrefix(targetPath, extractDir) {
|
||||||
|
return errors.Wrapf(breakoutError, "invalid symlink %q -> %q", path, hdr.Linkname)
|
||||||
|
}
|
||||||
|
if err := os.Symlink(hdr.Linkname, path); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
case tar.TypeXGlobalHeader:
|
||||||
|
log.G(ctx).Debug("PAX Global Extended Headers found and ignored")
|
||||||
|
return nil
|
||||||
|
|
||||||
|
default:
|
||||||
|
return errors.Errorf("unhandled tar header type %d\n", hdr.Typeflag)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lchown is not supported on Windows.
|
||||||
|
if runtime.GOOS != "windows" {
|
||||||
|
if err := os.Lchown(path, hdr.Uid, hdr.Gid); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for key, value := range hdr.Xattrs {
|
||||||
|
if err := setxattr(path, key, value); err != nil {
|
||||||
|
if errors.Cause(err) == syscall.ENOTSUP {
|
||||||
|
log.G(ctx).WithError(err).Warnf("ignored xattr %s in archive", key)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// There is no LChmod, so ignore mode for symlink. Also, this
|
||||||
|
// must happen after chown, as that can modify the file mode
|
||||||
|
if err := handleLChmod(hdr, path, hdrInfo); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := chtimes(path, boundTime(latestTime(hdr.AccessTime, hdr.ModTime)), boundTime(hdr.ModTime)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
131
vendor/github.com/containerd/containerd/archive/tar_linux.go
generated
vendored
Normal file
131
vendor/github.com/containerd/containerd/archive/tar_linux.go
generated
vendored
Normal file
@ -0,0 +1,131 @@
|
|||||||
|
package archive
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/tar"
|
||||||
|
"os"
|
||||||
|
"sync"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"github.com/opencontainers/runc/libcontainer/system"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/stevvooe/continuity/sysx"
|
||||||
|
)
|
||||||
|
|
||||||
|
func tarName(p string) (string, error) {
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func chmodTarEntry(perm os.FileMode) os.FileMode {
|
||||||
|
return perm
|
||||||
|
}
|
||||||
|
|
||||||
|
func setHeaderForSpecialDevice(hdr *tar.Header, name string, fi os.FileInfo) error {
|
||||||
|
s, ok := fi.Sys().(*syscall.Stat_t)
|
||||||
|
if !ok {
|
||||||
|
return errors.New("unsupported stat type")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Currently go does not fill in the major/minors
|
||||||
|
if s.Mode&syscall.S_IFBLK != 0 ||
|
||||||
|
s.Mode&syscall.S_IFCHR != 0 {
|
||||||
|
hdr.Devmajor = int64(major(uint64(s.Rdev)))
|
||||||
|
hdr.Devminor = int64(minor(uint64(s.Rdev)))
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func major(device uint64) uint64 {
|
||||||
|
return (device >> 8) & 0xfff
|
||||||
|
}
|
||||||
|
|
||||||
|
func minor(device uint64) uint64 {
|
||||||
|
return (device & 0xff) | ((device >> 12) & 0xfff00)
|
||||||
|
}
|
||||||
|
|
||||||
|
func mkdev(major int64, minor int64) uint32 {
|
||||||
|
return uint32(((minor & 0xfff00) << 12) | ((major & 0xfff) << 8) | (minor & 0xff))
|
||||||
|
}
|
||||||
|
|
||||||
|
func open(p string) (*os.File, error) {
|
||||||
|
return os.Open(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func openFile(name string, flag int, perm os.FileMode) (*os.File, error) {
|
||||||
|
return os.OpenFile(name, flag, perm)
|
||||||
|
}
|
||||||
|
|
||||||
|
func mkdirAll(path string, perm os.FileMode) error {
|
||||||
|
return os.MkdirAll(path, perm)
|
||||||
|
}
|
||||||
|
|
||||||
|
func prepareApply() func() {
|
||||||
|
// Unset unmask before doing an apply operation,
|
||||||
|
// restore unmask when complete
|
||||||
|
oldmask := syscall.Umask(0)
|
||||||
|
return func() {
|
||||||
|
syscall.Umask(oldmask)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func skipFile(*tar.Header) bool {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
inUserNS bool
|
||||||
|
nsOnce sync.Once
|
||||||
|
)
|
||||||
|
|
||||||
|
func setInUserNS() {
|
||||||
|
inUserNS = system.RunningInUserNS()
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleTarTypeBlockCharFifo is an OS-specific helper function used by
|
||||||
|
// createTarFile to handle the following types of header: Block; Char; Fifo
|
||||||
|
func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error {
|
||||||
|
nsOnce.Do(setInUserNS)
|
||||||
|
if inUserNS {
|
||||||
|
// cannot create a device if running in user namespace
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
mode := uint32(hdr.Mode & 07777)
|
||||||
|
switch hdr.Typeflag {
|
||||||
|
case tar.TypeBlock:
|
||||||
|
mode |= syscall.S_IFBLK
|
||||||
|
case tar.TypeChar:
|
||||||
|
mode |= syscall.S_IFCHR
|
||||||
|
case tar.TypeFifo:
|
||||||
|
mode |= syscall.S_IFIFO
|
||||||
|
}
|
||||||
|
|
||||||
|
return syscall.Mknod(path, mode, int(mkdev(hdr.Devmajor, hdr.Devminor)))
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error {
|
||||||
|
if hdr.Typeflag == tar.TypeLink {
|
||||||
|
if fi, err := os.Lstat(hdr.Linkname); err == nil && (fi.Mode()&os.ModeSymlink == 0) {
|
||||||
|
if err := os.Chmod(path, hdrInfo.Mode()); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if hdr.Typeflag != tar.TypeSymlink {
|
||||||
|
if err := os.Chmod(path, hdrInfo.Mode()); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getxattr(path, attr string) ([]byte, error) {
|
||||||
|
b, err := sysx.LGetxattr(path, attr)
|
||||||
|
if err == syscall.ENOTSUP || err == syscall.ENODATA {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return b, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func setxattr(path, key, value string) error {
|
||||||
|
return sysx.LSetxattr(path, key, []byte(value), 0)
|
||||||
|
}
|
104
vendor/github.com/containerd/containerd/archive/tar_windows.go
generated
vendored
Normal file
104
vendor/github.com/containerd/containerd/archive/tar_windows.go
generated
vendored
Normal file
@ -0,0 +1,104 @@
|
|||||||
|
package archive
|
||||||
|
|
||||||
|
import (
|
||||||
|
"archive/tar"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/containerd/containerd/sys"
|
||||||
|
)
|
||||||
|
|
||||||
|
// tarName returns platform-specific filepath
|
||||||
|
// to canonical posix-style path for tar archival. p is relative
|
||||||
|
// path.
|
||||||
|
func tarName(p string) (string, error) {
|
||||||
|
// windows: convert windows style relative path with backslashes
|
||||||
|
// into forward slashes. Since windows does not allow '/' or '\'
|
||||||
|
// in file names, it is mostly safe to replace however we must
|
||||||
|
// check just in case
|
||||||
|
if strings.Contains(p, "/") {
|
||||||
|
return "", fmt.Errorf("Windows path contains forward slash: %s", p)
|
||||||
|
}
|
||||||
|
|
||||||
|
return strings.Replace(p, string(os.PathSeparator), "/", -1), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// chmodTarEntry is used to adjust the file permissions used in tar header based
|
||||||
|
// on the platform the archival is done.
|
||||||
|
func chmodTarEntry(perm os.FileMode) os.FileMode {
|
||||||
|
perm &= 0755
|
||||||
|
// Add the x bit: make everything +x from windows
|
||||||
|
perm |= 0111
|
||||||
|
|
||||||
|
return perm
|
||||||
|
}
|
||||||
|
|
||||||
|
func setHeaderForSpecialDevice(*tar.Header, string, os.FileInfo) error {
|
||||||
|
// do nothing. no notion of Rdev, Inode, Nlink in stat on Windows
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func open(p string) (*os.File, error) {
|
||||||
|
// We use sys.OpenSequential to ensure we use sequential file
|
||||||
|
// access on Windows to avoid depleting the standby list.
|
||||||
|
return sys.OpenSequential(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
func openFile(name string, flag int, perm os.FileMode) (*os.File, error) {
|
||||||
|
// Source is regular file. We use sys.OpenFileSequential to use sequential
|
||||||
|
// file access to avoid depleting the standby list on Windows.
|
||||||
|
return sys.OpenFileSequential(name, flag, perm)
|
||||||
|
}
|
||||||
|
|
||||||
|
func mkdirAll(path string, perm os.FileMode) error {
|
||||||
|
return sys.MkdirAll(path, perm)
|
||||||
|
}
|
||||||
|
|
||||||
|
func prepareApply() func() {
|
||||||
|
// No umask or filesystem changes needed before apply
|
||||||
|
return func() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
func skipFile(hdr *tar.Header) bool {
|
||||||
|
// Windows does not support filenames with colons in them. Ignore
|
||||||
|
// these files. This is not a problem though (although it might
|
||||||
|
// appear that it is). Let's suppose a client is running docker pull.
|
||||||
|
// The daemon it points to is Windows. Would it make sense for the
|
||||||
|
// client to be doing a docker pull Ubuntu for example (which has files
|
||||||
|
// with colons in the name under /usr/share/man/man3)? No, absolutely
|
||||||
|
// not as it would really only make sense that they were pulling a
|
||||||
|
// Windows image. However, for development, it is necessary to be able
|
||||||
|
// to pull Linux images which are in the repository.
|
||||||
|
//
|
||||||
|
// TODO Windows. Once the registry is aware of what images are Windows-
|
||||||
|
// specific or Linux-specific, this warning should be changed to an error
|
||||||
|
// to cater for the situation where someone does manage to upload a Linux
|
||||||
|
// image but have it tagged as Windows inadvertently.
|
||||||
|
if strings.Contains(hdr.Name, ":") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// handleTarTypeBlockCharFifo is an OS-specific helper function used by
|
||||||
|
// createTarFile to handle the following types of header: Block; Char; Fifo
|
||||||
|
func handleTarTypeBlockCharFifo(hdr *tar.Header, path string) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleLChmod(hdr *tar.Header, path string, hdrInfo os.FileInfo) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getxattr(path, attr string) ([]byte, error) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func setxattr(path, key, value string) error {
|
||||||
|
// Return not support error, do not wrap underlying not supported
|
||||||
|
// since xattrs should not exist in windows diff archives
|
||||||
|
return errors.New("xattrs not supported on Windows")
|
||||||
|
}
|
38
vendor/github.com/containerd/containerd/archive/time.go
generated
vendored
Normal file
38
vendor/github.com/containerd/containerd/archive/time.go
generated
vendored
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
package archive
|
||||||
|
|
||||||
|
import (
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
minTime = time.Unix(0, 0)
|
||||||
|
maxTime time.Time
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
if unsafe.Sizeof(syscall.Timespec{}.Nsec) == 8 {
|
||||||
|
// This is a 64 bit timespec
|
||||||
|
// os.Chtimes limits time to the following
|
||||||
|
maxTime = time.Unix(0, 1<<63-1)
|
||||||
|
} else {
|
||||||
|
// This is a 32 bit timespec
|
||||||
|
maxTime = time.Unix(1<<31-1, 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func boundTime(t time.Time) time.Time {
|
||||||
|
if t.Before(minTime) || t.After(maxTime) {
|
||||||
|
return minTime
|
||||||
|
}
|
||||||
|
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
|
||||||
|
func latestTime(t1, t2 time.Time) time.Time {
|
||||||
|
if t1.Before(t2) {
|
||||||
|
return t2
|
||||||
|
}
|
||||||
|
return t1
|
||||||
|
}
|
21
vendor/github.com/containerd/containerd/archive/time_linux.go
generated
vendored
Normal file
21
vendor/github.com/containerd/containerd/archive/time_linux.go
generated
vendored
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
package archive
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
func chtimes(path string, atime, mtime time.Time) error {
|
||||||
|
var utimes [2]unix.Timespec
|
||||||
|
utimes[0] = unix.NsecToTimespec(atime.UnixNano())
|
||||||
|
utimes[1] = unix.NsecToTimespec(mtime.UnixNano())
|
||||||
|
|
||||||
|
if err := unix.UtimesNanoAt(unix.AT_FDCWD, path, utimes[0:], unix.AT_SYMLINK_NOFOLLOW); err != nil {
|
||||||
|
return errors.Wrap(err, "failed call to UtimesNanoAt")
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
25
vendor/github.com/containerd/containerd/archive/time_windows.go
generated
vendored
Normal file
25
vendor/github.com/containerd/containerd/archive/time_windows.go
generated
vendored
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
package archive
|
||||||
|
|
||||||
|
import (
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// chtimes will set the create time on a file using the given modtime.
|
||||||
|
// This requires calling SetFileTime and explicitly including the create time.
|
||||||
|
func chtimes(path string, atime, mtime time.Time) error {
|
||||||
|
ctimespec := syscall.NsecToTimespec(mtime.UnixNano())
|
||||||
|
pathp, e := syscall.UTF16PtrFromString(path)
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
h, e := syscall.CreateFile(pathp,
|
||||||
|
syscall.FILE_WRITE_ATTRIBUTES, syscall.FILE_SHARE_WRITE, nil,
|
||||||
|
syscall.OPEN_EXISTING, syscall.FILE_FLAG_BACKUP_SEMANTICS, 0)
|
||||||
|
if e != nil {
|
||||||
|
return e
|
||||||
|
}
|
||||||
|
defer syscall.Close(h)
|
||||||
|
c := syscall.NsecToFiletime(syscall.TimespecToNsec(ctimespec))
|
||||||
|
return syscall.SetFileTime(h, &c, nil, nil)
|
||||||
|
}
|
67
vendor/github.com/containerd/containerd/content/content.go
generated
vendored
Normal file
67
vendor/github.com/containerd/containerd/content/content.go
generated
vendored
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
package content
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/opencontainers/go-digest"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// ErrNotFound is returned when an item is not found.
|
||||||
|
//
|
||||||
|
// Use IsNotFound(err) to detect this condition.
|
||||||
|
ErrNotFound = errors.New("content: not found")
|
||||||
|
|
||||||
|
// ErrExists is returned when something exists when it may not be expected.
|
||||||
|
//
|
||||||
|
// Use IsExists(err) to detect this condition.
|
||||||
|
ErrExists = errors.New("content: exists")
|
||||||
|
|
||||||
|
bufPool = sync.Pool{
|
||||||
|
New: func() interface{} {
|
||||||
|
return make([]byte, 1<<20)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
type Info struct {
|
||||||
|
Digest digest.Digest
|
||||||
|
Size int64
|
||||||
|
CommittedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type Provider interface {
|
||||||
|
Reader(ctx context.Context, dgst digest.Digest) (io.ReadCloser, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type Status struct {
|
||||||
|
Ref string
|
||||||
|
Offset int64
|
||||||
|
Total int64
|
||||||
|
StartedAt time.Time
|
||||||
|
UpdatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
type Writer interface {
|
||||||
|
io.WriteCloser
|
||||||
|
Status() (Status, error)
|
||||||
|
Digest() digest.Digest
|
||||||
|
Commit(size int64, expected digest.Digest) error
|
||||||
|
Truncate(size int64) error
|
||||||
|
}
|
||||||
|
|
||||||
|
type Ingester interface {
|
||||||
|
Writer(ctx context.Context, ref string, size int64, expected digest.Digest) (Writer, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsNotFound(err error) bool {
|
||||||
|
return errors.Cause(err) == ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsExists(err error) bool {
|
||||||
|
return errors.Cause(err) == ErrExists
|
||||||
|
}
|
116
vendor/github.com/containerd/containerd/content/helpers.go
generated
vendored
Normal file
116
vendor/github.com/containerd/containerd/content/helpers.go
generated
vendored
Normal file
@ -0,0 +1,116 @@
|
|||||||
|
package content
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/ioutil"
|
||||||
|
|
||||||
|
"github.com/opencontainers/go-digest"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ReadBlob retrieves the entire contents of the blob from the provider.
|
||||||
|
//
|
||||||
|
// Avoid using this for large blobs, such as layers.
|
||||||
|
func ReadBlob(ctx context.Context, provider Provider, dgst digest.Digest) ([]byte, error) {
|
||||||
|
rc, err := provider.Reader(ctx, dgst)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rc.Close()
|
||||||
|
|
||||||
|
return ioutil.ReadAll(rc)
|
||||||
|
}
|
||||||
|
|
||||||
|
// WriteBlob writes data with the expected digest into the content store. If
|
||||||
|
// expected already exists, the method returns immediately and the reader will
|
||||||
|
// not be consumed.
|
||||||
|
//
|
||||||
|
// This is useful when the digest and size are known beforehand.
|
||||||
|
//
|
||||||
|
// Copy is buffered, so no need to wrap reader in buffered io.
|
||||||
|
func WriteBlob(ctx context.Context, cs Ingester, ref string, r io.Reader, size int64, expected digest.Digest) error {
|
||||||
|
cw, err := cs.Writer(ctx, ref, size, expected)
|
||||||
|
if err != nil {
|
||||||
|
if !IsExists(err) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil // all ready present
|
||||||
|
}
|
||||||
|
defer cw.Close()
|
||||||
|
|
||||||
|
ws, err := cw.Status()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if ws.Offset > 0 {
|
||||||
|
r, err = seekReader(r, ws.Offset, size)
|
||||||
|
if err != nil {
|
||||||
|
if !isUnseekable(err) {
|
||||||
|
return errors.Wrapf(err, "unabled to resume write to %v", ref)
|
||||||
|
}
|
||||||
|
|
||||||
|
// reader is unseekable, try to move the writer back to the start.
|
||||||
|
if err := cw.Truncate(0); err != nil {
|
||||||
|
return errors.Wrapf(err, "content writer truncate failed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := bufPool.Get().([]byte)
|
||||||
|
defer bufPool.Put(buf)
|
||||||
|
|
||||||
|
if _, err := io.CopyBuffer(cw, r, buf); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := cw.Commit(size, expected); err != nil {
|
||||||
|
if !IsExists(err) {
|
||||||
|
return errors.Wrapf(err, "failed commit on ref %q", ref)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
var errUnseekable = errors.New("seek not supported")
|
||||||
|
|
||||||
|
func isUnseekable(err error) bool {
|
||||||
|
return errors.Cause(err) == errUnseekable
|
||||||
|
}
|
||||||
|
|
||||||
|
// seekReader attempts to seek the reader to the given offset, either by
|
||||||
|
// resolving `io.Seeker` or by detecting `io.ReaderAt`.
|
||||||
|
func seekReader(r io.Reader, offset, size int64) (io.Reader, error) {
|
||||||
|
// attempt to resolve r as a seeker and setup the offset.
|
||||||
|
seeker, ok := r.(io.Seeker)
|
||||||
|
if ok {
|
||||||
|
nn, err := seeker.Seek(offset, io.SeekStart)
|
||||||
|
if nn != offset {
|
||||||
|
return nil, fmt.Errorf("failed to seek to offset %v", offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// ok, let's try io.ReaderAt!
|
||||||
|
readerAt, ok := r.(io.ReaderAt)
|
||||||
|
if ok && size > offset {
|
||||||
|
sr := io.NewSectionReader(readerAt, offset, size)
|
||||||
|
return sr, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return r, errors.Wrapf(errUnseekable, "seek to offset %v failed", offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
func readFileString(path string) (string, error) {
|
||||||
|
p, err := ioutil.ReadFile(path)
|
||||||
|
return string(p), err
|
||||||
|
}
|
56
vendor/github.com/containerd/containerd/content/locks.go
generated
vendored
Normal file
56
vendor/github.com/containerd/containerd/content/locks.go
generated
vendored
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
package content
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/nightlyone/lockfile"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
// In addition to providing inter-process locks for content ingest, we also
|
||||||
|
// define a global in process lock to prevent two goroutines writing to the
|
||||||
|
// same file.
|
||||||
|
//
|
||||||
|
// This is pretty unsophisticated for now. In the future, we'd probably like to
|
||||||
|
// have more information about who is holding which locks, as well as better
|
||||||
|
// error reporting.
|
||||||
|
|
||||||
|
var (
|
||||||
|
errLocked = errors.New("key is locked")
|
||||||
|
|
||||||
|
// locks lets us lock in process, as well as output of process.
|
||||||
|
locks = map[lockfile.Lockfile]struct{}{}
|
||||||
|
locksMu sync.Mutex
|
||||||
|
)
|
||||||
|
|
||||||
|
func tryLock(lock lockfile.Lockfile) error {
|
||||||
|
locksMu.Lock()
|
||||||
|
defer locksMu.Unlock()
|
||||||
|
|
||||||
|
if _, ok := locks[lock]; ok {
|
||||||
|
return errLocked
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := lock.TryLock(); err != nil {
|
||||||
|
if errors.Cause(err) == lockfile.ErrBusy {
|
||||||
|
return errLocked
|
||||||
|
}
|
||||||
|
|
||||||
|
return errors.Wrapf(err, "lock.TryLock() encountered an error")
|
||||||
|
}
|
||||||
|
|
||||||
|
locks[lock] = struct{}{}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func unlock(lock lockfile.Lockfile) error {
|
||||||
|
locksMu.Lock()
|
||||||
|
defer locksMu.Unlock()
|
||||||
|
|
||||||
|
if _, ok := locks[lock]; !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
delete(locks, lock)
|
||||||
|
return lock.Unlock()
|
||||||
|
}
|
368
vendor/github.com/containerd/containerd/content/store.go
generated
vendored
Normal file
368
vendor/github.com/containerd/containerd/content/store.go
generated
vendored
Normal file
@ -0,0 +1,368 @@
|
|||||||
|
package content
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/ioutil"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/containerd/containerd/log"
|
||||||
|
"github.com/nightlyone/lockfile"
|
||||||
|
digest "github.com/opencontainers/go-digest"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Store is digest-keyed store for content. All data written into the store is
|
||||||
|
// stored under a verifiable digest.
|
||||||
|
//
|
||||||
|
// Store can generally support multi-reader, single-writer ingest of data,
|
||||||
|
// including resumable ingest.
|
||||||
|
type Store struct {
|
||||||
|
root string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewStore(root string) (*Store, error) {
|
||||||
|
if err := os.MkdirAll(filepath.Join(root, "ingest"), 0777); err != nil && !os.IsExist(err) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Store{
|
||||||
|
root: root,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) Info(dgst digest.Digest) (Info, error) {
|
||||||
|
p := s.blobPath(dgst)
|
||||||
|
fi, err := os.Stat(p)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
err = ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
return Info{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return Info{
|
||||||
|
Digest: dgst,
|
||||||
|
Size: fi.Size(),
|
||||||
|
CommittedAt: fi.ModTime(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Open returns an io.ReadCloser for the blob.
|
||||||
|
//
|
||||||
|
// TODO(stevvooe): This would work much better as an io.ReaderAt in practice.
|
||||||
|
// Right now, we are doing type assertion to tease that out, but it won't scale
|
||||||
|
// well.
|
||||||
|
func (s *Store) Reader(ctx context.Context, dgst digest.Digest) (io.ReadCloser, error) {
|
||||||
|
fp, err := os.Open(s.blobPath(dgst))
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
err = ErrNotFound
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return fp, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete removes a blob by its digest.
|
||||||
|
//
|
||||||
|
// While this is safe to do concurrently, safe exist-removal logic must hold
|
||||||
|
// some global lock on the store.
|
||||||
|
func (cs *Store) Delete(dgst digest.Digest) error {
|
||||||
|
if err := os.RemoveAll(cs.blobPath(dgst)); err != nil {
|
||||||
|
if !os.IsNotExist(err) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return ErrNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO(stevvooe): Allow querying the set of blobs in the blob store.
|
||||||
|
|
||||||
|
// WalkFunc defines the callback for a blob walk.
|
||||||
|
//
|
||||||
|
// TODO(stevvooe): Remove the file info. Just need size and modtime. Perhaps,
|
||||||
|
// not a huge deal, considering we have a path, but let's not just let this one
|
||||||
|
// go without scrutiny.
|
||||||
|
type WalkFunc func(path string, fi os.FileInfo, dgst digest.Digest) error
|
||||||
|
|
||||||
|
func (cs *Store) Walk(fn WalkFunc) error {
|
||||||
|
root := filepath.Join(cs.root, "blobs")
|
||||||
|
var alg digest.Algorithm
|
||||||
|
return filepath.Walk(root, func(path string, fi os.FileInfo, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if !fi.IsDir() && !alg.Available() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO(stevvooe): There are few more cases with subdirs that should be
|
||||||
|
// handled in case the layout gets corrupted. This isn't strict enough
|
||||||
|
// an may spew bad data.
|
||||||
|
|
||||||
|
if path == root {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if filepath.Dir(path) == root {
|
||||||
|
alg = digest.Algorithm(filepath.Base(path))
|
||||||
|
|
||||||
|
if !alg.Available() {
|
||||||
|
alg = ""
|
||||||
|
return filepath.SkipDir
|
||||||
|
}
|
||||||
|
|
||||||
|
// descending into a hash directory
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
dgst := digest.NewDigestFromHex(alg.String(), filepath.Base(path))
|
||||||
|
if err := dgst.Validate(); err != nil {
|
||||||
|
// log error but don't report
|
||||||
|
log.L.WithError(err).WithField("path", path).Error("invalid digest for blob path")
|
||||||
|
// if we see this, it could mean some sort of corruption of the
|
||||||
|
// store or extra paths not expected previously.
|
||||||
|
}
|
||||||
|
|
||||||
|
return fn(path, fi, dgst)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Status returns the current status of a blob by the ingest ref.
|
||||||
|
func (s *Store) Status(ref string) (Status, error) {
|
||||||
|
return s.status(s.ingestRoot(ref))
|
||||||
|
}
|
||||||
|
|
||||||
|
// status works like stat above except uses the path to the ingest.
|
||||||
|
func (s *Store) status(ingestPath string) (Status, error) {
|
||||||
|
dp := filepath.Join(ingestPath, "data")
|
||||||
|
fi, err := os.Stat(dp)
|
||||||
|
if err != nil {
|
||||||
|
return Status{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
ref, err := readFileString(filepath.Join(ingestPath, "ref"))
|
||||||
|
if err != nil {
|
||||||
|
return Status{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return Status{
|
||||||
|
Ref: ref,
|
||||||
|
Offset: fi.Size(),
|
||||||
|
Total: s.total(ingestPath),
|
||||||
|
UpdatedAt: fi.ModTime(),
|
||||||
|
StartedAt: getStartTime(fi),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// total attempts to resolve the total expected size for the write.
|
||||||
|
func (s *Store) total(ingestPath string) int64 {
|
||||||
|
totalS, err := readFileString(filepath.Join(ingestPath, "total"))
|
||||||
|
if err != nil {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
total, err := strconv.ParseInt(totalS, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
// represents a corrupted file, should probably remove.
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
|
||||||
|
return total
|
||||||
|
}
|
||||||
|
|
||||||
|
// Writer begins or resumes the active writer identified by ref. If the writer
|
||||||
|
// is already in use, an error is returned. Only one writer may be in use per
|
||||||
|
// ref at a time.
|
||||||
|
//
|
||||||
|
// The argument `ref` is used to uniquely identify a long-lived writer transaction.
|
||||||
|
func (s *Store) Writer(ctx context.Context, ref string, total int64, expected digest.Digest) (Writer, error) {
|
||||||
|
path, refp, data, lock, err := s.ingestPaths(ref)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tryLock(lock); err != nil {
|
||||||
|
if !os.IsNotExist(errors.Cause(err)) {
|
||||||
|
return nil, errors.Wrapf(err, "locking %v failed", ref)
|
||||||
|
}
|
||||||
|
|
||||||
|
// if it doesn't exist, we'll make it so below!
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
digester = digest.Canonical.Digester()
|
||||||
|
offset int64
|
||||||
|
startedAt time.Time
|
||||||
|
updatedAt time.Time
|
||||||
|
)
|
||||||
|
|
||||||
|
// ensure that the ingest path has been created.
|
||||||
|
if err := os.Mkdir(path, 0755); err != nil {
|
||||||
|
if !os.IsExist(err) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
status, err := s.status(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "failed reading status of resume write")
|
||||||
|
}
|
||||||
|
|
||||||
|
if ref != status.Ref {
|
||||||
|
// NOTE(stevvooe): This is fairly catastrophic. Either we have some
|
||||||
|
// layout corruption or a hash collision for the ref key.
|
||||||
|
return nil, errors.Wrapf(err, "ref key does not match: %v != %v", ref, status.Ref)
|
||||||
|
}
|
||||||
|
|
||||||
|
if total > 0 && status.Total > 0 && total != status.Total {
|
||||||
|
return nil, errors.Errorf("provided total differs from status: %v != %v", total, status.Total)
|
||||||
|
}
|
||||||
|
|
||||||
|
// slow slow slow!!, send to goroutine or use resumable hashes
|
||||||
|
fp, err := os.Open(data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer fp.Close()
|
||||||
|
|
||||||
|
p := bufPool.Get().([]byte)
|
||||||
|
defer bufPool.Put(p)
|
||||||
|
|
||||||
|
offset, err = io.CopyBuffer(digester.Hash(), fp, p)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
updatedAt = status.UpdatedAt
|
||||||
|
startedAt = status.StartedAt
|
||||||
|
total = status.Total
|
||||||
|
} else {
|
||||||
|
// the ingest is new, we need to setup the target location.
|
||||||
|
// write the ref to a file for later use
|
||||||
|
if err := ioutil.WriteFile(refp, []byte(ref), 0666); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if total > 0 {
|
||||||
|
if err := ioutil.WriteFile(filepath.Join(path, "total"), []byte(fmt.Sprint(total)), 0666); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
startedAt = time.Now()
|
||||||
|
updatedAt = startedAt
|
||||||
|
}
|
||||||
|
|
||||||
|
fp, err := os.OpenFile(data, os.O_WRONLY|os.O_CREATE, 0666)
|
||||||
|
if err != nil {
|
||||||
|
return nil, errors.Wrap(err, "failed to open data file")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &writer{
|
||||||
|
s: s,
|
||||||
|
fp: fp,
|
||||||
|
lock: lock,
|
||||||
|
ref: ref,
|
||||||
|
path: path,
|
||||||
|
offset: offset,
|
||||||
|
total: total,
|
||||||
|
digester: digester,
|
||||||
|
startedAt: startedAt,
|
||||||
|
updatedAt: updatedAt,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Abort an active transaction keyed by ref. If the ingest is active, it will
|
||||||
|
// be cancelled. Any resources associated with the ingest will be cleaned.
|
||||||
|
func (s *Store) Abort(ref string) error {
|
||||||
|
root := s.ingestRoot(ref)
|
||||||
|
if err := os.RemoveAll(root); err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) Active() ([]Status, error) {
|
||||||
|
fp, err := os.Open(filepath.Join(s.root, "ingest"))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
defer fp.Close()
|
||||||
|
|
||||||
|
fis, err := fp.Readdir(-1)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var active []Status
|
||||||
|
for _, fi := range fis {
|
||||||
|
p := filepath.Join(s.root, "ingest", fi.Name())
|
||||||
|
stat, err := s.status(p)
|
||||||
|
if err != nil {
|
||||||
|
if !os.IsNotExist(err) {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO(stevvooe): This is a common error if uploads are being
|
||||||
|
// completed while making this listing. Need to consider taking a
|
||||||
|
// lock on the whole store to coordinate this aspect.
|
||||||
|
//
|
||||||
|
// Another option is to cleanup downloads asynchronously and
|
||||||
|
// coordinate this method with the cleanup process.
|
||||||
|
//
|
||||||
|
// For now, we just skip them, as they really don't exist.
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
active = append(active, stat)
|
||||||
|
}
|
||||||
|
|
||||||
|
return active, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cs *Store) blobPath(dgst digest.Digest) string {
|
||||||
|
return filepath.Join(cs.root, "blobs", dgst.Algorithm().String(), dgst.Hex())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) ingestRoot(ref string) string {
|
||||||
|
dgst := digest.FromString(ref)
|
||||||
|
return filepath.Join(s.root, "ingest", dgst.Hex())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ingestPaths are returned, including the lockfile. The paths are the following:
|
||||||
|
//
|
||||||
|
// - root: entire ingest directory
|
||||||
|
// - ref: name of the starting ref, must be unique
|
||||||
|
// - data: file where data is written
|
||||||
|
// - lock: lock file location
|
||||||
|
//
|
||||||
|
func (s *Store) ingestPaths(ref string) (string, string, string, lockfile.Lockfile, error) {
|
||||||
|
var (
|
||||||
|
fp = s.ingestRoot(ref)
|
||||||
|
rp = filepath.Join(fp, "ref")
|
||||||
|
lp = filepath.Join(fp, "lock")
|
||||||
|
dp = filepath.Join(fp, "data")
|
||||||
|
)
|
||||||
|
|
||||||
|
lock, err := lockfile.New(lp)
|
||||||
|
if err != nil {
|
||||||
|
return "", "", "", "", errors.Wrapf(err, "error creating lockfile %v", lp)
|
||||||
|
}
|
||||||
|
|
||||||
|
return fp, rp, dp, lock, nil
|
||||||
|
}
|
17
vendor/github.com/containerd/containerd/content/store_unix.go
generated
vendored
Normal file
17
vendor/github.com/containerd/containerd/content/store_unix.go
generated
vendored
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
// +build linux
|
||||||
|
|
||||||
|
package content
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func getStartTime(fi os.FileInfo) time.Time {
|
||||||
|
if st, ok := fi.Sys().(*syscall.Stat_t); ok {
|
||||||
|
return time.Unix(st.Ctim.Sec, st.Ctim.Nsec)
|
||||||
|
}
|
||||||
|
|
||||||
|
return fi.ModTime()
|
||||||
|
}
|
10
vendor/github.com/containerd/containerd/content/store_windows.go
generated
vendored
Normal file
10
vendor/github.com/containerd/containerd/content/store_windows.go
generated
vendored
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
package content
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func getStartTime(fi os.FileInfo) time.Time {
|
||||||
|
return fi.ModTime()
|
||||||
|
}
|
144
vendor/github.com/containerd/containerd/content/writer.go
generated
vendored
Normal file
144
vendor/github.com/containerd/containerd/content/writer.go
generated
vendored
Normal file
@ -0,0 +1,144 @@
|
|||||||
|
package content
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/containerd/containerd/log"
|
||||||
|
"github.com/nightlyone/lockfile"
|
||||||
|
"github.com/opencontainers/go-digest"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
// writer represents a write transaction against the blob store.
|
||||||
|
type writer struct {
|
||||||
|
s *Store
|
||||||
|
fp *os.File // opened data file
|
||||||
|
lock lockfile.Lockfile
|
||||||
|
path string // path to writer dir
|
||||||
|
ref string // ref key
|
||||||
|
offset int64
|
||||||
|
total int64
|
||||||
|
digester digest.Digester
|
||||||
|
startedAt time.Time
|
||||||
|
updatedAt time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *writer) Status() (Status, error) {
|
||||||
|
return Status{
|
||||||
|
Ref: w.ref,
|
||||||
|
Offset: w.offset,
|
||||||
|
Total: w.total,
|
||||||
|
StartedAt: w.startedAt,
|
||||||
|
UpdatedAt: w.updatedAt,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Digest returns the current digest of the content, up to the current write.
|
||||||
|
//
|
||||||
|
// Cannot be called concurrently with `Write`.
|
||||||
|
func (w *writer) Digest() digest.Digest {
|
||||||
|
return w.digester.Digest()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Write p to the transaction.
|
||||||
|
//
|
||||||
|
// Note that writes are unbuffered to the backing file. When writing, it is
|
||||||
|
// recommended to wrap in a bufio.Writer or, preferably, use io.CopyBuffer.
|
||||||
|
func (w *writer) Write(p []byte) (n int, err error) {
|
||||||
|
n, err = w.fp.Write(p)
|
||||||
|
w.digester.Hash().Write(p[:n])
|
||||||
|
w.offset += int64(len(p))
|
||||||
|
w.updatedAt = time.Now()
|
||||||
|
return n, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *writer) Commit(size int64, expected digest.Digest) error {
|
||||||
|
if err := w.fp.Sync(); err != nil {
|
||||||
|
return errors.Wrap(err, "sync failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
fi, err := w.fp.Stat()
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "stat on ingest file failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
// change to readonly, more important for read, but provides _some_
|
||||||
|
// protection from this point on. We use the existing perms with a mask
|
||||||
|
// only allowing reads honoring the umask on creation.
|
||||||
|
//
|
||||||
|
// This removes write and exec, only allowing read per the creation umask.
|
||||||
|
if err := w.fp.Chmod((fi.Mode() & os.ModePerm) &^ 0333); err != nil {
|
||||||
|
return errors.Wrap(err, "failed to change ingest file permissions")
|
||||||
|
}
|
||||||
|
|
||||||
|
if size > 0 && size != fi.Size() {
|
||||||
|
return errors.Errorf("%q failed size validation: %v != %v", w.ref, fi.Size(), size)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := w.fp.Close(); err != nil {
|
||||||
|
return errors.Wrap(err, "failed closing ingest")
|
||||||
|
}
|
||||||
|
|
||||||
|
dgst := w.digester.Digest()
|
||||||
|
if expected != "" && expected != dgst {
|
||||||
|
return errors.Errorf("unexpected digest: %v != %v", dgst, expected)
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
ingest = filepath.Join(w.path, "data")
|
||||||
|
target = w.s.blobPath(dgst)
|
||||||
|
)
|
||||||
|
|
||||||
|
// make sure parent directories of blob exist
|
||||||
|
if err := os.MkdirAll(filepath.Dir(target), 0755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// clean up!!
|
||||||
|
defer os.RemoveAll(w.path)
|
||||||
|
|
||||||
|
if err := os.Rename(ingest, target); err != nil {
|
||||||
|
if os.IsExist(err) {
|
||||||
|
// collision with the target file!
|
||||||
|
return ErrExists
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
unlock(w.lock)
|
||||||
|
w.fp = nil
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close the writer, flushing any unwritten data and leaving the progress in
|
||||||
|
// tact.
|
||||||
|
//
|
||||||
|
// If one needs to resume the transaction, a new writer can be obtained from
|
||||||
|
// `ContentStore.Resume` using the same key. The write can then be continued
|
||||||
|
// from it was left off.
|
||||||
|
//
|
||||||
|
// To abandon a transaction completely, first call close then `Store.Remove` to
|
||||||
|
// clean up the associated resources.
|
||||||
|
func (cw *writer) Close() (err error) {
|
||||||
|
if err := unlock(cw.lock); err != nil {
|
||||||
|
log.L.Debug("unlock failed: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if cw.fp != nil {
|
||||||
|
cw.fp.Sync()
|
||||||
|
return cw.fp.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *writer) Truncate(size int64) error {
|
||||||
|
if size != 0 {
|
||||||
|
return errors.New("Truncate: unsupported size")
|
||||||
|
}
|
||||||
|
w.offset = 0
|
||||||
|
w.digester.Hash().Reset()
|
||||||
|
return w.fp.Truncate(0)
|
||||||
|
}
|
120
vendor/github.com/containerd/containerd/fs/copy.go
generated
vendored
Normal file
120
vendor/github.com/containerd/containerd/fs/copy.go
generated
vendored
Normal file
@ -0,0 +1,120 @@
|
|||||||
|
package fs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io/ioutil"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
bufferPool = &sync.Pool{
|
||||||
|
New: func() interface{} {
|
||||||
|
return make([]byte, 32*1024)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// CopyDir copies the directory from src to dst.
|
||||||
|
// Most efficient copy of files is attempted.
|
||||||
|
func CopyDir(dst, src string) error {
|
||||||
|
inodes := map[uint64]string{}
|
||||||
|
return copyDirectory(dst, src, inodes)
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyDirectory(dst, src string, inodes map[uint64]string) error {
|
||||||
|
stat, err := os.Stat(src)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to stat %s", src)
|
||||||
|
}
|
||||||
|
if !stat.IsDir() {
|
||||||
|
return errors.Errorf("source is not directory")
|
||||||
|
}
|
||||||
|
|
||||||
|
if st, err := os.Stat(dst); err != nil {
|
||||||
|
if err := os.Mkdir(dst, stat.Mode()); err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to mkdir %s", dst)
|
||||||
|
}
|
||||||
|
} else if !st.IsDir() {
|
||||||
|
return errors.Errorf("cannot copy to non-directory: %s", dst)
|
||||||
|
} else {
|
||||||
|
if err := os.Chmod(dst, stat.Mode()); err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to chmod on %s", dst)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fis, err := ioutil.ReadDir(src)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to read %s", src)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := copyFileInfo(stat, dst); err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to copy file info for %s", dst)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, fi := range fis {
|
||||||
|
source := filepath.Join(src, fi.Name())
|
||||||
|
target := filepath.Join(dst, fi.Name())
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case fi.IsDir():
|
||||||
|
if err := copyDirectory(target, source, inodes); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
case (fi.Mode() & os.ModeType) == 0:
|
||||||
|
link, err := GetLinkSource(target, fi, inodes)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "failed to get hardlink")
|
||||||
|
}
|
||||||
|
if link != "" {
|
||||||
|
if err := os.Link(link, target); err != nil {
|
||||||
|
return errors.Wrap(err, "failed to create hard link")
|
||||||
|
}
|
||||||
|
} else if err := copyFile(source, target); err != nil {
|
||||||
|
return errors.Wrap(err, "failed to copy files")
|
||||||
|
}
|
||||||
|
case (fi.Mode() & os.ModeSymlink) == os.ModeSymlink:
|
||||||
|
link, err := os.Readlink(source)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to read link: %s", source)
|
||||||
|
}
|
||||||
|
if err := os.Symlink(link, target); err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to create symlink: %s", target)
|
||||||
|
}
|
||||||
|
case (fi.Mode() & os.ModeDevice) == os.ModeDevice:
|
||||||
|
if err := copyDevice(target, fi); err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to create device")
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
// TODO: Support pipes and sockets
|
||||||
|
return errors.Wrapf(err, "unsupported mode %s", fi.Mode())
|
||||||
|
}
|
||||||
|
if err := copyFileInfo(fi, target); err != nil {
|
||||||
|
return errors.Wrap(err, "failed to copy file info")
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := copyXAttrs(target, source); err != nil {
|
||||||
|
return errors.Wrap(err, "failed to copy xattrs")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyFile(source, target string) error {
|
||||||
|
src, err := os.Open(source)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to open source %s", source)
|
||||||
|
}
|
||||||
|
defer src.Close()
|
||||||
|
tgt, err := os.Create(target)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to open target %s", target)
|
||||||
|
}
|
||||||
|
defer tgt.Close()
|
||||||
|
|
||||||
|
return copyFileContent(tgt, src)
|
||||||
|
}
|
80
vendor/github.com/containerd/containerd/fs/copy_linux.go
generated
vendored
Normal file
80
vendor/github.com/containerd/containerd/fs/copy_linux.go
generated
vendored
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
package fs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/stevvooe/continuity/sysx"
|
||||||
|
)
|
||||||
|
|
||||||
|
func copyFileInfo(fi os.FileInfo, name string) error {
|
||||||
|
st := fi.Sys().(*syscall.Stat_t)
|
||||||
|
if err := os.Lchown(name, int(st.Uid), int(st.Gid)); err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to chown %s", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fi.Mode() & os.ModeSymlink) != os.ModeSymlink {
|
||||||
|
if err := os.Chmod(name, fi.Mode()); err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to chmod %s", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := syscall.UtimesNano(name, []syscall.Timespec{st.Atim, st.Mtim}); err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to utime %s", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyFileContent(dst, src *os.File) error {
|
||||||
|
st, err := src.Stat()
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrap(err, "unable to stat source")
|
||||||
|
}
|
||||||
|
|
||||||
|
n, err := sysx.CopyFileRange(src.Fd(), nil, dst.Fd(), nil, int(st.Size()), 0)
|
||||||
|
if err != nil {
|
||||||
|
if err != syscall.ENOSYS && err != syscall.EXDEV {
|
||||||
|
return errors.Wrap(err, "copy file range failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := bufferPool.Get().([]byte)
|
||||||
|
_, err = io.CopyBuffer(dst, src, buf)
|
||||||
|
bufferPool.Put(buf)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if int64(n) != st.Size() {
|
||||||
|
return errors.Wrapf(err, "short copy: %d of %d", int64(n), st.Size())
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyXAttrs(dst, src string) error {
|
||||||
|
xattrKeys, err := sysx.LListxattr(src)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to list xattrs on %s", src)
|
||||||
|
}
|
||||||
|
for _, xattr := range xattrKeys {
|
||||||
|
data, err := sysx.LGetxattr(src, xattr)
|
||||||
|
if err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to get xattr %q on %s", xattr, src)
|
||||||
|
}
|
||||||
|
if err := sysx.LSetxattr(dst, xattr, data, 0); err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to set xattr %q on %s", xattr, dst)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyDevice(dst string, fi os.FileInfo) error {
|
||||||
|
st, ok := fi.Sys().(*syscall.Stat_t)
|
||||||
|
if !ok {
|
||||||
|
return errors.New("unsupported stat type")
|
||||||
|
}
|
||||||
|
return syscall.Mknod(dst, uint32(fi.Mode()), int(st.Rdev))
|
||||||
|
}
|
33
vendor/github.com/containerd/containerd/fs/copy_windows.go
generated
vendored
Normal file
33
vendor/github.com/containerd/containerd/fs/copy_windows.go
generated
vendored
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
package fs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
func copyFileInfo(fi os.FileInfo, name string) error {
|
||||||
|
if err := os.Chmod(name, fi.Mode()); err != nil {
|
||||||
|
return errors.Wrapf(err, "failed to chmod %s", name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: copy windows specific metadata
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyFileContent(dst, src *os.File) error {
|
||||||
|
buf := bufferPool.Get().([]byte)
|
||||||
|
_, err := io.CopyBuffer(dst, src, buf)
|
||||||
|
bufferPool.Put(buf)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyXAttrs(dst, src string) error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func copyDevice(dst string, fi os.FileInfo) error {
|
||||||
|
return errors.New("device copy not supported")
|
||||||
|
}
|
301
vendor/github.com/containerd/containerd/fs/diff.go
generated
vendored
Normal file
301
vendor/github.com/containerd/containerd/fs/diff.go
generated
vendored
Normal file
@ -0,0 +1,301 @@
|
|||||||
|
package fs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"golang.org/x/sync/errgroup"
|
||||||
|
|
||||||
|
"github.com/Sirupsen/logrus"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ChangeKind is the type of modification that
|
||||||
|
// a change is making.
|
||||||
|
type ChangeKind int
|
||||||
|
|
||||||
|
const (
|
||||||
|
// ChangeKindAdd represents an addition of
|
||||||
|
// a file
|
||||||
|
ChangeKindAdd = iota
|
||||||
|
|
||||||
|
// ChangeKindModify represents a change to
|
||||||
|
// an existing file
|
||||||
|
ChangeKindModify
|
||||||
|
|
||||||
|
// ChangeKindDelete represents a delete of
|
||||||
|
// a file
|
||||||
|
ChangeKindDelete
|
||||||
|
)
|
||||||
|
|
||||||
|
func (k ChangeKind) String() string {
|
||||||
|
switch k {
|
||||||
|
case ChangeKindAdd:
|
||||||
|
return "add"
|
||||||
|
case ChangeKindModify:
|
||||||
|
return "modify"
|
||||||
|
case ChangeKindDelete:
|
||||||
|
return "delete"
|
||||||
|
default:
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Change represents single change between a diff and its parent.
|
||||||
|
type Change struct {
|
||||||
|
Kind ChangeKind
|
||||||
|
Path string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChangeFunc is the type of function called for each change
|
||||||
|
// computed during a directory changes calculation.
|
||||||
|
type ChangeFunc func(ChangeKind, string, os.FileInfo, error) error
|
||||||
|
|
||||||
|
// Changes computes changes between two directories calling the
|
||||||
|
// given change function for each computed change. The first
|
||||||
|
// directory is intended to the base directory and second
|
||||||
|
// directory the changed directory.
|
||||||
|
//
|
||||||
|
// The change callback is called by the order of path names and
|
||||||
|
// should be appliable in that order.
|
||||||
|
// Due to this apply ordering, the following is true
|
||||||
|
// - Removed directory trees only create a single change for the root
|
||||||
|
// directory removed. Remaining changes are implied.
|
||||||
|
// - A directory which is modified to become a file will not have
|
||||||
|
// delete entries for sub-path items, their removal is implied
|
||||||
|
// by the removal of the parent directory.
|
||||||
|
//
|
||||||
|
// Opaque directories will not be treated specially and each file
|
||||||
|
// removed from the base directory will show up as a removal.
|
||||||
|
//
|
||||||
|
// File content comparisons will be done on files which have timestamps
|
||||||
|
// which may have been truncated. If either of the files being compared
|
||||||
|
// has a zero value nanosecond value, each byte will be compared for
|
||||||
|
// differences. If 2 files have the same seconds value but different
|
||||||
|
// nanosecond values where one of those values is zero, the files will
|
||||||
|
// be considered unchanged if the content is the same. This behavior
|
||||||
|
// is to account for timestamp truncation during archiving.
|
||||||
|
func Changes(ctx context.Context, a, b string, changeFn ChangeFunc) error {
|
||||||
|
if a == "" {
|
||||||
|
logrus.Debugf("Using single walk diff for %s", b)
|
||||||
|
return addDirChanges(ctx, changeFn, b)
|
||||||
|
} else if diffOptions := detectDirDiff(b, a); diffOptions != nil {
|
||||||
|
logrus.Debugf("Using single walk diff for %s from %s", diffOptions.diffDir, a)
|
||||||
|
return diffDirChanges(ctx, changeFn, a, diffOptions)
|
||||||
|
}
|
||||||
|
|
||||||
|
logrus.Debugf("Using double walk diff for %s from %s", b, a)
|
||||||
|
return doubleWalkDiff(ctx, changeFn, a, b)
|
||||||
|
}
|
||||||
|
|
||||||
|
func addDirChanges(ctx context.Context, changeFn ChangeFunc, root string) error {
|
||||||
|
return filepath.Walk(root, func(path string, f os.FileInfo, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rebase path
|
||||||
|
path, err = filepath.Rel(root, path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
path = filepath.Join(string(os.PathSeparator), path)
|
||||||
|
|
||||||
|
// Skip root
|
||||||
|
if path == string(os.PathSeparator) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return changeFn(ChangeKindAdd, path, f, nil)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// diffDirOptions is used when the diff can be directly calculated from
|
||||||
|
// a diff directory to its base, without walking both trees.
|
||||||
|
type diffDirOptions struct {
|
||||||
|
diffDir string
|
||||||
|
skipChange func(string) (bool, error)
|
||||||
|
deleteChange func(string, string, os.FileInfo) (string, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// diffDirChanges walks the diff directory and compares changes against the base.
|
||||||
|
func diffDirChanges(ctx context.Context, changeFn ChangeFunc, base string, o *diffDirOptions) error {
|
||||||
|
changedDirs := make(map[string]struct{})
|
||||||
|
return filepath.Walk(o.diffDir, func(path string, f os.FileInfo, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rebase path
|
||||||
|
path, err = filepath.Rel(o.diffDir, path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
path = filepath.Join(string(os.PathSeparator), path)
|
||||||
|
|
||||||
|
// Skip root
|
||||||
|
if path == string(os.PathSeparator) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: handle opaqueness, start new double walker at this
|
||||||
|
// location to get deletes, and skip tree in single walker
|
||||||
|
|
||||||
|
if o.skipChange != nil {
|
||||||
|
if skip, err := o.skipChange(path); skip {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var kind ChangeKind
|
||||||
|
|
||||||
|
deletedFile, err := o.deleteChange(o.diffDir, path, f)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find out what kind of modification happened
|
||||||
|
if deletedFile != "" {
|
||||||
|
path = deletedFile
|
||||||
|
kind = ChangeKindDelete
|
||||||
|
f = nil
|
||||||
|
} else {
|
||||||
|
// Otherwise, the file was added
|
||||||
|
kind = ChangeKindAdd
|
||||||
|
|
||||||
|
// ...Unless it already existed in a base, in which case, it's a modification
|
||||||
|
stat, err := os.Stat(filepath.Join(base, path))
|
||||||
|
if err != nil && !os.IsNotExist(err) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
// The file existed in the base, so that's a modification
|
||||||
|
|
||||||
|
// However, if it's a directory, maybe it wasn't actually modified.
|
||||||
|
// If you modify /foo/bar/baz, then /foo will be part of the changed files only because it's the parent of bar
|
||||||
|
if stat.IsDir() && f.IsDir() {
|
||||||
|
if f.Size() == stat.Size() && f.Mode() == stat.Mode() && sameFsTime(f.ModTime(), stat.ModTime()) {
|
||||||
|
// Both directories are the same, don't record the change
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
kind = ChangeKindModify
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If /foo/bar/file.txt is modified, then /foo/bar must be part of the changed files.
|
||||||
|
// This block is here to ensure the change is recorded even if the
|
||||||
|
// modify time, mode and size of the parent directory in the rw and ro layers are all equal.
|
||||||
|
// Check https://github.com/docker/docker/pull/13590 for details.
|
||||||
|
if f.IsDir() {
|
||||||
|
changedDirs[path] = struct{}{}
|
||||||
|
}
|
||||||
|
if kind == ChangeKindAdd || kind == ChangeKindDelete {
|
||||||
|
parent := filepath.Dir(path)
|
||||||
|
if _, ok := changedDirs[parent]; !ok && parent != "/" {
|
||||||
|
pi, err := os.Stat(filepath.Join(o.diffDir, parent))
|
||||||
|
if err := changeFn(ChangeKindModify, parent, pi, err); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
changedDirs[parent] = struct{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return changeFn(kind, path, f, nil)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// doubleWalkDiff walks both directories to create a diff
|
||||||
|
func doubleWalkDiff(ctx context.Context, changeFn ChangeFunc, a, b string) (err error) {
|
||||||
|
g, ctx := errgroup.WithContext(ctx)
|
||||||
|
|
||||||
|
var (
|
||||||
|
c1 = make(chan *currentPath)
|
||||||
|
c2 = make(chan *currentPath)
|
||||||
|
|
||||||
|
f1, f2 *currentPath
|
||||||
|
rmdir string
|
||||||
|
)
|
||||||
|
g.Go(func() error {
|
||||||
|
defer close(c1)
|
||||||
|
return pathWalk(ctx, a, c1)
|
||||||
|
})
|
||||||
|
g.Go(func() error {
|
||||||
|
defer close(c2)
|
||||||
|
return pathWalk(ctx, b, c2)
|
||||||
|
})
|
||||||
|
g.Go(func() error {
|
||||||
|
for c1 != nil || c2 != nil {
|
||||||
|
if f1 == nil && c1 != nil {
|
||||||
|
f1, err = nextPath(ctx, c1)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if f1 == nil {
|
||||||
|
c1 = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if f2 == nil && c2 != nil {
|
||||||
|
f2, err = nextPath(ctx, c2)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if f2 == nil {
|
||||||
|
c2 = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if f1 == nil && f2 == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
var f os.FileInfo
|
||||||
|
k, p := pathChange(f1, f2)
|
||||||
|
switch k {
|
||||||
|
case ChangeKindAdd:
|
||||||
|
if rmdir != "" {
|
||||||
|
rmdir = ""
|
||||||
|
}
|
||||||
|
f = f2.f
|
||||||
|
f2 = nil
|
||||||
|
case ChangeKindDelete:
|
||||||
|
// Check if this file is already removed by being
|
||||||
|
// under of a removed directory
|
||||||
|
if rmdir != "" && strings.HasPrefix(f1.path, rmdir) {
|
||||||
|
f1 = nil
|
||||||
|
continue
|
||||||
|
} else if rmdir == "" && f1.f.IsDir() {
|
||||||
|
rmdir = f1.path + string(os.PathSeparator)
|
||||||
|
} else if rmdir != "" {
|
||||||
|
rmdir = ""
|
||||||
|
}
|
||||||
|
f1 = nil
|
||||||
|
case ChangeKindModify:
|
||||||
|
same, err := sameFile(f1, f2)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if f1.f.IsDir() && !f2.f.IsDir() {
|
||||||
|
rmdir = f1.path + string(os.PathSeparator)
|
||||||
|
} else if rmdir != "" {
|
||||||
|
rmdir = ""
|
||||||
|
}
|
||||||
|
f = f2.f
|
||||||
|
f1 = nil
|
||||||
|
f2 = nil
|
||||||
|
if same {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err := changeFn(k, p, f, nil); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
return g.Wait()
|
||||||
|
}
|
92
vendor/github.com/containerd/containerd/fs/diff_linux.go
generated
vendored
Normal file
92
vendor/github.com/containerd/containerd/fs/diff_linux.go
generated
vendored
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
package fs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"github.com/stevvooe/continuity/sysx"
|
||||||
|
)
|
||||||
|
|
||||||
|
// whiteouts are files with a special meaning for the layered filesystem.
|
||||||
|
// Docker uses AUFS whiteout files inside exported archives. In other
|
||||||
|
// filesystems these files are generated/handled on tar creation/extraction.
|
||||||
|
|
||||||
|
// whiteoutPrefix prefix means file is a whiteout. If this is followed by a
|
||||||
|
// filename this means that file has been removed from the base layer.
|
||||||
|
const whiteoutPrefix = ".wh."
|
||||||
|
|
||||||
|
// whiteoutMetaPrefix prefix means whiteout has a special meaning and is not
|
||||||
|
// for removing an actual file. Normally these files are excluded from exported
|
||||||
|
// archives.
|
||||||
|
const whiteoutMetaPrefix = whiteoutPrefix + whiteoutPrefix
|
||||||
|
|
||||||
|
// whiteoutLinkDir is a directory AUFS uses for storing hardlink links to other
|
||||||
|
// layers. Normally these should not go into exported archives and all changed
|
||||||
|
// hardlinks should be copied to the top layer.
|
||||||
|
const whiteoutLinkDir = whiteoutMetaPrefix + "plnk"
|
||||||
|
|
||||||
|
// whiteoutOpaqueDir file means directory has been made opaque - meaning
|
||||||
|
// readdir calls to this directory do not follow to lower layers.
|
||||||
|
const whiteoutOpaqueDir = whiteoutMetaPrefix + ".opq"
|
||||||
|
|
||||||
|
// detectDirDiff returns diff dir options if a directory could
|
||||||
|
// be found in the mount info for upper which is the direct
|
||||||
|
// diff with the provided lower directory
|
||||||
|
func detectDirDiff(upper, lower string) *diffDirOptions {
|
||||||
|
// TODO: get mount options for upper
|
||||||
|
// TODO: detect AUFS
|
||||||
|
// TODO: detect overlay
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func aufsMetadataSkip(path string) (skip bool, err error) {
|
||||||
|
skip, err = filepath.Match(string(os.PathSeparator)+whiteoutMetaPrefix+"*", path)
|
||||||
|
if err != nil {
|
||||||
|
skip = true
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func aufsDeletedFile(root, path string, fi os.FileInfo) (string, error) {
|
||||||
|
f := filepath.Base(path)
|
||||||
|
|
||||||
|
// If there is a whiteout, then the file was removed
|
||||||
|
if strings.HasPrefix(f, whiteoutPrefix) {
|
||||||
|
originalFile := f[len(whiteoutPrefix):]
|
||||||
|
return filepath.Join(filepath.Dir(path), originalFile), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// compareSysStat returns whether the stats are equivalent,
|
||||||
|
// whether the files are considered the same file, and
|
||||||
|
// an error
|
||||||
|
func compareSysStat(s1, s2 interface{}) (bool, error) {
|
||||||
|
ls1, ok := s1.(*syscall.Stat_t)
|
||||||
|
if !ok {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
ls2, ok := s2.(*syscall.Stat_t)
|
||||||
|
if !ok {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return ls1.Mode == ls2.Mode && ls1.Uid == ls2.Uid && ls1.Gid == ls2.Gid && ls1.Rdev == ls2.Rdev, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func compareCapabilities(p1, p2 string) (bool, error) {
|
||||||
|
c1, err := sysx.LGetxattr(p1, "security.capability")
|
||||||
|
if err != nil && err != syscall.ENODATA {
|
||||||
|
return false, errors.Wrapf(err, "failed to get xattr for %s", p1)
|
||||||
|
}
|
||||||
|
c2, err := sysx.LGetxattr(p2, "security.capability")
|
||||||
|
if err != nil && err != syscall.ENODATA {
|
||||||
|
return false, errors.Wrapf(err, "failed to get xattr for %s", p2)
|
||||||
|
}
|
||||||
|
return bytes.Equal(c1, c2), nil
|
||||||
|
}
|
15
vendor/github.com/containerd/containerd/fs/diff_windows.go
generated
vendored
Normal file
15
vendor/github.com/containerd/containerd/fs/diff_windows.go
generated
vendored
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
package fs
|
||||||
|
|
||||||
|
func detectDirDiff(upper, lower string) *diffDirOptions {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func compareSysStat(s1, s2 interface{}) (bool, error) {
|
||||||
|
// TODO: Use windows specific sys type
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func compareCapabilities(p1, p2 string) (bool, error) {
|
||||||
|
// TODO: Use windows equivalent
|
||||||
|
return true, nil
|
||||||
|
}
|
12
vendor/github.com/containerd/containerd/fs/hardlink.go
generated
vendored
Normal file
12
vendor/github.com/containerd/containerd/fs/hardlink.go
generated
vendored
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
package fs
|
||||||
|
|
||||||
|
import "os"
|
||||||
|
|
||||||
|
// GetLinkSource returns a path for the given name and
|
||||||
|
// file info to its link source in the provided inode
|
||||||
|
// map. If the given file name is not in the map and
|
||||||
|
// has other links, it is added to the inode map
|
||||||
|
// to be a source for other link locations.
|
||||||
|
func GetLinkSource(name string, fi os.FileInfo, inodes map[uint64]string) (string, error) {
|
||||||
|
return getHardLink(name, fi, inodes)
|
||||||
|
}
|
33
vendor/github.com/containerd/containerd/fs/hardlink_unix.go
generated
vendored
Normal file
33
vendor/github.com/containerd/containerd/fs/hardlink_unix.go
generated
vendored
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
// +build !windows
|
||||||
|
|
||||||
|
package fs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"syscall"
|
||||||
|
)
|
||||||
|
|
||||||
|
func getHardLink(name string, fi os.FileInfo, inodes map[uint64]string) (string, error) {
|
||||||
|
if fi.IsDir() {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
s, ok := fi.Sys().(*syscall.Stat_t)
|
||||||
|
if !ok {
|
||||||
|
return "", errors.New("unsupported stat type")
|
||||||
|
}
|
||||||
|
|
||||||
|
// If inode is not hardlinked, no reason to lookup or save inode
|
||||||
|
if s.Nlink == 1 {
|
||||||
|
return "", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
inode := uint64(s.Ino)
|
||||||
|
|
||||||
|
path, ok := inodes[inode]
|
||||||
|
if !ok {
|
||||||
|
inodes[inode] = name
|
||||||
|
}
|
||||||
|
return path, nil
|
||||||
|
}
|
7
vendor/github.com/containerd/containerd/fs/hardlink_windows.go
generated
vendored
Normal file
7
vendor/github.com/containerd/containerd/fs/hardlink_windows.go
generated
vendored
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
package fs
|
||||||
|
|
||||||
|
import "os"
|
||||||
|
|
||||||
|
func getHardLink(string, os.FileInfo, map[uint64]string) (string, error) {
|
||||||
|
return "", nil
|
||||||
|
}
|
162
vendor/github.com/containerd/containerd/fs/path.go
generated
vendored
Normal file
162
vendor/github.com/containerd/containerd/fs/path.go
generated
vendored
Normal file
@ -0,0 +1,162 @@
|
|||||||
|
package fs
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
type currentPath struct {
|
||||||
|
path string
|
||||||
|
f os.FileInfo
|
||||||
|
fullPath string
|
||||||
|
}
|
||||||
|
|
||||||
|
func pathChange(lower, upper *currentPath) (ChangeKind, string) {
|
||||||
|
if lower == nil {
|
||||||
|
if upper == nil {
|
||||||
|
panic("cannot compare nil paths")
|
||||||
|
}
|
||||||
|
return ChangeKindAdd, upper.path
|
||||||
|
}
|
||||||
|
if upper == nil {
|
||||||
|
return ChangeKindDelete, lower.path
|
||||||
|
}
|
||||||
|
// TODO: compare by directory
|
||||||
|
|
||||||
|
switch i := strings.Compare(lower.path, upper.path); {
|
||||||
|
case i < 0:
|
||||||
|
// File in lower that is not in upper
|
||||||
|
return ChangeKindDelete, lower.path
|
||||||
|
case i > 0:
|
||||||
|
// File in upper that is not in lower
|
||||||
|
return ChangeKindAdd, upper.path
|
||||||
|
default:
|
||||||
|
return ChangeKindModify, upper.path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func sameFile(f1, f2 *currentPath) (bool, error) {
|
||||||
|
if os.SameFile(f1.f, f2.f) {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
equalStat, err := compareSysStat(f1.f.Sys(), f2.f.Sys())
|
||||||
|
if err != nil || !equalStat {
|
||||||
|
return equalStat, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if eq, err := compareCapabilities(f1.fullPath, f2.fullPath); err != nil || !eq {
|
||||||
|
return eq, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// If not a directory also check size, modtime, and content
|
||||||
|
if !f1.f.IsDir() {
|
||||||
|
if f1.f.Size() != f2.f.Size() {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
t1 := f1.f.ModTime()
|
||||||
|
t2 := f2.f.ModTime()
|
||||||
|
|
||||||
|
if t1.Unix() != t2.Unix() {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the timestamp may have been truncated in one of the
|
||||||
|
// files, check content of file to determine difference
|
||||||
|
if t1.Nanosecond() == 0 || t2.Nanosecond() == 0 {
|
||||||
|
if f1.f.Size() > 0 {
|
||||||
|
eq, err := compareFileContent(f1.fullPath, f2.fullPath)
|
||||||
|
if err != nil || !eq {
|
||||||
|
return eq, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if t1.Nanosecond() != t2.Nanosecond() {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
const compareChuckSize = 32 * 1024
|
||||||
|
|
||||||
|
// compareFileContent compares the content of 2 same sized files
|
||||||
|
// by comparing each byte.
|
||||||
|
func compareFileContent(p1, p2 string) (bool, error) {
|
||||||
|
f1, err := os.Open(p1)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
defer f1.Close()
|
||||||
|
f2, err := os.Open(p2)
|
||||||
|
if err != nil {
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
defer f2.Close()
|
||||||
|
|
||||||
|
b1 := make([]byte, compareChuckSize)
|
||||||
|
b2 := make([]byte, compareChuckSize)
|
||||||
|
for {
|
||||||
|
n1, err1 := f1.Read(b1)
|
||||||
|
if err1 != nil && err1 != io.EOF {
|
||||||
|
return false, err1
|
||||||
|
}
|
||||||
|
n2, err2 := f2.Read(b2)
|
||||||
|
if err2 != nil && err2 != io.EOF {
|
||||||
|
return false, err2
|
||||||
|
}
|
||||||
|
if n1 != n2 || !bytes.Equal(b1[:n1], b2[:n2]) {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
if err1 == io.EOF && err2 == io.EOF {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func pathWalk(ctx context.Context, root string, pathC chan<- *currentPath) error {
|
||||||
|
return filepath.Walk(root, func(path string, f os.FileInfo, err error) error {
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rebase path
|
||||||
|
path, err = filepath.Rel(root, path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
path = filepath.Join(string(os.PathSeparator), path)
|
||||||
|
|
||||||
|
// Skip root
|
||||||
|
if path == string(os.PathSeparator) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
p := ¤tPath{
|
||||||
|
path: path,
|
||||||
|
f: f,
|
||||||
|
fullPath: filepath.Join(root, path),
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return ctx.Err()
|
||||||
|
case pathC <- p:
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func nextPath(ctx context.Context, pathC <-chan *currentPath) (*currentPath, error) {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return nil, ctx.Err()
|
||||||
|
case p := <-pathC:
|
||||||
|
return p, nil
|
||||||
|
}
|
||||||
|
}
|
13
vendor/github.com/containerd/containerd/fs/time.go
generated
vendored
Normal file
13
vendor/github.com/containerd/containerd/fs/time.go
generated
vendored
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
package fs
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// Gnu tar and the go tar writer don't have sub-second mtime
|
||||||
|
// precision, which is problematic when we apply changes via tar
|
||||||
|
// files, we handle this by comparing for exact times, *or* same
|
||||||
|
// second count and either a or b having exactly 0 nanoseconds
|
||||||
|
func sameFsTime(a, b time.Time) bool {
|
||||||
|
return a == b ||
|
||||||
|
(a.Unix() == b.Unix() &&
|
||||||
|
(a.Nanosecond() == 0 || b.Nanosecond() == 0))
|
||||||
|
}
|
144
vendor/github.com/containerd/containerd/images/handlers.go
generated
vendored
Normal file
144
vendor/github.com/containerd/containerd/images/handlers.go
generated
vendored
Normal file
@ -0,0 +1,144 @@
|
|||||||
|
package images
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
"github.com/containerd/containerd/content"
|
||||||
|
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
|
||||||
|
"github.com/pkg/errors"
|
||||||
|
"golang.org/x/sync/errgroup"
|
||||||
|
)
|
||||||
|
|
||||||
|
var SkipDesc = fmt.Errorf("skip descriptor")
|
||||||
|
|
||||||
|
type Handler interface {
|
||||||
|
Handle(ctx context.Context, desc ocispec.Descriptor) (subdescs []ocispec.Descriptor, err error)
|
||||||
|
}
|
||||||
|
|
||||||
|
type HandlerFunc func(ctx context.Context, desc ocispec.Descriptor) (subdescs []ocispec.Descriptor, err error)
|
||||||
|
|
||||||
|
func (fn HandlerFunc) Handle(ctx context.Context, desc ocispec.Descriptor) (subdescs []ocispec.Descriptor, err error) {
|
||||||
|
return fn(ctx, desc)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handlers returns a handler that will run the handlers in sequence.
|
||||||
|
func Handlers(handlers ...Handler) HandlerFunc {
|
||||||
|
return func(ctx context.Context, desc ocispec.Descriptor) (subdescs []ocispec.Descriptor, err error) {
|
||||||
|
var children []ocispec.Descriptor
|
||||||
|
for _, handler := range handlers {
|
||||||
|
ch, err := handler.Handle(ctx, desc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
children = append(children, ch...)
|
||||||
|
}
|
||||||
|
|
||||||
|
return children, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Walk the resources of an image and call the handler for each. If the handler
|
||||||
|
// decodes the sub-resources for each image,
|
||||||
|
//
|
||||||
|
// This differs from dispatch in that each sibling resource is considered
|
||||||
|
// synchronously.
|
||||||
|
func Walk(ctx context.Context, handler Handler, descs ...ocispec.Descriptor) error {
|
||||||
|
for _, desc := range descs {
|
||||||
|
|
||||||
|
children, err := handler.Handle(ctx, desc)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Cause(err) == SkipDesc {
|
||||||
|
return nil // don't traverse the children.
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(children) > 0 {
|
||||||
|
if err := Walk(ctx, handler, children...); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Dispatch runs the provided handler for content specified by the descriptors.
|
||||||
|
// If the handler decode subresources, they will be visited, as well.
|
||||||
|
//
|
||||||
|
// Handlers for siblings are run in parallel on the provided descriptors. A
|
||||||
|
// handler may return `SkipDesc` to signal to the dispatcher to not traverse
|
||||||
|
// any children.
|
||||||
|
//
|
||||||
|
// Typically, this function will be used with `FetchHandler`, often composed
|
||||||
|
// with other handlers.
|
||||||
|
//
|
||||||
|
// If any handler returns an error, the dispatch session will be canceled.
|
||||||
|
func Dispatch(ctx context.Context, handler Handler, descs ...ocispec.Descriptor) error {
|
||||||
|
eg, ctx := errgroup.WithContext(ctx)
|
||||||
|
for _, desc := range descs {
|
||||||
|
desc := desc
|
||||||
|
|
||||||
|
eg.Go(func() error {
|
||||||
|
desc := desc
|
||||||
|
|
||||||
|
children, err := handler.Handle(ctx, desc)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Cause(err) == SkipDesc {
|
||||||
|
return nil // don't traverse the children.
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(children) > 0 {
|
||||||
|
return Dispatch(ctx, handler, children...)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return eg.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ChildrenHandler decodes well-known manifests types and returns their children.
|
||||||
|
//
|
||||||
|
// This is useful for supporting recursive fetch and other use cases where you
|
||||||
|
// want to do a full walk of resources.
|
||||||
|
//
|
||||||
|
// One can also replace this with another implementation to allow descending of
|
||||||
|
// arbitrary types.
|
||||||
|
func ChildrenHandler(provider content.Provider) HandlerFunc {
|
||||||
|
return func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) {
|
||||||
|
switch desc.MediaType {
|
||||||
|
case MediaTypeDockerSchema2Manifest, ocispec.MediaTypeImageManifest:
|
||||||
|
case MediaTypeDockerSchema2Layer, MediaTypeDockerSchema2LayerGzip,
|
||||||
|
MediaTypeDockerSchema2Config:
|
||||||
|
return nil, nil
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("%v not yet supported", desc.MediaType)
|
||||||
|
}
|
||||||
|
|
||||||
|
p, err := content.ReadBlob(ctx, provider, desc.Digest)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO(stevvooe): We just assume oci manifest, for now. There may be
|
||||||
|
// subtle differences from the docker version.
|
||||||
|
var manifest ocispec.Manifest
|
||||||
|
if err := json.Unmarshal(p, &manifest); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var descs []ocispec.Descriptor
|
||||||
|
|
||||||
|
descs = append(descs, manifest.Config)
|
||||||
|
descs = append(descs, manifest.Layers...)
|
||||||
|
|
||||||
|
return descs, nil
|
||||||
|
}
|
||||||
|
}
|
125
vendor/github.com/containerd/containerd/images/image.go
generated
vendored
Normal file
125
vendor/github.com/containerd/containerd/images/image.go
generated
vendored
Normal file
@ -0,0 +1,125 @@
|
|||||||
|
package images
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io/ioutil"
|
||||||
|
|
||||||
|
"github.com/containerd/containerd/content"
|
||||||
|
"github.com/containerd/containerd/log"
|
||||||
|
digest "github.com/opencontainers/go-digest"
|
||||||
|
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Image provides the model for how containerd views container images.
|
||||||
|
type Image struct {
|
||||||
|
Name string
|
||||||
|
Target ocispec.Descriptor
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO(stevvooe): Many of these functions make strong platform assumptions,
|
||||||
|
// which are untrue in a lot of cases. More refactoring must be done here to
|
||||||
|
// make this work in all cases.
|
||||||
|
|
||||||
|
// Config resolves the image configuration descriptor.
|
||||||
|
//
|
||||||
|
// The caller can then use the descriptor to resolve and process the
|
||||||
|
// configuration of the image.
|
||||||
|
func (image *Image) Config(ctx context.Context, provider content.Provider) (ocispec.Descriptor, error) {
|
||||||
|
var configDesc ocispec.Descriptor
|
||||||
|
return configDesc, Walk(ctx, HandlerFunc(func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) {
|
||||||
|
switch image.Target.MediaType {
|
||||||
|
case MediaTypeDockerSchema2Manifest, ocispec.MediaTypeImageManifest:
|
||||||
|
rc, err := provider.Reader(ctx, image.Target.Digest)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rc.Close()
|
||||||
|
|
||||||
|
p, err := ioutil.ReadAll(rc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var manifest ocispec.Manifest
|
||||||
|
if err := json.Unmarshal(p, &manifest); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
configDesc = manifest.Config
|
||||||
|
|
||||||
|
return nil, nil
|
||||||
|
default:
|
||||||
|
return nil, errors.New("could not resolve config")
|
||||||
|
}
|
||||||
|
|
||||||
|
}), image.Target)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RootFS returns the unpacked diffids that make up and images rootfs.
|
||||||
|
//
|
||||||
|
// These are used to verify that a set of layers unpacked to the expected
|
||||||
|
// values.
|
||||||
|
func (image *Image) RootFS(ctx context.Context, provider content.Provider) ([]digest.Digest, error) {
|
||||||
|
desc, err := image.Config(ctx, provider)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
p, err := content.ReadBlob(ctx, provider, desc.Digest)
|
||||||
|
if err != nil {
|
||||||
|
log.G(ctx).Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var config ocispec.Image
|
||||||
|
if err := json.Unmarshal(p, &config); err != nil {
|
||||||
|
log.G(ctx).Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO(stevvooe): Remove this bit when OCI structure uses correct type for
|
||||||
|
// rootfs.DiffIDs.
|
||||||
|
var diffIDs []digest.Digest
|
||||||
|
for _, diffID := range config.RootFS.DiffIDs {
|
||||||
|
diffIDs = append(diffIDs, digest.Digest(diffID))
|
||||||
|
}
|
||||||
|
|
||||||
|
return diffIDs, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Size returns the total size of an image's packed resources.
|
||||||
|
func (image *Image) Size(ctx context.Context, provider content.Provider) (int64, error) {
|
||||||
|
var size int64
|
||||||
|
return size, Walk(ctx, HandlerFunc(func(ctx context.Context, desc ocispec.Descriptor) ([]ocispec.Descriptor, error) {
|
||||||
|
switch image.Target.MediaType {
|
||||||
|
case MediaTypeDockerSchema2Manifest, ocispec.MediaTypeImageManifest:
|
||||||
|
size += desc.Size
|
||||||
|
rc, err := provider.Reader(ctx, image.Target.Digest)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rc.Close()
|
||||||
|
|
||||||
|
p, err := ioutil.ReadAll(rc)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var manifest ocispec.Manifest
|
||||||
|
if err := json.Unmarshal(p, &manifest); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
size += manifest.Config.Size
|
||||||
|
|
||||||
|
for _, layer := range manifest.Layers {
|
||||||
|
size += layer.Size
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, nil
|
||||||
|
default:
|
||||||
|
return nil, errors.New("unsupported type")
|
||||||
|
}
|
||||||
|
|
||||||
|
}), image.Target)
|
||||||
|
}
|
13
vendor/github.com/containerd/containerd/images/mediatypes.go
generated
vendored
Normal file
13
vendor/github.com/containerd/containerd/images/mediatypes.go
generated
vendored
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
package images
|
||||||
|
|
||||||
|
// mediatype definitions for image components handled in containerd.
|
||||||
|
//
|
||||||
|
// oci components are generally referenced directly, although we may centralize
|
||||||
|
// here for clarity.
|
||||||
|
const (
|
||||||
|
MediaTypeDockerSchema2Layer = "application/vnd.docker.image.rootfs.diff.tar"
|
||||||
|
MediaTypeDockerSchema2LayerGzip = "application/vnd.docker.image.rootfs.diff.tar.gzip"
|
||||||
|
MediaTypeDockerSchema2Config = "application/vnd.docker.container.image.v1+json"
|
||||||
|
MediaTypeDockerSchema2Manifest = "application/vnd.docker.distribution.manifest.v2+json"
|
||||||
|
MediaTypeDockerSchema2ManifestList = "application/vnd.docker.distribution.manifest.list.v2+json"
|
||||||
|
)
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user