reconcile merge

Signed-off-by: Huamin Chen <hchen@redhat.com>
This commit is contained in:
Huamin Chen 2019-01-15 16:20:41 +00:00
parent 85b8415024
commit e46099a504
2425 changed files with 271763 additions and 40453 deletions

215
Gopkg.lock generated
View File

@ -9,14 +9,6 @@
revision = "ed0bb0e1557548aa028307f48728767cfe8f6345"
version = "v1.0.0"
[[projects]]
digest = "1:b13707423743d41665fd23f0c36b2f37bb49c30e94adb813319c44188a51ba22"
name = "github.com/ghodss/yaml"
packages = ["."]
pruneopts = ""
revision = "0ca9ea5df5451ffdf184b4428c902747c2c11cd7"
version = "v1.0.0"
[[projects]]
digest = "1:527e1e468c5586ef2645d143e9f5fbd50b4fe5abc8b1e25d9f1c416d22d24895"
name = "github.com/gogo/protobuf"
@ -40,6 +32,7 @@
digest = "1:3dd078fda7500c341bc26cfbc6c6a34614f295a2457149fc1045cab767cbcf18"
name = "github.com/golang/protobuf"
packages = [
"descriptor",
"proto",
"protoc-gen-go/descriptor",
"ptypes",
@ -52,6 +45,22 @@
revision = "aa810b61a9c79d51363740d207bb46cf8e620ed5"
version = "v1.2.0"
[[projects]]
branch = "master"
digest = "1:1e5b1e14524ed08301977b7b8e10c719ed853cbf3f24ecb66fae783a46f207a6"
name = "github.com/google/btree"
packages = ["."]
pruneopts = ""
revision = "4030bb1f1f0c35b30ca7009e9ebd06849dd45306"
[[projects]]
branch = "master"
digest = "1:754f77e9c839b24778a4b64422236d38515301d2baeb63113aa3edc42e6af692"
name = "github.com/google/gofuzz"
packages = ["."]
pruneopts = ""
revision = "24818f796faf91cd76ec7bddd72458fbced7a6c1"
[[projects]]
digest = "1:a25a2c5ae694b01713fb6cd03c3b1ac1ccc1902b9f0a922680a88ec254f968e1"
name = "github.com/google/uuid"
@ -60,15 +69,6 @@
revision = "9b3b1e0f5f99ae461456d768e7d301a7acdaa2d8"
version = "v1.1.0"
[[projects]]
branch = "master"
digest = "1:01f6264649510cce626f907688df44f80c8ba788d064756701d85c51f21eb0d6"
digest = "1:754f77e9c839b24778a4b64422236d38515301d2baeb63113aa3edc42e6af692"
name = "github.com/google/gofuzz"
packages = ["."]
pruneopts = ""
revision = "24818f796faf91cd76ec7bddd72458fbced7a6c1"
[[projects]]
digest = "1:16b2837c8b3cf045fa2cdc82af0cf78b19582701394484ae76b2c3bc3c99ad73"
name = "github.com/googleapis/gnostic"
@ -83,11 +83,14 @@
[[projects]]
branch = "master"
digest = "1:f81c8d7354cc0c6340f2f7a48724ee6c2b3db3e918ecd441c985b4d2d97dd3e7"
name = "github.com/howeyc/gopass"
packages = ["."]
digest = "1:5e345eb75d8bfb2b91cfbfe02a82a79c0b2ea55cf06c5a4d180a9321f36973b4"
name = "github.com/gregjones/httpcache"
packages = [
".",
"diskcache",
]
pruneopts = ""
revision = "bf9dde6d0d2c004a008c27aaee91170c786f6db8"
revision = "c63ab54fda8f77302f8d414e19933f2b6026a089"
[[projects]]
digest = "1:7ab38c15bd21e056e3115c8b526d201eaf74e0308da9370997c6b3c187115d36"
@ -105,19 +108,23 @@
revision = "1624edc4454b8682399def8740d46db5e4362ba4"
version = "v1.1.5"
[[projects]]
digest = "1:d1f1992c09d7b77bc5102cd8c369025d31d28dd5e6ca2a3a1a4ec9434724a4f5"
name = "github.com/kubernetes-csi/csi-lib-utils"
packages = ["protosanitizer"]
pruneopts = ""
revision = "5853414e1d4771302e0df10d1870c444c2135799"
version = "v0.2.0"
[[projects]]
branch = "master"
digest = "1:941f9605aec45f9e849500c1d315662401982efe492277d1a3bbf5488567321d"
>>>>>>> master
digest = "1:5031afaa62ff480905e90bed2d2fd74f07b12f4c0c30304bc4ab9472b55439d1"
name = "github.com/kubernetes-csi/drivers"
packages = ["pkg/csi-common"]
pruneopts = ""
revision = "8a7f2d3a4057ddcff31b7898bd4413dfdf3a3b67"
revision = "05e1ea84df03b90296869812fa42f4244bd5ab53"
[[projects]]
<<<<<<< HEAD
digest = "1:a5484d4fa43127138ae6e7b2299a6a52ae006c7f803d98d717f60abf3e97192e"
=======
digest = "1:0c0ff2a89c1bb0d01887e1dac043ad7efbf3ec77482ef058ac423d13497e16fd"
name = "github.com/modern-go/concurrent"
packages = ["."]
@ -134,8 +141,7 @@
version = "1.0.1"
[[projects]]
digest = "1:63e142fc50307bcb3c57494913cfc9c12f6061160bdf97a678f78c71615f939b"
>>>>>>> master
digest = "1:a5484d4fa43127138ae6e7b2299a6a52ae006c7f803d98d717f60abf3e97192e"
name = "github.com/pborman/uuid"
packages = ["."]
pruneopts = ""
@ -143,12 +149,28 @@
version = "v1.2"
[[projects]]
digest = "1:7365acd48986e205ccb8652cc746f09c8b7876030d53710ea6ef7d0bd0dcd7ca"
branch = "master"
digest = "1:c24598ffeadd2762552269271b3b1510df2d83ee6696c1e543a0ff653af494bc"
name = "github.com/petar/GoLLRB"
packages = ["llrb"]
pruneopts = ""
revision = "53be0d36a84c2a886ca057d34b6aa4468df9ccb4"
[[projects]]
digest = "1:b46305723171710475f2dd37547edd57b67b9de9f2a6267cafdd98331fd6897f"
name = "github.com/peterbourgon/diskv"
packages = ["."]
pruneopts = ""
revision = "5f041e8faa004a95c88a202771f4cc3e991971e6"
version = "v2.0.1"
[[projects]]
digest = "1:1d7e1867c49a6dd9856598ef7c3123604ea3daabf5b83f303ff457bcbc410b1d"
name = "github.com/pkg/errors"
packages = ["."]
pruneopts = ""
revision = "645ef00459ed84a119197bfb8d8205042c6df63d"
version = "v0.8.0"
revision = "ba968bfe8b2f7e042a574c888954fccecfa385b4"
version = "v0.8.1"
[[projects]]
digest = "1:cbaf13cdbfef0e4734ed8a7504f57fe893d471d62a35b982bf6fb3f036449a66"
@ -160,18 +182,19 @@
[[projects]]
branch = "master"
digest = "1:887074c37fcefc2f49b5ae9c6f9f36107341aec23185613d0e9f1ee81db7f94a"
digest = "1:59b49c47c11a48f1054529207f65907c014ecf5f9a7c0d9c0f1616dec7b062ed"
name = "golang.org/x/crypto"
packages = ["ssh/terminal"]
pruneopts = ""
revision = "505ab145d0a99da450461ae2c1a9f6cd10d1f447"
revision = "ff983b9c42bc9fbf91556e191cc8efb585c16908"
[[projects]]
branch = "master"
digest = "1:ea539c13b066dac72a940b62f37600a20ab8e88057397c78f3197c1a48475425"
digest = "1:7ec13687f85b25087fe05f6ea8dd116013a8263f8eb7e057da7664bc7599d2d4"
name = "golang.org/x/net"
packages = [
"context",
"context/ctxhttp",
"http/httpguts",
"http2",
"http2/hpack",
@ -180,18 +203,29 @@
"trace",
]
pruneopts = ""
revision = "351d144fa1fc0bd934e2408202be0c29f25e35a0"
revision = "915654e7eabcea33ae277abbecf52f0d8b7a9fdc"
[[projects]]
branch = "master"
digest = "1:f358024b019f87eecaadcb098113a40852c94fe58ea670ef3c3e2d2c7bd93db1"
digest = "1:790c83515921619a461cf47449bbdd5f58e35f689edc8164262cce7db4ae29ca"
name = "golang.org/x/oauth2"
packages = [
".",
"internal",
]
pruneopts = ""
revision = "36a7019397c4c86cf59eeab3bc0d188bac444277"
[[projects]]
branch = "master"
digest = "1:69b7ecfaddca30f8e8d97798822ff2b8ddfa7634ed16661561b54f30c63c2a42"
name = "golang.org/x/sys"
packages = [
"unix",
"windows",
]
pruneopts = ""
revision = "4ed8d59d0b35e1e29334a206d1b3f38b1e5dfb31"
revision = "a457fd036447854c0c02e89ea439481bdcf941a2"
[[projects]]
digest = "1:5acd3512b047305d49e8763eef7ba423901e85d5dd2fd1e71778a0ea8de10bd4"
@ -218,43 +252,60 @@
[[projects]]
branch = "master"
<<<<<<< HEAD
digest = "1:5fc6c317675b746d0c641b29aa0aab5fcb403c0d07afdbf0de86b0d447a0502a"
=======
digest = "1:14cb1d4240bcbbf1386ae763957e04e2765ec4e4ce7bb2769d05fa6faccd774e"
name = "golang.org/x/time"
packages = ["rate"]
pruneopts = ""
revision = "85acf8d2951cb2a3bde7632f9ff273ef0379bcbd"
[[projects]]
digest = "1:bc09e719c4e2a15d17163f5272d9a3131c45d77542b7fdc53ff518815bc19ab3"
name = "google.golang.org/appengine"
packages = [
"internal",
"internal/base",
"internal/datastore",
"internal/log",
"internal/remote_api",
"internal/urlfetch",
"urlfetch",
]
pruneopts = ""
revision = "e9657d882bb81064595ca3b56cbe2546bbabf7b1"
version = "v1.4.0"
[[projects]]
branch = "master"
digest = "1:282b4a7158a161508e442b0a1c24fcf771c66ada2c93921f4b8ddc6b0a5e0c9b"
>>>>>>> master
digest = "1:1aa609a0033ef2927e083f2e5e07203ca35fe21c4a24b563de9fea16ddaae9ba"
name = "google.golang.org/genproto"
packages = ["googleapis/rpc/status"]
pruneopts = ""
revision = "bd91e49a0898e27abb88c339b432fa53d7497ac0"
revision = "db91494dd46c1fdcbbde05e5ff5eb56df8f7d79a"
[[projects]]
digest = "1:1293087271e314cfa2b3decededba2ecba0ff327e7b7809e00f73f616449191c"
digest = "1:d141efe4aaad714e3059c340901aab3147b6253e58c85dafbcca3dd8b0e88ad6"
name = "google.golang.org/grpc"
packages = [
".",
"balancer",
"balancer/base",
"balancer/roundrobin",
"binarylog/grpc_binarylog_v1",
"codes",
"connectivity",
"credentials",
"credentials/internal",
"encoding",
"encoding/proto",
"grpclog",
"internal",
"internal/backoff",
"internal/binarylog",
"internal/channelz",
"internal/envconfig",
"internal/grpcrand",
"internal/grpcsync",
"internal/syscall",
"internal/transport",
"keepalive",
"metadata",
@ -268,13 +319,10 @@
"tap",
]
pruneopts = ""
revision = "2e463a05d100327ca47ac218281906921038fd95"
version = "v1.16.0"
revision = "df014850f6dee74ba2fc94874043a9f3f75fbfd8"
version = "v1.17.0"
[[projects]]
<<<<<<< HEAD
digest = "1:66b0292f815d508d11ed5fe94fdeb0bcc5a988703a08e73bf3cb3a415de676cf"
=======
digest = "1:75fb3fcfc73a8c723efde7777b40e8e8ff9babf30d8c56160d01beffea8a95a6"
name = "gopkg.in/inf.v0"
packages = ["."]
@ -291,7 +339,7 @@
version = "v2.2.2"
[[projects]]
digest = "1:2412b59688d0e4d359397d277a7fc68703c47666dd2498b43cc79acef84a64d7"
digest = "1:be67264067c68b1f601bfc4a6c102b1380ed0743147381de81ed11da88d2e246"
name = "k8s.io/api"
packages = [
"admissionregistration/v1alpha1",
@ -299,16 +347,19 @@
"apps/v1",
"apps/v1beta1",
"apps/v1beta2",
"auditregistration/v1alpha1",
"authentication/v1",
"authentication/v1beta1",
"authorization/v1",
"authorization/v1beta1",
"autoscaling/v1",
"autoscaling/v2beta1",
"autoscaling/v2beta2",
"batch/v1",
"batch/v1beta1",
"batch/v2alpha1",
"certificates/v1beta1",
"coordination/v1beta1",
"core/v1",
"events/v1beta1",
"extensions/v1beta1",
@ -318,18 +369,18 @@
"rbac/v1alpha1",
"rbac/v1beta1",
"scheduling/v1alpha1",
"scheduling/v1beta1",
"settings/v1alpha1",
"storage/v1",
"storage/v1alpha1",
"storage/v1beta1",
]
pruneopts = ""
revision = "7aac3e00a1b32fa476b83078cebaaca606b2fb48"
version = "kubernetes-1.10.0-beta.1"
revision = "89a74a8d264df0e993299876a8cde88379b940ee"
version = "kubernetes-1.13.0"
[[projects]]
digest = "1:9b07c796baf391a2dfa8c64bd5ddc28cbeb00723389f2f3da2e3d09b961f2e31"
>>>>>>> master
digest = "1:66b0292f815d508d11ed5fe94fdeb0bcc5a988703a08e73bf3cb3a415de676cf"
name = "k8s.io/apimachinery"
packages = [
"pkg/api/errors",
@ -357,6 +408,7 @@
"pkg/util/framer",
"pkg/util/intstr",
"pkg/util/json",
"pkg/util/naming",
"pkg/util/net",
"pkg/util/runtime",
"pkg/util/sets",
@ -373,18 +425,7 @@
version = "kubernetes-1.13.0"
[[projects]]
<<<<<<< HEAD
digest = "1:4f5eb833037cc0ba0bf8fe9cae6be9df62c19dd1c869415275c708daa8ccfda5"
name = "k8s.io/klog"
packages = ["."]
pruneopts = ""
revision = "a5bc97fbc634d635061f3146511332c7e313a55a"
version = "v0.1.0"
[[projects]]
digest = "1:a53c39a815a31aceb509f9987d7d8c65e74fcb1fcd5077eaf723a8defec1af90"
=======
digest = "1:4e43ae063c506514708f015c8ebf145456174116dd04c7fd3eab89ebb22def35"
digest = "1:96ab89894f66b77a0137bba12e607c6a9be992acadfb075b5602939e8519a157"
name = "k8s.io/client-go"
packages = [
"discovery",
@ -395,16 +436,19 @@
"kubernetes/typed/apps/v1",
"kubernetes/typed/apps/v1beta1",
"kubernetes/typed/apps/v1beta2",
"kubernetes/typed/auditregistration/v1alpha1",
"kubernetes/typed/authentication/v1",
"kubernetes/typed/authentication/v1beta1",
"kubernetes/typed/authorization/v1",
"kubernetes/typed/authorization/v1beta1",
"kubernetes/typed/autoscaling/v1",
"kubernetes/typed/autoscaling/v2beta1",
"kubernetes/typed/autoscaling/v2beta2",
"kubernetes/typed/batch/v1",
"kubernetes/typed/batch/v1beta1",
"kubernetes/typed/batch/v2alpha1",
"kubernetes/typed/certificates/v1beta1",
"kubernetes/typed/coordination/v1beta1",
"kubernetes/typed/core/v1",
"kubernetes/typed/events/v1beta1",
"kubernetes/typed/extensions/v1beta1",
@ -414,11 +458,16 @@
"kubernetes/typed/rbac/v1alpha1",
"kubernetes/typed/rbac/v1beta1",
"kubernetes/typed/scheduling/v1alpha1",
"kubernetes/typed/scheduling/v1beta1",
"kubernetes/typed/settings/v1alpha1",
"kubernetes/typed/storage/v1",
"kubernetes/typed/storage/v1alpha1",
"kubernetes/typed/storage/v1beta1",
"pkg/apis/clientauthentication",
"pkg/apis/clientauthentication/v1alpha1",
"pkg/apis/clientauthentication/v1beta1",
"pkg/version",
"plugin/pkg/client/auth/exec",
"rest",
"rest/watch",
"tools/auth",
@ -430,17 +479,25 @@
"tools/reference",
"transport",
"util/cert",
"util/connrotation",
"util/flowcontrol",
"util/homedir",
"util/integer",
]
pruneopts = ""
revision = "82eadfdc39007c2eb47e3ddeb7ed7d96365e409d"
version = "kubernetes-1.10.0-beta.1"
revision = "e64494209f554a6723674bd494d69445fb76a1d4"
version = "kubernetes-1.13.0"
[[projects]]
digest = "1:7107d2e83c67ac0dbd9b62e8e2bfe1a75b194864ea4fe30778f4842151cd356d"
>>>>>>> master
digest = "1:4f5eb833037cc0ba0bf8fe9cae6be9df62c19dd1c869415275c708daa8ccfda5"
name = "k8s.io/klog"
packages = ["."]
pruneopts = ""
revision = "a5bc97fbc634d635061f3146511332c7e313a55a"
version = "v0.1.0"
[[projects]]
digest = "1:9ac53939e57f04ea4886ed3c7b23612c65258de122c028a6c5ee8f9bdc0c51dd"
name = "k8s.io/kubernetes"
packages = [
"pkg/util/file",
@ -450,16 +507,24 @@
"pkg/util/nsenter",
]
pruneopts = ""
revision = "ddf47ac13c1a9483ea035a79cd7c10005ff21a6d"
version = "v1.13.0"
revision = "cff46ab41ff0bb44d8584413b598ad8360ec1def"
version = "v1.13.2"
[[projects]]
branch = "master"
digest = "1:bea542e853f98bfcc80ecbe8fe0f32bc52c97664102aacdd7dca676354ef2faa"
digest = "1:8b4b9c29be72c176988b04d5acc665c093b1efac228835f0a4716531c1f7563e"
name = "k8s.io/utils"
packages = ["exec"]
pruneopts = ""
revision = "0d26856f57b32ec3398579285e5c8a2bfe8c5243"
revision = "8a16e7dd8fb6d97d1331b0c79a16722f934b00b1"
[[projects]]
digest = "1:321081b4a44256715f2b68411d8eda9a17f17ebfe6f0cc61d2cc52d11c08acfa"
name = "sigs.k8s.io/yaml"
packages = ["."]
pruneopts = ""
revision = "fd68e9863619f6ec2fdd8625fe1f02e7c877e480"
version = "v1.1.0"
[solve-meta]
analyzer-name = "dep"

View File

@ -36,4 +36,4 @@
[[constraint]]
name = "k8s.io/client-go"
version = "kubernetes-1.10.0-beta.1"
version = "kubernetes-1.13.0"

View File

@ -23,8 +23,8 @@ import (
"syscall"
"time"
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/ceph/ceph-csi/pkg/util"
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/golang/glog"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/kubernetes-csi/drivers/pkg/csi-common"
@ -170,7 +170,7 @@ func (cs *controllerServer) CreateVolume(ctx context.Context, req *csi.CreateVol
}
if err := cs.MetadataStore.Create(volumeID, rbdVol); err != nil {
glog.Warningf("failed to store volume metadata with error: %v", err)
if err := deleteRBDImage(rbdVol, rbdVol.AdminId, req.GetControllerCreateSecrets()); err != nil {
if err := deleteRBDImage(rbdVol, rbdVol.AdminId, req.GetSecrets()); err != nil {
glog.V(3).Infof("failed to delete rbd image: %s/%s with error: %v", rbdVol.Pool, rbdVol.VolName, err)
return nil, err
}

View File

@ -73,17 +73,17 @@ type rbdSnapshot struct {
var (
// serializes operations based on "<rbd pool>/<rbd image>" as key
attachdetachMutex = keymutex.NewKeyMutex()
attachdetachMutex = keymutex.NewHashed(0)
// serializes operations based on "volume name" as key
volumeNameMutex = keymutex.NewKeyMutex()
volumeNameMutex = keymutex.NewHashed(0)
// serializes operations based on "volume id" as key
volumeIDMutex = keymutex.NewKeyMutex()
volumeIDMutex = keymutex.NewHashed(0)
// serializes operations based on "snapshot name" as key
snapshotNameMutex = keymutex.NewKeyMutex()
snapshotNameMutex = keymutex.NewHashed(0)
// serializes operations based on "snapshot id" as key
snapshotIDMutex = keymutex.NewKeyMutex()
snapshotIDMutex = keymutex.NewHashed(0)
// serializes operations based on "mount target path" as key
targetPathMutex = keymutex.NewKeyMutex()
targetPathMutex = keymutex.NewHashed(0)
supportedFeatures = sets.NewString("layering")
)

View File

@ -1,7 +0,0 @@
language: go
go:
- 1.3
- 1.4
script:
- go test
- go build

1
vendor/github.com/google/btree/.travis.yml generated vendored Normal file
View File

@ -0,0 +1 @@
language: go

202
vendor/github.com/google/btree/LICENSE generated vendored Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

12
vendor/github.com/google/btree/README.md generated vendored Normal file
View File

@ -0,0 +1,12 @@
# BTree implementation for Go
![Travis CI Build Status](https://api.travis-ci.org/google/btree.svg?branch=master)
This package provides an in-memory B-Tree implementation for Go, useful as
an ordered, mutable data structure.
The API is based off of the wonderful
http://godoc.org/github.com/petar/GoLLRB/llrb, and is meant to allow btree to
act as a drop-in replacement for gollrb trees.
See http://godoc.org/github.com/google/btree for documentation.

890
vendor/github.com/google/btree/btree.go generated vendored Normal file
View File

@ -0,0 +1,890 @@
// Copyright 2014 Google Inc.
//
// 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 btree implements in-memory B-Trees of arbitrary degree.
//
// btree implements an in-memory B-Tree for use as an ordered data structure.
// It is not meant for persistent storage solutions.
//
// It has a flatter structure than an equivalent red-black or other binary tree,
// which in some cases yields better memory usage and/or performance.
// See some discussion on the matter here:
// http://google-opensource.blogspot.com/2013/01/c-containers-that-save-memory-and-time.html
// Note, though, that this project is in no way related to the C++ B-Tree
// implementation written about there.
//
// Within this tree, each node contains a slice of items and a (possibly nil)
// slice of children. For basic numeric values or raw structs, this can cause
// efficiency differences when compared to equivalent C++ template code that
// stores values in arrays within the node:
// * Due to the overhead of storing values as interfaces (each
// value needs to be stored as the value itself, then 2 words for the
// interface pointing to that value and its type), resulting in higher
// memory use.
// * Since interfaces can point to values anywhere in memory, values are
// most likely not stored in contiguous blocks, resulting in a higher
// number of cache misses.
// These issues don't tend to matter, though, when working with strings or other
// heap-allocated structures, since C++-equivalent structures also must store
// pointers and also distribute their values across the heap.
//
// This implementation is designed to be a drop-in replacement to gollrb.LLRB
// trees, (http://github.com/petar/gollrb), an excellent and probably the most
// widely used ordered tree implementation in the Go ecosystem currently.
// Its functions, therefore, exactly mirror those of
// llrb.LLRB where possible. Unlike gollrb, though, we currently don't
// support storing multiple equivalent values.
package btree
import (
"fmt"
"io"
"sort"
"strings"
"sync"
)
// Item represents a single object in the tree.
type Item interface {
// Less tests whether the current item is less than the given argument.
//
// This must provide a strict weak ordering.
// If !a.Less(b) && !b.Less(a), we treat this to mean a == b (i.e. we can only
// hold one of either a or b in the tree).
Less(than Item) bool
}
const (
DefaultFreeListSize = 32
)
var (
nilItems = make(items, 16)
nilChildren = make(children, 16)
)
// FreeList represents a free list of btree nodes. By default each
// BTree has its own FreeList, but multiple BTrees can share the same
// FreeList.
// Two Btrees using the same freelist are safe for concurrent write access.
type FreeList struct {
mu sync.Mutex
freelist []*node
}
// NewFreeList creates a new free list.
// size is the maximum size of the returned free list.
func NewFreeList(size int) *FreeList {
return &FreeList{freelist: make([]*node, 0, size)}
}
func (f *FreeList) newNode() (n *node) {
f.mu.Lock()
index := len(f.freelist) - 1
if index < 0 {
f.mu.Unlock()
return new(node)
}
n = f.freelist[index]
f.freelist[index] = nil
f.freelist = f.freelist[:index]
f.mu.Unlock()
return
}
// freeNode adds the given node to the list, returning true if it was added
// and false if it was discarded.
func (f *FreeList) freeNode(n *node) (out bool) {
f.mu.Lock()
if len(f.freelist) < cap(f.freelist) {
f.freelist = append(f.freelist, n)
out = true
}
f.mu.Unlock()
return
}
// ItemIterator allows callers of Ascend* to iterate in-order over portions of
// the tree. When this function returns false, iteration will stop and the
// associated Ascend* function will immediately return.
type ItemIterator func(i Item) bool
// New creates a new B-Tree with the given degree.
//
// New(2), for example, will create a 2-3-4 tree (each node contains 1-3 items
// and 2-4 children).
func New(degree int) *BTree {
return NewWithFreeList(degree, NewFreeList(DefaultFreeListSize))
}
// NewWithFreeList creates a new B-Tree that uses the given node free list.
func NewWithFreeList(degree int, f *FreeList) *BTree {
if degree <= 1 {
panic("bad degree")
}
return &BTree{
degree: degree,
cow: &copyOnWriteContext{freelist: f},
}
}
// items stores items in a node.
type items []Item
// insertAt inserts a value into the given index, pushing all subsequent values
// forward.
func (s *items) insertAt(index int, item Item) {
*s = append(*s, nil)
if index < len(*s) {
copy((*s)[index+1:], (*s)[index:])
}
(*s)[index] = item
}
// removeAt removes a value at a given index, pulling all subsequent values
// back.
func (s *items) removeAt(index int) Item {
item := (*s)[index]
copy((*s)[index:], (*s)[index+1:])
(*s)[len(*s)-1] = nil
*s = (*s)[:len(*s)-1]
return item
}
// pop removes and returns the last element in the list.
func (s *items) pop() (out Item) {
index := len(*s) - 1
out = (*s)[index]
(*s)[index] = nil
*s = (*s)[:index]
return
}
// truncate truncates this instance at index so that it contains only the
// first index items. index must be less than or equal to length.
func (s *items) truncate(index int) {
var toClear items
*s, toClear = (*s)[:index], (*s)[index:]
for len(toClear) > 0 {
toClear = toClear[copy(toClear, nilItems):]
}
}
// find returns the index where the given item should be inserted into this
// list. 'found' is true if the item already exists in the list at the given
// index.
func (s items) find(item Item) (index int, found bool) {
i := sort.Search(len(s), func(i int) bool {
return item.Less(s[i])
})
if i > 0 && !s[i-1].Less(item) {
return i - 1, true
}
return i, false
}
// children stores child nodes in a node.
type children []*node
// insertAt inserts a value into the given index, pushing all subsequent values
// forward.
func (s *children) insertAt(index int, n *node) {
*s = append(*s, nil)
if index < len(*s) {
copy((*s)[index+1:], (*s)[index:])
}
(*s)[index] = n
}
// removeAt removes a value at a given index, pulling all subsequent values
// back.
func (s *children) removeAt(index int) *node {
n := (*s)[index]
copy((*s)[index:], (*s)[index+1:])
(*s)[len(*s)-1] = nil
*s = (*s)[:len(*s)-1]
return n
}
// pop removes and returns the last element in the list.
func (s *children) pop() (out *node) {
index := len(*s) - 1
out = (*s)[index]
(*s)[index] = nil
*s = (*s)[:index]
return
}
// truncate truncates this instance at index so that it contains only the
// first index children. index must be less than or equal to length.
func (s *children) truncate(index int) {
var toClear children
*s, toClear = (*s)[:index], (*s)[index:]
for len(toClear) > 0 {
toClear = toClear[copy(toClear, nilChildren):]
}
}
// node is an internal node in a tree.
//
// It must at all times maintain the invariant that either
// * len(children) == 0, len(items) unconstrained
// * len(children) == len(items) + 1
type node struct {
items items
children children
cow *copyOnWriteContext
}
func (n *node) mutableFor(cow *copyOnWriteContext) *node {
if n.cow == cow {
return n
}
out := cow.newNode()
if cap(out.items) >= len(n.items) {
out.items = out.items[:len(n.items)]
} else {
out.items = make(items, len(n.items), cap(n.items))
}
copy(out.items, n.items)
// Copy children
if cap(out.children) >= len(n.children) {
out.children = out.children[:len(n.children)]
} else {
out.children = make(children, len(n.children), cap(n.children))
}
copy(out.children, n.children)
return out
}
func (n *node) mutableChild(i int) *node {
c := n.children[i].mutableFor(n.cow)
n.children[i] = c
return c
}
// split splits the given node at the given index. The current node shrinks,
// and this function returns the item that existed at that index and a new node
// containing all items/children after it.
func (n *node) split(i int) (Item, *node) {
item := n.items[i]
next := n.cow.newNode()
next.items = append(next.items, n.items[i+1:]...)
n.items.truncate(i)
if len(n.children) > 0 {
next.children = append(next.children, n.children[i+1:]...)
n.children.truncate(i + 1)
}
return item, next
}
// maybeSplitChild checks if a child should be split, and if so splits it.
// Returns whether or not a split occurred.
func (n *node) maybeSplitChild(i, maxItems int) bool {
if len(n.children[i].items) < maxItems {
return false
}
first := n.mutableChild(i)
item, second := first.split(maxItems / 2)
n.items.insertAt(i, item)
n.children.insertAt(i+1, second)
return true
}
// insert inserts an item into the subtree rooted at this node, making sure
// no nodes in the subtree exceed maxItems items. Should an equivalent item be
// be found/replaced by insert, it will be returned.
func (n *node) insert(item Item, maxItems int) Item {
i, found := n.items.find(item)
if found {
out := n.items[i]
n.items[i] = item
return out
}
if len(n.children) == 0 {
n.items.insertAt(i, item)
return nil
}
if n.maybeSplitChild(i, maxItems) {
inTree := n.items[i]
switch {
case item.Less(inTree):
// no change, we want first split node
case inTree.Less(item):
i++ // we want second split node
default:
out := n.items[i]
n.items[i] = item
return out
}
}
return n.mutableChild(i).insert(item, maxItems)
}
// get finds the given key in the subtree and returns it.
func (n *node) get(key Item) Item {
i, found := n.items.find(key)
if found {
return n.items[i]
} else if len(n.children) > 0 {
return n.children[i].get(key)
}
return nil
}
// min returns the first item in the subtree.
func min(n *node) Item {
if n == nil {
return nil
}
for len(n.children) > 0 {
n = n.children[0]
}
if len(n.items) == 0 {
return nil
}
return n.items[0]
}
// max returns the last item in the subtree.
func max(n *node) Item {
if n == nil {
return nil
}
for len(n.children) > 0 {
n = n.children[len(n.children)-1]
}
if len(n.items) == 0 {
return nil
}
return n.items[len(n.items)-1]
}
// toRemove details what item to remove in a node.remove call.
type toRemove int
const (
removeItem toRemove = iota // removes the given item
removeMin // removes smallest item in the subtree
removeMax // removes largest item in the subtree
)
// remove removes an item from the subtree rooted at this node.
func (n *node) remove(item Item, minItems int, typ toRemove) Item {
var i int
var found bool
switch typ {
case removeMax:
if len(n.children) == 0 {
return n.items.pop()
}
i = len(n.items)
case removeMin:
if len(n.children) == 0 {
return n.items.removeAt(0)
}
i = 0
case removeItem:
i, found = n.items.find(item)
if len(n.children) == 0 {
if found {
return n.items.removeAt(i)
}
return nil
}
default:
panic("invalid type")
}
// If we get to here, we have children.
if len(n.children[i].items) <= minItems {
return n.growChildAndRemove(i, item, minItems, typ)
}
child := n.mutableChild(i)
// Either we had enough items to begin with, or we've done some
// merging/stealing, because we've got enough now and we're ready to return
// stuff.
if found {
// The item exists at index 'i', and the child we've selected can give us a
// predecessor, since if we've gotten here it's got > minItems items in it.
out := n.items[i]
// We use our special-case 'remove' call with typ=maxItem to pull the
// predecessor of item i (the rightmost leaf of our immediate left child)
// and set it into where we pulled the item from.
n.items[i] = child.remove(nil, minItems, removeMax)
return out
}
// Final recursive call. Once we're here, we know that the item isn't in this
// node and that the child is big enough to remove from.
return child.remove(item, minItems, typ)
}
// growChildAndRemove grows child 'i' to make sure it's possible to remove an
// item from it while keeping it at minItems, then calls remove to actually
// remove it.
//
// Most documentation says we have to do two sets of special casing:
// 1) item is in this node
// 2) item is in child
// In both cases, we need to handle the two subcases:
// A) node has enough values that it can spare one
// B) node doesn't have enough values
// For the latter, we have to check:
// a) left sibling has node to spare
// b) right sibling has node to spare
// c) we must merge
// To simplify our code here, we handle cases #1 and #2 the same:
// If a node doesn't have enough items, we make sure it does (using a,b,c).
// We then simply redo our remove call, and the second time (regardless of
// whether we're in case 1 or 2), we'll have enough items and can guarantee
// that we hit case A.
func (n *node) growChildAndRemove(i int, item Item, minItems int, typ toRemove) Item {
if i > 0 && len(n.children[i-1].items) > minItems {
// Steal from left child
child := n.mutableChild(i)
stealFrom := n.mutableChild(i - 1)
stolenItem := stealFrom.items.pop()
child.items.insertAt(0, n.items[i-1])
n.items[i-1] = stolenItem
if len(stealFrom.children) > 0 {
child.children.insertAt(0, stealFrom.children.pop())
}
} else if i < len(n.items) && len(n.children[i+1].items) > minItems {
// steal from right child
child := n.mutableChild(i)
stealFrom := n.mutableChild(i + 1)
stolenItem := stealFrom.items.removeAt(0)
child.items = append(child.items, n.items[i])
n.items[i] = stolenItem
if len(stealFrom.children) > 0 {
child.children = append(child.children, stealFrom.children.removeAt(0))
}
} else {
if i >= len(n.items) {
i--
}
child := n.mutableChild(i)
// merge with right child
mergeItem := n.items.removeAt(i)
mergeChild := n.children.removeAt(i + 1)
child.items = append(child.items, mergeItem)
child.items = append(child.items, mergeChild.items...)
child.children = append(child.children, mergeChild.children...)
n.cow.freeNode(mergeChild)
}
return n.remove(item, minItems, typ)
}
type direction int
const (
descend = direction(-1)
ascend = direction(+1)
)
// iterate provides a simple method for iterating over elements in the tree.
//
// When ascending, the 'start' should be less than 'stop' and when descending,
// the 'start' should be greater than 'stop'. Setting 'includeStart' to true
// will force the iterator to include the first item when it equals 'start',
// thus creating a "greaterOrEqual" or "lessThanEqual" rather than just a
// "greaterThan" or "lessThan" queries.
func (n *node) iterate(dir direction, start, stop Item, includeStart bool, hit bool, iter ItemIterator) (bool, bool) {
var ok, found bool
var index int
switch dir {
case ascend:
if start != nil {
index, _ = n.items.find(start)
}
for i := index; i < len(n.items); i++ {
if len(n.children) > 0 {
if hit, ok = n.children[i].iterate(dir, start, stop, includeStart, hit, iter); !ok {
return hit, false
}
}
if !includeStart && !hit && start != nil && !start.Less(n.items[i]) {
hit = true
continue
}
hit = true
if stop != nil && !n.items[i].Less(stop) {
return hit, false
}
if !iter(n.items[i]) {
return hit, false
}
}
if len(n.children) > 0 {
if hit, ok = n.children[len(n.children)-1].iterate(dir, start, stop, includeStart, hit, iter); !ok {
return hit, false
}
}
case descend:
if start != nil {
index, found = n.items.find(start)
if !found {
index = index - 1
}
} else {
index = len(n.items) - 1
}
for i := index; i >= 0; i-- {
if start != nil && !n.items[i].Less(start) {
if !includeStart || hit || start.Less(n.items[i]) {
continue
}
}
if len(n.children) > 0 {
if hit, ok = n.children[i+1].iterate(dir, start, stop, includeStart, hit, iter); !ok {
return hit, false
}
}
if stop != nil && !stop.Less(n.items[i]) {
return hit, false // continue
}
hit = true
if !iter(n.items[i]) {
return hit, false
}
}
if len(n.children) > 0 {
if hit, ok = n.children[0].iterate(dir, start, stop, includeStart, hit, iter); !ok {
return hit, false
}
}
}
return hit, true
}
// Used for testing/debugging purposes.
func (n *node) print(w io.Writer, level int) {
fmt.Fprintf(w, "%sNODE:%v\n", strings.Repeat(" ", level), n.items)
for _, c := range n.children {
c.print(w, level+1)
}
}
// BTree is an implementation of a B-Tree.
//
// BTree stores Item instances in an ordered structure, allowing easy insertion,
// removal, and iteration.
//
// Write operations are not safe for concurrent mutation by multiple
// goroutines, but Read operations are.
type BTree struct {
degree int
length int
root *node
cow *copyOnWriteContext
}
// copyOnWriteContext pointers determine node ownership... a tree with a write
// context equivalent to a node's write context is allowed to modify that node.
// A tree whose write context does not match a node's is not allowed to modify
// it, and must create a new, writable copy (IE: it's a Clone).
//
// When doing any write operation, we maintain the invariant that the current
// node's context is equal to the context of the tree that requested the write.
// We do this by, before we descend into any node, creating a copy with the
// correct context if the contexts don't match.
//
// Since the node we're currently visiting on any write has the requesting
// tree's context, that node is modifiable in place. Children of that node may
// not share context, but before we descend into them, we'll make a mutable
// copy.
type copyOnWriteContext struct {
freelist *FreeList
}
// Clone clones the btree, lazily. Clone should not be called concurrently,
// but the original tree (t) and the new tree (t2) can be used concurrently
// once the Clone call completes.
//
// The internal tree structure of b is marked read-only and shared between t and
// t2. Writes to both t and t2 use copy-on-write logic, creating new nodes
// whenever one of b's original nodes would have been modified. Read operations
// should have no performance degredation. Write operations for both t and t2
// will initially experience minor slow-downs caused by additional allocs and
// copies due to the aforementioned copy-on-write logic, but should converge to
// the original performance characteristics of the original tree.
func (t *BTree) Clone() (t2 *BTree) {
// Create two entirely new copy-on-write contexts.
// This operation effectively creates three trees:
// the original, shared nodes (old b.cow)
// the new b.cow nodes
// the new out.cow nodes
cow1, cow2 := *t.cow, *t.cow
out := *t
t.cow = &cow1
out.cow = &cow2
return &out
}
// maxItems returns the max number of items to allow per node.
func (t *BTree) maxItems() int {
return t.degree*2 - 1
}
// minItems returns the min number of items to allow per node (ignored for the
// root node).
func (t *BTree) minItems() int {
return t.degree - 1
}
func (c *copyOnWriteContext) newNode() (n *node) {
n = c.freelist.newNode()
n.cow = c
return
}
type freeType int
const (
ftFreelistFull freeType = iota // node was freed (available for GC, not stored in freelist)
ftStored // node was stored in the freelist for later use
ftNotOwned // node was ignored by COW, since it's owned by another one
)
// freeNode frees a node within a given COW context, if it's owned by that
// context. It returns what happened to the node (see freeType const
// documentation).
func (c *copyOnWriteContext) freeNode(n *node) freeType {
if n.cow == c {
// clear to allow GC
n.items.truncate(0)
n.children.truncate(0)
n.cow = nil
if c.freelist.freeNode(n) {
return ftStored
} else {
return ftFreelistFull
}
} else {
return ftNotOwned
}
}
// ReplaceOrInsert adds the given item to the tree. If an item in the tree
// already equals the given one, it is removed from the tree and returned.
// Otherwise, nil is returned.
//
// nil cannot be added to the tree (will panic).
func (t *BTree) ReplaceOrInsert(item Item) Item {
if item == nil {
panic("nil item being added to BTree")
}
if t.root == nil {
t.root = t.cow.newNode()
t.root.items = append(t.root.items, item)
t.length++
return nil
} else {
t.root = t.root.mutableFor(t.cow)
if len(t.root.items) >= t.maxItems() {
item2, second := t.root.split(t.maxItems() / 2)
oldroot := t.root
t.root = t.cow.newNode()
t.root.items = append(t.root.items, item2)
t.root.children = append(t.root.children, oldroot, second)
}
}
out := t.root.insert(item, t.maxItems())
if out == nil {
t.length++
}
return out
}
// Delete removes an item equal to the passed in item from the tree, returning
// it. If no such item exists, returns nil.
func (t *BTree) Delete(item Item) Item {
return t.deleteItem(item, removeItem)
}
// DeleteMin removes the smallest item in the tree and returns it.
// If no such item exists, returns nil.
func (t *BTree) DeleteMin() Item {
return t.deleteItem(nil, removeMin)
}
// DeleteMax removes the largest item in the tree and returns it.
// If no such item exists, returns nil.
func (t *BTree) DeleteMax() Item {
return t.deleteItem(nil, removeMax)
}
func (t *BTree) deleteItem(item Item, typ toRemove) Item {
if t.root == nil || len(t.root.items) == 0 {
return nil
}
t.root = t.root.mutableFor(t.cow)
out := t.root.remove(item, t.minItems(), typ)
if len(t.root.items) == 0 && len(t.root.children) > 0 {
oldroot := t.root
t.root = t.root.children[0]
t.cow.freeNode(oldroot)
}
if out != nil {
t.length--
}
return out
}
// AscendRange calls the iterator for every value in the tree within the range
// [greaterOrEqual, lessThan), until iterator returns false.
func (t *BTree) AscendRange(greaterOrEqual, lessThan Item, iterator ItemIterator) {
if t.root == nil {
return
}
t.root.iterate(ascend, greaterOrEqual, lessThan, true, false, iterator)
}
// AscendLessThan calls the iterator for every value in the tree within the range
// [first, pivot), until iterator returns false.
func (t *BTree) AscendLessThan(pivot Item, iterator ItemIterator) {
if t.root == nil {
return
}
t.root.iterate(ascend, nil, pivot, false, false, iterator)
}
// AscendGreaterOrEqual calls the iterator for every value in the tree within
// the range [pivot, last], until iterator returns false.
func (t *BTree) AscendGreaterOrEqual(pivot Item, iterator ItemIterator) {
if t.root == nil {
return
}
t.root.iterate(ascend, pivot, nil, true, false, iterator)
}
// Ascend calls the iterator for every value in the tree within the range
// [first, last], until iterator returns false.
func (t *BTree) Ascend(iterator ItemIterator) {
if t.root == nil {
return
}
t.root.iterate(ascend, nil, nil, false, false, iterator)
}
// DescendRange calls the iterator for every value in the tree within the range
// [lessOrEqual, greaterThan), until iterator returns false.
func (t *BTree) DescendRange(lessOrEqual, greaterThan Item, iterator ItemIterator) {
if t.root == nil {
return
}
t.root.iterate(descend, lessOrEqual, greaterThan, true, false, iterator)
}
// DescendLessOrEqual calls the iterator for every value in the tree within the range
// [pivot, first], until iterator returns false.
func (t *BTree) DescendLessOrEqual(pivot Item, iterator ItemIterator) {
if t.root == nil {
return
}
t.root.iterate(descend, pivot, nil, true, false, iterator)
}
// DescendGreaterThan calls the iterator for every value in the tree within
// the range (pivot, last], until iterator returns false.
func (t *BTree) DescendGreaterThan(pivot Item, iterator ItemIterator) {
if t.root == nil {
return
}
t.root.iterate(descend, nil, pivot, false, false, iterator)
}
// Descend calls the iterator for every value in the tree within the range
// [last, first], until iterator returns false.
func (t *BTree) Descend(iterator ItemIterator) {
if t.root == nil {
return
}
t.root.iterate(descend, nil, nil, false, false, iterator)
}
// Get looks for the key item in the tree, returning it. It returns nil if
// unable to find that item.
func (t *BTree) Get(key Item) Item {
if t.root == nil {
return nil
}
return t.root.get(key)
}
// Min returns the smallest item in the tree, or nil if the tree is empty.
func (t *BTree) Min() Item {
return min(t.root)
}
// Max returns the largest item in the tree, or nil if the tree is empty.
func (t *BTree) Max() Item {
return max(t.root)
}
// Has returns true if the given key is in the tree.
func (t *BTree) Has(key Item) bool {
return t.Get(key) != nil
}
// Len returns the number of items currently in the tree.
func (t *BTree) Len() int {
return t.length
}
// Clear removes all items from the btree. If addNodesToFreelist is true,
// t's nodes are added to its freelist as part of this call, until the freelist
// is full. Otherwise, the root node is simply dereferenced and the subtree
// left to Go's normal GC processes.
//
// This can be much faster
// than calling Delete on all elements, because that requires finding/removing
// each element in the tree and updating the tree accordingly. It also is
// somewhat faster than creating a new tree to replace the old one, because
// nodes from the old tree are reclaimed into the freelist for use by the new
// one, instead of being lost to the garbage collector.
//
// This call takes:
// O(1): when addNodesToFreelist is false, this is a single operation.
// O(1): when the freelist is already full, it breaks out immediately
// O(freelist size): when the freelist is empty and the nodes are all owned
// by this tree, nodes are added to the freelist until full.
// O(tree size): when all nodes are owned by another tree, all nodes are
// iterated over looking for nodes to add to the freelist, and due to
// ownership, none are.
func (t *BTree) Clear(addNodesToFreelist bool) {
if t.root != nil && addNodesToFreelist {
t.root.reset(t.cow)
}
t.root, t.length = nil, 0
}
// reset returns a subtree to the freelist. It breaks out immediately if the
// freelist is full, since the only benefit of iterating is to fill that
// freelist up. Returns true if parent reset call should continue.
func (n *node) reset(c *copyOnWriteContext) bool {
for _, child := range n.children {
if !child.reset(c) {
return false
}
}
return c.freeNode(n) != ftFreelistFull
}
// Int implements the Item interface for integers.
type Int int
// Less returns true if int(a) < int(b).
func (a Int) Less(b Item) bool {
return a < b.(Int)
}

76
vendor/github.com/google/btree/btree_mem.go generated vendored Normal file
View File

@ -0,0 +1,76 @@
// Copyright 2014 Google Inc.
//
// 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.
// +build ignore
// This binary compares memory usage between btree and gollrb.
package main
import (
"flag"
"fmt"
"math/rand"
"runtime"
"time"
"github.com/google/btree"
"github.com/petar/GoLLRB/llrb"
)
var (
size = flag.Int("size", 1000000, "size of the tree to build")
degree = flag.Int("degree", 8, "degree of btree")
gollrb = flag.Bool("llrb", false, "use llrb instead of btree")
)
func main() {
flag.Parse()
vals := rand.Perm(*size)
var t, v interface{}
v = vals
var stats runtime.MemStats
for i := 0; i < 10; i++ {
runtime.GC()
}
fmt.Println("-------- BEFORE ----------")
runtime.ReadMemStats(&stats)
fmt.Printf("%+v\n", stats)
start := time.Now()
if *gollrb {
tr := llrb.New()
for _, v := range vals {
tr.ReplaceOrInsert(llrb.Int(v))
}
t = tr // keep it around
} else {
tr := btree.New(*degree)
for _, v := range vals {
tr.ReplaceOrInsert(btree.Int(v))
}
t = tr // keep it around
}
fmt.Printf("%v inserts in %v\n", *size, time.Since(start))
fmt.Println("-------- AFTER ----------")
runtime.ReadMemStats(&stats)
fmt.Printf("%+v\n", stats)
for i := 0; i < 10; i++ {
runtime.GC()
}
fmt.Println("-------- AFTER GC ----------")
runtime.ReadMemStats(&stats)
fmt.Printf("%+v\n", stats)
if t == v {
fmt.Println("to make sure vals and tree aren't GC'd")
}
}

785
vendor/github.com/google/btree/btree_test.go generated vendored Normal file
View File

@ -0,0 +1,785 @@
// Copyright 2014 Google Inc.
//
// 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 btree
import (
"flag"
"fmt"
"math/rand"
"reflect"
"sort"
"sync"
"testing"
"time"
)
func init() {
seed := time.Now().Unix()
fmt.Println(seed)
rand.Seed(seed)
}
// perm returns a random permutation of n Int items in the range [0, n).
func perm(n int) (out []Item) {
for _, v := range rand.Perm(n) {
out = append(out, Int(v))
}
return
}
// rang returns an ordered list of Int items in the range [0, n).
func rang(n int) (out []Item) {
for i := 0; i < n; i++ {
out = append(out, Int(i))
}
return
}
// all extracts all items from a tree in order as a slice.
func all(t *BTree) (out []Item) {
t.Ascend(func(a Item) bool {
out = append(out, a)
return true
})
return
}
// rangerev returns a reversed ordered list of Int items in the range [0, n).
func rangrev(n int) (out []Item) {
for i := n - 1; i >= 0; i-- {
out = append(out, Int(i))
}
return
}
// allrev extracts all items from a tree in reverse order as a slice.
func allrev(t *BTree) (out []Item) {
t.Descend(func(a Item) bool {
out = append(out, a)
return true
})
return
}
var btreeDegree = flag.Int("degree", 32, "B-Tree degree")
func TestBTree(t *testing.T) {
tr := New(*btreeDegree)
const treeSize = 10000
for i := 0; i < 10; i++ {
if min := tr.Min(); min != nil {
t.Fatalf("empty min, got %+v", min)
}
if max := tr.Max(); max != nil {
t.Fatalf("empty max, got %+v", max)
}
for _, item := range perm(treeSize) {
if x := tr.ReplaceOrInsert(item); x != nil {
t.Fatal("insert found item", item)
}
}
for _, item := range perm(treeSize) {
if x := tr.ReplaceOrInsert(item); x == nil {
t.Fatal("insert didn't find item", item)
}
}
if min, want := tr.Min(), Item(Int(0)); min != want {
t.Fatalf("min: want %+v, got %+v", want, min)
}
if max, want := tr.Max(), Item(Int(treeSize-1)); max != want {
t.Fatalf("max: want %+v, got %+v", want, max)
}
got := all(tr)
want := rang(treeSize)
if !reflect.DeepEqual(got, want) {
t.Fatalf("mismatch:\n got: %v\nwant: %v", got, want)
}
gotrev := allrev(tr)
wantrev := rangrev(treeSize)
if !reflect.DeepEqual(gotrev, wantrev) {
t.Fatalf("mismatch:\n got: %v\nwant: %v", got, want)
}
for _, item := range perm(treeSize) {
if x := tr.Delete(item); x == nil {
t.Fatalf("didn't find %v", item)
}
}
if got = all(tr); len(got) > 0 {
t.Fatalf("some left!: %v", got)
}
}
}
func ExampleBTree() {
tr := New(*btreeDegree)
for i := Int(0); i < 10; i++ {
tr.ReplaceOrInsert(i)
}
fmt.Println("len: ", tr.Len())
fmt.Println("get3: ", tr.Get(Int(3)))
fmt.Println("get100: ", tr.Get(Int(100)))
fmt.Println("del4: ", tr.Delete(Int(4)))
fmt.Println("del100: ", tr.Delete(Int(100)))
fmt.Println("replace5: ", tr.ReplaceOrInsert(Int(5)))
fmt.Println("replace100:", tr.ReplaceOrInsert(Int(100)))
fmt.Println("min: ", tr.Min())
fmt.Println("delmin: ", tr.DeleteMin())
fmt.Println("max: ", tr.Max())
fmt.Println("delmax: ", tr.DeleteMax())
fmt.Println("len: ", tr.Len())
// Output:
// len: 10
// get3: 3
// get100: <nil>
// del4: 4
// del100: <nil>
// replace5: 5
// replace100: <nil>
// min: 0
// delmin: 0
// max: 100
// delmax: 100
// len: 8
}
func TestDeleteMin(t *testing.T) {
tr := New(3)
for _, v := range perm(100) {
tr.ReplaceOrInsert(v)
}
var got []Item
for v := tr.DeleteMin(); v != nil; v = tr.DeleteMin() {
got = append(got, v)
}
if want := rang(100); !reflect.DeepEqual(got, want) {
t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want)
}
}
func TestDeleteMax(t *testing.T) {
tr := New(3)
for _, v := range perm(100) {
tr.ReplaceOrInsert(v)
}
var got []Item
for v := tr.DeleteMax(); v != nil; v = tr.DeleteMax() {
got = append(got, v)
}
// Reverse our list.
for i := 0; i < len(got)/2; i++ {
got[i], got[len(got)-i-1] = got[len(got)-i-1], got[i]
}
if want := rang(100); !reflect.DeepEqual(got, want) {
t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want)
}
}
func TestAscendRange(t *testing.T) {
tr := New(2)
for _, v := range perm(100) {
tr.ReplaceOrInsert(v)
}
var got []Item
tr.AscendRange(Int(40), Int(60), func(a Item) bool {
got = append(got, a)
return true
})
if want := rang(100)[40:60]; !reflect.DeepEqual(got, want) {
t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want)
}
got = got[:0]
tr.AscendRange(Int(40), Int(60), func(a Item) bool {
if a.(Int) > 50 {
return false
}
got = append(got, a)
return true
})
if want := rang(100)[40:51]; !reflect.DeepEqual(got, want) {
t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want)
}
}
func TestDescendRange(t *testing.T) {
tr := New(2)
for _, v := range perm(100) {
tr.ReplaceOrInsert(v)
}
var got []Item
tr.DescendRange(Int(60), Int(40), func(a Item) bool {
got = append(got, a)
return true
})
if want := rangrev(100)[39:59]; !reflect.DeepEqual(got, want) {
t.Fatalf("descendrange:\n got: %v\nwant: %v", got, want)
}
got = got[:0]
tr.DescendRange(Int(60), Int(40), func(a Item) bool {
if a.(Int) < 50 {
return false
}
got = append(got, a)
return true
})
if want := rangrev(100)[39:50]; !reflect.DeepEqual(got, want) {
t.Fatalf("descendrange:\n got: %v\nwant: %v", got, want)
}
}
func TestAscendLessThan(t *testing.T) {
tr := New(*btreeDegree)
for _, v := range perm(100) {
tr.ReplaceOrInsert(v)
}
var got []Item
tr.AscendLessThan(Int(60), func(a Item) bool {
got = append(got, a)
return true
})
if want := rang(100)[:60]; !reflect.DeepEqual(got, want) {
t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want)
}
got = got[:0]
tr.AscendLessThan(Int(60), func(a Item) bool {
if a.(Int) > 50 {
return false
}
got = append(got, a)
return true
})
if want := rang(100)[:51]; !reflect.DeepEqual(got, want) {
t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want)
}
}
func TestDescendLessOrEqual(t *testing.T) {
tr := New(*btreeDegree)
for _, v := range perm(100) {
tr.ReplaceOrInsert(v)
}
var got []Item
tr.DescendLessOrEqual(Int(40), func(a Item) bool {
got = append(got, a)
return true
})
if want := rangrev(100)[59:]; !reflect.DeepEqual(got, want) {
t.Fatalf("descendlessorequal:\n got: %v\nwant: %v", got, want)
}
got = got[:0]
tr.DescendLessOrEqual(Int(60), func(a Item) bool {
if a.(Int) < 50 {
return false
}
got = append(got, a)
return true
})
if want := rangrev(100)[39:50]; !reflect.DeepEqual(got, want) {
t.Fatalf("descendlessorequal:\n got: %v\nwant: %v", got, want)
}
}
func TestAscendGreaterOrEqual(t *testing.T) {
tr := New(*btreeDegree)
for _, v := range perm(100) {
tr.ReplaceOrInsert(v)
}
var got []Item
tr.AscendGreaterOrEqual(Int(40), func(a Item) bool {
got = append(got, a)
return true
})
if want := rang(100)[40:]; !reflect.DeepEqual(got, want) {
t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want)
}
got = got[:0]
tr.AscendGreaterOrEqual(Int(40), func(a Item) bool {
if a.(Int) > 50 {
return false
}
got = append(got, a)
return true
})
if want := rang(100)[40:51]; !reflect.DeepEqual(got, want) {
t.Fatalf("ascendrange:\n got: %v\nwant: %v", got, want)
}
}
func TestDescendGreaterThan(t *testing.T) {
tr := New(*btreeDegree)
for _, v := range perm(100) {
tr.ReplaceOrInsert(v)
}
var got []Item
tr.DescendGreaterThan(Int(40), func(a Item) bool {
got = append(got, a)
return true
})
if want := rangrev(100)[:59]; !reflect.DeepEqual(got, want) {
t.Fatalf("descendgreaterthan:\n got: %v\nwant: %v", got, want)
}
got = got[:0]
tr.DescendGreaterThan(Int(40), func(a Item) bool {
if a.(Int) < 50 {
return false
}
got = append(got, a)
return true
})
if want := rangrev(100)[:50]; !reflect.DeepEqual(got, want) {
t.Fatalf("descendgreaterthan:\n got: %v\nwant: %v", got, want)
}
}
const benchmarkTreeSize = 10000
func BenchmarkInsert(b *testing.B) {
b.StopTimer()
insertP := perm(benchmarkTreeSize)
b.StartTimer()
i := 0
for i < b.N {
tr := New(*btreeDegree)
for _, item := range insertP {
tr.ReplaceOrInsert(item)
i++
if i >= b.N {
return
}
}
}
}
func BenchmarkSeek(b *testing.B) {
b.StopTimer()
size := 100000
insertP := perm(size)
tr := New(*btreeDegree)
for _, item := range insertP {
tr.ReplaceOrInsert(item)
}
b.StartTimer()
for i := 0; i < b.N; i++ {
tr.AscendGreaterOrEqual(Int(i%size), func(i Item) bool { return false })
}
}
func BenchmarkDeleteInsert(b *testing.B) {
b.StopTimer()
insertP := perm(benchmarkTreeSize)
tr := New(*btreeDegree)
for _, item := range insertP {
tr.ReplaceOrInsert(item)
}
b.StartTimer()
for i := 0; i < b.N; i++ {
tr.Delete(insertP[i%benchmarkTreeSize])
tr.ReplaceOrInsert(insertP[i%benchmarkTreeSize])
}
}
func BenchmarkDeleteInsertCloneOnce(b *testing.B) {
b.StopTimer()
insertP := perm(benchmarkTreeSize)
tr := New(*btreeDegree)
for _, item := range insertP {
tr.ReplaceOrInsert(item)
}
tr = tr.Clone()
b.StartTimer()
for i := 0; i < b.N; i++ {
tr.Delete(insertP[i%benchmarkTreeSize])
tr.ReplaceOrInsert(insertP[i%benchmarkTreeSize])
}
}
func BenchmarkDeleteInsertCloneEachTime(b *testing.B) {
b.StopTimer()
insertP := perm(benchmarkTreeSize)
tr := New(*btreeDegree)
for _, item := range insertP {
tr.ReplaceOrInsert(item)
}
b.StartTimer()
for i := 0; i < b.N; i++ {
tr = tr.Clone()
tr.Delete(insertP[i%benchmarkTreeSize])
tr.ReplaceOrInsert(insertP[i%benchmarkTreeSize])
}
}
func BenchmarkDelete(b *testing.B) {
b.StopTimer()
insertP := perm(benchmarkTreeSize)
removeP := perm(benchmarkTreeSize)
b.StartTimer()
i := 0
for i < b.N {
b.StopTimer()
tr := New(*btreeDegree)
for _, v := range insertP {
tr.ReplaceOrInsert(v)
}
b.StartTimer()
for _, item := range removeP {
tr.Delete(item)
i++
if i >= b.N {
return
}
}
if tr.Len() > 0 {
panic(tr.Len())
}
}
}
func BenchmarkGet(b *testing.B) {
b.StopTimer()
insertP := perm(benchmarkTreeSize)
removeP := perm(benchmarkTreeSize)
b.StartTimer()
i := 0
for i < b.N {
b.StopTimer()
tr := New(*btreeDegree)
for _, v := range insertP {
tr.ReplaceOrInsert(v)
}
b.StartTimer()
for _, item := range removeP {
tr.Get(item)
i++
if i >= b.N {
return
}
}
}
}
func BenchmarkGetCloneEachTime(b *testing.B) {
b.StopTimer()
insertP := perm(benchmarkTreeSize)
removeP := perm(benchmarkTreeSize)
b.StartTimer()
i := 0
for i < b.N {
b.StopTimer()
tr := New(*btreeDegree)
for _, v := range insertP {
tr.ReplaceOrInsert(v)
}
b.StartTimer()
for _, item := range removeP {
tr = tr.Clone()
tr.Get(item)
i++
if i >= b.N {
return
}
}
}
}
type byInts []Item
func (a byInts) Len() int {
return len(a)
}
func (a byInts) Less(i, j int) bool {
return a[i].(Int) < a[j].(Int)
}
func (a byInts) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func BenchmarkAscend(b *testing.B) {
arr := perm(benchmarkTreeSize)
tr := New(*btreeDegree)
for _, v := range arr {
tr.ReplaceOrInsert(v)
}
sort.Sort(byInts(arr))
b.ResetTimer()
for i := 0; i < b.N; i++ {
j := 0
tr.Ascend(func(item Item) bool {
if item.(Int) != arr[j].(Int) {
b.Fatalf("mismatch: expected: %v, got %v", arr[j].(Int), item.(Int))
}
j++
return true
})
}
}
func BenchmarkDescend(b *testing.B) {
arr := perm(benchmarkTreeSize)
tr := New(*btreeDegree)
for _, v := range arr {
tr.ReplaceOrInsert(v)
}
sort.Sort(byInts(arr))
b.ResetTimer()
for i := 0; i < b.N; i++ {
j := len(arr) - 1
tr.Descend(func(item Item) bool {
if item.(Int) != arr[j].(Int) {
b.Fatalf("mismatch: expected: %v, got %v", arr[j].(Int), item.(Int))
}
j--
return true
})
}
}
func BenchmarkAscendRange(b *testing.B) {
arr := perm(benchmarkTreeSize)
tr := New(*btreeDegree)
for _, v := range arr {
tr.ReplaceOrInsert(v)
}
sort.Sort(byInts(arr))
b.ResetTimer()
for i := 0; i < b.N; i++ {
j := 100
tr.AscendRange(Int(100), arr[len(arr)-100], func(item Item) bool {
if item.(Int) != arr[j].(Int) {
b.Fatalf("mismatch: expected: %v, got %v", arr[j].(Int), item.(Int))
}
j++
return true
})
if j != len(arr)-100 {
b.Fatalf("expected: %v, got %v", len(arr)-100, j)
}
}
}
func BenchmarkDescendRange(b *testing.B) {
arr := perm(benchmarkTreeSize)
tr := New(*btreeDegree)
for _, v := range arr {
tr.ReplaceOrInsert(v)
}
sort.Sort(byInts(arr))
b.ResetTimer()
for i := 0; i < b.N; i++ {
j := len(arr) - 100
tr.DescendRange(arr[len(arr)-100], Int(100), func(item Item) bool {
if item.(Int) != arr[j].(Int) {
b.Fatalf("mismatch: expected: %v, got %v", arr[j].(Int), item.(Int))
}
j--
return true
})
if j != 100 {
b.Fatalf("expected: %v, got %v", len(arr)-100, j)
}
}
}
func BenchmarkAscendGreaterOrEqual(b *testing.B) {
arr := perm(benchmarkTreeSize)
tr := New(*btreeDegree)
for _, v := range arr {
tr.ReplaceOrInsert(v)
}
sort.Sort(byInts(arr))
b.ResetTimer()
for i := 0; i < b.N; i++ {
j := 100
k := 0
tr.AscendGreaterOrEqual(Int(100), func(item Item) bool {
if item.(Int) != arr[j].(Int) {
b.Fatalf("mismatch: expected: %v, got %v", arr[j].(Int), item.(Int))
}
j++
k++
return true
})
if j != len(arr) {
b.Fatalf("expected: %v, got %v", len(arr), j)
}
if k != len(arr)-100 {
b.Fatalf("expected: %v, got %v", len(arr)-100, k)
}
}
}
func BenchmarkDescendLessOrEqual(b *testing.B) {
arr := perm(benchmarkTreeSize)
tr := New(*btreeDegree)
for _, v := range arr {
tr.ReplaceOrInsert(v)
}
sort.Sort(byInts(arr))
b.ResetTimer()
for i := 0; i < b.N; i++ {
j := len(arr) - 100
k := len(arr)
tr.DescendLessOrEqual(arr[len(arr)-100], func(item Item) bool {
if item.(Int) != arr[j].(Int) {
b.Fatalf("mismatch: expected: %v, got %v", arr[j].(Int), item.(Int))
}
j--
k--
return true
})
if j != -1 {
b.Fatalf("expected: %v, got %v", -1, j)
}
if k != 99 {
b.Fatalf("expected: %v, got %v", 99, k)
}
}
}
const cloneTestSize = 10000
func cloneTest(t *testing.T, b *BTree, start int, p []Item, wg *sync.WaitGroup, trees *[]*BTree) {
t.Logf("Starting new clone at %v", start)
*trees = append(*trees, b)
for i := start; i < cloneTestSize; i++ {
b.ReplaceOrInsert(p[i])
if i%(cloneTestSize/5) == 0 {
wg.Add(1)
go cloneTest(t, b.Clone(), i+1, p, wg, trees)
}
}
wg.Done()
}
func TestCloneConcurrentOperations(t *testing.T) {
b := New(*btreeDegree)
trees := []*BTree{}
p := perm(cloneTestSize)
var wg sync.WaitGroup
wg.Add(1)
go cloneTest(t, b, 0, p, &wg, &trees)
wg.Wait()
want := rang(cloneTestSize)
t.Logf("Starting equality checks on %d trees", len(trees))
for i, tree := range trees {
if !reflect.DeepEqual(want, all(tree)) {
t.Errorf("tree %v mismatch", i)
}
}
t.Log("Removing half from first half")
toRemove := rang(cloneTestSize)[cloneTestSize/2:]
for i := 0; i < len(trees)/2; i++ {
tree := trees[i]
wg.Add(1)
go func() {
for _, item := range toRemove {
tree.Delete(item)
}
wg.Done()
}()
}
wg.Wait()
t.Log("Checking all values again")
for i, tree := range trees {
var wantpart []Item
if i < len(trees)/2 {
wantpart = want[:cloneTestSize/2]
} else {
wantpart = want
}
if got := all(tree); !reflect.DeepEqual(wantpart, got) {
t.Errorf("tree %v mismatch, want %v got %v", i, len(want), len(got))
}
}
}
func BenchmarkDeleteAndRestore(b *testing.B) {
items := perm(16392)
b.ResetTimer()
b.Run(`CopyBigFreeList`, func(b *testing.B) {
fl := NewFreeList(16392)
tr := NewWithFreeList(*btreeDegree, fl)
for _, v := range items {
tr.ReplaceOrInsert(v)
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
dels := make([]Item, 0, tr.Len())
tr.Ascend(ItemIterator(func(b Item) bool {
dels = append(dels, b)
return true
}))
for _, del := range dels {
tr.Delete(del)
}
// tr is now empty, we make a new empty copy of it.
tr = NewWithFreeList(*btreeDegree, fl)
for _, v := range items {
tr.ReplaceOrInsert(v)
}
}
})
b.Run(`Copy`, func(b *testing.B) {
tr := New(*btreeDegree)
for _, v := range items {
tr.ReplaceOrInsert(v)
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
dels := make([]Item, 0, tr.Len())
tr.Ascend(ItemIterator(func(b Item) bool {
dels = append(dels, b)
return true
}))
for _, del := range dels {
tr.Delete(del)
}
// tr is now empty, we make a new empty copy of it.
tr = New(*btreeDegree)
for _, v := range items {
tr.ReplaceOrInsert(v)
}
}
})
b.Run(`ClearBigFreelist`, func(b *testing.B) {
fl := NewFreeList(16392)
tr := NewWithFreeList(*btreeDegree, fl)
for _, v := range items {
tr.ReplaceOrInsert(v)
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
tr.Clear(true)
for _, v := range items {
tr.ReplaceOrInsert(v)
}
}
})
b.Run(`Clear`, func(b *testing.B) {
tr := New(*btreeDegree)
for _, v := range items {
tr.ReplaceOrInsert(v)
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
tr.Clear(true)
for _, v := range items {
tr.ReplaceOrInsert(v)
}
}
})
}

19
vendor/github.com/gregjones/httpcache/.travis.yml generated vendored Normal file
View File

@ -0,0 +1,19 @@
sudo: false
language: go
go:
- 1.6.x
- 1.7.x
- 1.8.x
- 1.9.x
- master
matrix:
allow_failures:
- go: master
fast_finish: true
install:
- # Do nothing. This is needed to prevent default install action "go get -t -v ./..." from happening here (we want it to happen inside script step).
script:
- go get -t -v ./...
- diff -u <(echo -n) <(gofmt -d .)
- go tool vet .
- go test -v -race ./...

7
vendor/github.com/gregjones/httpcache/LICENSE.txt generated vendored Normal file
View File

@ -0,0 +1,7 @@
Copyright © 2012 Greg Jones (greg.jones@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.

25
vendor/github.com/gregjones/httpcache/README.md generated vendored Normal file
View File

@ -0,0 +1,25 @@
httpcache
=========
[![Build Status](https://travis-ci.org/gregjones/httpcache.svg?branch=master)](https://travis-ci.org/gregjones/httpcache) [![GoDoc](https://godoc.org/github.com/gregjones/httpcache?status.svg)](https://godoc.org/github.com/gregjones/httpcache)
Package httpcache provides a http.RoundTripper implementation that works as a mostly [RFC 7234](https://tools.ietf.org/html/rfc7234) compliant cache for http responses.
It is only suitable for use as a 'private' cache (i.e. for a web-browser or an API-client and not for a shared proxy).
Cache Backends
--------------
- The built-in 'memory' cache stores responses in an in-memory map.
- [`github.com/gregjones/httpcache/diskcache`](https://github.com/gregjones/httpcache/tree/master/diskcache) provides a filesystem-backed cache using the [diskv](https://github.com/peterbourgon/diskv) library.
- [`github.com/gregjones/httpcache/memcache`](https://github.com/gregjones/httpcache/tree/master/memcache) provides memcache implementations, for both App Engine and 'normal' memcache servers.
- [`sourcegraph.com/sourcegraph/s3cache`](https://sourcegraph.com/github.com/sourcegraph/s3cache) uses Amazon S3 for storage.
- [`github.com/gregjones/httpcache/leveldbcache`](https://github.com/gregjones/httpcache/tree/master/leveldbcache) provides a filesystem-backed cache using [leveldb](https://github.com/syndtr/goleveldb/leveldb).
- [`github.com/die-net/lrucache`](https://github.com/die-net/lrucache) provides an in-memory cache that will evict least-recently used entries.
- [`github.com/die-net/lrucache/twotier`](https://github.com/die-net/lrucache/tree/master/twotier) allows caches to be combined, for example to use lrucache above with a persistent disk-cache.
- [`github.com/birkelund/boltdbcache`](https://github.com/birkelund/boltdbcache) provides a BoltDB implementation (based on the [bbolt](https://github.com/coreos/bbolt) fork).
License
-------
- [MIT License](LICENSE.txt)

View File

@ -0,0 +1,61 @@
// Package diskcache provides an implementation of httpcache.Cache that uses the diskv package
// to supplement an in-memory map with persistent storage
//
package diskcache
import (
"bytes"
"crypto/md5"
"encoding/hex"
"github.com/peterbourgon/diskv"
"io"
)
// Cache is an implementation of httpcache.Cache that supplements the in-memory map with persistent storage
type Cache struct {
d *diskv.Diskv
}
// Get returns the response corresponding to key if present
func (c *Cache) Get(key string) (resp []byte, ok bool) {
key = keyToFilename(key)
resp, err := c.d.Read(key)
if err != nil {
return []byte{}, false
}
return resp, true
}
// Set saves a response to the cache as key
func (c *Cache) Set(key string, resp []byte) {
key = keyToFilename(key)
c.d.WriteStream(key, bytes.NewReader(resp), true)
}
// Delete removes the response with key from the cache
func (c *Cache) Delete(key string) {
key = keyToFilename(key)
c.d.Erase(key)
}
func keyToFilename(key string) string {
h := md5.New()
io.WriteString(h, key)
return hex.EncodeToString(h.Sum(nil))
}
// New returns a new Cache that will store files in basePath
func New(basePath string) *Cache {
return &Cache{
d: diskv.New(diskv.Options{
BasePath: basePath,
CacheSizeMax: 100 * 1024 * 1024, // 100MB
}),
}
}
// NewWithDiskv returns a new Cache using the provided Diskv as underlying
// storage.
func NewWithDiskv(d *diskv.Diskv) *Cache {
return &Cache{d}
}

View File

@ -0,0 +1,42 @@
package diskcache
import (
"bytes"
"io/ioutil"
"os"
"testing"
)
func TestDiskCache(t *testing.T) {
tempDir, err := ioutil.TempDir("", "httpcache")
if err != nil {
t.Fatalf("TempDir: %v", err)
}
defer os.RemoveAll(tempDir)
cache := New(tempDir)
key := "testKey"
_, ok := cache.Get(key)
if ok {
t.Fatal("retrieved key before adding it")
}
val := []byte("some bytes")
cache.Set(key, val)
retVal, ok := cache.Get(key)
if !ok {
t.Fatal("could not retrieve an element we just added")
}
if !bytes.Equal(retVal, val) {
t.Fatal("retrieved a different value than what we put in")
}
cache.Delete(key)
_, ok = cache.Get(key)
if ok {
t.Fatal("deleted key still present")
}
}

551
vendor/github.com/gregjones/httpcache/httpcache.go generated vendored Normal file
View File

@ -0,0 +1,551 @@
// Package httpcache provides a http.RoundTripper implementation that works as a
// mostly RFC-compliant cache for http responses.
//
// It is only suitable for use as a 'private' cache (i.e. for a web-browser or an API-client
// and not for a shared proxy).
//
package httpcache
import (
"bufio"
"bytes"
"errors"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"strings"
"sync"
"time"
)
const (
stale = iota
fresh
transparent
// XFromCache is the header added to responses that are returned from the cache
XFromCache = "X-From-Cache"
)
// A Cache interface is used by the Transport to store and retrieve responses.
type Cache interface {
// Get returns the []byte representation of a cached response and a bool
// set to true if the value isn't empty
Get(key string) (responseBytes []byte, ok bool)
// Set stores the []byte representation of a response against a key
Set(key string, responseBytes []byte)
// Delete removes the value associated with the key
Delete(key string)
}
// cacheKey returns the cache key for req.
func cacheKey(req *http.Request) string {
if req.Method == http.MethodGet {
return req.URL.String()
} else {
return req.Method + " " + req.URL.String()
}
}
// CachedResponse returns the cached http.Response for req if present, and nil
// otherwise.
func CachedResponse(c Cache, req *http.Request) (resp *http.Response, err error) {
cachedVal, ok := c.Get(cacheKey(req))
if !ok {
return
}
b := bytes.NewBuffer(cachedVal)
return http.ReadResponse(bufio.NewReader(b), req)
}
// MemoryCache is an implemtation of Cache that stores responses in an in-memory map.
type MemoryCache struct {
mu sync.RWMutex
items map[string][]byte
}
// Get returns the []byte representation of the response and true if present, false if not
func (c *MemoryCache) Get(key string) (resp []byte, ok bool) {
c.mu.RLock()
resp, ok = c.items[key]
c.mu.RUnlock()
return resp, ok
}
// Set saves response resp to the cache with key
func (c *MemoryCache) Set(key string, resp []byte) {
c.mu.Lock()
c.items[key] = resp
c.mu.Unlock()
}
// Delete removes key from the cache
func (c *MemoryCache) Delete(key string) {
c.mu.Lock()
delete(c.items, key)
c.mu.Unlock()
}
// NewMemoryCache returns a new Cache that will store items in an in-memory map
func NewMemoryCache() *MemoryCache {
c := &MemoryCache{items: map[string][]byte{}}
return c
}
// Transport is an implementation of http.RoundTripper that will return values from a cache
// where possible (avoiding a network request) and will additionally add validators (etag/if-modified-since)
// to repeated requests allowing servers to return 304 / Not Modified
type Transport struct {
// The RoundTripper interface actually used to make requests
// If nil, http.DefaultTransport is used
Transport http.RoundTripper
Cache Cache
// If true, responses returned from the cache will be given an extra header, X-From-Cache
MarkCachedResponses bool
}
// NewTransport returns a new Transport with the
// provided Cache implementation and MarkCachedResponses set to true
func NewTransport(c Cache) *Transport {
return &Transport{Cache: c, MarkCachedResponses: true}
}
// Client returns an *http.Client that caches responses.
func (t *Transport) Client() *http.Client {
return &http.Client{Transport: t}
}
// varyMatches will return false unless all of the cached values for the headers listed in Vary
// match the new request
func varyMatches(cachedResp *http.Response, req *http.Request) bool {
for _, header := range headerAllCommaSepValues(cachedResp.Header, "vary") {
header = http.CanonicalHeaderKey(header)
if header != "" && req.Header.Get(header) != cachedResp.Header.Get("X-Varied-"+header) {
return false
}
}
return true
}
// RoundTrip takes a Request and returns a Response
//
// If there is a fresh Response already in cache, then it will be returned without connecting to
// the server.
//
// If there is a stale Response, then any validators it contains will be set on the new request
// to give the server a chance to respond with NotModified. If this happens, then the cached Response
// will be returned.
func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
cacheKey := cacheKey(req)
cacheable := (req.Method == "GET" || req.Method == "HEAD") && req.Header.Get("range") == ""
var cachedResp *http.Response
if cacheable {
cachedResp, err = CachedResponse(t.Cache, req)
} else {
// Need to invalidate an existing value
t.Cache.Delete(cacheKey)
}
transport := t.Transport
if transport == nil {
transport = http.DefaultTransport
}
if cacheable && cachedResp != nil && err == nil {
if t.MarkCachedResponses {
cachedResp.Header.Set(XFromCache, "1")
}
if varyMatches(cachedResp, req) {
// Can only use cached value if the new request doesn't Vary significantly
freshness := getFreshness(cachedResp.Header, req.Header)
if freshness == fresh {
return cachedResp, nil
}
if freshness == stale {
var req2 *http.Request
// Add validators if caller hasn't already done so
etag := cachedResp.Header.Get("etag")
if etag != "" && req.Header.Get("etag") == "" {
req2 = cloneRequest(req)
req2.Header.Set("if-none-match", etag)
}
lastModified := cachedResp.Header.Get("last-modified")
if lastModified != "" && req.Header.Get("last-modified") == "" {
if req2 == nil {
req2 = cloneRequest(req)
}
req2.Header.Set("if-modified-since", lastModified)
}
if req2 != nil {
req = req2
}
}
}
resp, err = transport.RoundTrip(req)
if err == nil && req.Method == "GET" && resp.StatusCode == http.StatusNotModified {
// Replace the 304 response with the one from cache, but update with some new headers
endToEndHeaders := getEndToEndHeaders(resp.Header)
for _, header := range endToEndHeaders {
cachedResp.Header[header] = resp.Header[header]
}
resp = cachedResp
} else if (err != nil || (cachedResp != nil && resp.StatusCode >= 500)) &&
req.Method == "GET" && canStaleOnError(cachedResp.Header, req.Header) {
// In case of transport failure and stale-if-error activated, returns cached content
// when available
return cachedResp, nil
} else {
if err != nil || resp.StatusCode != http.StatusOK {
t.Cache.Delete(cacheKey)
}
if err != nil {
return nil, err
}
}
} else {
reqCacheControl := parseCacheControl(req.Header)
if _, ok := reqCacheControl["only-if-cached"]; ok {
resp = newGatewayTimeoutResponse(req)
} else {
resp, err = transport.RoundTrip(req)
if err != nil {
return nil, err
}
}
}
if cacheable && canStore(parseCacheControl(req.Header), parseCacheControl(resp.Header)) {
for _, varyKey := range headerAllCommaSepValues(resp.Header, "vary") {
varyKey = http.CanonicalHeaderKey(varyKey)
fakeHeader := "X-Varied-" + varyKey
reqValue := req.Header.Get(varyKey)
if reqValue != "" {
resp.Header.Set(fakeHeader, reqValue)
}
}
switch req.Method {
case "GET":
// Delay caching until EOF is reached.
resp.Body = &cachingReadCloser{
R: resp.Body,
OnEOF: func(r io.Reader) {
resp := *resp
resp.Body = ioutil.NopCloser(r)
respBytes, err := httputil.DumpResponse(&resp, true)
if err == nil {
t.Cache.Set(cacheKey, respBytes)
}
},
}
default:
respBytes, err := httputil.DumpResponse(resp, true)
if err == nil {
t.Cache.Set(cacheKey, respBytes)
}
}
} else {
t.Cache.Delete(cacheKey)
}
return resp, nil
}
// ErrNoDateHeader indicates that the HTTP headers contained no Date header.
var ErrNoDateHeader = errors.New("no Date header")
// Date parses and returns the value of the Date header.
func Date(respHeaders http.Header) (date time.Time, err error) {
dateHeader := respHeaders.Get("date")
if dateHeader == "" {
err = ErrNoDateHeader
return
}
return time.Parse(time.RFC1123, dateHeader)
}
type realClock struct{}
func (c *realClock) since(d time.Time) time.Duration {
return time.Since(d)
}
type timer interface {
since(d time.Time) time.Duration
}
var clock timer = &realClock{}
// getFreshness will return one of fresh/stale/transparent based on the cache-control
// values of the request and the response
//
// fresh indicates the response can be returned
// stale indicates that the response needs validating before it is returned
// transparent indicates the response should not be used to fulfil the request
//
// Because this is only a private cache, 'public' and 'private' in cache-control aren't
// signficant. Similarly, smax-age isn't used.
func getFreshness(respHeaders, reqHeaders http.Header) (freshness int) {
respCacheControl := parseCacheControl(respHeaders)
reqCacheControl := parseCacheControl(reqHeaders)
if _, ok := reqCacheControl["no-cache"]; ok {
return transparent
}
if _, ok := respCacheControl["no-cache"]; ok {
return stale
}
if _, ok := reqCacheControl["only-if-cached"]; ok {
return fresh
}
date, err := Date(respHeaders)
if err != nil {
return stale
}
currentAge := clock.since(date)
var lifetime time.Duration
var zeroDuration time.Duration
// If a response includes both an Expires header and a max-age directive,
// the max-age directive overrides the Expires header, even if the Expires header is more restrictive.
if maxAge, ok := respCacheControl["max-age"]; ok {
lifetime, err = time.ParseDuration(maxAge + "s")
if err != nil {
lifetime = zeroDuration
}
} else {
expiresHeader := respHeaders.Get("Expires")
if expiresHeader != "" {
expires, err := time.Parse(time.RFC1123, expiresHeader)
if err != nil {
lifetime = zeroDuration
} else {
lifetime = expires.Sub(date)
}
}
}
if maxAge, ok := reqCacheControl["max-age"]; ok {
// the client is willing to accept a response whose age is no greater than the specified time in seconds
lifetime, err = time.ParseDuration(maxAge + "s")
if err != nil {
lifetime = zeroDuration
}
}
if minfresh, ok := reqCacheControl["min-fresh"]; ok {
// the client wants a response that will still be fresh for at least the specified number of seconds.
minfreshDuration, err := time.ParseDuration(minfresh + "s")
if err == nil {
currentAge = time.Duration(currentAge + minfreshDuration)
}
}
if maxstale, ok := reqCacheControl["max-stale"]; ok {
// Indicates that the client is willing to accept a response that has exceeded its expiration time.
// If max-stale is assigned a value, then the client is willing to accept a response that has exceeded
// its expiration time by no more than the specified number of seconds.
// If no value is assigned to max-stale, then the client is willing to accept a stale response of any age.
//
// Responses served only because of a max-stale value are supposed to have a Warning header added to them,
// but that seems like a hassle, and is it actually useful? If so, then there needs to be a different
// return-value available here.
if maxstale == "" {
return fresh
}
maxstaleDuration, err := time.ParseDuration(maxstale + "s")
if err == nil {
currentAge = time.Duration(currentAge - maxstaleDuration)
}
}
if lifetime > currentAge {
return fresh
}
return stale
}
// Returns true if either the request or the response includes the stale-if-error
// cache control extension: https://tools.ietf.org/html/rfc5861
func canStaleOnError(respHeaders, reqHeaders http.Header) bool {
respCacheControl := parseCacheControl(respHeaders)
reqCacheControl := parseCacheControl(reqHeaders)
var err error
lifetime := time.Duration(-1)
if staleMaxAge, ok := respCacheControl["stale-if-error"]; ok {
if staleMaxAge != "" {
lifetime, err = time.ParseDuration(staleMaxAge + "s")
if err != nil {
return false
}
} else {
return true
}
}
if staleMaxAge, ok := reqCacheControl["stale-if-error"]; ok {
if staleMaxAge != "" {
lifetime, err = time.ParseDuration(staleMaxAge + "s")
if err != nil {
return false
}
} else {
return true
}
}
if lifetime >= 0 {
date, err := Date(respHeaders)
if err != nil {
return false
}
currentAge := clock.since(date)
if lifetime > currentAge {
return true
}
}
return false
}
func getEndToEndHeaders(respHeaders http.Header) []string {
// These headers are always hop-by-hop
hopByHopHeaders := map[string]struct{}{
"Connection": struct{}{},
"Keep-Alive": struct{}{},
"Proxy-Authenticate": struct{}{},
"Proxy-Authorization": struct{}{},
"Te": struct{}{},
"Trailers": struct{}{},
"Transfer-Encoding": struct{}{},
"Upgrade": struct{}{},
}
for _, extra := range strings.Split(respHeaders.Get("connection"), ",") {
// any header listed in connection, if present, is also considered hop-by-hop
if strings.Trim(extra, " ") != "" {
hopByHopHeaders[http.CanonicalHeaderKey(extra)] = struct{}{}
}
}
endToEndHeaders := []string{}
for respHeader, _ := range respHeaders {
if _, ok := hopByHopHeaders[respHeader]; !ok {
endToEndHeaders = append(endToEndHeaders, respHeader)
}
}
return endToEndHeaders
}
func canStore(reqCacheControl, respCacheControl cacheControl) (canStore bool) {
if _, ok := respCacheControl["no-store"]; ok {
return false
}
if _, ok := reqCacheControl["no-store"]; ok {
return false
}
return true
}
func newGatewayTimeoutResponse(req *http.Request) *http.Response {
var braw bytes.Buffer
braw.WriteString("HTTP/1.1 504 Gateway Timeout\r\n\r\n")
resp, err := http.ReadResponse(bufio.NewReader(&braw), req)
if err != nil {
panic(err)
}
return resp
}
// cloneRequest returns a clone of the provided *http.Request.
// The clone is a shallow copy of the struct and its Header map.
// (This function copyright goauth2 authors: https://code.google.com/p/goauth2)
func cloneRequest(r *http.Request) *http.Request {
// shallow copy of the struct
r2 := new(http.Request)
*r2 = *r
// deep copy of the Header
r2.Header = make(http.Header)
for k, s := range r.Header {
r2.Header[k] = s
}
return r2
}
type cacheControl map[string]string
func parseCacheControl(headers http.Header) cacheControl {
cc := cacheControl{}
ccHeader := headers.Get("Cache-Control")
for _, part := range strings.Split(ccHeader, ",") {
part = strings.Trim(part, " ")
if part == "" {
continue
}
if strings.ContainsRune(part, '=') {
keyval := strings.Split(part, "=")
cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",")
} else {
cc[part] = ""
}
}
return cc
}
// headerAllCommaSepValues returns all comma-separated values (each
// with whitespace trimmed) for header name in headers. According to
// Section 4.2 of the HTTP/1.1 spec
// (http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2),
// values from multiple occurrences of a header should be concatenated, if
// the header's value is a comma-separated list.
func headerAllCommaSepValues(headers http.Header, name string) []string {
var vals []string
for _, val := range headers[http.CanonicalHeaderKey(name)] {
fields := strings.Split(val, ",")
for i, f := range fields {
fields[i] = strings.TrimSpace(f)
}
vals = append(vals, fields...)
}
return vals
}
// cachingReadCloser is a wrapper around ReadCloser R that calls OnEOF
// handler with a full copy of the content read from R when EOF is
// reached.
type cachingReadCloser struct {
// Underlying ReadCloser.
R io.ReadCloser
// OnEOF is called with a copy of the content of R when EOF is reached.
OnEOF func(io.Reader)
buf bytes.Buffer // buf stores a copy of the content of R.
}
// Read reads the next len(p) bytes from R or until R is drained. The
// return value n is the number of bytes read. If R has no data to
// return, err is io.EOF and OnEOF is called with a full copy of what
// has been read so far.
func (r *cachingReadCloser) Read(p []byte) (n int, err error) {
n, err = r.R.Read(p)
r.buf.Write(p[:n])
if err == io.EOF {
r.OnEOF(bytes.NewReader(r.buf.Bytes()))
}
return n, err
}
func (r *cachingReadCloser) Close() error {
return r.R.Close()
}
// NewMemoryCacheTransport returns a new Transport using the in-memory cache implementation
func NewMemoryCacheTransport() *Transport {
c := NewMemoryCache()
t := NewTransport(c)
return t
}

1475
vendor/github.com/gregjones/httpcache/httpcache_test.go generated vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,51 @@
// Package leveldbcache provides an implementation of httpcache.Cache that
// uses github.com/syndtr/goleveldb/leveldb
package leveldbcache
import (
"github.com/syndtr/goleveldb/leveldb"
)
// Cache is an implementation of httpcache.Cache with leveldb storage
type Cache struct {
db *leveldb.DB
}
// Get returns the response corresponding to key if present
func (c *Cache) Get(key string) (resp []byte, ok bool) {
var err error
resp, err = c.db.Get([]byte(key), nil)
if err != nil {
return []byte{}, false
}
return resp, true
}
// Set saves a response to the cache as key
func (c *Cache) Set(key string, resp []byte) {
c.db.Put([]byte(key), resp, nil)
}
// Delete removes the response with key from the cache
func (c *Cache) Delete(key string) {
c.db.Delete([]byte(key), nil)
}
// New returns a new Cache that will store leveldb in path
func New(path string) (*Cache, error) {
cache := &Cache{}
var err error
cache.db, err = leveldb.OpenFile(path, nil)
if err != nil {
return nil, err
}
return cache, nil
}
// NewWithDB returns a new Cache using the provided leveldb as underlying
// storage.
func NewWithDB(db *leveldb.DB) *Cache {
return &Cache{db}
}

View File

@ -0,0 +1,46 @@
package leveldbcache
import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"testing"
)
func TestDiskCache(t *testing.T) {
tempDir, err := ioutil.TempDir("", "httpcache")
if err != nil {
t.Fatalf("TempDir: %v", err)
}
defer os.RemoveAll(tempDir)
cache, err := New(filepath.Join(tempDir, "db"))
if err != nil {
t.Fatalf("New leveldb,: %v", err)
}
key := "testKey"
_, ok := cache.Get(key)
if ok {
t.Fatal("retrieved key before adding it")
}
val := []byte("some bytes")
cache.Set(key, val)
retVal, ok := cache.Get(key)
if !ok {
t.Fatal("could not retrieve an element we just added")
}
if !bytes.Equal(retVal, val) {
t.Fatal("retrieved a different value than what we put in")
}
cache.Delete(key)
_, ok = cache.Get(key)
if ok {
t.Fatal("deleted key still present")
}
}

View File

@ -0,0 +1,61 @@
// +build appengine
// Package memcache provides an implementation of httpcache.Cache that uses App
// Engine's memcache package to store cached responses.
//
// When not built for Google App Engine, this package will provide an
// implementation that connects to a specified memcached server. See the
// memcache.go file in this package for details.
package memcache
import (
"appengine"
"appengine/memcache"
)
// Cache is an implementation of httpcache.Cache that caches responses in App
// Engine's memcache.
type Cache struct {
appengine.Context
}
// cacheKey modifies an httpcache key for use in memcache. Specifically, it
// prefixes keys to avoid collision with other data stored in memcache.
func cacheKey(key string) string {
return "httpcache:" + key
}
// Get returns the response corresponding to key if present.
func (c *Cache) Get(key string) (resp []byte, ok bool) {
item, err := memcache.Get(c.Context, cacheKey(key))
if err != nil {
if err != memcache.ErrCacheMiss {
c.Context.Errorf("error getting cached response: %v", err)
}
return nil, false
}
return item.Value, true
}
// Set saves a response to the cache as key.
func (c *Cache) Set(key string, resp []byte) {
item := &memcache.Item{
Key: cacheKey(key),
Value: resp,
}
if err := memcache.Set(c.Context, item); err != nil {
c.Context.Errorf("error caching response: %v", err)
}
}
// Delete removes the response with key from the cache.
func (c *Cache) Delete(key string) {
if err := memcache.Delete(c.Context, cacheKey(key)); err != nil {
c.Context.Errorf("error deleting cached response: %v", err)
}
}
// New returns a new Cache for the given context.
func New(ctx appengine.Context) *Cache {
return &Cache{ctx}
}

View File

@ -0,0 +1,44 @@
// +build appengine
package memcache
import (
"bytes"
"testing"
"appengine/aetest"
)
func TestAppEngine(t *testing.T) {
ctx, err := aetest.NewContext(nil)
if err != nil {
t.Fatal(err)
}
defer ctx.Close()
cache := New(ctx)
key := "testKey"
_, ok := cache.Get(key)
if ok {
t.Fatal("retrieved key before adding it")
}
val := []byte("some bytes")
cache.Set(key, val)
retVal, ok := cache.Get(key)
if !ok {
t.Fatal("could not retrieve an element we just added")
}
if !bytes.Equal(retVal, val) {
t.Fatal("retrieved a different value than what we put in")
}
cache.Delete(key)
_, ok = cache.Get(key)
if ok {
t.Fatal("deleted key still present")
}
}

View File

@ -0,0 +1,60 @@
// +build !appengine
// Package memcache provides an implementation of httpcache.Cache that uses
// gomemcache to store cached responses.
//
// When built for Google App Engine, this package will provide an
// implementation that uses App Engine's memcache service. See the
// appengine.go file in this package for details.
package memcache
import (
"github.com/bradfitz/gomemcache/memcache"
)
// Cache is an implementation of httpcache.Cache that caches responses in a
// memcache server.
type Cache struct {
*memcache.Client
}
// cacheKey modifies an httpcache key for use in memcache. Specifically, it
// prefixes keys to avoid collision with other data stored in memcache.
func cacheKey(key string) string {
return "httpcache:" + key
}
// Get returns the response corresponding to key if present.
func (c *Cache) Get(key string) (resp []byte, ok bool) {
item, err := c.Client.Get(cacheKey(key))
if err != nil {
return nil, false
}
return item.Value, true
}
// Set saves a response to the cache as key.
func (c *Cache) Set(key string, resp []byte) {
item := &memcache.Item{
Key: cacheKey(key),
Value: resp,
}
c.Client.Set(item)
}
// Delete removes the response with key from the cache.
func (c *Cache) Delete(key string) {
c.Client.Delete(cacheKey(key))
}
// New returns a new Cache using the provided memcache server(s) with equal
// weight. If a server is listed multiple times, it gets a proportional amount
// of weight.
func New(server ...string) *Cache {
return NewWithClient(memcache.New(server...))
}
// NewWithClient returns a new Cache with the given memcache client.
func NewWithClient(client *memcache.Client) *Cache {
return &Cache{client}
}

View File

@ -0,0 +1,47 @@
// +build !appengine
package memcache
import (
"bytes"
"net"
"testing"
)
const testServer = "localhost:11211"
func TestMemCache(t *testing.T) {
conn, err := net.Dial("tcp", testServer)
if err != nil {
// TODO: rather than skip the test, fall back to a faked memcached server
t.Skipf("skipping test; no server running at %s", testServer)
}
conn.Write([]byte("flush_all\r\n")) // flush memcache
conn.Close()
cache := New(testServer)
key := "testKey"
_, ok := cache.Get(key)
if ok {
t.Fatal("retrieved key before adding it")
}
val := []byte("some bytes")
cache.Set(key, val)
retVal, ok := cache.Get(key)
if !ok {
t.Fatal("could not retrieve an element we just added")
}
if !bytes.Equal(retVal, val) {
t.Fatal("retrieved a different value than what we put in")
}
cache.Delete(key)
_, ok = cache.Get(key)
if ok {
t.Fatal("deleted key still present")
}
}

43
vendor/github.com/gregjones/httpcache/redis/redis.go generated vendored Normal file
View File

@ -0,0 +1,43 @@
// Package redis provides a redis interface for http caching.
package redis
import (
"github.com/gomodule/redigo/redis"
"github.com/gregjones/httpcache"
)
// cache is an implementation of httpcache.Cache that caches responses in a
// redis server.
type cache struct {
redis.Conn
}
// cacheKey modifies an httpcache key for use in redis. Specifically, it
// prefixes keys to avoid collision with other data stored in redis.
func cacheKey(key string) string {
return "rediscache:" + key
}
// Get returns the response corresponding to key if present.
func (c cache) Get(key string) (resp []byte, ok bool) {
item, err := redis.Bytes(c.Do("GET", cacheKey(key)))
if err != nil {
return nil, false
}
return item, true
}
// Set saves a response to the cache as key.
func (c cache) Set(key string, resp []byte) {
c.Do("SET", cacheKey(key), resp)
}
// Delete removes the response with key from the cache.
func (c cache) Delete(key string) {
c.Do("DEL", cacheKey(key))
}
// NewWithClient returns a new Cache with the given redis connection.
func NewWithClient(client redis.Conn) httpcache.Cache {
return cache{client}
}

View File

@ -0,0 +1,43 @@
package redis
import (
"bytes"
"testing"
"github.com/gomodule/redigo/redis"
)
func TestRedisCache(t *testing.T) {
conn, err := redis.Dial("tcp", "localhost:6379")
if err != nil {
// TODO: rather than skip the test, fall back to a faked redis server
t.Skipf("skipping test; no server running at localhost:6379")
}
conn.Do("FLUSHALL")
cache := NewWithClient(conn)
key := "testKey"
_, ok := cache.Get(key)
if ok {
t.Fatal("retrieved key before adding it")
}
val := []byte("some bytes")
cache.Set(key, val)
retVal, ok := cache.Get(key)
if !ok {
t.Fatal("could not retrieve an element we just added")
}
if !bytes.Equal(retVal, val) {
t.Fatal("retrieved a different value than what we put in")
}
cache.Delete(key)
_, ok = cache.Get(key)
if ok {
t.Fatal("deleted key still present")
}
}

View File

@ -1,11 +0,0 @@
language: go
os:
- linux
- osx
go:
- 1.3
- 1.4
- 1.5
- tip

View File

@ -1,15 +0,0 @@
ISC License
Copyright (c) 2012 Chris Howey
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@ -1,384 +0,0 @@
Unless otherwise noted, all files in this distribution are released
under the Common Development and Distribution License (CDDL).
Exceptions are noted within the associated source files.
--------------------------------------------------------------------
COMMON DEVELOPMENT AND DISTRIBUTION LICENSE Version 1.0
1. Definitions.
1.1. "Contributor" means each individual or entity that creates
or contributes to the creation of Modifications.
1.2. "Contributor Version" means the combination of the Original
Software, prior Modifications used by a Contributor (if any),
and the Modifications made by that particular Contributor.
1.3. "Covered Software" means (a) the Original Software, or (b)
Modifications, or (c) the combination of files containing
Original Software with files containing Modifications, in
each case including portions thereof.
1.4. "Executable" means the Covered Software in any form other
than Source Code.
1.5. "Initial Developer" means the individual or entity that first
makes Original Software available under this License.
1.6. "Larger Work" means a work which combines Covered Software or
portions thereof with code not governed by the terms of this
License.
1.7. "License" means this document.
1.8. "Licensable" means having the right to grant, to the maximum
extent possible, whether at the time of the initial grant or
subsequently acquired, any and all of the rights conveyed
herein.
1.9. "Modifications" means the Source Code and Executable form of
any of the following:
A. Any file that results from an addition to, deletion from or
modification of the contents of a file containing Original
Software or previous Modifications;
B. Any new file that contains any part of the Original
Software or previous Modifications; or
C. Any new file that is contributed or otherwise made
available under the terms of this License.
1.10. "Original Software" means the Source Code and Executable
form of computer software code that is originally released
under this License.
1.11. "Patent Claims" means any patent claim(s), now owned or
hereafter acquired, including without limitation, method,
process, and apparatus claims, in any patent Licensable by
grantor.
1.12. "Source Code" means (a) the common form of computer software
code in which modifications are made and (b) associated
documentation included in or with such code.
1.13. "You" (or "Your") means an individual or a legal entity
exercising rights under, and complying with all of the terms
of, this License. For legal entities, "You" includes any
entity which controls, is controlled by, or is under common
control with You. For purposes of this definition,
"control" means (a) the power, direct or indirect, to cause
the direction or management of such entity, whether by
contract or otherwise, or (b) ownership of more than fifty
percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants.
2.1. The Initial Developer Grant.
Conditioned upon Your compliance with Section 3.1 below and
subject to third party intellectual property claims, the Initial
Developer hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or
trademark) Licensable by Initial Developer, to use,
reproduce, modify, display, perform, sublicense and
distribute the Original Software (or portions thereof),
with or without Modifications, and/or as part of a Larger
Work; and
(b) under Patent Claims infringed by the making, using or
selling of Original Software, to make, have made, use,
practice, sell, and offer for sale, and/or otherwise
dispose of the Original Software (or portions thereof).
(c) The licenses granted in Sections 2.1(a) and (b) are
effective on the date Initial Developer first distributes
or otherwise makes the Original Software available to a
third party under the terms of this License.
(d) Notwithstanding Section 2.1(b) above, no patent license is
granted: (1) for code that You delete from the Original
Software, or (2) for infringements caused by: (i) the
modification of the Original Software, or (ii) the
combination of the Original Software with other software
or devices.
2.2. Contributor Grant.
Conditioned upon Your compliance with Section 3.1 below and
subject to third party intellectual property claims, each
Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or
trademark) Licensable by Contributor to use, reproduce,
modify, display, perform, sublicense and distribute the
Modifications created by such Contributor (or portions
thereof), either on an unmodified basis, with other
Modifications, as Covered Software and/or as part of a
Larger Work; and
(b) under Patent Claims infringed by the making, using, or
selling of Modifications made by that Contributor either
alone and/or in combination with its Contributor Version
(or portions of such combination), to make, use, sell,
offer for sale, have made, and/or otherwise dispose of:
(1) Modifications made by that Contributor (or portions
thereof); and (2) the combination of Modifications made by
that Contributor with its Contributor Version (or portions
of such combination).
(c) The licenses granted in Sections 2.2(a) and 2.2(b) are
effective on the date Contributor first distributes or
otherwise makes the Modifications available to a third
party.
(d) Notwithstanding Section 2.2(b) above, no patent license is
granted: (1) for any code that Contributor has deleted
from the Contributor Version; (2) for infringements caused
by: (i) third party modifications of Contributor Version,
or (ii) the combination of Modifications made by that
Contributor with other software (except as part of the
Contributor Version) or other devices; or (3) under Patent
Claims infringed by Covered Software in the absence of
Modifications made by that Contributor.
3. Distribution Obligations.
3.1. Availability of Source Code.
Any Covered Software that You distribute or otherwise make
available in Executable form must also be made available in Source
Code form and that Source Code form must be distributed only under
the terms of this License. You must include a copy of this
License with every copy of the Source Code form of the Covered
Software You distribute or otherwise make available. You must
inform recipients of any such Covered Software in Executable form
as to how they can obtain such Covered Software in Source Code
form in a reasonable manner on or through a medium customarily
used for software exchange.
3.2. Modifications.
The Modifications that You create or to which You contribute are
governed by the terms of this License. You represent that You
believe Your Modifications are Your original creation(s) and/or
You have sufficient rights to grant the rights conveyed by this
License.
3.3. Required Notices.
You must include a notice in each of Your Modifications that
identifies You as the Contributor of the Modification. You may
not remove or alter any copyright, patent or trademark notices
contained within the Covered Software, or any notices of licensing
or any descriptive text giving attribution to any Contributor or
the Initial Developer.
3.4. Application of Additional Terms.
You may not offer or impose any terms on any Covered Software in
Source Code form that alters or restricts the applicable version
of this License or the recipients' rights hereunder. You may
choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of
Covered Software. However, you may do so only on Your own behalf,
and not on behalf of the Initial Developer or any Contributor.
You must make it absolutely clear that any such warranty, support,
indemnity or liability obligation is offered by You alone, and You
hereby agree to indemnify the Initial Developer and every
Contributor for any liability incurred by the Initial Developer or
such Contributor as a result of warranty, support, indemnity or
liability terms You offer.
3.5. Distribution of Executable Versions.
You may distribute the Executable form of the Covered Software
under the terms of this License or under the terms of a license of
Your choice, which may contain terms different from this License,
provided that You are in compliance with the terms of this License
and that the license for the Executable form does not attempt to
limit or alter the recipient's rights in the Source Code form from
the rights set forth in this License. If You distribute the
Covered Software in Executable form under a different license, You
must make it absolutely clear that any terms which differ from
this License are offered by You alone, not by the Initial
Developer or Contributor. You hereby agree to indemnify the
Initial Developer and every Contributor for any liability incurred
by the Initial Developer or such Contributor as a result of any
such terms You offer.
3.6. Larger Works.
You may create a Larger Work by combining Covered Software with
other code not governed by the terms of this License and
distribute the Larger Work as a single product. In such a case,
You must make sure the requirements of this License are fulfilled
for the Covered Software.
4. Versions of the License.
4.1. New Versions.
Sun Microsystems, Inc. is the initial license steward and may
publish revised and/or new versions of this License from time to
time. Each version will be given a distinguishing version number.
Except as provided in Section 4.3, no one other than the license
steward has the right to modify this License.
4.2. Effect of New Versions.
You may always continue to use, distribute or otherwise make the
Covered Software available under the terms of the version of the
License under which You originally received the Covered Software.
If the Initial Developer includes a notice in the Original
Software prohibiting it from being distributed or otherwise made
available under any subsequent version of the License, You must
distribute and make the Covered Software available under the terms
of the version of the License under which You originally received
the Covered Software. Otherwise, You may also choose to use,
distribute or otherwise make the Covered Software available under
the terms of any subsequent version of the License published by
the license steward.
4.3. Modified Versions.
When You are an Initial Developer and You want to create a new
license for Your Original Software, You may create and use a
modified version of this License if You: (a) rename the license
and remove any references to the name of the license steward
(except to note that the license differs from this License); and
(b) otherwise make it clear that the license contains terms which
differ from this License.
5. DISCLAIMER OF WARRANTY.
COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS"
BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED
SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR
PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND
PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY
COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE
INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY
NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF
WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF
ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS
DISCLAIMER.
6. TERMINATION.
6.1. This License and the rights granted hereunder will terminate
automatically if You fail to comply with terms herein and fail to
cure such breach within 30 days of becoming aware of the breach.
Provisions which, by their nature, must remain in effect beyond
the termination of this License shall survive.
6.2. If You assert a patent infringement claim (excluding
declaratory judgment actions) against Initial Developer or a
Contributor (the Initial Developer or Contributor against whom You
assert such claim is referred to as "Participant") alleging that
the Participant Software (meaning the Contributor Version where
the Participant is a Contributor or the Original Software where
the Participant is the Initial Developer) directly or indirectly
infringes any patent, then any and all rights granted directly or
indirectly to You by such Participant, the Initial Developer (if
the Initial Developer is not the Participant) and all Contributors
under Sections 2.1 and/or 2.2 of this License shall, upon 60 days
notice from Participant terminate prospectively and automatically
at the expiration of such 60 day notice period, unless if within
such 60 day period You withdraw Your claim with respect to the
Participant Software against such Participant either unilaterally
or pursuant to a written agreement with Participant.
6.3. In the event of termination under Sections 6.1 or 6.2 above,
all end user licenses that have been validly granted by You or any
distributor hereunder prior to termination (excluding licenses
granted to You by any distributor) shall survive termination.
7. LIMITATION OF LIABILITY.
UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT
(INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE
INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF
COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE
LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR
CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT
LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK
STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER
COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN
INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF
LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL
INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT
APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO
NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR
CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT
APPLY TO YOU.
8. U.S. GOVERNMENT END USERS.
The Covered Software is a "commercial item," as that term is
defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of "commercial
computer software" (as that term is defined at 48
C.F.R. 252.227-7014(a)(1)) and "commercial computer software
documentation" as such terms are used in 48 C.F.R. 12.212
(Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48
C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all
U.S. Government End Users acquire Covered Software with only those
rights set forth herein. This U.S. Government Rights clause is in
lieu of, and supersedes, any other FAR, DFAR, or other clause or
provision that addresses Government rights in computer software
under this License.
9. MISCELLANEOUS.
This License represents the complete agreement concerning subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. This License shall be governed
by the law of the jurisdiction specified in a notice contained
within the Original Software (except to the extent applicable law,
if any, provides otherwise), excluding such jurisdiction's
conflict-of-law provisions. Any litigation relating to this
License shall be subject to the jurisdiction of the courts located
in the jurisdiction and venue specified in a notice contained
within the Original Software, with the losing party responsible
for costs, including, without limitation, court costs and
reasonable attorneys' fees and expenses. The application of the
United Nations Convention on Contracts for the International Sale
of Goods is expressly excluded. Any law or regulation which
provides that the language of a contract shall be construed
against the drafter shall not apply to this License. You agree
that You alone are responsible for compliance with the United
States export administration regulations (and the export control
laws and regulation of any other countries) when You use,
distribute or otherwise make available any Covered Software.
10. RESPONSIBILITY FOR CLAIMS.
As between Initial Developer and the Contributors, each party is
responsible for claims and damages arising, directly or
indirectly, out of its utilization of rights under this License
and You agree to work with Initial Developer and Contributors to
distribute such responsibility on an equitable basis. Nothing
herein is intended or shall be deemed to constitute any admission
of liability.
--------------------------------------------------------------------
NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND
DISTRIBUTION LICENSE (CDDL)
For Covered Software in this distribution, this License shall
be governed by the laws of the State of California (excluding
conflict-of-law provisions).
Any litigation relating to this License shall be subject to the
jurisdiction of the Federal Courts of the Northern District of
California and the state courts of the State of California, with
venue lying in Santa Clara County, California.

View File

@ -1,27 +0,0 @@
# getpasswd in Go [![GoDoc](https://godoc.org/github.com/howeyc/gopass?status.svg)](https://godoc.org/github.com/howeyc/gopass) [![Build Status](https://secure.travis-ci.org/howeyc/gopass.png?branch=master)](http://travis-ci.org/howeyc/gopass)
Retrieve password from user terminal or piped input without echo.
Verified on BSD, Linux, and Windows.
Example:
```go
package main
import "fmt"
import "github.com/howeyc/gopass"
func main() {
fmt.Printf("Password: ")
// Silent. For printing *'s use gopass.GetPasswdMasked()
pass, err := gopass.GetPasswd()
if err != nil {
// Handle gopass.ErrInterrupted or getch() read error
}
// Do something with pass
}
```
Caution: Multi-byte characters not supported!

View File

@ -1,110 +0,0 @@
package gopass
import (
"errors"
"fmt"
"io"
"os"
)
type FdReader interface {
io.Reader
Fd() uintptr
}
var defaultGetCh = func(r io.Reader) (byte, error) {
buf := make([]byte, 1)
if n, err := r.Read(buf); n == 0 || err != nil {
if err != nil {
return 0, err
}
return 0, io.EOF
}
return buf[0], nil
}
var (
maxLength = 512
ErrInterrupted = errors.New("interrupted")
ErrMaxLengthExceeded = fmt.Errorf("maximum byte limit (%v) exceeded", maxLength)
// Provide variable so that tests can provide a mock implementation.
getch = defaultGetCh
)
// getPasswd returns the input read from terminal.
// If prompt is not empty, it will be output as a prompt to the user
// If masked is true, typing will be matched by asterisks on the screen.
// Otherwise, typing will echo nothing.
func getPasswd(prompt string, masked bool, r FdReader, w io.Writer) ([]byte, error) {
var err error
var pass, bs, mask []byte
if masked {
bs = []byte("\b \b")
mask = []byte("*")
}
if isTerminal(r.Fd()) {
if oldState, err := makeRaw(r.Fd()); err != nil {
return pass, err
} else {
defer func() {
restore(r.Fd(), oldState)
fmt.Fprintln(w)
}()
}
}
if prompt != "" {
fmt.Fprint(w, prompt)
}
// Track total bytes read, not just bytes in the password. This ensures any
// errors that might flood the console with nil or -1 bytes infinitely are
// capped.
var counter int
for counter = 0; counter <= maxLength; counter++ {
if v, e := getch(r); e != nil {
err = e
break
} else if v == 127 || v == 8 {
if l := len(pass); l > 0 {
pass = pass[:l-1]
fmt.Fprint(w, string(bs))
}
} else if v == 13 || v == 10 {
break
} else if v == 3 {
err = ErrInterrupted
break
} else if v != 0 {
pass = append(pass, v)
fmt.Fprint(w, string(mask))
}
}
if counter > maxLength {
err = ErrMaxLengthExceeded
}
return pass, err
}
// GetPasswd returns the password read from the terminal without echoing input.
// The returned byte array does not include end-of-line characters.
func GetPasswd() ([]byte, error) {
return getPasswd("", false, os.Stdin, os.Stdout)
}
// GetPasswdMasked returns the password read from the terminal, echoing asterisks.
// The returned byte array does not include end-of-line characters.
func GetPasswdMasked() ([]byte, error) {
return getPasswd("", true, os.Stdin, os.Stdout)
}
// GetPasswdPrompt prompts the user and returns the password read from the terminal.
// If mask is true, then asterisks are echoed.
// The returned byte array does not include end-of-line characters.
func GetPasswdPrompt(prompt string, mask bool, r FdReader, w io.Writer) ([]byte, error) {
return getPasswd(prompt, mask, r, w)
}

View File

@ -1,225 +0,0 @@
package gopass
import (
"bufio"
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"testing"
"time"
)
// TestGetPasswd tests the password creation and output based on a byte buffer
// as input to mock the underlying getch() methods.
func TestGetPasswd(t *testing.T) {
type testData struct {
input []byte
// Due to how backspaces are written, it is easier to manually write
// each expected output for the masked cases.
masked string
password string
byesLeft int
reason string
}
ds := []testData{
testData{[]byte("abc\n"), "***", "abc", 0, "Password parsing should stop at \\n"},
testData{[]byte("abc\r"), "***", "abc", 0, "Password parsing should stop at \\r"},
testData{[]byte("a\nbc\n"), "*", "a", 3, "Password parsing should stop at \\n"},
testData{[]byte("*!]|\n"), "****", "*!]|", 0, "Special characters shouldn't affect the password."},
testData{[]byte("abc\r\n"), "***", "abc", 1,
"Password parsing should stop at \\r; Windows LINE_MODE should be unset so \\r is not converted to \\r\\n."},
testData{[]byte{'a', 'b', 'c', 8, '\n'}, "***\b \b", "ab", 0, "Backspace byte should remove the last read byte."},
testData{[]byte{'a', 'b', 127, 'c', '\n'}, "**\b \b*", "ac", 0, "Delete byte should remove the last read byte."},
testData{[]byte{'a', 'b', 127, 'c', 8, 127, '\n'}, "**\b \b*\b \b\b \b", "", 0, "Successive deletes continue to delete."},
testData{[]byte{8, 8, 8, '\n'}, "", "", 0, "Deletes before characters are noops."},
testData{[]byte{8, 8, 8, 'a', 'b', 'c', '\n'}, "***", "abc", 0, "Deletes before characters are noops."},
testData{[]byte{'a', 'b', 0, 'c', '\n'}, "***", "abc", 0,
"Nil byte should be ignored due; may get unintended nil bytes from syscalls on Windows."},
}
// Redirecting output for tests as they print to os.Stdout but we want to
// capture and test the output.
for _, masked := range []bool{true, false} {
for _, d := range ds {
pipeBytesToStdin(d.input)
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err.Error())
}
result, err := getPasswd("", masked, os.Stdin, w)
if err != nil {
t.Errorf("Error getting password: %s", err.Error())
}
leftOnBuffer := flushStdin()
// Test output (masked and unmasked). Delete/backspace actually
// deletes, overwrites and deletes again. As a result, we need to
// remove those from the pipe afterwards to mimic the console's
// interpretation of those bytes.
w.Close()
output, err := ioutil.ReadAll(r)
if err != nil {
t.Fatal(err.Error())
}
var expectedOutput []byte
if masked {
expectedOutput = []byte(d.masked)
} else {
expectedOutput = []byte("")
}
if bytes.Compare(expectedOutput, output) != 0 {
t.Errorf("Expected output to equal %v (%q) but got %v (%q) instead when masked=%v. %s", expectedOutput, string(expectedOutput), output, string(output), masked, d.reason)
}
if string(result) != d.password {
t.Errorf("Expected %q but got %q instead when masked=%v. %s", d.password, result, masked, d.reason)
}
if leftOnBuffer != d.byesLeft {
t.Errorf("Expected %v bytes left on buffer but instead got %v when masked=%v. %s", d.byesLeft, leftOnBuffer, masked, d.reason)
}
}
}
}
// TestPipe ensures we get our expected pipe behavior.
func TestPipe(t *testing.T) {
type testData struct {
input string
password string
expError error
}
ds := []testData{
testData{"abc", "abc", io.EOF},
testData{"abc\n", "abc", nil},
testData{"abc\r", "abc", nil},
testData{"abc\r\n", "abc", nil},
}
for _, d := range ds {
_, err := pipeToStdin(d.input)
if err != nil {
t.Log("Error writing input to stdin:", err)
t.FailNow()
}
pass, err := GetPasswd()
if string(pass) != d.password {
t.Errorf("Expected %q but got %q instead.", d.password, string(pass))
}
if err != d.expError {
t.Errorf("Expected %v but got %q instead.", d.expError, err)
}
}
}
// flushStdin reads from stdin for .5 seconds to ensure no bytes are left on
// the buffer. Returns the number of bytes read.
func flushStdin() int {
ch := make(chan byte)
go func(ch chan byte) {
reader := bufio.NewReader(os.Stdin)
for {
b, err := reader.ReadByte()
if err != nil { // Maybe log non io.EOF errors, if you want
close(ch)
return
}
ch <- b
}
close(ch)
}(ch)
numBytes := 0
for {
select {
case _, ok := <-ch:
if !ok {
return numBytes
}
numBytes++
case <-time.After(500 * time.Millisecond):
return numBytes
}
}
return numBytes
}
// pipeToStdin pipes the given string onto os.Stdin by replacing it with an
// os.Pipe. The write end of the pipe is closed so that EOF is read after the
// final byte.
func pipeToStdin(s string) (int, error) {
pipeReader, pipeWriter, err := os.Pipe()
if err != nil {
fmt.Println("Error getting os pipes:", err)
os.Exit(1)
}
os.Stdin = pipeReader
w, err := pipeWriter.WriteString(s)
pipeWriter.Close()
return w, err
}
func pipeBytesToStdin(b []byte) (int, error) {
return pipeToStdin(string(b))
}
// TestGetPasswd_Err tests errors are properly handled from getch()
func TestGetPasswd_Err(t *testing.T) {
var inBuffer *bytes.Buffer
getch = func(io.Reader) (byte, error) {
b, err := inBuffer.ReadByte()
if err != nil {
return 13, err
}
if b == 'z' {
return 'z', fmt.Errorf("Forced error; byte returned should not be considered accurate.")
}
return b, nil
}
defer func() { getch = defaultGetCh }()
for input, expectedPassword := range map[string]string{"abc": "abc", "abzc": "ab"} {
inBuffer = bytes.NewBufferString(input)
p, err := GetPasswdMasked()
if string(p) != expectedPassword {
t.Errorf("Expected %q but got %q instead.", expectedPassword, p)
}
if err == nil {
t.Errorf("Expected error to be returned.")
}
}
}
func TestMaxPasswordLength(t *testing.T) {
type testData struct {
input []byte
expectedErr error
// Helper field to output in case of failure; rather than hundreds of
// bytes.
inputDesc string
}
ds := []testData{
testData{append(bytes.Repeat([]byte{'a'}, maxLength), '\n'), nil, fmt.Sprintf("%v 'a' bytes followed by a newline", maxLength)},
testData{append(bytes.Repeat([]byte{'a'}, maxLength+1), '\n'), ErrMaxLengthExceeded, fmt.Sprintf("%v 'a' bytes followed by a newline", maxLength+1)},
testData{append(bytes.Repeat([]byte{0x00}, maxLength+1), '\n'), ErrMaxLengthExceeded, fmt.Sprintf("%v 0x00 bytes followed by a newline", maxLength+1)},
}
for _, d := range ds {
pipeBytesToStdin(d.input)
_, err := GetPasswd()
if err != d.expectedErr {
t.Errorf("Expected error to be %v; isntead got %v from %v", d.expectedErr, err, d.inputDesc)
}
}
}

View File

@ -1,25 +0,0 @@
// +build !solaris
package gopass
import "golang.org/x/crypto/ssh/terminal"
type terminalState struct {
state *terminal.State
}
func isTerminal(fd uintptr) bool {
return terminal.IsTerminal(int(fd))
}
func makeRaw(fd uintptr) (*terminalState, error) {
state, err := terminal.MakeRaw(int(fd))
return &terminalState{
state: state,
}, err
}
func restore(fd uintptr, oldState *terminalState) error {
return terminal.Restore(int(fd), oldState.state)
}

View File

@ -1,69 +0,0 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
// Below is derived from Solaris source, so CDDL license is included.
package gopass
import (
"syscall"
"golang.org/x/sys/unix"
)
type terminalState struct {
state *unix.Termios
}
// isTerminal returns true if there is a terminal attached to the given
// file descriptor.
// Source: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libbc/libc/gen/common/isatty.c
func isTerminal(fd uintptr) bool {
var termio unix.Termio
err := unix.IoctlSetTermio(int(fd), unix.TCGETA, &termio)
return err == nil
}
// makeRaw puts the terminal connected to the given file descriptor into raw
// mode and returns the previous state of the terminal so that it can be
// restored.
// Source: http://src.illumos.org/source/xref/illumos-gate/usr/src/lib/libast/common/uwin/getpass.c
func makeRaw(fd uintptr) (*terminalState, error) {
oldTermiosPtr, err := unix.IoctlGetTermios(int(fd), unix.TCGETS)
if err != nil {
return nil, err
}
oldTermios := *oldTermiosPtr
newTermios := oldTermios
newTermios.Lflag &^= syscall.ECHO | syscall.ECHOE | syscall.ECHOK | syscall.ECHONL
if err := unix.IoctlSetTermios(int(fd), unix.TCSETS, &newTermios); err != nil {
return nil, err
}
return &terminalState{
state: oldTermiosPtr,
}, nil
}
func restore(fd uintptr, oldState *terminalState) error {
return unix.IoctlSetTermios(int(fd), unix.TCSETS, oldState.state)
}

View File

@ -0,0 +1,31 @@
# Contributing Guidelines
Welcome to Kubernetes. We are excited about the prospect of you joining our [community](https://github.com/kubernetes/community)! The Kubernetes community abides by the CNCF [code of conduct](code-of-conduct.md). Here is an excerpt:
_As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities._
## Getting Started
We have full documentation on how to get started contributing here:
<!---
If your repo has certain guidelines for contribution, put them here ahead of the general k8s resources
-->
- [Contributor License Agreement](https://git.k8s.io/community/CLA.md) Kubernetes projects require that you sign a Contributor License Agreement (CLA) before we can accept your pull requests
- [Kubernetes Contributor Guide](http://git.k8s.io/community/contributors/guide) - Main contributor documentation, or you can just jump directly to the [contributing section](http://git.k8s.io/community/contributors/guide#contributing)
- [Contributor Cheat Sheet](https://git.k8s.io/community/contributors/guide/contributor-cheatsheet.md) - Common resources for existing developers
## Mentorship
- [Mentoring Initiatives](https://git.k8s.io/community/mentoring) - We have a diverse set of mentorship programs available that are always looking for volunteers!
<!---
Custom Information - if you're copying this template for the first time you can add custom content here, for example:
## Contact Information
- [Slack channel](https://kubernetes.slack.com/messages/kubernetes-users) - Replace `kubernetes-users` with your slack channel string, this will send users directly to your channel.
- [Mailing list](URL)
-->

View File

@ -0,0 +1,149 @@
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
[[projects]]
digest = "1:ffe9824d294da03b391f44e1ae8281281b4afc1bdaa9588c9097785e3af10cec"
name = "github.com/davecgh/go-spew"
packages = ["spew"]
pruneopts = "UT"
revision = "8991bc29aa16c548c550c7ff78260e27b9ab7c73"
version = "v1.1.1"
[[projects]]
digest = "1:9cab16c200148edbdc9f314f69bf71987085f618ec107385bd6634be21d1aae8"
name = "github.com/golang/protobuf"
packages = [
"descriptor",
"proto",
"protoc-gen-go/descriptor",
"ptypes",
"ptypes/any",
"ptypes/duration",
"ptypes/timestamp",
"ptypes/wrappers",
]
pruneopts = "UT"
revision = "aa810b61a9c79d51363740d207bb46cf8e620ed5"
version = "v1.2.0"
[[projects]]
digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe"
name = "github.com/pmezard/go-difflib"
packages = ["difflib"]
pruneopts = "UT"
revision = "792786c7400a136282c1664665ae0a8db921c6c2"
version = "v1.0.0"
[[projects]]
digest = "1:18752d0b95816a1b777505a97f71c7467a8445b8ffb55631a7bf779f6ba4fa83"
name = "github.com/stretchr/testify"
packages = ["assert"]
pruneopts = "UT"
revision = "f35b8ab0b5a2cef36673838d662e249dd9c94686"
version = "v1.2.2"
[[projects]]
branch = "master"
digest = "1:6ca51c5d8a610b3da56856df7a8f8f3e075eba8d5f7a4acbadd79b2d2a368054"
name = "golang.org/x/net"
packages = [
"context",
"http/httpguts",
"http2",
"http2/hpack",
"idna",
"internal/timeseries",
"trace",
]
pruneopts = "UT"
revision = "fae4c4e3ad76c295c3d6d259f898136b4bf833a8"
[[projects]]
branch = "master"
digest = "1:8775d8a768d9e65e8b659172804aac5db1fc8d563ba766470a6c2698c57c61a7"
name = "golang.org/x/sys"
packages = ["unix"]
pruneopts = "UT"
revision = "4ed8d59d0b35e1e29334a206d1b3f38b1e5dfb31"
[[projects]]
digest = "1:a2ab62866c75542dd18d2b069fec854577a20211d7c0ea6ae746072a1dccdd18"
name = "golang.org/x/text"
packages = [
"collate",
"collate/build",
"internal/colltab",
"internal/gen",
"internal/tag",
"internal/triegen",
"internal/ucd",
"language",
"secure/bidirule",
"transform",
"unicode/bidi",
"unicode/cldr",
"unicode/norm",
"unicode/rangetable",
]
pruneopts = "UT"
revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0"
version = "v0.3.0"
[[projects]]
branch = "master"
digest = "1:56b0bca90b7e5d1facf5fbdacba23e4e0ce069d25381b8e2f70ef1e7ebfb9c1a"
name = "google.golang.org/genproto"
packages = ["googleapis/rpc/status"]
pruneopts = "UT"
revision = "31ac5d88444a9e7ad18077db9a165d793ad06a2e"
[[projects]]
digest = "1:c3ad9841823db6da420a5625b367913b4ff54bbe60e8e3c98bd20e243e62e2d2"
name = "google.golang.org/grpc"
packages = [
".",
"balancer",
"balancer/base",
"balancer/roundrobin",
"codes",
"connectivity",
"credentials",
"encoding",
"encoding/proto",
"grpclog",
"internal",
"internal/backoff",
"internal/channelz",
"internal/envconfig",
"internal/grpcrand",
"internal/transport",
"keepalive",
"metadata",
"naming",
"peer",
"resolver",
"resolver/dns",
"resolver/passthrough",
"stats",
"status",
"tap",
]
pruneopts = "UT"
revision = "2e463a05d100327ca47ac218281906921038fd95"
version = "v1.16.0"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
input-imports = [
"github.com/golang/protobuf/descriptor",
"github.com/golang/protobuf/proto",
"github.com/golang/protobuf/protoc-gen-go/descriptor",
"github.com/golang/protobuf/ptypes/timestamp",
"github.com/golang/protobuf/ptypes/wrappers",
"github.com/stretchr/testify/assert",
"golang.org/x/net/context",
"google.golang.org/grpc",
]
solver-name = "gps-cdcl"
solver-version = 1

View File

@ -0,0 +1,6 @@
# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html
# for detailed Gopkg.toml documentation.
[prune]
go-tests = true
unused-packages = true

201
vendor/github.com/kubernetes-csi/csi-lib-utils/LICENSE generated vendored Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,35 @@
# Copyright 2018 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.
.PHONY: all clean test
ifdef V
TESTARGS = -v
else
TESTARGS =
endif
all:
go build `go list ./... | grep -v 'vendor'`
clean:
true
test:
go test `go list ./... | grep -v ^vendor` $(TESTARGS)
go vet `go list ./... | grep -v ^vendor`
diff="$$(gofmt -d $$(find . -name '*.go' | grep -v ^./vendor))" && \
( [ -z "$$diff" ] || ( \
echo "\nvvvvvv formatting errors, fix with patch -p1 vvvvvvvvvv\n$$diff\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n"; \
false ) )

View File

@ -0,0 +1,4 @@
# See the OWNERS docs: https://git.k8s.io/community/contributors/guide/owners.md
approvers:
- saad-ali

View File

@ -0,0 +1,19 @@
# csi-lib-utils
TBD
## Community, discussion, contribution, and support
Learn how to engage with the Kubernetes community on the [community page](http://kubernetes.io/community/).
You can reach the maintainers of this project at:
- [Slack](http://slack.k8s.io/)
- [Mailing List](https://groups.google.com/forum/#!forum/kubernetes-dev)
### Code of conduct
Participation in the Kubernetes community is governed by the [Kubernetes Code of Conduct](code-of-conduct.md).
[owners]: https://git.k8s.io/community/contributors/guide/owners.md
[Creative Commons 4.0]: https://git.k8s.io/website/LICENSE

View File

@ -0,0 +1,13 @@
# Defined below are the security contacts for this repo.
#
# They are the contact point for the Product Security Team to reach out
# to for triaging and handling of incoming issues.
#
# The below names agree to abide by the
# [Embargo Policy](https://github.com/kubernetes/sig-release/blob/master/security-release-process-documentation/security-release-process.md#embargo-policy)
# and will be removed and replaced if they violate that agreement.
#
# DO NOT REPORT SECURITY VULNERABILITIES DIRECTLY TO THESE NAMES, FOLLOW THE
# INSTRUCTIONS AT https://kubernetes.io/security/
saad-ali

View File

@ -0,0 +1,3 @@
# Kubernetes Community Code of Conduct
Please refer to our [Kubernetes Community Code of Conduct](https://git.k8s.io/community/code-of-conduct.md)

View File

@ -0,0 +1,177 @@
/*
Copyright 2018 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 protosanitizer supports logging of gRPC messages without
// accidentally revealing sensitive fields.
package protosanitizer
import (
"encoding/json"
"fmt"
"reflect"
"strings"
"github.com/golang/protobuf/descriptor"
"github.com/golang/protobuf/proto"
protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor"
protobufdescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
)
// StripSecrets returns a wrapper around the original CSI gRPC message
// which has a Stringer implementation that serializes the message
// as one-line JSON, but without including secret information.
// Instead of the secret value(s), the string "***stripped***" is
// included in the result.
//
// StripSecrets relies on an extension in CSI 1.0 and thus can only
// be used for messages based on that or a more recent spec!
//
// StripSecrets itself is fast and therefore it is cheap to pass the
// result to logging functions which may or may not end up serializing
// the parameter depending on the current log level.
func StripSecrets(msg interface{}) fmt.Stringer {
return &stripSecrets{msg, isCSI1Secret}
}
// StripSecretsCSI03 is like StripSecrets, except that it works
// for messages based on CSI 0.3 and older. It does not work
// for CSI 1.0, use StripSecrets for that.
func StripSecretsCSI03(msg interface{}) fmt.Stringer {
return &stripSecrets{msg, isCSI03Secret}
}
type stripSecrets struct {
msg interface{}
isSecretField func(field *protobuf.FieldDescriptorProto) bool
}
func (s *stripSecrets) String() string {
// First convert to a generic representation. That's less efficient
// than using reflect directly, but easier to work with.
var parsed interface{}
b, err := json.Marshal(s.msg)
if err != nil {
return fmt.Sprintf("<<json.Marshal %T: %s>>", s.msg, err)
}
if err := json.Unmarshal(b, &parsed); err != nil {
return fmt.Sprintf("<<json.Unmarshal %T: %s>>", s.msg, err)
}
// Now remove secrets from the generic representation of the message.
s.strip(parsed, s.msg)
// Re-encoded the stripped representation and return that.
b, err = json.Marshal(parsed)
if err != nil {
return fmt.Sprintf("<<json.Marshal %T: %s>>", s.msg, err)
}
return string(b)
}
func (s *stripSecrets) strip(parsed interface{}, msg interface{}) {
protobufMsg, ok := msg.(descriptor.Message)
if !ok {
// Not a protobuf message, so we are done.
return
}
// The corresponding map in the parsed JSON representation.
parsedFields, ok := parsed.(map[string]interface{})
if !ok {
// Probably nil.
return
}
// Walk through all fields and replace those with ***stripped*** that
// are marked as secret. This relies on protobuf adding "json:" tags
// on each field where the name matches the field name in the protobuf
// spec (like volume_capabilities). The field.GetJsonName() method returns
// a different name (volumeCapabilities) which we don't use.
_, md := descriptor.ForMessage(protobufMsg)
fields := md.GetField()
if fields != nil {
for _, field := range fields {
if s.isSecretField(field) {
// Overwrite only if already set.
if _, ok := parsedFields[field.GetName()]; ok {
parsedFields[field.GetName()] = "***stripped***"
}
} else if field.GetType() == protobuf.FieldDescriptorProto_TYPE_MESSAGE {
// When we get here,
// the type name is something like ".csi.v1.CapacityRange" (leading dot!)
// and looking up "csi.v1.CapacityRange"
// returns the type of a pointer to a pointer
// to CapacityRange. We need a pointer to such
// a value for recursive stripping.
typeName := field.GetTypeName()
if strings.HasPrefix(typeName, ".") {
typeName = typeName[1:]
}
t := proto.MessageType(typeName)
if t == nil || t.Kind() != reflect.Ptr {
// Shouldn't happen, but
// better check anyway instead
// of panicking.
continue
}
v := reflect.New(t.Elem())
// Recursively strip the message(s) that
// the field contains.
i := v.Interface()
entry := parsedFields[field.GetName()]
if slice, ok := entry.([]interface{}); ok {
// Array of values, like VolumeCapabilities in CreateVolumeRequest.
for _, entry := range slice {
s.strip(entry, i)
}
} else {
// Single value.
s.strip(entry, i)
}
}
}
}
}
// isCSI1Secret uses the csi.E_CsiSecret extension from CSI 1.0 to
// determine whether a field contains secrets.
func isCSI1Secret(field *protobuf.FieldDescriptorProto) bool {
ex, err := proto.GetExtension(field.Options, e_CsiSecret)
return err == nil && ex != nil && *ex.(*bool)
}
// Copied from the CSI 1.0 spec (https://github.com/container-storage-interface/spec/blob/37e74064635d27c8e33537c863b37ccb1182d4f8/lib/go/csi/csi.pb.go#L4520-L4527)
// to avoid a package dependency that would prevent usage of this package
// in repos using an older version of the spec.
//
// Future revision of the CSI spec must not change this extensions, otherwise
// they will break filtering in binaries based on the 1.0 version of the spec.
var e_CsiSecret = &proto.ExtensionDesc{
ExtendedType: (*protobufdescriptor.FieldOptions)(nil),
ExtensionType: (*bool)(nil),
Field: 1059,
Name: "csi.v1.csi_secret",
Tag: "varint,1059,opt,name=csi_secret,json=csiSecret",
Filename: "github.com/container-storage-interface/spec/csi.proto",
}
// isCSI03Secret relies on the naming convention in CSI <= 0.3
// to determine whether a field contains secrets.
func isCSI03Secret(field *protobuf.FieldDescriptorProto) bool {
return strings.HasSuffix(field.GetName(), "_secrets")
}

View File

@ -0,0 +1,224 @@
/*
Copyright 2018 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 protosanitizer
import (
"fmt"
"testing"
"github.com/golang/protobuf/proto"
csi03 "github.com/kubernetes-csi/csi-lib-utils/protosanitizer/test/csi03"
csi "github.com/kubernetes-csi/csi-lib-utils/protosanitizer/test/csi10"
"github.com/kubernetes-csi/csi-lib-utils/protosanitizer/test/csitest"
"github.com/stretchr/testify/assert"
)
func TestStripSecrets(t *testing.T) {
secretName := "secret-abc"
secretValue := "123"
// CSI 0.3.0.
createVolumeCSI03 := &csi03.CreateVolumeRequest{
AccessibilityRequirements: &csi03.TopologyRequirement{
Requisite: []*csi03.Topology{
&csi03.Topology{
Segments: map[string]string{
"foo": "bar",
"x": "y",
},
},
&csi03.Topology{
Segments: map[string]string{
"a": "b",
},
},
},
},
Name: "foo",
VolumeCapabilities: []*csi03.VolumeCapability{
&csi03.VolumeCapability{
AccessType: &csi03.VolumeCapability_Mount{
Mount: &csi03.VolumeCapability_MountVolume{
FsType: "ext4",
},
},
},
},
CapacityRange: &csi03.CapacityRange{
RequiredBytes: 1024,
},
ControllerCreateSecrets: map[string]string{
secretName: secretValue,
"secret-xyz": "987",
},
}
// Current spec.
createVolume := &csi.CreateVolumeRequest{
AccessibilityRequirements: &csi.TopologyRequirement{
Requisite: []*csi.Topology{
&csi.Topology{
Segments: map[string]string{
"foo": "bar",
"x": "y",
},
},
&csi.Topology{
Segments: map[string]string{
"a": "b",
},
},
},
},
Name: "foo",
VolumeCapabilities: []*csi.VolumeCapability{
&csi.VolumeCapability{
AccessType: &csi.VolumeCapability_Mount{
Mount: &csi.VolumeCapability_MountVolume{
FsType: "ext4",
},
},
},
},
CapacityRange: &csi.CapacityRange{
RequiredBytes: 1024,
},
Secrets: map[string]string{
secretName: secretValue,
"secret-xyz": "987",
},
}
// Revised spec with more secret fields.
createVolumeFuture := &csitest.CreateVolumeRequest{
CapacityRange: &csitest.CapacityRange{
RequiredBytes: 1024,
},
MaybeSecretMap: map[int64]*csitest.VolumeCapability{
1: &csitest.VolumeCapability{ArraySecret: "aaa"},
2: &csitest.VolumeCapability{ArraySecret: "bbb"},
},
Name: "foo",
NewSecretInt: 42,
Seecreets: map[string]string{
secretName: secretValue,
"secret-xyz": "987",
},
VolumeCapabilities: []*csitest.VolumeCapability{
&csitest.VolumeCapability{
AccessType: &csitest.VolumeCapability_Mount{
Mount: &csitest.VolumeCapability_MountVolume{
FsType: "ext4",
},
},
ArraySecret: "knock knock",
},
&csitest.VolumeCapability{
ArraySecret: "Who's there?",
},
},
VolumeContentSource: &csitest.VolumeContentSource{
Type: &csitest.VolumeContentSource_Volume{
Volume: &csitest.VolumeContentSource_VolumeSource{
VolumeId: "abc",
OneofSecretField: "hello",
},
},
NestedSecretField: "world",
},
}
type testcase struct {
original, stripped interface{}
}
cases := []testcase{
{nil, "null"},
{1, "1"},
{"hello world", `"hello world"`},
{true, "true"},
{false, "false"},
{&csi.CreateVolumeRequest{}, `{}`},
// Test case from https://github.com/kubernetes-csi/csi-lib-utils/pull/1#pullrequestreview-180126394.
{&csi.CreateVolumeRequest{
Name: "test-volume",
CapacityRange: &csi.CapacityRange{
RequiredBytes: int64(1024),
LimitBytes: int64(1024),
},
VolumeCapabilities: []*csi.VolumeCapability{
&csi.VolumeCapability{
AccessType: &csi.VolumeCapability_Mount{
Mount: &csi.VolumeCapability_MountVolume{
FsType: "ext4",
MountFlags: []string{"flag1", "flag2", "flag3"},
},
},
AccessMode: &csi.VolumeCapability_AccessMode{
Mode: csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER,
},
},
},
Secrets: map[string]string{"secret1": "secret1", "secret2": "secret2"},
Parameters: map[string]string{"param1": "param1", "param2": "param2"},
VolumeContentSource: &csi.VolumeContentSource{},
AccessibilityRequirements: &csi.TopologyRequirement{},
}, `{"accessibility_requirements":{},"capacity_range":{"limit_bytes":1024,"required_bytes":1024},"name":"test-volume","parameters":{"param1":"param1","param2":"param2"},"secrets":"***stripped***","volume_capabilities":[{"AccessType":{"Mount":{"fs_type":"ext4","mount_flags":["flag1","flag2","flag3"]}},"access_mode":{"mode":5}}],"volume_content_source":{"Type":null}}`},
{createVolume, `{"accessibility_requirements":{"requisite":[{"segments":{"foo":"bar","x":"y"}},{"segments":{"a":"b"}}]},"capacity_range":{"required_bytes":1024},"name":"foo","secrets":"***stripped***","volume_capabilities":[{"AccessType":{"Mount":{"fs_type":"ext4"}}}]}`},
{createVolumeCSI03, `{"accessibility_requirements":{"requisite":[{"segments":{"foo":"bar","x":"y"}},{"segments":{"a":"b"}}]},"capacity_range":{"required_bytes":1024},"controller_create_secrets":"***stripped***","name":"foo","volume_capabilities":[{"AccessType":{"Mount":{"fs_type":"ext4"}}}]}`},
{&csitest.CreateVolumeRequest{}, `{}`},
{createVolumeFuture,
// Secrets are *not* removed from all fields yet. This will have to be fixed one way or another
// before the CSI spec can start using secrets there (currently it doesn't).
// The test is still useful because it shows that also complicated fields get serialized.
// `{"capacity_range":{"required_bytes":1024},"maybe_secret_map":{"1":{"AccessType":null,"array_secret":"***stripped***"},"2":{"AccessType":null,"array_secret":"***stripped***"}},"name":"foo","new_secret_int":"***stripped***","seecreets":"***stripped***","volume_capabilities":[{"AccessType":{"Mount":{"fs_type":"ext4"}},"array_secret":"***stripped***"},{"AccessType":null,"array_secret":"***stripped***"}],"volume_content_source":{"Type":{"Volume":{"oneof_secret_field":"***stripped***","volume_id":"abc"}},"nested_secret_field":"***stripped***"}}`,
`{"capacity_range":{"required_bytes":1024},"maybe_secret_map":{"1":{"AccessType":null,"array_secret":"aaa"},"2":{"AccessType":null,"array_secret":"bbb"}},"name":"foo","new_secret_int":"***stripped***","seecreets":"***stripped***","volume_capabilities":[{"AccessType":{"Mount":{"fs_type":"ext4"}},"array_secret":"***stripped***"},{"AccessType":null,"array_secret":"***stripped***"}],"volume_content_source":{"Type":{"Volume":{"oneof_secret_field":"hello","volume_id":"abc"}},"nested_secret_field":"***stripped***"}}`,
},
}
// Message from revised spec as received by a sidecar based on the current spec.
// The XXX_unrecognized field contains secrets and must not get logged.
unknownFields := &csi.CreateVolumeRequest{}
data, err := proto.Marshal(createVolumeFuture)
if assert.NoError(t, err, "marshall future message") &&
assert.NoError(t, proto.Unmarshal(data, unknownFields), "unmarshal with unknown fields") {
cases = append(cases, testcase{unknownFields,
`{"capacity_range":{"required_bytes":1024},"name":"foo","secrets":"***stripped***","volume_capabilities":[{"AccessType":{"Mount":{"fs_type":"ext4"}}},{"AccessType":null}],"volume_content_source":{"Type":{"Volume":{"volume_id":"abc"}}}}`,
})
}
for _, c := range cases {
before := fmt.Sprint(c.original)
var stripped fmt.Stringer
if _, ok := c.original.(*csi03.CreateVolumeRequest); ok {
stripped = StripSecretsCSI03(c.original)
} else {
stripped = StripSecrets(c.original)
}
if assert.Equal(t, c.stripped, fmt.Sprintf("%s", stripped), "unexpected result for fmt s of %s", c.original) {
if assert.Equal(t, c.stripped, fmt.Sprintf("%v", stripped), "unexpected result for fmt v of %s", c.original) {
assert.Equal(t, c.stripped, fmt.Sprintf("%+v", stripped), "unexpected result for fmt +v of %s", c.original)
}
}
assert.Equal(t, before, fmt.Sprint(c.original), "original value modified")
}
// The secret is hidden because StripSecrets is a struct referencing it.
dump := fmt.Sprintf("%#v", StripSecrets(createVolume))
assert.NotContains(t, dump, secretName)
assert.NotContains(t, dump, secretValue)
}

View File

@ -0,0 +1,5 @@
/protoc
/protoc-gen-go
/csi.a
/.protoc
.build

View File

@ -0,0 +1,136 @@
all: build
########################################################################
## GOLANG ##
########################################################################
# If GOPATH isn't defined then set its default location.
ifeq (,$(strip $(GOPATH)))
GOPATH := $(HOME)/go
else
# If GOPATH is already set then update GOPATH to be its own
# first element.
GOPATH := $(word 1,$(subst :, ,$(GOPATH)))
endif
export GOPATH
########################################################################
## PROTOC ##
########################################################################
# Only set PROTOC_VER if it has an empty value.
ifeq (,$(strip $(PROTOC_VER)))
PROTOC_VER := 3.5.1
endif
PROTOC_OS := $(shell uname -s)
ifeq (Darwin,$(PROTOC_OS))
PROTOC_OS := osx
endif
PROTOC_ARCH := $(shell uname -m)
ifeq (i386,$(PROTOC_ARCH))
PROTOC_ARCH := x86_32
endif
PROTOC := ./protoc
PROTOC_ZIP := protoc-$(PROTOC_VER)-$(PROTOC_OS)-$(PROTOC_ARCH).zip
PROTOC_URL := https://github.com/google/protobuf/releases/download/v$(PROTOC_VER)/$(PROTOC_ZIP)
PROTOC_TMP_DIR := .protoc
PROTOC_TMP_BIN := $(PROTOC_TMP_DIR)/bin/protoc
$(PROTOC):
-mkdir -p "$(PROTOC_TMP_DIR)" && \
curl -L $(PROTOC_URL) -o "$(PROTOC_TMP_DIR)/$(PROTOC_ZIP)" && \
unzip "$(PROTOC_TMP_DIR)/$(PROTOC_ZIP)" -d "$(PROTOC_TMP_DIR)" && \
chmod 0755 "$(PROTOC_TMP_BIN)" && \
cp -f "$(PROTOC_TMP_BIN)" "$@"
stat "$@" > /dev/null 2>&1
########################################################################
## PROTOC-GEN-GO ##
########################################################################
# This is the recipe for getting and installing the go plug-in
# for protoc
PROTOC_GEN_GO_PKG := github.com/golang/protobuf/protoc-gen-go
PROTOC_GEN_GO := protoc-gen-go
$(PROTOC_GEN_GO): PROTOBUF_PKG := $(dir $(PROTOC_GEN_GO_PKG))
$(PROTOC_GEN_GO): PROTOBUF_VERSION := v1.2.0
$(PROTOC_GEN_GO):
mkdir -p $(dir $(GOPATH)/src/$(PROTOBUF_PKG))
test -d $(GOPATH)/src/$(PROTOBUF_PKG)/.git || git clone https://$(PROTOBUF_PKG) $(GOPATH)/src/$(PROTOBUF_PKG)
(cd $(GOPATH)/src/$(PROTOBUF_PKG) && \
(test "$$(git describe --tags | head -1)" = "$(PROTOBUF_VERSION)" || \
(git fetch && git checkout tags/$(PROTOBUF_VERSION))))
(cd $(GOPATH)/src/$(PROTOBUF_PKG) && go get -v -d $$(go list -f '{{ .ImportPath }}' ./...)) && \
go build -o "$@" $(PROTOC_GEN_GO_PKG)
########################################################################
## PATH ##
########################################################################
# Update PATH with the current directory. This enables the protoc
# binary to discover the protoc-gen-go binary, built inside this
# directory.
export PATH := $(shell pwd):$(PATH)
########################################################################
## BUILD ##
########################################################################
CSI_PROTO := ./csitest.proto
CSI_PKG_ROOT := github.com/kubernetes-csi/csi-lib-utils/protosanitizer/test
CSI_PKG_SUB := $(shell cat $(CSI_PROTO) | sed -n -e 's/^package.\([^;]*\).v[0-9]\+;$$/\1/p'|tr '.' '/')
CSI_BUILD := $(CSI_PKG_SUB)/.build
CSI_GO := $(CSI_PKG_SUB)/csitest.pb.go
CSI_A := csi.a
CSI_GO_TMP := $(CSI_BUILD)/$(CSI_PKG_ROOT)/csitest.pb.go
# This recipe generates the go language bindings to a temp area.
$(CSI_GO_TMP): HERE := $(shell pwd)
$(CSI_GO_TMP): PTYPES_PKG := github.com/golang/protobuf/ptypes
$(CSI_GO_TMP): GO_OUT := plugins=grpc
$(CSI_GO_TMP): GO_OUT := $(GO_OUT),Mgoogle/protobuf/descriptor.proto=github.com/golang/protobuf/protoc-gen-go/descriptor
$(CSI_GO_TMP): GO_OUT := $(GO_OUT),Mgoogle/protobuf/wrappers.proto=$(PTYPES_PKG)/wrappers
$(CSI_GO_TMP): GO_OUT := $(GO_OUT):"$(HERE)/$(CSI_BUILD)"
$(CSI_GO_TMP): INCLUDE := -I$(GOPATH)/src -I$(HERE)/$(PROTOC_TMP_DIR)/include
$(CSI_GO_TMP): $(CSI_PROTO) | $(PROTOC) $(PROTOC_GEN_GO)
@mkdir -p "$(@D)"
(cd "$(GOPATH)/src" && \
$(HERE)/$(PROTOC) $(INCLUDE) --go_out=$(GO_OUT) "$(CSI_PKG_ROOT)/$(<F)")
# The temp language bindings are compared to the ones that are
# versioned. If they are different then it means the language
# bindings were not updated prior to being committed.
$(CSI_GO): $(CSI_GO_TMP)
ifeq (true,$(TRAVIS))
diff "$@" "$?"
else
@mkdir -p "$(@D)"
diff "$@" "$?" > /dev/null 2>&1 || cp -f "$?" "$@"
endif
# This recipe builds the Go archive from the sources in three steps:
#
# 1. Go get any missing dependencies.
# 2. Cache the packages.
# 3. Build the archive file.
$(CSI_A): $(CSI_GO)
go get -v -d ./...
go install ./$(CSI_PKG_SUB)
go build -o "$@" ./$(CSI_PKG_SUB)
build: $(CSI_A)
clean:
go clean -i ./...
rm -rf "$(CSI_A)" "$(CSI_GO)" "$(CSI_BUILD)"
clobber: clean
rm -fr "$(PROTOC)" "$(PROTOC_GEN_GO)" "$(CSI_PKG_SUB)" "$(PROTOC_TMP_DIR)"
.PHONY: clean clobber

View File

@ -0,0 +1,2 @@
This is a *modified* version of the CSI 1.0.0 spec. It's only purpose is
to test the stripping of secret fields.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -3,303 +3,245 @@
[[projects]]
branch = "master"
digest = "1:c0bec5f9b98d0bc872ff5e834fac186b807b656683bd29cb82fb207a1513fabb"
name = "github.com/beorn7/perks"
packages = ["quantile"]
pruneopts = ""
revision = "3a771d992973f24aa725d07868b467d1ddfceafb"
[[projects]]
digest = "1:93147eb1d6f08d39f2c0efe3d29ee043bda72be7a8b3b367eb08c72c18524638"
name = "github.com/container-storage-interface/spec"
packages = ["lib/go/csi"]
pruneopts = ""
revision = "ed0bb0e1557548aa028307f48728767cfe8f6345"
version = "v1.0.0"
[[projects]]
digest = "1:0deddd908b6b4b768cfc272c16ee61e7088a60f7fe2f06c547bd3d8e1f8b8e77"
name = "github.com/davecgh/go-spew"
packages = ["spew"]
pruneopts = ""
revision = "8991bc29aa16c548c550c7ff78260e27b9ab7c73"
version = "v1.1.1"
[[projects]]
digest = "1:2c87cf00343faf42f84cbda2e475281542497a250a85c5cfa50747f55028e2d8"
name = "github.com/docker/distribution"
packages = [
"digestset",
"reference",
"reference"
]
pruneopts = ""
revision = "5db89f0ca68677abc5eefce8f2a0a772c98ba52d"
[[projects]]
digest = "1:6e73003ecd35f4487a5e88270d3ca0a81bc80dc88053ac7e4dcfec5fba30d918"
name = "github.com/gogo/protobuf"
packages = [
"proto",
"sortkeys",
"sortkeys"
]
pruneopts = ""
revision = "636bf0302bc95575d69441b25a2603156ffdddf1"
version = "v1.1.1"
[[projects]]
branch = "master"
digest = "1:107b233e45174dbab5b1324201d092ea9448e58243ab9f039e4c0f332e121e3a"
name = "github.com/golang/glog"
packages = ["."]
pruneopts = ""
revision = "23def4e6c14b4da8ac2ed8007337bc5eb5007998"
[[projects]]
branch = "master"
digest = "1:aa2251148505e561bfa8cd6b69a319b37761da57b0b25529c4af08389559e3b9"
name = "github.com/golang/groupcache"
packages = ["lru"]
pruneopts = ""
revision = "c65c006176ff7ff98bb916961c7abbc6b0afc0aa"
[[projects]]
digest = "1:3dd078fda7500c341bc26cfbc6c6a34614f295a2457149fc1045cab767cbcf18"
name = "github.com/golang/protobuf"
packages = [
"descriptor",
"proto",
"protoc-gen-go/descriptor",
"ptypes",
"ptypes/any",
"ptypes/duration",
"ptypes/timestamp",
"ptypes/wrappers",
"ptypes/wrappers"
]
pruneopts = ""
revision = "aa810b61a9c79d51363740d207bb46cf8e620ed5"
version = "v1.2.0"
[[projects]]
branch = "master"
digest = "1:1e5b1e14524ed08301977b7b8e10c719ed853cbf3f24ecb66fae783a46f207a6"
name = "github.com/google/btree"
packages = ["."]
pruneopts = ""
revision = "4030bb1f1f0c35b30ca7009e9ebd06849dd45306"
[[projects]]
branch = "master"
digest = "1:754f77e9c839b24778a4b64422236d38515301d2baeb63113aa3edc42e6af692"
name = "github.com/google/gofuzz"
packages = ["."]
pruneopts = ""
revision = "24818f796faf91cd76ec7bddd72458fbced7a6c1"
[[projects]]
digest = "1:5247b135b5492aa232a731acdcb52b08f32b874cb398f21ab460396eadbe866b"
name = "github.com/google/uuid"
packages = ["."]
pruneopts = ""
revision = "d460ce9f8df2e77fb1ba55ca87fafed96c607494"
version = "v1.0.0"
[[projects]]
digest = "1:16b2837c8b3cf045fa2cdc82af0cf78b19582701394484ae76b2c3bc3c99ad73"
name = "github.com/googleapis/gnostic"
packages = [
"OpenAPIv2",
"compiler",
"extensions",
"extensions"
]
pruneopts = ""
revision = "7c663266750e7d82587642f65e60bc4083f1f84e"
version = "v0.2.0"
[[projects]]
branch = "master"
digest = "1:5e345eb75d8bfb2b91cfbfe02a82a79c0b2ea55cf06c5a4d180a9321f36973b4"
name = "github.com/gregjones/httpcache"
packages = [
".",
"diskcache",
"diskcache"
]
pruneopts = ""
revision = "c63ab54fda8f77302f8d414e19933f2b6026a089"
[[projects]]
digest = "1:3313a63031ae281e5f6fd7b0bbca733dfa04d2429df86519e3b4d4c016ccb836"
name = "github.com/hashicorp/golang-lru"
packages = [
".",
"simplelru",
"simplelru"
]
pruneopts = ""
revision = "20f1fb78b0740ba8c3cb143a61e86ba5c8669768"
version = "v0.5.0"
[[projects]]
digest = "1:870d441fe217b8e689d7949fef6e43efbc787e50f200cb1e70dbca9204a1d6be"
name = "github.com/inconshreveable/mousetrap"
packages = ["."]
pruneopts = ""
revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75"
version = "v1.0"
[[projects]]
digest = "1:b79fc583e4dc7055ed86742e22164ac41bf8c0940722dbcb600f1a3ace1a8cb5"
name = "github.com/json-iterator/go"
packages = ["."]
pruneopts = ""
revision = "1624edc4454b8682399def8740d46db5e4362ba4"
version = "v1.1.5"
[[projects]]
digest = "1:63722a4b1e1717be7b98fc686e0b30d5e7f734b9e93d7dee86293b6deab7ea28"
name = "github.com/kubernetes-csi/csi-lib-utils"
packages = ["protosanitizer"]
revision = "5853414e1d4771302e0df10d1870c444c2135799"
version = "v0.2.0"
[[projects]]
name = "github.com/matttproud/golang_protobuf_extensions"
packages = ["pbutil"]
pruneopts = ""
revision = "c12348ce28de40eed0136aa2b644d0ee0650e56c"
version = "v1.0.1"
[[projects]]
digest = "1:0c0ff2a89c1bb0d01887e1dac043ad7efbf3ec77482ef058ac423d13497e16fd"
name = "github.com/modern-go/concurrent"
packages = ["."]
pruneopts = ""
revision = "bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94"
version = "1.0.3"
[[projects]]
digest = "1:e32bdbdb7c377a07a9a46378290059822efdce5c8d96fe71940d87cb4f918855"
name = "github.com/modern-go/reflect2"
packages = ["."]
pruneopts = ""
revision = "4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd"
version = "1.0.1"
[[projects]]
digest = "1:5d9b668b0b4581a978f07e7d2e3314af18eb27b3fb5d19b70185b7c575723d11"
name = "github.com/opencontainers/go-digest"
packages = ["."]
pruneopts = ""
revision = "279bed98673dd5bef374d3b6e4b09e2af76183bf"
version = "v1.0.0-rc1"
[[projects]]
digest = "1:a5484d4fa43127138ae6e7b2299a6a52ae006c7f803d98d717f60abf3e97192e"
name = "github.com/pborman/uuid"
packages = ["."]
pruneopts = ""
revision = "adf5a7427709b9deb95d29d3fa8a2bf9cfd388f1"
version = "v1.2"
[[projects]]
branch = "master"
digest = "1:c24598ffeadd2762552269271b3b1510df2d83ee6696c1e543a0ff653af494bc"
name = "github.com/petar/GoLLRB"
packages = ["llrb"]
pruneopts = ""
revision = "53be0d36a84c2a886ca057d34b6aa4468df9ccb4"
[[projects]]
digest = "1:b46305723171710475f2dd37547edd57b67b9de9f2a6267cafdd98331fd6897f"
name = "github.com/peterbourgon/diskv"
packages = ["."]
pruneopts = ""
revision = "5f041e8faa004a95c88a202771f4cc3e991971e6"
version = "v2.0.1"
[[projects]]
digest = "1:256484dbbcd271f9ecebc6795b2df8cad4c458dd0f5fd82a8c2fa0c29f233411"
name = "github.com/pmezard/go-difflib"
packages = ["difflib"]
pruneopts = ""
revision = "792786c7400a136282c1664665ae0a8db921c6c2"
version = "v1.0.0"
[[projects]]
digest = "1:8b2082f564fe20dbb43a621ee0d57ae2777656ab14111d100d3d92d1b5b958b9"
name = "github.com/prometheus/client_golang"
packages = [
"prometheus",
"prometheus/internal",
"prometheus/internal"
]
pruneopts = ""
revision = "abad2d1bd44235a26707c172eab6bca5bf2dbad3"
version = "v0.9.1"
[[projects]]
branch = "master"
digest = "1:185cf55b1f44a1bf243558901c3f06efa5c64ba62cfdcbb1bf7bbe8c3fb68561"
name = "github.com/prometheus/client_model"
packages = ["go"]
pruneopts = ""
revision = "5c3871d89910bfb32f5fcab2aa4b9ec68e65a99f"
[[projects]]
branch = "master"
digest = "1:d522feb599bd02a4b76d3ad20b91668c87028a6b5fd19a1bed994e26f6cd3c6d"
name = "github.com/prometheus/common"
packages = [
"expfmt",
"internal/bitbucket.org/ww/goautoneg",
"model",
"model"
]
pruneopts = ""
revision = "41aa239b4cce3c56ab88fc366ae8b0a6423fa239"
[[projects]]
branch = "master"
digest = "1:1f62ed2c173c42c1edad2e94e127318ea11b0d28c62590c82a8d2d3cde189afe"
name = "github.com/prometheus/procfs"
packages = [
".",
"internal/util",
"nfs",
"xfs",
"xfs"
]
pruneopts = ""
revision = "185b4288413d2a0dd0806f78c90dde719829e5ae"
[[projects]]
digest = "1:a1403cc8a94b8d7956ee5e9694badef0e7b051af289caad1cf668331e3ffa4f6"
name = "github.com/spf13/cobra"
packages = ["."]
pruneopts = ""
revision = "ef82de70bb3f60c65fb8eebacbb2d122ef517385"
version = "v0.0.3"
[[projects]]
digest = "1:cbaf13cdbfef0e4734ed8a7504f57fe893d471d62a35b982bf6fb3f036449a66"
name = "github.com/spf13/pflag"
packages = ["."]
pruneopts = ""
revision = "298182f68c66c05229eb03ac171abe6e309ee79a"
version = "v1.0.3"
[[projects]]
digest = "1:c587772fb8ad29ad4db67575dad25ba17a51f072ff18a22b4f0257a4d9c24f75"
name = "github.com/stretchr/testify"
packages = ["assert"]
pruneopts = ""
revision = "f35b8ab0b5a2cef36673838d662e249dd9c94686"
version = "v1.2.2"
[[projects]]
branch = "master"
digest = "1:f7be435e0ca22e2cd62b2d2542081a231685837170a87a3662abb7cdf9f3f1cd"
name = "golang.org/x/crypto"
packages = [
"ed25519",
"ed25519/internal/edwards25519",
"pbkdf2",
"ssh/terminal",
"ssh/terminal"
]
pruneopts = ""
revision = "3d3f9f413869b949e48070b5bc593aa22cc2b8f2"
[[projects]]
branch = "master"
digest = "1:fbc2896199a45d32325e24ceb56624c7db49f9cfb068f739ee53339a8fb183b3"
name = "golang.org/x/net"
packages = [
"context",
@ -309,35 +251,29 @@
"http2/hpack",
"idna",
"internal/timeseries",
"trace",
"trace"
]
pruneopts = ""
revision = "88d92db4c548972d942ac2a3531a8a9a34c82ca6"
[[projects]]
branch = "master"
digest = "1:51d339a1d79f5c617fba14414aefb7dfd184b8ba0ddbb9f95251430b67c8aab8"
name = "golang.org/x/oauth2"
packages = [
".",
"internal",
"internal"
]
pruneopts = ""
revision = "f42d05182288abf10faef86d16c0d07b8d40ea2d"
[[projects]]
branch = "master"
digest = "1:3f5c191d90f1cf365ff1f88e4b08eb766ee6ade1cb2e4efd7c316cf7e015ac17"
name = "golang.org/x/sys"
packages = [
"unix",
"windows",
"windows"
]
pruneopts = ""
revision = "66b7b1311ac80bbafcd2daeef9a5e6e2cd1e2399"
[[projects]]
digest = "1:5acd3512b047305d49e8763eef7ba423901e85d5dd2fd1e71778a0ea8de10bd4"
name = "golang.org/x/text"
packages = [
"collate",
@ -353,22 +289,18 @@
"unicode/bidi",
"unicode/cldr",
"unicode/norm",
"unicode/rangetable",
"unicode/rangetable"
]
pruneopts = ""
revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0"
version = "v0.3.0"
[[projects]]
branch = "master"
digest = "1:14cb1d4240bcbbf1386ae763957e04e2765ec4e4ce7bb2769d05fa6faccd774e"
name = "golang.org/x/time"
packages = ["rate"]
pruneopts = ""
revision = "85acf8d2951cb2a3bde7632f9ff273ef0379bcbd"
[[projects]]
digest = "1:77d3cff3a451d50be4b52db9c7766c0d8570ba47593f0c9dc72173adb208e788"
name = "google.golang.org/appengine"
packages = [
"internal",
@ -377,22 +309,18 @@
"internal/log",
"internal/remote_api",
"internal/urlfetch",
"urlfetch",
"urlfetch"
]
pruneopts = ""
revision = "4a4468ece617fc8205e99368fa2200e9d1fad421"
version = "v1.3.0"
[[projects]]
branch = "master"
digest = "1:212d4045ef941b209a154001718705dc723bd77e0200fcea36d15ec87ed49dec"
name = "google.golang.org/genproto"
packages = ["googleapis/rpc/status"]
pruneopts = ""
revision = "b5d43981345bdb2c233eb4bf3277847b48c6fdc6"
[[projects]]
digest = "1:1293087271e314cfa2b3decededba2ecba0ff327e7b7809e00f73f616449191c"
name = "google.golang.org/grpc"
packages = [
".",
@ -420,43 +348,35 @@
"resolver/passthrough",
"stats",
"status",
"tap",
"tap"
]
pruneopts = ""
revision = "2e463a05d100327ca47ac218281906921038fd95"
version = "v1.16.0"
[[projects]]
digest = "1:75fb3fcfc73a8c723efde7777b40e8e8ff9babf30d8c56160d01beffea8a95a6"
name = "gopkg.in/inf.v0"
packages = ["."]
pruneopts = ""
revision = "d2d2541c53f18d2a059457998ce2876cc8e67cbf"
version = "v0.9.1"
[[projects]]
digest = "1:ddc5fa8f9159bea7d1ce58143e6d8fd8054018f7bc3709940aa7f7bc92855ed9"
name = "gopkg.in/square/go-jose.v2"
packages = [
".",
"cipher",
"json",
"jwt",
"jwt"
]
pruneopts = ""
revision = "ef984e69dd356202fd4e4910d4d9c24468bdf0b8"
version = "v2.1.9"
[[projects]]
digest = "1:f0620375dd1f6251d9973b5f2596228cc8042e887cd7f827e4220bc1ce8c30e2"
name = "gopkg.in/yaml.v2"
packages = ["."]
pruneopts = ""
revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183"
version = "v2.2.1"
[[projects]]
digest = "1:5f076f6f9c3ac4f2b99d79dc7974eabd3f51be35254aa0d8c4cf920fdb9c7ff8"
name = "k8s.io/api"
packages = [
"admissionregistration/v1alpha1",
@ -489,23 +409,19 @@
"settings/v1alpha1",
"storage/v1",
"storage/v1alpha1",
"storage/v1beta1",
"storage/v1beta1"
]
pruneopts = ""
revision = "fd83cbc87e7632ccd8bbab63d2b673d4e0c631cc"
version = "kubernetes-1.12.0"
[[projects]]
branch = "master"
digest = "1:570ce571245b39b4fc8a1a5552079e00b1be3aa2c3755b7be76d3eb7d7b8c0ad"
name = "k8s.io/apiextensions-apiserver"
packages = ["pkg/features"]
pruneopts = ""
revision = "2c43ee60e25b6e421b37db431bad60e7416a6fd4"
[[projects]]
branch = "master"
digest = "1:cebe5f04ee0890c78c57a957e9d69892cebe60ccda4d1001d9f759a70b1e1bd1"
name = "k8s.io/apimachinery"
packages = [
"pkg/api/equality",
@ -553,27 +469,23 @@
"pkg/version",
"pkg/watch",
"third_party/forked/golang/json",
"third_party/forked/golang/reflect",
"third_party/forked/golang/reflect"
]
pruneopts = ""
revision = "2a7c9300402896b3c073f2f47df85527c94f83a0"
[[projects]]
digest = "1:f129d76e4103ddcd176f1a07051eb1826922e54f489032bef8283f7f9c32c4f0"
name = "k8s.io/apiserver"
packages = [
"pkg/authentication/authenticator",
"pkg/authentication/serviceaccount",
"pkg/authentication/user",
"pkg/features",
"pkg/util/feature",
"pkg/util/feature"
]
pruneopts = ""
revision = "e85ad7b666fef0476185731329f4cff1536efff8"
version = "kubernetes-1.12.0"
[[projects]]
digest = "1:5d4153d12c3aed2c90a94262520d2498d5afa4d692554af55e65a7c5af0bc399"
name = "k8s.io/client-go"
packages = [
"discovery",
@ -701,43 +613,35 @@
"util/connrotation",
"util/flowcontrol",
"util/integer",
"util/retry",
"util/retry"
]
pruneopts = ""
revision = "1638f8970cefaa404ff3a62950f88b08292b2696"
version = "v9.0.0"
[[projects]]
branch = "master"
digest = "1:ae938748bf72ccd682e9009b6a3dcfedb695ace9cca3ef2ea9f8fd31411b3a44"
name = "k8s.io/csi-api"
packages = [
"pkg/apis/csi/v1alpha1",
"pkg/client/clientset/versioned",
"pkg/client/clientset/versioned/scheme",
"pkg/client/clientset/versioned/typed/csi/v1alpha1",
"pkg/client/clientset/versioned/typed/csi/v1alpha1"
]
pruneopts = ""
revision = "3ace7a84ffef58a17488dcefe2432bbeb74a5c7b"
[[projects]]
digest = "1:4f5eb833037cc0ba0bf8fe9cae6be9df62c19dd1c869415275c708daa8ccfda5"
name = "k8s.io/klog"
packages = ["."]
pruneopts = ""
revision = "a5bc97fbc634d635061f3146511332c7e313a55a"
version = "v0.1.0"
[[projects]]
branch = "master"
digest = "1:d3fdd2e6dafedf0cd13d327cb62c8675d1f309d5587245e3ad35b083589675af"
name = "k8s.io/kube-openapi"
packages = ["pkg/util/proto"]
pruneopts = ""
revision = "c59034cc13d587f5ef4e85ca0ade0c1866ae8e1d"
[[projects]]
digest = "1:6061aa42761235df375f20fa4a1aa6d1845cba3687575f3adb2ef3f3bc540af5"
name = "k8s.io/kubernetes"
packages = [
"pkg/api/legacyscheme",
@ -785,49 +689,29 @@
"pkg/volume/util/fs",
"pkg/volume/util/recyclerclient",
"pkg/volume/util/types",
"pkg/volume/util/volumepathhandler",
"pkg/volume/util/volumepathhandler"
]
pruneopts = ""
revision = "17c77c7898218073f14c8d573582e8d2313dc740"
version = "v1.12.2"
[[projects]]
branch = "master"
digest = "1:1aa5e3a611782785b985a64a27254bf93e9a23b24a5b9f3c4dfc49fb6e07fa39"
name = "k8s.io/utils"
packages = [
"exec",
"pointer",
"pointer"
]
pruneopts = ""
revision = "1bd4f387aa67de2eec07a362c10bc8bd7fe74237"
[[projects]]
digest = "1:321081b4a44256715f2b68411d8eda9a17f17ebfe6f0cc61d2cc52d11c08acfa"
name = "sigs.k8s.io/yaml"
packages = ["."]
pruneopts = ""
revision = "fd68e9863619f6ec2fdd8625fe1f02e7c877e480"
version = "v1.1.0"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
input-imports = [
"github.com/container-storage-interface/spec/lib/go/csi",
"github.com/golang/glog",
"github.com/golang/protobuf/ptypes",
"github.com/golang/protobuf/ptypes/timestamp",
"github.com/pborman/uuid",
"github.com/spf13/cobra",
"github.com/stretchr/testify/assert",
"golang.org/x/net/context",
"google.golang.org/grpc",
"google.golang.org/grpc/codes",
"google.golang.org/grpc/status",
"k8s.io/kubernetes/pkg/util/mount",
"k8s.io/kubernetes/pkg/volume/util",
"k8s.io/utils/exec",
]
inputs-digest = "def5c710353323b5914b2b6c19a4ffe3a328764a00ae74f8bca45931f1b2e3ca"
solver-name = "gps-cdcl"
solver-version = 1

View File

@ -20,6 +20,9 @@
# name = "github.com/x/y"
# version = "2.4.0"
[prune]
go-tests = true
unused-packages = true
[[constraint]]
name = "github.com/container-storage-interface/spec"
@ -76,3 +79,7 @@
[[override]]
name = "gopkg.in/square/go-jose.v2"
version = "2.1.7"
[[constraint]]
name = "github.com/kubernetes-csi/csi-lib-utils"
version = "0.2.0"

View File

@ -0,0 +1,13 @@
# Defined below are the security contacts for this repo.
#
# They are the contact point for the Product Security Team to reach out
# to for triaging and handling of incoming issues.
#
# The below names agree to abide by the
# [Embargo Policy](https://github.com/kubernetes/sig-release/blob/master/security-release-process-documentation/security-release-process.md#embargo-policy)
# and will be removed and replaced if they violate that agreement.
#
# DO NOT REPORT SECURITY VULNERABILITIES DIRECTLY TO THESE NAMES, FOLLOW THE
# INSTRUCTIONS AT https://kubernetes.io/security/
saad-ali

View File

@ -0,0 +1,6 @@
The .yaml files in this directory depend on the RBAC files that were
released together the CSI sidecar containers. Check the repos and/or
release notes for the CSI sidecar containers for details.
https://kubernetes-csi.github.io/docs/ has an example that puts all
pieces together.

View File

@ -11,7 +11,7 @@ spec:
labels:
app: csi-hostpathplugin
spec:
serviceAccountName: csi-node-sa
serviceAccountName: csi-driver-registrar
hostNetwork: true
containers:
- name: driver-registrar

View File

@ -22,6 +22,7 @@ import (
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/golang/glog"
"github.com/kubernetes-csi/csi-lib-utils/protosanitizer"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
@ -94,12 +95,12 @@ func RunControllerandNodePublishServer(endpoint string, d *CSIDriver, cs csi.Con
func logGRPC(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
glog.V(3).Infof("GRPC call: %s", info.FullMethod)
glog.V(5).Infof("GRPC request: %+v", req)
glog.V(5).Infof("GRPC request: %s", protosanitizer.StripSecrets(req))
resp, err := handler(ctx, req)
if err != nil {
glog.Errorf("GRPC error: %v", err)
} else {
glog.V(5).Infof("GRPC response: %+v", resp)
glog.V(5).Infof("GRPC response: %s", protosanitizer.StripSecrets(resp))
}
return resp, err
}

View File

@ -57,9 +57,21 @@ func (cs *controllerServer) CreateVolume(ctx context.Context, req *csi.CreateVol
if len(req.GetName()) == 0 {
return nil, status.Error(codes.InvalidArgument, "Name missing in request")
}
if req.GetVolumeCapabilities() == nil {
caps := req.GetVolumeCapabilities()
if caps == nil {
return nil, status.Error(codes.InvalidArgument, "Volume Capabilities missing in request")
}
for _, cap := range caps {
if cap.GetBlock() != nil {
return nil, status.Error(codes.Unimplemented, "Block Volume not supported")
}
}
// A real driver would also need to check that the other
// fields in VolumeCapabilities are sane. The check above is
// just enough to pass the "[Testpattern: Dynamic PV (block
// volmode)] volumeMode should fail in binding dynamic
// provisioned PV to PVC" storage E2E test.
// Need to check for already existing volume name, and if found
// check for the requested capacity and already allocated capacity
if exVol, err := getVolumeByName(req.GetName()); err == nil {

23
vendor/github.com/petar/GoLLRB/.gitignore generated vendored Normal file
View File

@ -0,0 +1,23 @@
syntax:glob
*.[568ao]
*.ao
*.so
*.pyc
*.swp
*.swo
._*
.nfs.*
[568a].out
*~
*.orig
*.pb.go
core
_obj
_test
src/pkg/Make.deps
_testmain.go
syntax:regexp
^pkg/
^src/cmd/(.*)/6?\1$
^.*/core.[0-9]*$

4
vendor/github.com/petar/GoLLRB/AUTHORS generated vendored Normal file
View File

@ -0,0 +1,4 @@
Petar Maymounkov <petar@5ttt.org>
Vadim Vygonets <vadik@vygo.net>
Ian Smith <iansmith@acm.org>
Martin Bruse

27
vendor/github.com/petar/GoLLRB/LICENSE generated vendored Normal file
View File

@ -0,0 +1,27 @@
Copyright (c) 2010, Petar Maymounkov
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
(*) Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
(*) Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
(*) Neither the name of Petar Maymounkov nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

66
vendor/github.com/petar/GoLLRB/README.md generated vendored Normal file
View File

@ -0,0 +1,66 @@
# GoLLRB
GoLLRB is a Left-Leaning Red-Black (LLRB) implementation of 2-3 balanced binary
search trees in Go Language.
## Overview
As of this writing and to the best of the author's knowledge,
Go still does not have a balanced binary search tree (BBST) data structure.
These data structures are quite useful in a variety of cases. A BBST maintains
elements in sorted order under dynamic updates (inserts and deletes) and can
support various order-specific queries. Furthermore, in practice one often
implements other common data structures like Priority Queues, using BBST's.
2-3 trees (a type of BBST's), as well as the runtime-similar 2-3-4 trees, are
the de facto standard BBST algoritms found in implementations of Python, Java,
and other libraries. The LLRB method of implementing 2-3 trees is a recent
improvement over the traditional implementation. The LLRB approach was
discovered relatively recently (in 2008) by Robert Sedgewick of Princeton
University.
GoLLRB is a Go implementation of LLRB 2-3 trees.
## Maturity
GoLLRB has been used in some pretty heavy-weight machine learning tasks over many gigabytes of data.
I consider it to be in stable, perhaps even production, shape. There are no known bugs.
## Installation
With a healthy Go Language installed, simply run `go get github.com/petar/GoLLRB/llrb`
## Example
package main
import (
"fmt"
"github.com/petar/GoLLRB/llrb"
)
func lessInt(a, b interface{}) bool { return a.(int) < b.(int) }
func main() {
tree := llrb.New(lessInt)
tree.ReplaceOrInsert(1)
tree.ReplaceOrInsert(2)
tree.ReplaceOrInsert(3)
tree.ReplaceOrInsert(4)
tree.DeleteMin()
tree.Delete(4)
c := tree.IterAscend()
for {
u := <-c
if u == nil {
break
}
fmt.Printf("%d\n", int(u.(int)))
}
}
## About
GoLLRB was written by [Petar Maymounkov](http://pdos.csail.mit.edu/~petar/).
Follow me on [Twitter @maymounkov](http://www.twitter.com/maymounkov)!

4401
vendor/github.com/petar/GoLLRB/doc/Sedgewick-LLRB.pdf generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,475 @@
public class RedBlackBST<Key extends Comparable<Key>, Value>
{
private static final int BST = 0;
private static final int TD234 = 1;
private static final int BU23 = 2;
private static final boolean RED = true;
private static final boolean BLACK = false;
private Node root; // root of the BST
private int k; // ordinal for drawing
private final int species; // species kind of tree for insert
private int heightBLACK; // black height of tree
RedBlackBST(int species)
{ this.species = species; }
private class Node
{
Key key; // key
Value value; // associated data
Node left, right; // left and right subtrees
boolean color; // color of parent link
private int N; // number of nodes in tree rooted here
private int height; // height of tree rooted here
private double xc, yc; // for drawing
Node(Key key, Value value)
{
this.key = key;
this.value = value;
this.color = RED;
this.N = 1;
this.height = 1;
}
}
public int size()
{ return size(root); }
private int size(Node x)
{
if (x == null) return 0;
else return x.N;
}
public int rootRank()
{
if (root == null) return 0;
else return size(root.left);
}
public int height()
{ return height(root); }
public int heightB()
{ return heightBLACK; }
private int height(Node x)
{
if (x == null) return 0;
else return x.height;
}
public boolean contains(Key key)
{ return (get(key) != null); }
public Value get(Key key)
{ return get(root, key); }
private Value get(Node x, Key key)
{
if (x == null) return null;
if (eq (key, x.key)) return x.value;
if (less(key, x.key)) return get(x.left, key);
else return get(x.right, key);
}
public Key min()
{
if (root == null) return null;
else return min(root);
}
private Key min(Node x)
{
if (x.left == null) return x.key;
else return min(x.left);
}
public Key max()
{
if (root == null) return null;
else return max(root);
}
private Key max(Node x)
{
if (x.right == null) return x.key;
else return max(x.right);
}
public void put(Key key, Value value)
{
root = insert(root, key, value);
if (isRed(root)) heightBLACK++;
root.color = BLACK;
}
private Node insert(Node h, Key key, Value value)
{
if (h == null)
return new Node(key, value);
if (species == TD234)
if (isRed(h.left) && isRed(h.right))
colorFlip(h);
if (eq(key, h.key))
h.value = value;
else if (less(key, h.key))
h.left = insert(h.left, key, value);
else
h.right = insert(h.right, key, value);
if (species == BST) return setN(h);
if (isRed(h.right))
h = rotateLeft(h);
if (isRed(h.left) && isRed(h.left.left))
h = rotateRight(h);
if (species == BU23)
if (isRed(h.left) && isRed(h.right))
colorFlip(h);
return setN(h);
}
public void deleteMin()
{
root = deleteMin(root);
root.color = BLACK;
}
private Node deleteMin(Node h)
{
if (h.left == null)
return null;
if (!isRed(h.left) && !isRed(h.left.left))
h = moveRedLeft(h);
h.left = deleteMin(h.left);
return fixUp(h);
}
public void deleteMax()
{
root = deleteMax(root);
root.color = BLACK;
}
private Node deleteMax(Node h)
{
// if (h.right == null)
// {
// if (h.left != null)
// h.left.color = BLACK;
// return h.left;
// }
if (isRed(h.left))
h = rotateRight(h);
if (h.right == null)
return null;
if (!isRed(h.right) && !isRed(h.right.left))
h = moveRedRight(h);
h.right = deleteMax(h.right);
return fixUp(h);
}
public void delete(Key key)
{
root = delete(root, key);
root.color = BLACK;
}
private Node delete(Node h, Key key)
{
if (less(key, h.key))
{
if (!isRed(h.left) && !isRed(h.left.left))
h = moveRedLeft(h);
h.left = delete(h.left, key);
}
else
{
if (isRed(h.left))
h = rotateRight(h);
if (eq(key, h.key) && (h.right == null))
return null;
if (!isRed(h.right) && !isRed(h.right.left))
h = moveRedRight(h);
if (eq(key, h.key))
{
h.value = get(h.right, min(h.right));
h.key = min(h.right);
h.right = deleteMin(h.right);
}
else h.right = delete(h.right, key);
}
return fixUp(h);
}
// Helper methods
private boolean less(Key a, Key b) { return a.compareTo(b) < 0; }
private boolean eq (Key a, Key b) { return a.compareTo(b) == 0; }
private boolean isRed(Node x)
{
if (x == null) return false;
return (x.color == RED);
}
private void colorFlip(Node h)
{
h.color = !h.color;
h.left.color = !h.left.color;
h.right.color = !h.right.color;
}
private Node rotateLeft(Node h)
{ // Make a right-leaning 3-node lean to the left.
Node x = h.right;
h.right = x.left;
x.left = setN(h);
x.color = x.left.color;
x.left.color = RED;
return setN(x);
}
private Node rotateRight(Node h)
{ // Make a left-leaning 3-node lean to the right.
Node x = h.left;
h.left = x.right;
x.right = setN(h);
x.color = x.right.color;
x.right.color = RED;
return setN(x);
}
private Node moveRedLeft(Node h)
{ // Assuming that h is red and both h.left and h.left.left
// are black, make h.left or one of its children red.
colorFlip(h);
if (isRed(h.right.left))
{
h.right = rotateRight(h.right);
h = rotateLeft(h);
colorFlip(h);
}
return h;
}
private Node moveRedRight(Node h)
{ // Assuming that h is red and both h.right and h.right.left
// are black, make h.right or one of its children red.
colorFlip(h);
if (isRed(h.left.left))
{
h = rotateRight(h);
colorFlip(h);
}
return h;
}
private Node fixUp(Node h)
{
if (isRed(h.right))
h = rotateLeft(h);
if (isRed(h.left) && isRed(h.left.left))
h = rotateRight(h);
if (isRed(h.left) && isRed(h.right))
colorFlip(h);
return setN(h);
}
private Node setN(Node h)
{
h.N = size(h.left) + size(h.right) + 1;
if (height(h.left) > height(h.right)) h.height = height(h.left) + 1;
else h.height = height(h.right) + 1;
return h;
}
public String toString()
{
if (root == null) return "";
else return heightB() + " " + toString(root);
}
public String toString(Node x)
{
String s = "(";
if (x.left == null) s += "("; else s += toString(x.left);
if (isRed(x)) s += "*";
if (x.right == null) s += ")"; else s += toString(x.right);
return s + ")";
}
// Methods for tree drawing
public void draw(double y, double lineWidth, double nodeSize)
{
k = 0;
setcoords(root, y);
StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.setPenRadius(lineWidth);
drawlines(root);
StdDraw.setPenColor(StdDraw.WHITE);
drawnodes(root, nodeSize);
}
public void setcoords(Node x, double d)
{
if (x == null) return;
setcoords(x.left, d-.04);
x.xc = (0.5 + k++)/size(); x.yc = d - .04;
setcoords(x.right, d-.04);
}
public void drawlines(Node x)
{
if (x == null) return;
drawlines(x.left);
if (x.left != null)
{
if (x.left.color == RED) StdDraw.setPenColor(StdDraw.RED);
else StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.line(x.xc, x.yc, x.left.xc, x.left.yc);
}
if (x.right != null)
{
if (x.right.color == RED) StdDraw.setPenColor(StdDraw.RED);
else StdDraw.setPenColor(StdDraw.BLACK);
StdDraw.line(x.xc, x.yc, x.right.xc, x.right.yc);
}
drawlines(x.right);
}
public void drawnodes(Node x, double nodeSize)
{
if (x == null) return;
drawnodes(x.left, nodeSize);
StdDraw.filledCircle(x.xc, x.yc, nodeSize);
drawnodes(x.right, nodeSize);
}
public void mark(Key key)
{
StdDraw.setPenColor(StdDraw.BLACK);
marknodes(key, root);
}
public void marknodes(Key key, Node x)
{
if (x == null) return;
marknodes(key, x.left);
if (eq(key, x.key))
StdDraw.filledCircle(x.xc, x.yc, .004);
marknodes(key, x.right);
}
public int ipl()
{ return ipl(root); }
public int ipl(Node x)
{
if (x == null) return 0;
return size(x) - 1 + ipl(x.left) + ipl(x.right);
}
public int sizeRed()
{ return sizeRed(root); }
public int sizeRed(Node x)
{
if (x == null) return 0;
if (isRed(x)) return 1 + sizeRed(x.left) + sizeRed(x.right);
else return sizeRed(x.left) + sizeRed(x.right);
}
// Integrity checks
public boolean check()
{ // Is this tree a red-black tree?
return isBST() && is234() && isBalanced();
}
private boolean isBST()
{ // Is this tree a BST?
return isBST(root, min(), max());
}
private boolean isBST(Node x, Key min, Key max)
{ // Are all the values in the BST rooted at x between min and max,
// and does the same property hold for both subtrees?
if (x == null) return true;
if (less(x.key, min) || less(max, x.key)) return false;
return isBST(x.left, min, x.key) && isBST(x.right, x.key, max);
}
private boolean is234() { return is234(root); }
private boolean is234(Node x)
{ // Does the tree have no red right links, and at most two (left)
// red links in a row on any path?
if (x == null) return true;
if (isRed(x.right)) return false;
if (isRed(x))
if (isRed(x.left))
if (isRed(x.left.left)) return false;
return is234(x.left) && is234(x.right);
}
private boolean isBalanced()
{ // Do all paths from root to leaf have same number of black edges?
int black = 0; // number of black links on path from root to min
Node x = root;
while (x != null)
{
if (!isRed(x)) black++;
x = x.left;
}
return isBalanced(root, black);
}
private boolean isBalanced(Node x, int black)
{ // Does every path from the root to a leaf have the given number
// of black links?
if (x == null && black == 0) return true;
else if (x == null && black != 0) return false;
if (!isRed(x)) black--;
return isBalanced(x.left, black) && isBalanced(x.right, black);
}
public static void main(String[] args)
{
StdDraw.setPenRadius(.0025);
int species = Integer.parseInt(args[0]);
RedBlackBST<Integer, Integer> st;
st = new RedBlackBST<Integer, Integer>(species);
int[] a = { 3, 1, 4, 2, 5, 9, 6, 8, 7 };
for (int i = 0; i < a.length; i++)
st.put(a[i], i);
StdOut.println(st);
StdDraw.clear(StdDraw.LIGHT_GRAY);
st.draw(.95, .0025, .008);
StdOut.println(st.min() + " " + st.max() + " " + st.check());
StdOut.println(st.ipl());
StdOut.println(st.heightB());
}
}

Binary file not shown.

26
vendor/github.com/petar/GoLLRB/example/ex1.go generated vendored Normal file
View File

@ -0,0 +1,26 @@
package main
import (
"fmt"
"github.com/petar/GoLLRB/llrb"
)
func lessInt(a, b interface{}) bool { return a.(int) < b.(int) }
func main() {
tree := llrb.New(lessInt)
tree.ReplaceOrInsert(1)
tree.ReplaceOrInsert(2)
tree.ReplaceOrInsert(3)
tree.ReplaceOrInsert(4)
tree.DeleteMin()
tree.Delete(4)
c := tree.IterAscend()
for {
u := <-c
if u == nil {
break
}
fmt.Printf("%d\n", int(u.(int)))
}
}

39
vendor/github.com/petar/GoLLRB/llrb/avgvar.go generated vendored Normal file
View File

@ -0,0 +1,39 @@
// Copyright 2010 Petar Maymounkov. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package llrb
import "math"
// avgVar maintains the average and variance of a stream of numbers
// in a space-efficient manner.
type avgVar struct {
count int64
sum, sumsq float64
}
func (av *avgVar) Init() {
av.count = 0
av.sum = 0.0
av.sumsq = 0.0
}
func (av *avgVar) Add(sample float64) {
av.count++
av.sum += sample
av.sumsq += sample * sample
}
func (av *avgVar) GetCount() int64 { return av.count }
func (av *avgVar) GetAvg() float64 { return av.sum / float64(av.count) }
func (av *avgVar) GetTotal() float64 { return av.sum }
func (av *avgVar) GetVar() float64 {
a := av.GetAvg()
return av.sumsq/float64(av.count) - a*a
}
func (av *avgVar) GetStdDev() float64 { return math.Sqrt(av.GetVar()) }

93
vendor/github.com/petar/GoLLRB/llrb/iterator.go generated vendored Normal file
View File

@ -0,0 +1,93 @@
package llrb
type ItemIterator func(i Item) bool
//func (t *Tree) Ascend(iterator ItemIterator) {
// t.AscendGreaterOrEqual(Inf(-1), iterator)
//}
func (t *LLRB) AscendRange(greaterOrEqual, lessThan Item, iterator ItemIterator) {
t.ascendRange(t.root, greaterOrEqual, lessThan, iterator)
}
func (t *LLRB) ascendRange(h *Node, inf, sup Item, iterator ItemIterator) bool {
if h == nil {
return true
}
if !less(h.Item, sup) {
return t.ascendRange(h.Left, inf, sup, iterator)
}
if less(h.Item, inf) {
return t.ascendRange(h.Right, inf, sup, iterator)
}
if !t.ascendRange(h.Left, inf, sup, iterator) {
return false
}
if !iterator(h.Item) {
return false
}
return t.ascendRange(h.Right, inf, sup, iterator)
}
// AscendGreaterOrEqual will call iterator once for each element greater or equal to
// pivot in ascending order. It will stop whenever the iterator returns false.
func (t *LLRB) AscendGreaterOrEqual(pivot Item, iterator ItemIterator) {
t.ascendGreaterOrEqual(t.root, pivot, iterator)
}
func (t *LLRB) ascendGreaterOrEqual(h *Node, pivot Item, iterator ItemIterator) bool {
if h == nil {
return true
}
if !less(h.Item, pivot) {
if !t.ascendGreaterOrEqual(h.Left, pivot, iterator) {
return false
}
if !iterator(h.Item) {
return false
}
}
return t.ascendGreaterOrEqual(h.Right, pivot, iterator)
}
func (t *LLRB) AscendLessThan(pivot Item, iterator ItemIterator) {
t.ascendLessThan(t.root, pivot, iterator)
}
func (t *LLRB) ascendLessThan(h *Node, pivot Item, iterator ItemIterator) bool {
if h == nil {
return true
}
if !t.ascendLessThan(h.Left, pivot, iterator) {
return false
}
if !iterator(h.Item) {
return false
}
if less(h.Item, pivot) {
return t.ascendLessThan(h.Left, pivot, iterator)
}
return true
}
// DescendLessOrEqual will call iterator once for each element less than the
// pivot in descending order. It will stop whenever the iterator returns false.
func (t *LLRB) DescendLessOrEqual(pivot Item, iterator ItemIterator) {
t.descendLessOrEqual(t.root, pivot, iterator)
}
func (t *LLRB) descendLessOrEqual(h *Node, pivot Item, iterator ItemIterator) bool {
if h == nil {
return true
}
if less(h.Item, pivot) || !less(pivot, h.Item) {
if !t.descendLessOrEqual(h.Right, pivot, iterator) {
return false
}
if !iterator(h.Item) {
return false
}
}
return t.descendLessOrEqual(h.Left, pivot, iterator)
}

76
vendor/github.com/petar/GoLLRB/llrb/iterator_test.go generated vendored Normal file
View File

@ -0,0 +1,76 @@
package llrb
import (
"reflect"
"testing"
)
func TestAscendGreaterOrEqual(t *testing.T) {
tree := New()
tree.InsertNoReplace(Int(4))
tree.InsertNoReplace(Int(6))
tree.InsertNoReplace(Int(1))
tree.InsertNoReplace(Int(3))
var ary []Item
tree.AscendGreaterOrEqual(Int(-1), func(i Item) bool {
ary = append(ary, i)
return true
})
expected := []Item{Int(1), Int(3), Int(4), Int(6)}
if !reflect.DeepEqual(ary, expected) {
t.Errorf("expected %v but got %v", expected, ary)
}
ary = nil
tree.AscendGreaterOrEqual(Int(3), func(i Item) bool {
ary = append(ary, i)
return true
})
expected = []Item{Int(3), Int(4), Int(6)}
if !reflect.DeepEqual(ary, expected) {
t.Errorf("expected %v but got %v", expected, ary)
}
ary = nil
tree.AscendGreaterOrEqual(Int(2), func(i Item) bool {
ary = append(ary, i)
return true
})
expected = []Item{Int(3), Int(4), Int(6)}
if !reflect.DeepEqual(ary, expected) {
t.Errorf("expected %v but got %v", expected, ary)
}
}
func TestDescendLessOrEqual(t *testing.T) {
tree := New()
tree.InsertNoReplace(Int(4))
tree.InsertNoReplace(Int(6))
tree.InsertNoReplace(Int(1))
tree.InsertNoReplace(Int(3))
var ary []Item
tree.DescendLessOrEqual(Int(10), func(i Item) bool {
ary = append(ary, i)
return true
})
expected := []Item{Int(6), Int(4), Int(3), Int(1)}
if !reflect.DeepEqual(ary, expected) {
t.Errorf("expected %v but got %v", expected, ary)
}
ary = nil
tree.DescendLessOrEqual(Int(4), func(i Item) bool {
ary = append(ary, i)
return true
})
expected = []Item{Int(4), Int(3), Int(1)}
if !reflect.DeepEqual(ary, expected) {
t.Errorf("expected %v but got %v", expected, ary)
}
ary = nil
tree.DescendLessOrEqual(Int(5), func(i Item) bool {
ary = append(ary, i)
return true
})
expected = []Item{Int(4), Int(3), Int(1)}
if !reflect.DeepEqual(ary, expected) {
t.Errorf("expected %v but got %v", expected, ary)
}
}

46
vendor/github.com/petar/GoLLRB/llrb/llrb-stats.go generated vendored Normal file
View File

@ -0,0 +1,46 @@
// Copyright 2010 Petar Maymounkov. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package llrb
// GetHeight() returns an item in the tree with key @key, and it's height in the tree
func (t *LLRB) GetHeight(key Item) (result Item, depth int) {
return t.getHeight(t.root, key)
}
func (t *LLRB) getHeight(h *Node, item Item) (Item, int) {
if h == nil {
return nil, 0
}
if less(item, h.Item) {
result, depth := t.getHeight(h.Left, item)
return result, depth + 1
}
if less(h.Item, item) {
result, depth := t.getHeight(h.Right, item)
return result, depth + 1
}
return h.Item, 0
}
// HeightStats() returns the average and standard deviation of the height
// of elements in the tree
func (t *LLRB) HeightStats() (avg, stddev float64) {
av := &avgVar{}
heightStats(t.root, 0, av)
return av.GetAvg(), av.GetStdDev()
}
func heightStats(h *Node, d int, av *avgVar) {
if h == nil {
return
}
av.Add(float64(d))
if h.Left != nil {
heightStats(h.Left, d+1, av)
}
if h.Right != nil {
heightStats(h.Right, d+1, av)
}
}

456
vendor/github.com/petar/GoLLRB/llrb/llrb.go generated vendored Normal file
View File

@ -0,0 +1,456 @@
// Copyright 2010 Petar Maymounkov. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// A Left-Leaning Red-Black (LLRB) implementation of 2-3 balanced binary search trees,
// based on the following work:
//
// http://www.cs.princeton.edu/~rs/talks/LLRB/08Penn.pdf
// http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf
// http://www.cs.princeton.edu/~rs/talks/LLRB/Java/RedBlackBST.java
//
// 2-3 trees (and the run-time equivalent 2-3-4 trees) are the de facto standard BST
// algoritms found in implementations of Python, Java, and other libraries. The LLRB
// implementation of 2-3 trees is a recent improvement on the traditional implementation,
// observed and documented by Robert Sedgewick.
//
package llrb
// Tree is a Left-Leaning Red-Black (LLRB) implementation of 2-3 trees
type LLRB struct {
count int
root *Node
}
type Node struct {
Item
Left, Right *Node // Pointers to left and right child nodes
Black bool // If set, the color of the link (incoming from the parent) is black
// In the LLRB, new nodes are always red, hence the zero-value for node
}
type Item interface {
Less(than Item) bool
}
//
func less(x, y Item) bool {
if x == pinf {
return false
}
if x == ninf {
return true
}
return x.Less(y)
}
// Inf returns an Item that is "bigger than" any other item, if sign is positive.
// Otherwise it returns an Item that is "smaller than" any other item.
func Inf(sign int) Item {
if sign == 0 {
panic("sign")
}
if sign > 0 {
return pinf
}
return ninf
}
var (
ninf = nInf{}
pinf = pInf{}
)
type nInf struct{}
func (nInf) Less(Item) bool {
return true
}
type pInf struct{}
func (pInf) Less(Item) bool {
return false
}
// New() allocates a new tree
func New() *LLRB {
return &LLRB{}
}
// SetRoot sets the root node of the tree.
// It is intended to be used by functions that deserialize the tree.
func (t *LLRB) SetRoot(r *Node) {
t.root = r
}
// Root returns the root node of the tree.
// It is intended to be used by functions that serialize the tree.
func (t *LLRB) Root() *Node {
return t.root
}
// Len returns the number of nodes in the tree.
func (t *LLRB) Len() int { return t.count }
// Has returns true if the tree contains an element whose order is the same as that of key.
func (t *LLRB) Has(key Item) bool {
return t.Get(key) != nil
}
// Get retrieves an element from the tree whose order is the same as that of key.
func (t *LLRB) Get(key Item) Item {
h := t.root
for h != nil {
switch {
case less(key, h.Item):
h = h.Left
case less(h.Item, key):
h = h.Right
default:
return h.Item
}
}
return nil
}
// Min returns the minimum element in the tree.
func (t *LLRB) Min() Item {
h := t.root
if h == nil {
return nil
}
for h.Left != nil {
h = h.Left
}
return h.Item
}
// Max returns the maximum element in the tree.
func (t *LLRB) Max() Item {
h := t.root
if h == nil {
return nil
}
for h.Right != nil {
h = h.Right
}
return h.Item
}
func (t *LLRB) ReplaceOrInsertBulk(items ...Item) {
for _, i := range items {
t.ReplaceOrInsert(i)
}
}
func (t *LLRB) InsertNoReplaceBulk(items ...Item) {
for _, i := range items {
t.InsertNoReplace(i)
}
}
// ReplaceOrInsert inserts item into the tree. If an existing
// element has the same order, it is removed from the tree and returned.
func (t *LLRB) ReplaceOrInsert(item Item) Item {
if item == nil {
panic("inserting nil item")
}
var replaced Item
t.root, replaced = t.replaceOrInsert(t.root, item)
t.root.Black = true
if replaced == nil {
t.count++
}
return replaced
}
func (t *LLRB) replaceOrInsert(h *Node, item Item) (*Node, Item) {
if h == nil {
return newNode(item), nil
}
h = walkDownRot23(h)
var replaced Item
if less(item, h.Item) { // BUG
h.Left, replaced = t.replaceOrInsert(h.Left, item)
} else if less(h.Item, item) {
h.Right, replaced = t.replaceOrInsert(h.Right, item)
} else {
replaced, h.Item = h.Item, item
}
h = walkUpRot23(h)
return h, replaced
}
// InsertNoReplace inserts item into the tree. If an existing
// element has the same order, both elements remain in the tree.
func (t *LLRB) InsertNoReplace(item Item) {
if item == nil {
panic("inserting nil item")
}
t.root = t.insertNoReplace(t.root, item)
t.root.Black = true
t.count++
}
func (t *LLRB) insertNoReplace(h *Node, item Item) *Node {
if h == nil {
return newNode(item)
}
h = walkDownRot23(h)
if less(item, h.Item) {
h.Left = t.insertNoReplace(h.Left, item)
} else {
h.Right = t.insertNoReplace(h.Right, item)
}
return walkUpRot23(h)
}
// Rotation driver routines for 2-3 algorithm
func walkDownRot23(h *Node) *Node { return h }
func walkUpRot23(h *Node) *Node {
if isRed(h.Right) && !isRed(h.Left) {
h = rotateLeft(h)
}
if isRed(h.Left) && isRed(h.Left.Left) {
h = rotateRight(h)
}
if isRed(h.Left) && isRed(h.Right) {
flip(h)
}
return h
}
// Rotation driver routines for 2-3-4 algorithm
func walkDownRot234(h *Node) *Node {
if isRed(h.Left) && isRed(h.Right) {
flip(h)
}
return h
}
func walkUpRot234(h *Node) *Node {
if isRed(h.Right) && !isRed(h.Left) {
h = rotateLeft(h)
}
if isRed(h.Left) && isRed(h.Left.Left) {
h = rotateRight(h)
}
return h
}
// DeleteMin deletes the minimum element in the tree and returns the
// deleted item or nil otherwise.
func (t *LLRB) DeleteMin() Item {
var deleted Item
t.root, deleted = deleteMin(t.root)
if t.root != nil {
t.root.Black = true
}
if deleted != nil {
t.count--
}
return deleted
}
// deleteMin code for LLRB 2-3 trees
func deleteMin(h *Node) (*Node, Item) {
if h == nil {
return nil, nil
}
if h.Left == nil {
return nil, h.Item
}
if !isRed(h.Left) && !isRed(h.Left.Left) {
h = moveRedLeft(h)
}
var deleted Item
h.Left, deleted = deleteMin(h.Left)
return fixUp(h), deleted
}
// DeleteMax deletes the maximum element in the tree and returns
// the deleted item or nil otherwise
func (t *LLRB) DeleteMax() Item {
var deleted Item
t.root, deleted = deleteMax(t.root)
if t.root != nil {
t.root.Black = true
}
if deleted != nil {
t.count--
}
return deleted
}
func deleteMax(h *Node) (*Node, Item) {
if h == nil {
return nil, nil
}
if isRed(h.Left) {
h = rotateRight(h)
}
if h.Right == nil {
return nil, h.Item
}
if !isRed(h.Right) && !isRed(h.Right.Left) {
h = moveRedRight(h)
}
var deleted Item
h.Right, deleted = deleteMax(h.Right)
return fixUp(h), deleted
}
// Delete deletes an item from the tree whose key equals key.
// The deleted item is return, otherwise nil is returned.
func (t *LLRB) Delete(key Item) Item {
var deleted Item
t.root, deleted = t.delete(t.root, key)
if t.root != nil {
t.root.Black = true
}
if deleted != nil {
t.count--
}
return deleted
}
func (t *LLRB) delete(h *Node, item Item) (*Node, Item) {
var deleted Item
if h == nil {
return nil, nil
}
if less(item, h.Item) {
if h.Left == nil { // item not present. Nothing to delete
return h, nil
}
if !isRed(h.Left) && !isRed(h.Left.Left) {
h = moveRedLeft(h)
}
h.Left, deleted = t.delete(h.Left, item)
} else {
if isRed(h.Left) {
h = rotateRight(h)
}
// If @item equals @h.Item and no right children at @h
if !less(h.Item, item) && h.Right == nil {
return nil, h.Item
}
// PETAR: Added 'h.Right != nil' below
if h.Right != nil && !isRed(h.Right) && !isRed(h.Right.Left) {
h = moveRedRight(h)
}
// If @item equals @h.Item, and (from above) 'h.Right != nil'
if !less(h.Item, item) {
var subDeleted Item
h.Right, subDeleted = deleteMin(h.Right)
if subDeleted == nil {
panic("logic")
}
deleted, h.Item = h.Item, subDeleted
} else { // Else, @item is bigger than @h.Item
h.Right, deleted = t.delete(h.Right, item)
}
}
return fixUp(h), deleted
}
// Internal node manipulation routines
func newNode(item Item) *Node { return &Node{Item: item} }
func isRed(h *Node) bool {
if h == nil {
return false
}
return !h.Black
}
func rotateLeft(h *Node) *Node {
x := h.Right
if x.Black {
panic("rotating a black link")
}
h.Right = x.Left
x.Left = h
x.Black = h.Black
h.Black = false
return x
}
func rotateRight(h *Node) *Node {
x := h.Left
if x.Black {
panic("rotating a black link")
}
h.Left = x.Right
x.Right = h
x.Black = h.Black
h.Black = false
return x
}
// REQUIRE: Left and Right children must be present
func flip(h *Node) {
h.Black = !h.Black
h.Left.Black = !h.Left.Black
h.Right.Black = !h.Right.Black
}
// REQUIRE: Left and Right children must be present
func moveRedLeft(h *Node) *Node {
flip(h)
if isRed(h.Right.Left) {
h.Right = rotateRight(h.Right)
h = rotateLeft(h)
flip(h)
}
return h
}
// REQUIRE: Left and Right children must be present
func moveRedRight(h *Node) *Node {
flip(h)
if isRed(h.Left.Left) {
h = rotateRight(h)
flip(h)
}
return h
}
func fixUp(h *Node) *Node {
if isRed(h.Right) {
h = rotateLeft(h)
}
if isRed(h.Left) && isRed(h.Left.Left) {
h = rotateRight(h)
}
if isRed(h.Left) && isRed(h.Right) {
flip(h)
}
return h
}

239
vendor/github.com/petar/GoLLRB/llrb/llrb_test.go generated vendored Normal file
View File

@ -0,0 +1,239 @@
// Copyright 2010 Petar Maymounkov. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package llrb
import (
"math"
"math/rand"
"testing"
)
func TestCases(t *testing.T) {
tree := New()
tree.ReplaceOrInsert(Int(1))
tree.ReplaceOrInsert(Int(1))
if tree.Len() != 1 {
t.Errorf("expecting len 1")
}
if !tree.Has(Int(1)) {
t.Errorf("expecting to find key=1")
}
tree.Delete(Int(1))
if tree.Len() != 0 {
t.Errorf("expecting len 0")
}
if tree.Has(Int(1)) {
t.Errorf("not expecting to find key=1")
}
tree.Delete(Int(1))
if tree.Len() != 0 {
t.Errorf("expecting len 0")
}
if tree.Has(Int(1)) {
t.Errorf("not expecting to find key=1")
}
}
func TestReverseInsertOrder(t *testing.T) {
tree := New()
n := 100
for i := 0; i < n; i++ {
tree.ReplaceOrInsert(Int(n - i))
}
i := 0
tree.AscendGreaterOrEqual(Int(0), func(item Item) bool {
i++
if item.(Int) != Int(i) {
t.Errorf("bad order: got %d, expect %d", item.(Int), i)
}
return true
})
}
func TestRange(t *testing.T) {
tree := New()
order := []String{
"ab", "aba", "abc", "a", "aa", "aaa", "b", "a-", "a!",
}
for _, i := range order {
tree.ReplaceOrInsert(i)
}
k := 0
tree.AscendRange(String("ab"), String("ac"), func(item Item) bool {
if k > 3 {
t.Fatalf("returned more items than expected")
}
i1 := order[k]
i2 := item.(String)
if i1 != i2 {
t.Errorf("expecting %s, got %s", i1, i2)
}
k++
return true
})
}
func TestRandomInsertOrder(t *testing.T) {
tree := New()
n := 1000
perm := rand.Perm(n)
for i := 0; i < n; i++ {
tree.ReplaceOrInsert(Int(perm[i]))
}
j := 0
tree.AscendGreaterOrEqual(Int(0), func(item Item) bool {
if item.(Int) != Int(j) {
t.Fatalf("bad order")
}
j++
return true
})
}
func TestRandomReplace(t *testing.T) {
tree := New()
n := 100
perm := rand.Perm(n)
for i := 0; i < n; i++ {
tree.ReplaceOrInsert(Int(perm[i]))
}
perm = rand.Perm(n)
for i := 0; i < n; i++ {
if replaced := tree.ReplaceOrInsert(Int(perm[i])); replaced == nil || replaced.(Int) != Int(perm[i]) {
t.Errorf("error replacing")
}
}
}
func TestRandomInsertSequentialDelete(t *testing.T) {
tree := New()
n := 1000
perm := rand.Perm(n)
for i := 0; i < n; i++ {
tree.ReplaceOrInsert(Int(perm[i]))
}
for i := 0; i < n; i++ {
tree.Delete(Int(i))
}
}
func TestRandomInsertDeleteNonExistent(t *testing.T) {
tree := New()
n := 100
perm := rand.Perm(n)
for i := 0; i < n; i++ {
tree.ReplaceOrInsert(Int(perm[i]))
}
if tree.Delete(Int(200)) != nil {
t.Errorf("deleted non-existent item")
}
if tree.Delete(Int(-2)) != nil {
t.Errorf("deleted non-existent item")
}
for i := 0; i < n; i++ {
if u := tree.Delete(Int(i)); u == nil || u.(Int) != Int(i) {
t.Errorf("delete failed")
}
}
if tree.Delete(Int(200)) != nil {
t.Errorf("deleted non-existent item")
}
if tree.Delete(Int(-2)) != nil {
t.Errorf("deleted non-existent item")
}
}
func TestRandomInsertPartialDeleteOrder(t *testing.T) {
tree := New()
n := 100
perm := rand.Perm(n)
for i := 0; i < n; i++ {
tree.ReplaceOrInsert(Int(perm[i]))
}
for i := 1; i < n-1; i++ {
tree.Delete(Int(i))
}
j := 0
tree.AscendGreaterOrEqual(Int(0), func(item Item) bool {
switch j {
case 0:
if item.(Int) != Int(0) {
t.Errorf("expecting 0")
}
case 1:
if item.(Int) != Int(n-1) {
t.Errorf("expecting %d", n-1)
}
}
j++
return true
})
}
func TestRandomInsertStats(t *testing.T) {
tree := New()
n := 100000
perm := rand.Perm(n)
for i := 0; i < n; i++ {
tree.ReplaceOrInsert(Int(perm[i]))
}
avg, _ := tree.HeightStats()
expAvg := math.Log2(float64(n)) - 1.5
if math.Abs(avg-expAvg) >= 2.0 {
t.Errorf("too much deviation from expected average height")
}
}
func BenchmarkInsert(b *testing.B) {
tree := New()
for i := 0; i < b.N; i++ {
tree.ReplaceOrInsert(Int(b.N - i))
}
}
func BenchmarkDelete(b *testing.B) {
b.StopTimer()
tree := New()
for i := 0; i < b.N; i++ {
tree.ReplaceOrInsert(Int(b.N - i))
}
b.StartTimer()
for i := 0; i < b.N; i++ {
tree.Delete(Int(i))
}
}
func BenchmarkDeleteMin(b *testing.B) {
b.StopTimer()
tree := New()
for i := 0; i < b.N; i++ {
tree.ReplaceOrInsert(Int(b.N - i))
}
b.StartTimer()
for i := 0; i < b.N; i++ {
tree.DeleteMin()
}
}
func TestInsertNoReplace(t *testing.T) {
tree := New()
n := 1000
for q := 0; q < 2; q++ {
perm := rand.Perm(n)
for i := 0; i < n; i++ {
tree.InsertNoReplace(Int(perm[i]))
}
}
j := 0
tree.AscendGreaterOrEqual(Int(0), func(item Item) bool {
if item.(Int) != Int(j/2) {
t.Fatalf("bad order")
}
j++
return true
})
}

17
vendor/github.com/petar/GoLLRB/llrb/util.go generated vendored Normal file
View File

@ -0,0 +1,17 @@
// Copyright 2010 Petar Maymounkov. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package llrb
type Int int
func (x Int) Less(than Item) bool {
return x < than.(Int)
}
type String string
func (x String) Less(than Item) bool {
return x < than.(String)
}

19
vendor/github.com/peterbourgon/diskv/LICENSE generated vendored Normal file
View File

@ -0,0 +1,19 @@
Copyright (c) 2011-2012 Peter Bourgon
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.

141
vendor/github.com/peterbourgon/diskv/README.md generated vendored Normal file
View File

@ -0,0 +1,141 @@
# What is diskv?
Diskv (disk-vee) is a simple, persistent key-value store written in the Go
language. It starts with an incredibly simple API for storing arbitrary data on
a filesystem by key, and builds several layers of performance-enhancing
abstraction on top. The end result is a conceptually simple, but highly
performant, disk-backed storage system.
[![Build Status][1]][2]
[1]: https://drone.io/github.com/peterbourgon/diskv/status.png
[2]: https://drone.io/github.com/peterbourgon/diskv/latest
# Installing
Install [Go 1][3], either [from source][4] or [with a prepackaged binary][5].
Then,
```bash
$ go get github.com/peterbourgon/diskv
```
[3]: http://golang.org
[4]: http://golang.org/doc/install/source
[5]: http://golang.org/doc/install
# Usage
```go
package main
import (
"fmt"
"github.com/peterbourgon/diskv"
)
func main() {
// Simplest transform function: put all the data files into the base dir.
flatTransform := func(s string) []string { return []string{} }
// Initialize a new diskv store, rooted at "my-data-dir", with a 1MB cache.
d := diskv.New(diskv.Options{
BasePath: "my-data-dir",
Transform: flatTransform,
CacheSizeMax: 1024 * 1024,
})
// Write three bytes to the key "alpha".
key := "alpha"
d.Write(key, []byte{'1', '2', '3'})
// Read the value back out of the store.
value, _ := d.Read(key)
fmt.Printf("%v\n", value)
// Erase the key+value from the store (and the disk).
d.Erase(key)
}
```
More complex examples can be found in the "examples" subdirectory.
# Theory
## Basic idea
At its core, diskv is a map of a key (`string`) to arbitrary data (`[]byte`).
The data is written to a single file on disk, with the same name as the key.
The key determines where that file will be stored, via a user-provided
`TransformFunc`, which takes a key and returns a slice (`[]string`)
corresponding to a path list where the key file will be stored. The simplest
TransformFunc,
```go
func SimpleTransform (key string) []string {
return []string{}
}
```
will place all keys in the same, base directory. The design is inspired by
[Redis diskstore][6]; a TransformFunc which emulates the default diskstore
behavior is available in the content-addressable-storage example.
[6]: http://groups.google.com/group/redis-db/browse_thread/thread/d444bc786689bde9?pli=1
**Note** that your TransformFunc should ensure that one valid key doesn't
transform to a subset of another valid key. That is, it shouldn't be possible
to construct valid keys that resolve to directory names. As a concrete example,
if your TransformFunc splits on every 3 characters, then
```go
d.Write("abcabc", val) // OK: written to <base>/abc/abc/abcabc
d.Write("abc", val) // Error: attempted write to <base>/abc/abc, but it's a directory
```
This will be addressed in an upcoming version of diskv.
Probably the most important design principle behind diskv is that your data is
always flatly available on the disk. diskv will never do anything that would
prevent you from accessing, copying, backing up, or otherwise interacting with
your data via common UNIX commandline tools.
## Adding a cache
An in-memory caching layer is provided by combining the BasicStore
functionality with a simple map structure, and keeping it up-to-date as
appropriate. Since the map structure in Go is not threadsafe, it's combined
with a RWMutex to provide safe concurrent access.
## Adding order
diskv is a key-value store and therefore inherently unordered. An ordering
system can be injected into the store by passing something which satisfies the
diskv.Index interface. (A default implementation, using Google's
[btree][7] package, is provided.) Basically, diskv keeps an ordered (by a
user-provided Less function) index of the keys, which can be queried.
[7]: https://github.com/google/btree
## Adding compression
Something which implements the diskv.Compression interface may be passed
during store creation, so that all Writes and Reads are filtered through
a compression/decompression pipeline. Several default implementations,
using stdlib compression algorithms, are provided. Note that data is cached
compressed; the cost of decompression is borne with each Read.
## Streaming
diskv also now provides ReadStream and WriteStream methods, to allow very large
data to be handled efficiently.
# Future plans
* Needs plenty of robust testing: huge datasets, etc...
* More thorough benchmarking
* Your suggestions for use-cases I haven't thought of

336
vendor/github.com/peterbourgon/diskv/basic_test.go generated vendored Normal file
View File

@ -0,0 +1,336 @@
package diskv
import (
"bytes"
"errors"
"testing"
"time"
)
func cmpBytes(a, b []byte) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return false
}
}
return true
}
func (d *Diskv) isCached(key string) bool {
d.mu.RLock()
defer d.mu.RUnlock()
_, ok := d.cache[key]
return ok
}
func TestWriteReadErase(t *testing.T) {
d := New(Options{
BasePath: "test-data",
CacheSizeMax: 1024,
})
defer d.EraseAll()
k, v := "a", []byte{'b'}
if err := d.Write(k, v); err != nil {
t.Fatalf("write: %s", err)
}
if readVal, err := d.Read(k); err != nil {
t.Fatalf("read: %s", err)
} else if bytes.Compare(v, readVal) != 0 {
t.Fatalf("read: expected %s, got %s", v, readVal)
}
if err := d.Erase(k); err != nil {
t.Fatalf("erase: %s", err)
}
}
func TestWRECache(t *testing.T) {
d := New(Options{
BasePath: "test-data",
CacheSizeMax: 1024,
})
defer d.EraseAll()
k, v := "xxx", []byte{' ', ' ', ' '}
if d.isCached(k) {
t.Fatalf("key cached before Write and Read")
}
if err := d.Write(k, v); err != nil {
t.Fatalf("write: %s", err)
}
if d.isCached(k) {
t.Fatalf("key cached before Read")
}
if readVal, err := d.Read(k); err != nil {
t.Fatalf("read: %s", err)
} else if bytes.Compare(v, readVal) != 0 {
t.Fatalf("read: expected %s, got %s", v, readVal)
}
for i := 0; i < 10 && !d.isCached(k); i++ {
time.Sleep(10 * time.Millisecond)
}
if !d.isCached(k) {
t.Fatalf("key not cached after Read")
}
if err := d.Erase(k); err != nil {
t.Fatalf("erase: %s", err)
}
if d.isCached(k) {
t.Fatalf("key cached after Erase")
}
}
func TestStrings(t *testing.T) {
d := New(Options{
BasePath: "test-data",
CacheSizeMax: 1024,
})
defer d.EraseAll()
keys := map[string]bool{"a": false, "b": false, "c": false, "d": false}
v := []byte{'1'}
for k := range keys {
if err := d.Write(k, v); err != nil {
t.Fatalf("write: %s: %s", k, err)
}
}
for k := range d.Keys(nil) {
if _, present := keys[k]; present {
t.Logf("got: %s", k)
keys[k] = true
} else {
t.Fatalf("strings() returns unknown key: %s", k)
}
}
for k, found := range keys {
if !found {
t.Errorf("never got %s", k)
}
}
}
func TestZeroByteCache(t *testing.T) {
d := New(Options{
BasePath: "test-data",
CacheSizeMax: 0,
})
defer d.EraseAll()
k, v := "a", []byte{'1', '2', '3'}
if err := d.Write(k, v); err != nil {
t.Fatalf("Write: %s", err)
}
if d.isCached(k) {
t.Fatalf("key cached, expected not-cached")
}
if _, err := d.Read(k); err != nil {
t.Fatalf("Read: %s", err)
}
if d.isCached(k) {
t.Fatalf("key cached, expected not-cached")
}
}
func TestOneByteCache(t *testing.T) {
d := New(Options{
BasePath: "test-data",
CacheSizeMax: 1,
})
defer d.EraseAll()
k1, k2, v1, v2 := "a", "b", []byte{'1'}, []byte{'1', '2'}
if err := d.Write(k1, v1); err != nil {
t.Fatal(err)
}
if v, err := d.Read(k1); err != nil {
t.Fatal(err)
} else if !cmpBytes(v, v1) {
t.Fatalf("Read: expected %s, got %s", string(v1), string(v))
}
for i := 0; i < 10 && !d.isCached(k1); i++ {
time.Sleep(10 * time.Millisecond)
}
if !d.isCached(k1) {
t.Fatalf("expected 1-byte value to be cached, but it wasn't")
}
if err := d.Write(k2, v2); err != nil {
t.Fatal(err)
}
if _, err := d.Read(k2); err != nil {
t.Fatalf("--> %s", err)
}
for i := 0; i < 10 && (!d.isCached(k1) || d.isCached(k2)); i++ {
time.Sleep(10 * time.Millisecond) // just wait for lazy-cache
}
if !d.isCached(k1) {
t.Fatalf("1-byte value was uncached for no reason")
}
if d.isCached(k2) {
t.Fatalf("2-byte value was cached, but cache max size is 1")
}
}
func TestStaleCache(t *testing.T) {
d := New(Options{
BasePath: "test-data",
CacheSizeMax: 1,
})
defer d.EraseAll()
k, first, second := "a", "first", "second"
if err := d.Write(k, []byte(first)); err != nil {
t.Fatal(err)
}
v, err := d.Read(k)
if err != nil {
t.Fatal(err)
}
if string(v) != first {
t.Errorf("expected '%s', got '%s'", first, v)
}
if err := d.Write(k, []byte(second)); err != nil {
t.Fatal(err)
}
v, err = d.Read(k)
if err != nil {
t.Fatal(err)
}
if string(v) != second {
t.Errorf("expected '%s', got '%s'", second, v)
}
}
func TestHas(t *testing.T) {
d := New(Options{
BasePath: "test-data",
CacheSizeMax: 1024,
})
defer d.EraseAll()
for k, v := range map[string]string{
"a": "1",
"foo": "2",
"012345": "3",
} {
d.Write(k, []byte(v))
}
d.Read("foo") // cache one of them
if !d.isCached("foo") {
t.Errorf("'foo' didn't get cached")
}
for _, tuple := range []struct {
key string
expected bool
}{
{"a", true},
{"b", false},
{"foo", true},
{"bar", false},
{"01234", false},
{"012345", true},
{"0123456", false},
} {
if expected, got := tuple.expected, d.Has(tuple.key); expected != got {
t.Errorf("Has(%s): expected %v, got %v", tuple.key, expected, got)
}
}
}
type BrokenReader struct{}
func (BrokenReader) Read(p []byte) (n int, err error) {
return 0, errors.New("failed to read")
}
func TestRemovesIncompleteFiles(t *testing.T) {
opts := Options{
BasePath: "test-data",
CacheSizeMax: 1024,
}
d := New(opts)
defer d.EraseAll()
key, stream, sync := "key", BrokenReader{}, false
if err := d.WriteStream(key, stream, sync); err == nil {
t.Fatalf("Expected i/o copy error, none received.")
}
if _, err := d.Read(key); err == nil {
t.Fatal("Could read the key, but it shouldn't exist")
}
}
func TestTempDir(t *testing.T) {
opts := Options{
BasePath: "test-data",
TempDir: "test-data-temp",
CacheSizeMax: 1024,
}
d := New(opts)
defer d.EraseAll()
k, v := "a", []byte{'b'}
if err := d.Write(k, v); err != nil {
t.Fatalf("write: %s", err)
}
if readVal, err := d.Read(k); err != nil {
t.Fatalf("read: %s", err)
} else if bytes.Compare(v, readVal) != 0 {
t.Fatalf("read: expected %s, got %s", v, readVal)
}
if err := d.Erase(k); err != nil {
t.Fatalf("erase: %s", err)
}
}
type CrashingReader struct{}
func (CrashingReader) Read(p []byte) (n int, err error) {
panic("System has crashed while reading the stream")
}
func TestAtomicWrite(t *testing.T) {
opts := Options{
BasePath: "test-data",
// Test would fail if TempDir is not set here.
TempDir: "test-data-temp",
CacheSizeMax: 1024,
}
d := New(opts)
defer d.EraseAll()
key := "key"
func() {
defer func() {
recover() // Ignore panicking error
}()
stream := CrashingReader{}
d.WriteStream(key, stream, false)
}()
if d.Has(key) {
t.Fatal("Has key, but it shouldn't exist")
}
if _, ok := <-d.Keys(nil); ok {
t.Fatal("Store isn't empty")
}
}

64
vendor/github.com/peterbourgon/diskv/compression.go generated vendored Normal file
View File

@ -0,0 +1,64 @@
package diskv
import (
"compress/flate"
"compress/gzip"
"compress/zlib"
"io"
)
// Compression is an interface that Diskv uses to implement compression of
// data. Writer takes a destination io.Writer and returns a WriteCloser that
// compresses all data written through it. Reader takes a source io.Reader and
// returns a ReadCloser that decompresses all data read through it. You may
// define these methods on your own type, or use one of the NewCompression
// helpers.
type Compression interface {
Writer(dst io.Writer) (io.WriteCloser, error)
Reader(src io.Reader) (io.ReadCloser, error)
}
// NewGzipCompression returns a Gzip-based Compression.
func NewGzipCompression() Compression {
return NewGzipCompressionLevel(flate.DefaultCompression)
}
// NewGzipCompressionLevel returns a Gzip-based Compression with the given level.
func NewGzipCompressionLevel(level int) Compression {
return &genericCompression{
wf: func(w io.Writer) (io.WriteCloser, error) { return gzip.NewWriterLevel(w, level) },
rf: func(r io.Reader) (io.ReadCloser, error) { return gzip.NewReader(r) },
}
}
// NewZlibCompression returns a Zlib-based Compression.
func NewZlibCompression() Compression {
return NewZlibCompressionLevel(flate.DefaultCompression)
}
// NewZlibCompressionLevel returns a Zlib-based Compression with the given level.
func NewZlibCompressionLevel(level int) Compression {
return NewZlibCompressionLevelDict(level, nil)
}
// NewZlibCompressionLevelDict returns a Zlib-based Compression with the given
// level, based on the given dictionary.
func NewZlibCompressionLevelDict(level int, dict []byte) Compression {
return &genericCompression{
func(w io.Writer) (io.WriteCloser, error) { return zlib.NewWriterLevelDict(w, level, dict) },
func(r io.Reader) (io.ReadCloser, error) { return zlib.NewReaderDict(r, dict) },
}
}
type genericCompression struct {
wf func(w io.Writer) (io.WriteCloser, error)
rf func(r io.Reader) (io.ReadCloser, error)
}
func (g *genericCompression) Writer(dst io.Writer) (io.WriteCloser, error) {
return g.wf(dst)
}
func (g *genericCompression) Reader(src io.Reader) (io.ReadCloser, error) {
return g.rf(src)
}

View File

@ -0,0 +1,72 @@
package diskv
import (
"compress/flate"
"fmt"
"math/rand"
"os"
"testing"
"time"
)
func init() {
rand.Seed(time.Now().UnixNano())
}
func testCompressionWith(t *testing.T, c Compression, name string) {
d := New(Options{
BasePath: "compression-test",
CacheSizeMax: 0,
Compression: c,
})
defer d.EraseAll()
sz := 4096
val := make([]byte, sz)
for i := 0; i < sz; i++ {
val[i] = byte('a' + rand.Intn(26)) // {a-z}; should compress some
}
key := "a"
if err := d.Write(key, val); err != nil {
t.Fatalf("write failed: %s", err)
}
targetFile := fmt.Sprintf("%s%c%s", d.BasePath, os.PathSeparator, key)
fi, err := os.Stat(targetFile)
if err != nil {
t.Fatalf("%s: %s", targetFile, err)
}
if fi.Size() >= int64(sz) {
t.Fatalf("%s: size=%d, expected smaller", targetFile, fi.Size())
}
t.Logf("%s compressed %d to %d", name, sz, fi.Size())
readVal, err := d.Read(key)
if len(readVal) != sz {
t.Fatalf("read: expected size=%d, got size=%d", sz, len(readVal))
}
for i := 0; i < sz; i++ {
if readVal[i] != val[i] {
t.Fatalf("i=%d: expected %v, got %v", i, val[i], readVal[i])
}
}
}
func TestGzipDefault(t *testing.T) {
testCompressionWith(t, NewGzipCompression(), "gzip")
}
func TestGzipBestCompression(t *testing.T) {
testCompressionWith(t, NewGzipCompressionLevel(flate.BestCompression), "gzip-max")
}
func TestGzipBestSpeed(t *testing.T) {
testCompressionWith(t, NewGzipCompressionLevel(flate.BestSpeed), "gzip-min")
}
func TestZlib(t *testing.T) {
testCompressionWith(t, NewZlibCompression(), "zlib")
}

624
vendor/github.com/peterbourgon/diskv/diskv.go generated vendored Normal file
View File

@ -0,0 +1,624 @@
// Diskv (disk-vee) is a simple, persistent, key-value store.
// It stores all data flatly on the filesystem.
package diskv
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"syscall"
)
const (
defaultBasePath = "diskv"
defaultFilePerm os.FileMode = 0666
defaultPathPerm os.FileMode = 0777
)
var (
defaultTransform = func(s string) []string { return []string{} }
errCanceled = errors.New("canceled")
errEmptyKey = errors.New("empty key")
errBadKey = errors.New("bad key")
errImportDirectory = errors.New("can't import a directory")
)
// TransformFunction transforms a key into a slice of strings, with each
// element in the slice representing a directory in the file path where the
// key's entry will eventually be stored.
//
// For example, if TransformFunc transforms "abcdef" to ["ab", "cde", "f"],
// the final location of the data file will be <basedir>/ab/cde/f/abcdef
type TransformFunction func(s string) []string
// Options define a set of properties that dictate Diskv behavior.
// All values are optional.
type Options struct {
BasePath string
Transform TransformFunction
CacheSizeMax uint64 // bytes
PathPerm os.FileMode
FilePerm os.FileMode
// If TempDir is set, it will enable filesystem atomic writes by
// writing temporary files to that location before being moved
// to BasePath.
// Note that TempDir MUST be on the same device/partition as
// BasePath.
TempDir string
Index Index
IndexLess LessFunction
Compression Compression
}
// Diskv implements the Diskv interface. You shouldn't construct Diskv
// structures directly; instead, use the New constructor.
type Diskv struct {
Options
mu sync.RWMutex
cache map[string][]byte
cacheSize uint64
}
// New returns an initialized Diskv structure, ready to use.
// If the path identified by baseDir already contains data,
// it will be accessible, but not yet cached.
func New(o Options) *Diskv {
if o.BasePath == "" {
o.BasePath = defaultBasePath
}
if o.Transform == nil {
o.Transform = defaultTransform
}
if o.PathPerm == 0 {
o.PathPerm = defaultPathPerm
}
if o.FilePerm == 0 {
o.FilePerm = defaultFilePerm
}
d := &Diskv{
Options: o,
cache: map[string][]byte{},
cacheSize: 0,
}
if d.Index != nil && d.IndexLess != nil {
d.Index.Initialize(d.IndexLess, d.Keys(nil))
}
return d
}
// Write synchronously writes the key-value pair to disk, making it immediately
// available for reads. Write relies on the filesystem to perform an eventual
// sync to physical media. If you need stronger guarantees, see WriteStream.
func (d *Diskv) Write(key string, val []byte) error {
return d.WriteStream(key, bytes.NewBuffer(val), false)
}
// WriteStream writes the data represented by the io.Reader to the disk, under
// the provided key. If sync is true, WriteStream performs an explicit sync on
// the file as soon as it's written.
//
// bytes.Buffer provides io.Reader semantics for basic data types.
func (d *Diskv) WriteStream(key string, r io.Reader, sync bool) error {
if len(key) <= 0 {
return errEmptyKey
}
d.mu.Lock()
defer d.mu.Unlock()
return d.writeStreamWithLock(key, r, sync)
}
// createKeyFileWithLock either creates the key file directly, or
// creates a temporary file in TempDir if it is set.
func (d *Diskv) createKeyFileWithLock(key string) (*os.File, error) {
if d.TempDir != "" {
if err := os.MkdirAll(d.TempDir, d.PathPerm); err != nil {
return nil, fmt.Errorf("temp mkdir: %s", err)
}
f, err := ioutil.TempFile(d.TempDir, "")
if err != nil {
return nil, fmt.Errorf("temp file: %s", err)
}
if err := f.Chmod(d.FilePerm); err != nil {
f.Close() // error deliberately ignored
os.Remove(f.Name()) // error deliberately ignored
return nil, fmt.Errorf("chmod: %s", err)
}
return f, nil
}
mode := os.O_WRONLY | os.O_CREATE | os.O_TRUNC // overwrite if exists
f, err := os.OpenFile(d.completeFilename(key), mode, d.FilePerm)
if err != nil {
return nil, fmt.Errorf("open file: %s", err)
}
return f, nil
}
// writeStream does no input validation checking.
func (d *Diskv) writeStreamWithLock(key string, r io.Reader, sync bool) error {
if err := d.ensurePathWithLock(key); err != nil {
return fmt.Errorf("ensure path: %s", err)
}
f, err := d.createKeyFileWithLock(key)
if err != nil {
return fmt.Errorf("create key file: %s", err)
}
wc := io.WriteCloser(&nopWriteCloser{f})
if d.Compression != nil {
wc, err = d.Compression.Writer(f)
if err != nil {
f.Close() // error deliberately ignored
os.Remove(f.Name()) // error deliberately ignored
return fmt.Errorf("compression writer: %s", err)
}
}
if _, err := io.Copy(wc, r); err != nil {
f.Close() // error deliberately ignored
os.Remove(f.Name()) // error deliberately ignored
return fmt.Errorf("i/o copy: %s", err)
}
if err := wc.Close(); err != nil {
f.Close() // error deliberately ignored
os.Remove(f.Name()) // error deliberately ignored
return fmt.Errorf("compression close: %s", err)
}
if sync {
if err := f.Sync(); err != nil {
f.Close() // error deliberately ignored
os.Remove(f.Name()) // error deliberately ignored
return fmt.Errorf("file sync: %s", err)
}
}
if err := f.Close(); err != nil {
return fmt.Errorf("file close: %s", err)
}
if f.Name() != d.completeFilename(key) {
if err := os.Rename(f.Name(), d.completeFilename(key)); err != nil {
os.Remove(f.Name()) // error deliberately ignored
return fmt.Errorf("rename: %s", err)
}
}
if d.Index != nil {
d.Index.Insert(key)
}
d.bustCacheWithLock(key) // cache only on read
return nil
}
// Import imports the source file into diskv under the destination key. If the
// destination key already exists, it's overwritten. If move is true, the
// source file is removed after a successful import.
func (d *Diskv) Import(srcFilename, dstKey string, move bool) (err error) {
if dstKey == "" {
return errEmptyKey
}
if fi, err := os.Stat(srcFilename); err != nil {
return err
} else if fi.IsDir() {
return errImportDirectory
}
d.mu.Lock()
defer d.mu.Unlock()
if err := d.ensurePathWithLock(dstKey); err != nil {
return fmt.Errorf("ensure path: %s", err)
}
if move {
if err := syscall.Rename(srcFilename, d.completeFilename(dstKey)); err == nil {
d.bustCacheWithLock(dstKey)
return nil
} else if err != syscall.EXDEV {
// If it failed due to being on a different device, fall back to copying
return err
}
}
f, err := os.Open(srcFilename)
if err != nil {
return err
}
defer f.Close()
err = d.writeStreamWithLock(dstKey, f, false)
if err == nil && move {
err = os.Remove(srcFilename)
}
return err
}
// Read reads the key and returns the value.
// If the key is available in the cache, Read won't touch the disk.
// If the key is not in the cache, Read will have the side-effect of
// lazily caching the value.
func (d *Diskv) Read(key string) ([]byte, error) {
rc, err := d.ReadStream(key, false)
if err != nil {
return []byte{}, err
}
defer rc.Close()
return ioutil.ReadAll(rc)
}
// ReadStream reads the key and returns the value (data) as an io.ReadCloser.
// If the value is cached from a previous read, and direct is false,
// ReadStream will use the cached value. Otherwise, it will return a handle to
// the file on disk, and cache the data on read.
//
// If direct is true, ReadStream will lazily delete any cached value for the
// key, and return a direct handle to the file on disk.
//
// If compression is enabled, ReadStream taps into the io.Reader stream prior
// to decompression, and caches the compressed data.
func (d *Diskv) ReadStream(key string, direct bool) (io.ReadCloser, error) {
d.mu.RLock()
defer d.mu.RUnlock()
if val, ok := d.cache[key]; ok {
if !direct {
buf := bytes.NewBuffer(val)
if d.Compression != nil {
return d.Compression.Reader(buf)
}
return ioutil.NopCloser(buf), nil
}
go func() {
d.mu.Lock()
defer d.mu.Unlock()
d.uncacheWithLock(key, uint64(len(val)))
}()
}
return d.readWithRLock(key)
}
// read ignores the cache, and returns an io.ReadCloser representing the
// decompressed data for the given key, streamed from the disk. Clients should
// acquire a read lock on the Diskv and check the cache themselves before
// calling read.
func (d *Diskv) readWithRLock(key string) (io.ReadCloser, error) {
filename := d.completeFilename(key)
fi, err := os.Stat(filename)
if err != nil {
return nil, err
}
if fi.IsDir() {
return nil, os.ErrNotExist
}
f, err := os.Open(filename)
if err != nil {
return nil, err
}
var r io.Reader
if d.CacheSizeMax > 0 {
r = newSiphon(f, d, key)
} else {
r = &closingReader{f}
}
var rc = io.ReadCloser(ioutil.NopCloser(r))
if d.Compression != nil {
rc, err = d.Compression.Reader(r)
if err != nil {
return nil, err
}
}
return rc, nil
}
// closingReader provides a Reader that automatically closes the
// embedded ReadCloser when it reaches EOF
type closingReader struct {
rc io.ReadCloser
}
func (cr closingReader) Read(p []byte) (int, error) {
n, err := cr.rc.Read(p)
if err == io.EOF {
if closeErr := cr.rc.Close(); closeErr != nil {
return n, closeErr // close must succeed for Read to succeed
}
}
return n, err
}
// siphon is like a TeeReader: it copies all data read through it to an
// internal buffer, and moves that buffer to the cache at EOF.
type siphon struct {
f *os.File
d *Diskv
key string
buf *bytes.Buffer
}
// newSiphon constructs a siphoning reader that represents the passed file.
// When a successful series of reads ends in an EOF, the siphon will write
// the buffered data to Diskv's cache under the given key.
func newSiphon(f *os.File, d *Diskv, key string) io.Reader {
return &siphon{
f: f,
d: d,
key: key,
buf: &bytes.Buffer{},
}
}
// Read implements the io.Reader interface for siphon.
func (s *siphon) Read(p []byte) (int, error) {
n, err := s.f.Read(p)
if err == nil {
return s.buf.Write(p[0:n]) // Write must succeed for Read to succeed
}
if err == io.EOF {
s.d.cacheWithoutLock(s.key, s.buf.Bytes()) // cache may fail
if closeErr := s.f.Close(); closeErr != nil {
return n, closeErr // close must succeed for Read to succeed
}
return n, err
}
return n, err
}
// Erase synchronously erases the given key from the disk and the cache.
func (d *Diskv) Erase(key string) error {
d.mu.Lock()
defer d.mu.Unlock()
d.bustCacheWithLock(key)
// erase from index
if d.Index != nil {
d.Index.Delete(key)
}
// erase from disk
filename := d.completeFilename(key)
if s, err := os.Stat(filename); err == nil {
if s.IsDir() {
return errBadKey
}
if err = os.Remove(filename); err != nil {
return err
}
} else {
// Return err as-is so caller can do os.IsNotExist(err).
return err
}
// clean up and return
d.pruneDirsWithLock(key)
return nil
}
// EraseAll will delete all of the data from the store, both in the cache and on
// the disk. Note that EraseAll doesn't distinguish diskv-related data from non-
// diskv-related data. Care should be taken to always specify a diskv base
// directory that is exclusively for diskv data.
func (d *Diskv) EraseAll() error {
d.mu.Lock()
defer d.mu.Unlock()
d.cache = make(map[string][]byte)
d.cacheSize = 0
if d.TempDir != "" {
os.RemoveAll(d.TempDir) // errors ignored
}
return os.RemoveAll(d.BasePath)
}
// Has returns true if the given key exists.
func (d *Diskv) Has(key string) bool {
d.mu.Lock()
defer d.mu.Unlock()
if _, ok := d.cache[key]; ok {
return true
}
filename := d.completeFilename(key)
s, err := os.Stat(filename)
if err != nil {
return false
}
if s.IsDir() {
return false
}
return true
}
// Keys returns a channel that will yield every key accessible by the store,
// in undefined order. If a cancel channel is provided, closing it will
// terminate and close the keys channel.
func (d *Diskv) Keys(cancel <-chan struct{}) <-chan string {
return d.KeysPrefix("", cancel)
}
// KeysPrefix returns a channel that will yield every key accessible by the
// store with the given prefix, in undefined order. If a cancel channel is
// provided, closing it will terminate and close the keys channel. If the
// provided prefix is the empty string, all keys will be yielded.
func (d *Diskv) KeysPrefix(prefix string, cancel <-chan struct{}) <-chan string {
var prepath string
if prefix == "" {
prepath = d.BasePath
} else {
prepath = d.pathFor(prefix)
}
c := make(chan string)
go func() {
filepath.Walk(prepath, walker(c, prefix, cancel))
close(c)
}()
return c
}
// walker returns a function which satisfies the filepath.WalkFunc interface.
// It sends every non-directory file entry down the channel c.
func walker(c chan<- string, prefix string, cancel <-chan struct{}) filepath.WalkFunc {
return func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() || !strings.HasPrefix(info.Name(), prefix) {
return nil // "pass"
}
select {
case c <- info.Name():
case <-cancel:
return errCanceled
}
return nil
}
}
// pathFor returns the absolute path for location on the filesystem where the
// data for the given key will be stored.
func (d *Diskv) pathFor(key string) string {
return filepath.Join(d.BasePath, filepath.Join(d.Transform(key)...))
}
// ensurePathWithLock is a helper function that generates all necessary
// directories on the filesystem for the given key.
func (d *Diskv) ensurePathWithLock(key string) error {
return os.MkdirAll(d.pathFor(key), d.PathPerm)
}
// completeFilename returns the absolute path to the file for the given key.
func (d *Diskv) completeFilename(key string) string {
return filepath.Join(d.pathFor(key), key)
}
// cacheWithLock attempts to cache the given key-value pair in the store's
// cache. It can fail if the value is larger than the cache's maximum size.
func (d *Diskv) cacheWithLock(key string, val []byte) error {
valueSize := uint64(len(val))
if err := d.ensureCacheSpaceWithLock(valueSize); err != nil {
return fmt.Errorf("%s; not caching", err)
}
// be very strict about memory guarantees
if (d.cacheSize + valueSize) > d.CacheSizeMax {
panic(fmt.Sprintf("failed to make room for value (%d/%d)", valueSize, d.CacheSizeMax))
}
d.cache[key] = val
d.cacheSize += valueSize
return nil
}
// cacheWithoutLock acquires the store's (write) mutex and calls cacheWithLock.
func (d *Diskv) cacheWithoutLock(key string, val []byte) error {
d.mu.Lock()
defer d.mu.Unlock()
return d.cacheWithLock(key, val)
}
func (d *Diskv) bustCacheWithLock(key string) {
if val, ok := d.cache[key]; ok {
d.uncacheWithLock(key, uint64(len(val)))
}
}
func (d *Diskv) uncacheWithLock(key string, sz uint64) {
d.cacheSize -= sz
delete(d.cache, key)
}
// pruneDirsWithLock deletes empty directories in the path walk leading to the
// key k. Typically this function is called after an Erase is made.
func (d *Diskv) pruneDirsWithLock(key string) error {
pathlist := d.Transform(key)
for i := range pathlist {
dir := filepath.Join(d.BasePath, filepath.Join(pathlist[:len(pathlist)-i]...))
// thanks to Steven Blenkinsop for this snippet
switch fi, err := os.Stat(dir); true {
case err != nil:
return err
case !fi.IsDir():
panic(fmt.Sprintf("corrupt dirstate at %s", dir))
}
nlinks, err := filepath.Glob(filepath.Join(dir, "*"))
if err != nil {
return err
} else if len(nlinks) > 0 {
return nil // has subdirs -- do not prune
}
if err = os.Remove(dir); err != nil {
return err
}
}
return nil
}
// ensureCacheSpaceWithLock deletes entries from the cache in arbitrary order
// until the cache has at least valueSize bytes available.
func (d *Diskv) ensureCacheSpaceWithLock(valueSize uint64) error {
if valueSize > d.CacheSizeMax {
return fmt.Errorf("value size (%d bytes) too large for cache (%d bytes)", valueSize, d.CacheSizeMax)
}
safe := func() bool { return (d.cacheSize + valueSize) <= d.CacheSizeMax }
for key, val := range d.cache {
if safe() {
break
}
d.uncacheWithLock(key, uint64(len(val)))
}
if !safe() {
panic(fmt.Sprintf("%d bytes still won't fit in the cache! (max %d bytes)", valueSize, d.CacheSizeMax))
}
return nil
}
// nopWriteCloser wraps an io.Writer and provides a no-op Close method to
// satisfy the io.WriteCloser interface.
type nopWriteCloser struct {
io.Writer
}
func (wc *nopWriteCloser) Write(p []byte) (int, error) { return wc.Writer.Write(p) }
func (wc *nopWriteCloser) Close() error { return nil }

View File

@ -0,0 +1,63 @@
package main
import (
"crypto/md5"
"fmt"
"io"
"github.com/peterbourgon/diskv"
)
const transformBlockSize = 2 // grouping of chars per directory depth
func blockTransform(s string) []string {
var (
sliceSize = len(s) / transformBlockSize
pathSlice = make([]string, sliceSize)
)
for i := 0; i < sliceSize; i++ {
from, to := i*transformBlockSize, (i*transformBlockSize)+transformBlockSize
pathSlice[i] = s[from:to]
}
return pathSlice
}
func main() {
d := diskv.New(diskv.Options{
BasePath: "data",
Transform: blockTransform,
CacheSizeMax: 1024 * 1024, // 1MB
})
for _, valueStr := range []string{
"I am the very model of a modern Major-General",
"I've information vegetable, animal, and mineral",
"I know the kings of England, and I quote the fights historical",
"From Marathon to Waterloo, in order categorical",
"I'm very well acquainted, too, with matters mathematical",
"I understand equations, both the simple and quadratical",
"About binomial theorem I'm teeming with a lot o' news",
"With many cheerful facts about the square of the hypotenuse",
} {
d.Write(md5sum(valueStr), []byte(valueStr))
}
var keyCount int
for key := range d.Keys(nil) {
val, err := d.Read(key)
if err != nil {
panic(fmt.Sprintf("key %s had no value", key))
}
fmt.Printf("%s: %s\n", key, val)
keyCount++
}
fmt.Printf("%d total keys\n", keyCount)
// d.EraseAll() // leave it commented out to see how data is kept on disk
}
func md5sum(s string) string {
h := md5.New()
io.WriteString(h, s)
return fmt.Sprintf("%x", h.Sum(nil))
}

View File

@ -0,0 +1,30 @@
package main
import (
"fmt"
"github.com/peterbourgon/diskv"
)
func main() {
d := diskv.New(diskv.Options{
BasePath: "my-diskv-data-directory",
Transform: func(s string) []string { return []string{} },
CacheSizeMax: 1024 * 1024, // 1MB
})
key := "alpha"
if err := d.Write(key, []byte{'1', '2', '3'}); err != nil {
panic(err)
}
value, err := d.Read(key)
if err != nil {
panic(err)
}
fmt.Printf("%v\n", value)
if err := d.Erase(key); err != nil {
panic(err)
}
}

76
vendor/github.com/peterbourgon/diskv/import_test.go generated vendored Normal file
View File

@ -0,0 +1,76 @@
package diskv_test
import (
"bytes"
"io/ioutil"
"os"
"github.com/peterbourgon/diskv"
"testing"
)
func TestImportMove(t *testing.T) {
b := []byte(`0123456789`)
f, err := ioutil.TempFile("", "temp-test")
if err != nil {
t.Fatal(err)
}
if _, err := f.Write(b); err != nil {
t.Fatal(err)
}
f.Close()
d := diskv.New(diskv.Options{
BasePath: "test-import-move",
})
defer d.EraseAll()
key := "key"
if err := d.Write(key, []byte(`TBD`)); err != nil {
t.Fatal(err)
}
if err := d.Import(f.Name(), key, true); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(f.Name()); err == nil || !os.IsNotExist(err) {
t.Errorf("expected temp file to be gone, but err = %v", err)
}
if !d.Has(key) {
t.Errorf("%q not present", key)
}
if buf, err := d.Read(key); err != nil || bytes.Compare(b, buf) != 0 {
t.Errorf("want %q, have %q (err = %v)", string(b), string(buf), err)
}
}
func TestImportCopy(t *testing.T) {
b := []byte(`¡åéîòü!`)
f, err := ioutil.TempFile("", "temp-test")
if err != nil {
t.Fatal(err)
}
if _, err := f.Write(b); err != nil {
t.Fatal(err)
}
f.Close()
d := diskv.New(diskv.Options{
BasePath: "test-import-copy",
})
defer d.EraseAll()
if err := d.Import(f.Name(), "key", false); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(f.Name()); err != nil {
t.Errorf("expected temp file to remain, but got err = %v", err)
}
}

115
vendor/github.com/peterbourgon/diskv/index.go generated vendored Normal file
View File

@ -0,0 +1,115 @@
package diskv
import (
"sync"
"github.com/google/btree"
)
// Index is a generic interface for things that can
// provide an ordered list of keys.
type Index interface {
Initialize(less LessFunction, keys <-chan string)
Insert(key string)
Delete(key string)
Keys(from string, n int) []string
}
// LessFunction is used to initialize an Index of keys in a specific order.
type LessFunction func(string, string) bool
// btreeString is a custom data type that satisfies the BTree Less interface,
// making the strings it wraps sortable by the BTree package.
type btreeString struct {
s string
l LessFunction
}
// Less satisfies the BTree.Less interface using the btreeString's LessFunction.
func (s btreeString) Less(i btree.Item) bool {
return s.l(s.s, i.(btreeString).s)
}
// BTreeIndex is an implementation of the Index interface using google/btree.
type BTreeIndex struct {
sync.RWMutex
LessFunction
*btree.BTree
}
// Initialize populates the BTree tree with data from the keys channel,
// according to the passed less function. It's destructive to the BTreeIndex.
func (i *BTreeIndex) Initialize(less LessFunction, keys <-chan string) {
i.Lock()
defer i.Unlock()
i.LessFunction = less
i.BTree = rebuild(less, keys)
}
// Insert inserts the given key (only) into the BTree tree.
func (i *BTreeIndex) Insert(key string) {
i.Lock()
defer i.Unlock()
if i.BTree == nil || i.LessFunction == nil {
panic("uninitialized index")
}
i.BTree.ReplaceOrInsert(btreeString{s: key, l: i.LessFunction})
}
// Delete removes the given key (only) from the BTree tree.
func (i *BTreeIndex) Delete(key string) {
i.Lock()
defer i.Unlock()
if i.BTree == nil || i.LessFunction == nil {
panic("uninitialized index")
}
i.BTree.Delete(btreeString{s: key, l: i.LessFunction})
}
// Keys yields a maximum of n keys in order. If the passed 'from' key is empty,
// Keys will return the first n keys. If the passed 'from' key is non-empty, the
// first key in the returned slice will be the key that immediately follows the
// passed key, in key order.
func (i *BTreeIndex) Keys(from string, n int) []string {
i.RLock()
defer i.RUnlock()
if i.BTree == nil || i.LessFunction == nil {
panic("uninitialized index")
}
if i.BTree.Len() <= 0 {
return []string{}
}
btreeFrom := btreeString{s: from, l: i.LessFunction}
skipFirst := true
if len(from) <= 0 || !i.BTree.Has(btreeFrom) {
// no such key, so fabricate an always-smallest item
btreeFrom = btreeString{s: "", l: func(string, string) bool { return true }}
skipFirst = false
}
keys := []string{}
iterator := func(i btree.Item) bool {
keys = append(keys, i.(btreeString).s)
return len(keys) < n
}
i.BTree.AscendGreaterOrEqual(btreeFrom, iterator)
if skipFirst && len(keys) > 0 {
keys = keys[1:]
}
return keys
}
// rebuildIndex does the work of regenerating the index
// with the given keys.
func rebuild(less LessFunction, keys <-chan string) *btree.BTree {
tree := btree.New(2)
for key := range keys {
tree.ReplaceOrInsert(btreeString{s: key, l: less})
}
return tree
}

148
vendor/github.com/peterbourgon/diskv/index_test.go generated vendored Normal file
View File

@ -0,0 +1,148 @@
package diskv
import (
"bytes"
"reflect"
"testing"
"time"
)
func strLess(a, b string) bool { return a < b }
func cmpStrings(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := 0; i < len(a); i++ {
if a[i] != b[i] {
return false
}
}
return true
}
func (d *Diskv) isIndexed(key string) bool {
if d.Index == nil {
return false
}
for _, got := range d.Index.Keys("", 1000) {
if got == key {
return true
}
}
return false
}
func TestIndexOrder(t *testing.T) {
d := New(Options{
BasePath: "index-test",
Transform: func(string) []string { return []string{} },
CacheSizeMax: 1024,
Index: &BTreeIndex{},
IndexLess: strLess,
})
defer d.EraseAll()
v := []byte{'1', '2', '3'}
d.Write("a", v)
if !d.isIndexed("a") {
t.Fatalf("'a' not indexed after write")
}
d.Write("1", v)
d.Write("m", v)
d.Write("-", v)
d.Write("A", v)
expectedKeys := []string{"-", "1", "A", "a", "m"}
keys := []string{}
for _, key := range d.Index.Keys("", 100) {
keys = append(keys, key)
}
if !cmpStrings(keys, expectedKeys) {
t.Fatalf("got %s, expected %s", keys, expectedKeys)
}
}
func TestIndexLoad(t *testing.T) {
d1 := New(Options{
BasePath: "index-test",
Transform: func(string) []string { return []string{} },
CacheSizeMax: 1024,
})
defer d1.EraseAll()
val := []byte{'1', '2', '3'}
keys := []string{"a", "b", "c", "d", "e", "f", "g"}
for _, key := range keys {
d1.Write(key, val)
}
d2 := New(Options{
BasePath: "index-test",
Transform: func(string) []string { return []string{} },
CacheSizeMax: 1024,
Index: &BTreeIndex{},
IndexLess: strLess,
})
defer d2.EraseAll()
// check d2 has properly loaded existing d1 data
for _, key := range keys {
if !d2.isIndexed(key) {
t.Fatalf("key '%s' not indexed on secondary", key)
}
}
// cache one
if readValue, err := d2.Read(keys[0]); err != nil {
t.Fatalf("%s", err)
} else if bytes.Compare(val, readValue) != 0 {
t.Fatalf("%s: got %s, expected %s", keys[0], readValue, val)
}
// make sure it got cached
for i := 0; i < 10 && !d2.isCached(keys[0]); i++ {
time.Sleep(10 * time.Millisecond)
}
if !d2.isCached(keys[0]) {
t.Fatalf("key '%s' not cached", keys[0])
}
// kill the disk
d1.EraseAll()
// cached value should still be there in the second
if readValue, err := d2.Read(keys[0]); err != nil {
t.Fatalf("%s", err)
} else if bytes.Compare(val, readValue) != 0 {
t.Fatalf("%s: got %s, expected %s", keys[0], readValue, val)
}
// but not in the original
if _, err := d1.Read(keys[0]); err == nil {
t.Fatalf("expected error reading from flushed store")
}
}
func TestIndexKeysEmptyFrom(t *testing.T) {
d := New(Options{
BasePath: "index-test",
Transform: func(string) []string { return []string{} },
CacheSizeMax: 1024,
Index: &BTreeIndex{},
IndexLess: strLess,
})
defer d.EraseAll()
for _, k := range []string{"a", "c", "z", "b", "x", "b", "y"} {
d.Write(k, []byte("1"))
}
want := []string{"a", "b", "c", "x", "y", "z"}
have := d.Index.Keys("", 99)
if !reflect.DeepEqual(want, have) {
t.Errorf("want %v, have %v", want, have)
}
}

121
vendor/github.com/peterbourgon/diskv/issues_test.go generated vendored Normal file
View File

@ -0,0 +1,121 @@
package diskv
import (
"bytes"
"io/ioutil"
"sync"
"testing"
"time"
)
// ReadStream from cache shouldn't panic on a nil dereference from a nonexistent
// Compression :)
func TestIssue2A(t *testing.T) {
d := New(Options{
BasePath: "test-issue-2a",
Transform: func(string) []string { return []string{} },
CacheSizeMax: 1024,
})
defer d.EraseAll()
input := "abcdefghijklmnopqrstuvwxy"
key, writeBuf, sync := "a", bytes.NewBufferString(input), false
if err := d.WriteStream(key, writeBuf, sync); err != nil {
t.Fatal(err)
}
for i := 0; i < 2; i++ {
began := time.Now()
rc, err := d.ReadStream(key, false)
if err != nil {
t.Fatal(err)
}
buf, err := ioutil.ReadAll(rc)
if err != nil {
t.Fatal(err)
}
if !cmpBytes(buf, []byte(input)) {
t.Fatalf("read #%d: '%s' != '%s'", i+1, string(buf), input)
}
rc.Close()
t.Logf("read #%d in %s", i+1, time.Since(began))
}
}
// ReadStream on a key that resolves to a directory should return an error.
func TestIssue2B(t *testing.T) {
blockTransform := func(s string) []string {
transformBlockSize := 3
sliceSize := len(s) / transformBlockSize
pathSlice := make([]string, sliceSize)
for i := 0; i < sliceSize; i++ {
from, to := i*transformBlockSize, (i*transformBlockSize)+transformBlockSize
pathSlice[i] = s[from:to]
}
return pathSlice
}
d := New(Options{
BasePath: "test-issue-2b",
Transform: blockTransform,
CacheSizeMax: 0,
})
defer d.EraseAll()
v := []byte{'1', '2', '3'}
if err := d.Write("abcabc", v); err != nil {
t.Fatal(err)
}
_, err := d.ReadStream("abc", false)
if err == nil {
t.Fatal("ReadStream('abc') should return error")
}
t.Logf("ReadStream('abc') returned error: %v", err)
}
// Ensure ReadStream with direct=true isn't racy.
func TestIssue17(t *testing.T) {
var (
basePath = "test-data"
)
dWrite := New(Options{
BasePath: basePath,
CacheSizeMax: 0,
})
defer dWrite.EraseAll()
dRead := New(Options{
BasePath: basePath,
CacheSizeMax: 50,
})
cases := map[string]string{
"a": `1234567890`,
"b": `2345678901`,
"c": `3456789012`,
"d": `4567890123`,
"e": `5678901234`,
}
for k, v := range cases {
if err := dWrite.Write(k, []byte(v)); err != nil {
t.Fatalf("during write: %s", err)
}
dRead.Read(k) // ensure it's added to cache
}
var wg sync.WaitGroup
start := make(chan struct{})
for k, v := range cases {
wg.Add(1)
go func(k, v string) {
<-start
dRead.ReadStream(k, true)
wg.Done()
}(k, v)
}
close(start)
wg.Wait()
}

231
vendor/github.com/peterbourgon/diskv/keys_test.go generated vendored Normal file
View File

@ -0,0 +1,231 @@
package diskv_test
import (
"reflect"
"runtime"
"strings"
"testing"
"github.com/peterbourgon/diskv"
)
var (
keysTestData = map[string]string{
"ab01cd01": "When we started building CoreOS",
"ab01cd02": "we looked at all the various components available to us",
"ab01cd03": "re-using the best tools",
"ef01gh04": "and building the ones that did not exist",
"ef02gh05": "We believe strongly in the Unix philosophy",
"xxxxxxxx": "tools should be independently useful",
}
prefixes = []string{
"", // all
"a",
"ab",
"ab0",
"ab01",
"ab01cd0",
"ab01cd01",
"ab01cd01x", // none
"b", // none
"b0", // none
"0", // none
"01", // none
"e",
"ef",
"efx", // none
"ef01gh0",
"ef01gh04",
"ef01gh05",
"ef01gh06", // none
}
)
func TestKeysFlat(t *testing.T) {
transform := func(s string) []string {
if s == "" {
t.Fatalf(`transform should not be called with ""`)
}
return []string{}
}
d := diskv.New(diskv.Options{
BasePath: "test-data",
Transform: transform,
})
defer d.EraseAll()
for k, v := range keysTestData {
d.Write(k, []byte(v))
}
checkKeys(t, d.Keys(nil), keysTestData)
}
func TestKeysNested(t *testing.T) {
d := diskv.New(diskv.Options{
BasePath: "test-data",
Transform: blockTransform(2),
})
defer d.EraseAll()
for k, v := range keysTestData {
d.Write(k, []byte(v))
}
checkKeys(t, d.Keys(nil), keysTestData)
}
func TestKeysPrefixFlat(t *testing.T) {
d := diskv.New(diskv.Options{
BasePath: "test-data",
})
defer d.EraseAll()
for k, v := range keysTestData {
d.Write(k, []byte(v))
}
for _, prefix := range prefixes {
checkKeys(t, d.KeysPrefix(prefix, nil), filterPrefix(keysTestData, prefix))
}
}
func TestKeysPrefixNested(t *testing.T) {
d := diskv.New(diskv.Options{
BasePath: "test-data",
Transform: blockTransform(2),
})
defer d.EraseAll()
for k, v := range keysTestData {
d.Write(k, []byte(v))
}
for _, prefix := range prefixes {
checkKeys(t, d.KeysPrefix(prefix, nil), filterPrefix(keysTestData, prefix))
}
}
func TestKeysCancel(t *testing.T) {
d := diskv.New(diskv.Options{
BasePath: "test-data",
})
defer d.EraseAll()
for k, v := range keysTestData {
d.Write(k, []byte(v))
}
var (
cancel = make(chan struct{})
received = 0
cancelAfter = len(keysTestData) / 2
)
for key := range d.Keys(cancel) {
received++
if received >= cancelAfter {
close(cancel)
runtime.Gosched() // allow walker to detect cancel
}
t.Logf("received %d: %q", received, key)
}
if want, have := cancelAfter, received; want != have {
t.Errorf("want %d, have %d")
}
}
func checkKeys(t *testing.T, c <-chan string, want map[string]string) {
for k := range c {
if _, ok := want[k]; !ok {
t.Errorf("%q yielded but not expected", k)
continue
}
delete(want, k)
t.Logf("%q yielded OK", k)
}
if len(want) != 0 {
t.Errorf("%d expected key(s) not yielded: %s", len(want), strings.Join(flattenKeys(want), ", "))
}
}
func blockTransform(blockSize int) func(string) []string {
return func(s string) []string {
var (
sliceSize = len(s) / blockSize
pathSlice = make([]string, sliceSize)
)
for i := 0; i < sliceSize; i++ {
from, to := i*blockSize, (i*blockSize)+blockSize
pathSlice[i] = s[from:to]
}
return pathSlice
}
}
func filterPrefix(in map[string]string, prefix string) map[string]string {
out := map[string]string{}
for k, v := range in {
if strings.HasPrefix(k, prefix) {
out[k] = v
}
}
return out
}
func TestFilterPrefix(t *testing.T) {
input := map[string]string{
"all": "",
"and": "",
"at": "",
"available": "",
"best": "",
"building": "",
"components": "",
"coreos": "",
"did": "",
"exist": "",
"looked": "",
"not": "",
"ones": "",
"re-using": "",
"started": "",
"that": "",
"the": "",
"to": "",
"tools": "",
"us": "",
"various": "",
"we": "",
"when": "",
}
for prefix, want := range map[string]map[string]string{
"a": map[string]string{"all": "", "and": "", "at": "", "available": ""},
"al": map[string]string{"all": ""},
"all": map[string]string{"all": ""},
"alll": map[string]string{},
"c": map[string]string{"components": "", "coreos": ""},
"co": map[string]string{"components": "", "coreos": ""},
"com": map[string]string{"components": ""},
} {
have := filterPrefix(input, prefix)
if !reflect.DeepEqual(want, have) {
t.Errorf("%q: want %v, have %v", prefix, flattenKeys(want), flattenKeys(have))
}
}
}
func flattenKeys(m map[string]string) []string {
a := make([]string, 0, len(m))
for k := range m {
a = append(a, k)
}
return a
}

153
vendor/github.com/peterbourgon/diskv/speed_test.go generated vendored Normal file
View File

@ -0,0 +1,153 @@
package diskv
import (
"fmt"
"math/rand"
"testing"
)
func shuffle(keys []string) {
ints := rand.Perm(len(keys))
for i := range keys {
keys[i], keys[ints[i]] = keys[ints[i]], keys[i]
}
}
func genValue(size int) []byte {
v := make([]byte, size)
for i := 0; i < size; i++ {
v[i] = uint8((rand.Int() % 26) + 97) // a-z
}
return v
}
const (
keyCount = 1000
)
func genKeys() []string {
keys := make([]string, keyCount)
for i := 0; i < keyCount; i++ {
keys[i] = fmt.Sprintf("%d", i)
}
return keys
}
func (d *Diskv) load(keys []string, val []byte) {
for _, key := range keys {
d.Write(key, val)
}
}
func benchRead(b *testing.B, size, cachesz int) {
b.StopTimer()
d := New(Options{
BasePath: "speed-test",
Transform: func(string) []string { return []string{} },
CacheSizeMax: uint64(cachesz),
})
defer d.EraseAll()
keys := genKeys()
value := genValue(size)
d.load(keys, value)
shuffle(keys)
b.SetBytes(int64(size))
b.StartTimer()
for i := 0; i < b.N; i++ {
_, _ = d.Read(keys[i%len(keys)])
}
b.StopTimer()
}
func benchWrite(b *testing.B, size int, withIndex bool) {
b.StopTimer()
options := Options{
BasePath: "speed-test",
Transform: func(string) []string { return []string{} },
CacheSizeMax: 0,
}
if withIndex {
options.Index = &BTreeIndex{}
options.IndexLess = strLess
}
d := New(options)
defer d.EraseAll()
keys := genKeys()
value := genValue(size)
shuffle(keys)
b.SetBytes(int64(size))
b.StartTimer()
for i := 0; i < b.N; i++ {
d.Write(keys[i%len(keys)], value)
}
b.StopTimer()
}
func BenchmarkWrite__32B_NoIndex(b *testing.B) {
benchWrite(b, 32, false)
}
func BenchmarkWrite__1KB_NoIndex(b *testing.B) {
benchWrite(b, 1024, false)
}
func BenchmarkWrite__4KB_NoIndex(b *testing.B) {
benchWrite(b, 4096, false)
}
func BenchmarkWrite_10KB_NoIndex(b *testing.B) {
benchWrite(b, 10240, false)
}
func BenchmarkWrite__32B_WithIndex(b *testing.B) {
benchWrite(b, 32, true)
}
func BenchmarkWrite__1KB_WithIndex(b *testing.B) {
benchWrite(b, 1024, true)
}
func BenchmarkWrite__4KB_WithIndex(b *testing.B) {
benchWrite(b, 4096, true)
}
func BenchmarkWrite_10KB_WithIndex(b *testing.B) {
benchWrite(b, 10240, true)
}
func BenchmarkRead__32B_NoCache(b *testing.B) {
benchRead(b, 32, 0)
}
func BenchmarkRead__1KB_NoCache(b *testing.B) {
benchRead(b, 1024, 0)
}
func BenchmarkRead__4KB_NoCache(b *testing.B) {
benchRead(b, 4096, 0)
}
func BenchmarkRead_10KB_NoCache(b *testing.B) {
benchRead(b, 10240, 0)
}
func BenchmarkRead__32B_WithCache(b *testing.B) {
benchRead(b, 32, keyCount*32*2)
}
func BenchmarkRead__1KB_WithCache(b *testing.B) {
benchRead(b, 1024, keyCount*1024*2)
}
func BenchmarkRead__4KB_WithCache(b *testing.B) {
benchRead(b, 4096, keyCount*4096*2)
}
func BenchmarkRead_10KB_WithCache(b *testing.B) {
benchRead(b, 10240, keyCount*4096*2)
}

117
vendor/github.com/peterbourgon/diskv/stream_test.go generated vendored Normal file
View File

@ -0,0 +1,117 @@
package diskv
import (
"bytes"
"io/ioutil"
"testing"
)
func TestBasicStreamCaching(t *testing.T) {
d := New(Options{
BasePath: "test-data",
CacheSizeMax: 1024,
})
defer d.EraseAll()
input := "a1b2c3"
key, writeBuf, sync := "a", bytes.NewBufferString(input), true
if err := d.WriteStream(key, writeBuf, sync); err != nil {
t.Fatal(err)
}
if d.isCached(key) {
t.Fatalf("'%s' cached, but shouldn't be (yet)", key)
}
rc, err := d.ReadStream(key, false)
if err != nil {
t.Fatal(err)
}
readBuf, err := ioutil.ReadAll(rc)
if err != nil {
t.Fatal(err)
}
if !cmpBytes(readBuf, []byte(input)) {
t.Fatalf("'%s' != '%s'", string(readBuf), input)
}
if !d.isCached(key) {
t.Fatalf("'%s' isn't cached, but should be", key)
}
}
func TestReadStreamDirect(t *testing.T) {
var (
basePath = "test-data"
)
dWrite := New(Options{
BasePath: basePath,
CacheSizeMax: 0,
})
defer dWrite.EraseAll()
dRead := New(Options{
BasePath: basePath,
CacheSizeMax: 1024,
})
// Write
key, val1, val2 := "a", []byte(`1234567890`), []byte(`aaaaaaaaaa`)
if err := dWrite.Write(key, val1); err != nil {
t.Fatalf("during first write: %s", err)
}
// First, caching read.
val, err := dRead.Read(key)
if err != nil {
t.Fatalf("during initial read: %s", err)
}
t.Logf("read 1: %s => %s", key, string(val))
if !cmpBytes(val1, val) {
t.Errorf("expected %q, got %q", string(val1), string(val))
}
if !dRead.isCached(key) {
t.Errorf("%q should be cached, but isn't", key)
}
// Write a different value.
if err := dWrite.Write(key, val2); err != nil {
t.Fatalf("during second write: %s", err)
}
// Second read, should hit cache and get the old value.
val, err = dRead.Read(key)
if err != nil {
t.Fatalf("during second (cache-hit) read: %s", err)
}
t.Logf("read 2: %s => %s", key, string(val))
if !cmpBytes(val1, val) {
t.Errorf("expected %q, got %q", string(val1), string(val))
}
// Third, direct read, should get the updated value.
rc, err := dRead.ReadStream(key, true)
if err != nil {
t.Fatalf("during third (direct) read, ReadStream: %s", err)
}
defer rc.Close()
val, err = ioutil.ReadAll(rc)
if err != nil {
t.Fatalf("during third (direct) read, ReadAll: %s", err)
}
t.Logf("read 3: %s => %s", key, string(val))
if !cmpBytes(val2, val) {
t.Errorf("expected %q, got %q", string(val1), string(val))
}
// Fourth read, should hit cache and get the new value.
val, err = dRead.Read(key)
if err != nil {
t.Fatalf("during fourth (cache-hit) read: %s", err)
}
t.Logf("read 4: %s => %s", key, string(val))
if !cmpBytes(val2, val) {
t.Errorf("expected %q, got %q", string(val1), string(val))
}
}

View File

@ -1,10 +1,14 @@
language: go
go_import_path: github.com/pkg/errors
go:
- 1.4.3
- 1.5.4
- 1.6.2
- 1.7.1
- 1.4.x
- 1.5.x
- 1.6.x
- 1.7.x
- 1.8.x
- 1.9.x
- 1.10.x
- 1.11.x
- tip
script:

View File

@ -1,4 +1,4 @@
# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors)
# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors) [![Sourcegraph](https://sourcegraph.com/github.com/pkg/errors/-/badge.svg)](https://sourcegraph.com/github.com/pkg/errors?badge)
Package errors provides simple error handling primitives.
@ -47,6 +47,6 @@ We welcome pull requests, bug fixes and issue reports. With that said, the bar f
Before proposing a change, please discuss your change by raising an issue.
## Licence
## License
BSD-2-Clause

View File

@ -15,6 +15,7 @@ func noErrors(at, depth int) error {
}
return noErrors(at+1, depth)
}
func yesErrors(at, depth int) error {
if at >= depth {
return New("ye error")
@ -22,8 +23,11 @@ func yesErrors(at, depth int) error {
return yesErrors(at+1, depth)
}
// GlobalE is an exported global to store the result of benchmark results,
// preventing the compiler from optimising the benchmark functions away.
var GlobalE error
func BenchmarkErrors(b *testing.B) {
var toperr error
type run struct {
stack int
std bool
@ -53,7 +57,7 @@ func BenchmarkErrors(b *testing.B) {
err = f(0, r.stack)
}
b.StopTimer()
toperr = err
GlobalE = err
})
}
}

View File

@ -6,7 +6,7 @@
// return err
// }
//
// which applied recursively up the call stack results in error reports
// which when applied recursively up the call stack results in error reports
// without context or debugging information. The errors package allows
// programmers to add context to the failure path in their code in a way
// that does not destroy the original value of the error.
@ -15,16 +15,17 @@
//
// The errors.Wrap function returns a new error that adds context to the
// original error by recording a stack trace at the point Wrap is called,
// and the supplied message. For example
// together with the supplied message. For example
//
// _, err := ioutil.ReadAll(r)
// if err != nil {
// return errors.Wrap(err, "read failed")
// }
//
// If additional control is required the errors.WithStack and errors.WithMessage
// functions destructure errors.Wrap into its component operations of annotating
// an error with a stack trace and an a message, respectively.
// If additional control is required, the errors.WithStack and
// errors.WithMessage functions destructure errors.Wrap into its component
// operations: annotating an error with a stack trace and with a message,
// respectively.
//
// Retrieving the cause of an error
//
@ -38,7 +39,7 @@
// }
//
// can be inspected by errors.Cause. errors.Cause will recursively retrieve
// the topmost error which does not implement causer, which is assumed to be
// the topmost error that does not implement causer, which is assumed to be
// the original cause. For example:
//
// switch err := errors.Cause(err).(type) {
@ -48,16 +49,16 @@
// // unknown error
// }
//
// causer interface is not exported by this package, but is considered a part
// of stable public API.
// Although the causer interface is not exported by this package, it is
// considered a part of its stable public interface.
//
// Formatted printing of errors
//
// All error values returned from this package implement fmt.Formatter and can
// be formatted by the fmt package. The following verbs are supported
// be formatted by the fmt package. The following verbs are supported:
//
// %s print the error. If the error has a Cause it will be
// printed recursively
// printed recursively.
// %v see %s
// %+v extended format. Each Frame of the error's StackTrace will
// be printed in detail.
@ -65,13 +66,13 @@
// Retrieving the stack trace of an error or wrapper
//
// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are
// invoked. This information can be retrieved with the following interface.
// invoked. This information can be retrieved with the following interface:
//
// type stackTracer interface {
// StackTrace() errors.StackTrace
// }
//
// Where errors.StackTrace is defined as
// The returned errors.StackTrace type is defined as
//
// type StackTrace []Frame
//
@ -85,8 +86,8 @@
// }
// }
//
// stackTracer interface is not exported by this package, but is considered a part
// of stable public API.
// Although the stackTracer interface is not exported by this package, it is
// considered a part of its stable public interface.
//
// See the documentation for Frame.Format for more details.
package errors
@ -192,7 +193,7 @@ func Wrap(err error, message string) error {
}
// Wrapf returns an error annotating err with a stack trace
// at the point Wrapf is call, and the format specifier.
// at the point Wrapf is called, and the format specifier.
// If err is nil, Wrapf returns nil.
func Wrapf(err error, format string, args ...interface{}) error {
if err == nil {
@ -220,6 +221,18 @@ func WithMessage(err error, message string) error {
}
}
// WithMessagef annotates err with the format specifier.
// If err is nil, WithMessagef returns nil.
func WithMessagef(err error, format string, args ...interface{}) error {
if err == nil {
return nil
}
return &withMessage{
cause: err,
msg: fmt.Sprintf(format, args...),
}
}
type withMessage struct {
cause error
msg string

View File

@ -196,7 +196,32 @@ func TestWithMessage(t *testing.T) {
t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want)
}
}
}
func TestWithMessagefNil(t *testing.T) {
got := WithMessagef(nil, "no error")
if got != nil {
t.Errorf("WithMessage(nil, \"no error\"): got %#v, expected nil", got)
}
}
func TestWithMessagef(t *testing.T) {
tests := []struct {
err error
message string
want string
}{
{io.EOF, "read error", "read error: EOF"},
{WithMessagef(io.EOF, "read error without format specifier"), "client error", "client error: read error without format specifier: EOF"},
{WithMessagef(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"},
}
for _, tt := range tests {
got := WithMessagef(tt.err, tt.message).Error()
if got != tt.want {
t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want)
}
}
}
// errors.New, etc values are not expected to be compared by value

View File

@ -491,7 +491,7 @@ type wrapper struct {
want []string
}
func prettyBlocks(blocks []string, prefix ...string) string {
func prettyBlocks(blocks []string) string {
var out []string
for _, b := range blocks {

View File

@ -46,7 +46,8 @@ func (f Frame) line() int {
//
// Format accepts flags that alter the printing of some verbs, as follows:
//
// %+s path of source file relative to the compile time GOPATH
// %+s function name and path of source file relative to the compile time
// GOPATH separated by \n\t (<funcname>\n\t<path>)
// %+v equivalent to %+s:%d
func (f Frame) Format(s fmt.State, verb rune) {
switch verb {
@ -79,6 +80,14 @@ func (f Frame) Format(s fmt.State, verb rune) {
// StackTrace is stack of Frames from innermost (newest) to outermost (oldest).
type StackTrace []Frame
// Format formats the stack of Frames according to the fmt.Formatter interface.
//
// %s lists source files for each Frame in the stack
// %v lists the source file and line number for each Frame in the stack
//
// Format accepts flags that alter the printing of some verbs, as follows:
//
// %+v Prints filename, function, and line number for each Frame in the stack.
func (st StackTrace) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
@ -136,43 +145,3 @@ func funcname(name string) string {
i = strings.Index(name, ".")
return name[i+1:]
}
func trimGOPATH(name, file string) string {
// Here we want to get the source file path relative to the compile time
// GOPATH. As of Go 1.6.x there is no direct way to know the compiled
// GOPATH at runtime, but we can infer the number of path segments in the
// GOPATH. We note that fn.Name() returns the function name qualified by
// the import path, which does not include the GOPATH. Thus we can trim
// segments from the beginning of the file path until the number of path
// separators remaining is one more than the number of path separators in
// the function name. For example, given:
//
// GOPATH /home/user
// file /home/user/src/pkg/sub/file.go
// fn.Name() pkg/sub.Type.Method
//
// We want to produce:
//
// pkg/sub/file.go
//
// From this we can easily see that fn.Name() has one less path separator
// than our desired output. We count separators from the end of the file
// path until it finds two more than in the function name and then move
// one character forward to preserve the initial path segment without a
// leading separator.
const sep = "/"
goal := strings.Count(name, sep) + 2
i := len(file)
for n := 0; n < goal; n++ {
i = strings.LastIndex(file[:i], sep)
if i == -1 {
// not enough separators found, set i so that the slice expression
// below leaves file unmodified
i = -len(sep)
break
}
}
// get back to 0 or trim the leading separator
file = file[i+len(sep):]
return file
}

View File

@ -146,24 +146,6 @@ func TestFuncname(t *testing.T) {
}
}
func TestTrimGOPATH(t *testing.T) {
var tests = []struct {
Frame
want string
}{{
Frame(initpc),
"github.com/pkg/errors/stack_test.go",
}}
for i, tt := range tests {
pc := tt.Frame.pc()
fn := runtime.FuncForPC(pc)
file, _ := fn.FileLine(pc)
got := trimGOPATH(fn.Name(), file)
testFormatRegexp(t, i, got, "%s", tt.want)
}
}
func TestStackTrace(t *testing.T) {
tests := []struct {
err error
@ -171,24 +153,24 @@ func TestStackTrace(t *testing.T) {
}{{
New("ooh"), []string{
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:172",
"\t.+/github.com/pkg/errors/stack_test.go:154",
},
}, {
Wrap(New("ooh"), "ahh"), []string{
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:177", // this is the stack of Wrap, not New
"\t.+/github.com/pkg/errors/stack_test.go:159", // this is the stack of Wrap, not New
},
}, {
Cause(Wrap(New("ooh"), "ahh")), []string{
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:182", // this is the stack of New
"\t.+/github.com/pkg/errors/stack_test.go:164", // this is the stack of New
},
}, {
func() error { return New("ooh") }(), []string{
`github.com/pkg/errors.(func·009|TestStackTrace.func1)` +
"\n\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New
"\n\t.+/github.com/pkg/errors/stack_test.go:169", // this is the stack of New
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New's caller
"\t.+/github.com/pkg/errors/stack_test.go:169", // this is the stack of New's caller
},
}, {
Cause(func() error {
@ -197,11 +179,11 @@ func TestStackTrace(t *testing.T) {
}()
}()), []string{
`github.com/pkg/errors.(func·010|TestStackTrace.func2.1)` +
"\n\t.+/github.com/pkg/errors/stack_test.go:196", // this is the stack of Errorf
"\n\t.+/github.com/pkg/errors/stack_test.go:178", // this is the stack of Errorf
`github.com/pkg/errors.(func·011|TestStackTrace.func2)` +
"\n\t.+/github.com/pkg/errors/stack_test.go:197", // this is the stack of Errorf's caller
"\n\t.+/github.com/pkg/errors/stack_test.go:179", // this is the stack of Errorf's caller
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:198", // this is the stack of Errorf's caller's caller
"\t.+/github.com/pkg/errors/stack_test.go:180", // this is the stack of Errorf's caller's caller
},
}}
for i, tt := range tests {
@ -271,19 +253,19 @@ func TestStackTraceFormat(t *testing.T) {
}, {
stackTrace()[:2],
"%v",
`\[stack_test.go:225 stack_test.go:272\]`,
`\[stack_test.go:207 stack_test.go:254\]`,
}, {
stackTrace()[:2],
"%+v",
"\n" +
"github.com/pkg/errors.stackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:225\n" +
"\t.+/github.com/pkg/errors/stack_test.go:207\n" +
"github.com/pkg/errors.TestStackTraceFormat\n" +
"\t.+/github.com/pkg/errors/stack_test.go:276",
"\t.+/github.com/pkg/errors/stack_test.go:258",
}, {
stackTrace()[:2],
"%#v",
`\[\]errors.Frame{stack_test.go:225, stack_test.go:284}`,
`\[\]errors.Frame{stack_test.go:207, stack_test.go:266}`,
}}
for i, tt := range tests {

View File

@ -125,8 +125,8 @@ func (e *gfP12) Mul(a, b *gfP12, pool *bnPool) *gfP12 {
}
func (e *gfP12) MulScalar(a *gfP12, b *gfP6, pool *bnPool) *gfP12 {
e.x.Mul(e.x, b, pool)
e.y.Mul(e.y, b, pool)
e.x.Mul(a.x, b, pool)
e.y.Mul(a.y, b, pool)
return e
}

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